feat: improve chat realtime and media composer UX
All checks were successful
CI / test (push) Successful in 27s
All checks were successful
CI / test (push) Successful in 27s
- add media preview and upload confirmation for image/video - add upload progress tracking for presigned uploads - keep voice recording/upload flow with better UI states - include related realtime/chat updates currently in working tree
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { http } from "./http";
|
||||
import type { Chat, ChatType, Message, MessageType } from "../chat/types";
|
||||
import axios from "axios";
|
||||
|
||||
export async function getChats(): Promise<Chat[]> {
|
||||
const { data } = await http.get<Chat[]>("/chats");
|
||||
@@ -51,6 +52,23 @@ export async function requestUploadUrl(file: File): Promise<UploadUrlResponse> {
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function uploadToPresignedUrl(
|
||||
uploadUrl: string,
|
||||
requiredHeaders: Record<string, string>,
|
||||
file: File,
|
||||
onProgress?: (percent: number) => void
|
||||
): Promise<void> {
|
||||
await axios.put(uploadUrl, file, {
|
||||
headers: requiredHeaders,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (!onProgress || !progressEvent.total) {
|
||||
return;
|
||||
}
|
||||
onProgress(Math.round((progressEvent.loaded * 100) / progressEvent.total));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function attachFile(messageId: number, fileUrl: string, fileType: string, fileSize: number): Promise<void> {
|
||||
await http.post("/media/attachments", {
|
||||
message_id: messageId,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { attachFile, requestUploadUrl, sendMessage } from "../api/chats";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { attachFile, requestUploadUrl, sendMessage, uploadToPresignedUrl } from "../api/chats";
|
||||
import { useAuthStore } from "../store/authStore";
|
||||
import { useChatStore } from "../store/chatStore";
|
||||
import { buildWsUrl } from "../utils/ws";
|
||||
@@ -12,6 +12,21 @@ export function MessageComposer() {
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const recorderRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<BlobPart[]>([]);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [selectedType, setSelectedType] = useState<"file" | "image" | "video" | "audio">("file");
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (previewUrl) {
|
||||
URL.revokeObjectURL(previewUrl);
|
||||
}
|
||||
};
|
||||
}, [previewUrl]);
|
||||
|
||||
function getWs(): WebSocket | null {
|
||||
if (!accessToken || !activeChatId) {
|
||||
@@ -40,34 +55,109 @@ export function MessageComposer() {
|
||||
if (!activeChatId) {
|
||||
return;
|
||||
}
|
||||
const upload = await requestUploadUrl(file);
|
||||
await fetch(upload.upload_url, {
|
||||
method: "PUT",
|
||||
headers: upload.required_headers,
|
||||
body: file
|
||||
});
|
||||
const message = await sendMessage(activeChatId, upload.file_url, messageType);
|
||||
await attachFile(message.id, upload.file_url, file.type || "application/octet-stream", file.size);
|
||||
prependMessage(activeChatId, message);
|
||||
setIsUploading(true);
|
||||
setUploadProgress(0);
|
||||
setUploadError(null);
|
||||
try {
|
||||
const upload = await requestUploadUrl(file);
|
||||
await uploadToPresignedUrl(upload.upload_url, upload.required_headers, file, setUploadProgress);
|
||||
const message = await sendMessage(activeChatId, upload.file_url, messageType);
|
||||
await attachFile(message.id, upload.file_url, file.type || "application/octet-stream", file.size);
|
||||
prependMessage(activeChatId, message);
|
||||
} catch {
|
||||
setUploadError("Upload failed. Please try again.");
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function inferType(file: File): "file" | "image" | "video" | "audio" {
|
||||
if (file.type.startsWith("image/")) {
|
||||
return "image";
|
||||
}
|
||||
if (file.type.startsWith("video/")) {
|
||||
return "video";
|
||||
}
|
||||
if (file.type.startsWith("audio/")) {
|
||||
return "audio";
|
||||
}
|
||||
return "file";
|
||||
}
|
||||
|
||||
async function startRecord() {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
const recorder = new MediaRecorder(stream);
|
||||
chunksRef.current = [];
|
||||
recorder.ondataavailable = (e) => chunksRef.current.push(e.data);
|
||||
recorder.onstop = async () => {
|
||||
const blob = new Blob(chunksRef.current, { type: "audio/webm" });
|
||||
const file = new File([blob], `voice-${Date.now()}.webm`, { type: "audio/webm" });
|
||||
await handleUpload(file, "voice");
|
||||
};
|
||||
recorderRef.current = recorder;
|
||||
recorder.start();
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
const recorder = new MediaRecorder(stream);
|
||||
chunksRef.current = [];
|
||||
recorder.ondataavailable = (e) => chunksRef.current.push(e.data);
|
||||
recorder.onstop = async () => {
|
||||
const blob = new Blob(chunksRef.current, { type: "audio/webm" });
|
||||
const file = new File([blob], `voice-${Date.now()}.webm`, { type: "audio/webm" });
|
||||
setIsRecording(false);
|
||||
await handleUpload(file, "voice");
|
||||
};
|
||||
recorderRef.current = recorder;
|
||||
recorder.start();
|
||||
setIsRecording(true);
|
||||
} catch {
|
||||
setUploadError("Microphone access denied.");
|
||||
}
|
||||
}
|
||||
|
||||
function stopRecord() {
|
||||
recorderRef.current?.stop();
|
||||
recorderRef.current = null;
|
||||
setIsRecording(false);
|
||||
}
|
||||
|
||||
function selectFile(file: File) {
|
||||
setUploadError(null);
|
||||
setSelectedFile(file);
|
||||
const fileType = inferType(file);
|
||||
setSelectedType(fileType);
|
||||
if (previewUrl) {
|
||||
URL.revokeObjectURL(previewUrl);
|
||||
}
|
||||
if (fileType === "image" || fileType === "video") {
|
||||
setPreviewUrl(URL.createObjectURL(file));
|
||||
} else {
|
||||
setPreviewUrl(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendSelectedFile() {
|
||||
if (!selectedFile) {
|
||||
return;
|
||||
}
|
||||
await handleUpload(selectedFile, selectedType);
|
||||
if (previewUrl) {
|
||||
URL.revokeObjectURL(previewUrl);
|
||||
}
|
||||
setSelectedFile(null);
|
||||
setPreviewUrl(null);
|
||||
setSelectedType("file");
|
||||
setUploadProgress(0);
|
||||
}
|
||||
|
||||
function cancelSelectedFile() {
|
||||
if (previewUrl) {
|
||||
URL.revokeObjectURL(previewUrl);
|
||||
}
|
||||
setSelectedFile(null);
|
||||
setPreviewUrl(null);
|
||||
setSelectedType("file");
|
||||
setUploadProgress(0);
|
||||
setUploadError(null);
|
||||
}
|
||||
|
||||
function formatBytes(size: number): string {
|
||||
if (size < 1024) {
|
||||
return `${size} B`;
|
||||
}
|
||||
if (size < 1024 * 1024) {
|
||||
return `${(size / 1024).toFixed(1)} KB`;
|
||||
}
|
||||
return `${(size / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -89,24 +179,60 @@ export function MessageComposer() {
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
{selectedFile ? (
|
||||
<div className="mb-2 rounded border border-slate-700 bg-slate-900 p-3 text-sm">
|
||||
<div className="mb-2 font-semibold">Ready to send</div>
|
||||
<div className="mb-1 break-all text-slate-300">{selectedFile.name}</div>
|
||||
<div className="mb-2 text-xs text-slate-400">{formatBytes(selectedFile.size)}</div>
|
||||
{previewUrl && selectedType === "image" ? (
|
||||
<img className="mb-2 max-h-56 rounded object-contain" src={previewUrl} alt={selectedFile.name} />
|
||||
) : null}
|
||||
{previewUrl && selectedType === "video" ? (
|
||||
<video className="mb-2 max-h-56 w-full rounded" src={previewUrl} controls muted />
|
||||
) : null}
|
||||
{isUploading ? (
|
||||
<div className="mb-2">
|
||||
<div className="mb-1 text-xs text-slate-300">Uploading: {uploadProgress}%</div>
|
||||
<div className="h-2 rounded bg-slate-700">
|
||||
<div className="h-2 rounded bg-accent transition-all" style={{ width: `${uploadProgress}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
className="rounded bg-accent px-3 py-1 font-semibold text-black disabled:opacity-50"
|
||||
onClick={() => void sendSelectedFile()}
|
||||
disabled={isUploading}
|
||||
>
|
||||
Send media
|
||||
</button>
|
||||
<button className="rounded bg-slate-700 px-3 py-1 disabled:opacity-50" onClick={cancelSelectedFile} disabled={isUploading}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{uploadError ? <div className="mb-2 text-sm text-red-400">{uploadError}</div> : null}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<label className="cursor-pointer rounded bg-slate-700 px-3 py-1">
|
||||
Upload
|
||||
<input
|
||||
className="hidden"
|
||||
type="file"
|
||||
disabled={isUploading}
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
void handleUpload(file, "file");
|
||||
selectFile(file);
|
||||
}
|
||||
e.currentTarget.value = "";
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<button className="rounded bg-slate-700 px-3 py-1" onClick={startRecord}>
|
||||
Record Voice
|
||||
<button className="rounded bg-slate-700 px-3 py-1 disabled:opacity-50" onClick={startRecord} disabled={isUploading || isRecording}>
|
||||
{isRecording ? "Recording..." : "Record Voice"}
|
||||
</button>
|
||||
<button className="rounded bg-slate-700 px-3 py-1" onClick={stopRecord}>
|
||||
<button className="rounded bg-slate-700 px-3 py-1 disabled:opacity-50" onClick={stopRecord} disabled={!isRecording}>
|
||||
Stop
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -27,9 +27,9 @@ export function MessageList() {
|
||||
<div className={`mb-3 flex ${message.sender_id === me?.id ? "justify-end" : "justify-start"}`} key={message.id}>
|
||||
<div className="max-w-[80%] rounded-lg bg-slate-800 px-3 py-2">
|
||||
{message.type === "voice" && message.text ? (
|
||||
<audio controls src={message.text} />
|
||||
renderContent(message.type, message.text)
|
||||
) : (
|
||||
<p className="whitespace-pre-wrap break-words">{message.text}</p>
|
||||
renderContent(message.type, message.text)
|
||||
)}
|
||||
<p className="mt-1 text-right text-[11px] text-slate-400">{formatTime(message.created_at)}</p>
|
||||
</div>
|
||||
@@ -42,3 +42,25 @@ export function MessageList() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function renderContent(messageType: string, text: string | null) {
|
||||
if (!text) {
|
||||
return <p className="text-slate-300">[empty]</p>;
|
||||
}
|
||||
if (messageType === "image") {
|
||||
return <img alt="attachment" className="max-h-64 rounded" src={text} />;
|
||||
}
|
||||
if (messageType === "video" || messageType === "circle_video") {
|
||||
return <video className="max-h-64 rounded" controls src={text} />;
|
||||
}
|
||||
if (messageType === "audio" || messageType === "voice") {
|
||||
return <audio controls src={text} />;
|
||||
}
|
||||
if (messageType === "file") {
|
||||
return (
|
||||
<a className="text-accent underline" href={text} rel="noreferrer" target="_blank">
|
||||
Open file
|
||||
</a>
|
||||
);
|
||||
}
|
||||
return <p className="whitespace-pre-wrap break-words">{text}</p>;
|
||||
}
|
||||
|
||||
@@ -4,10 +4,10 @@ import { searchUsers } from "../api/users";
|
||||
import type { ChatType, UserSearchItem } from "../chat/types";
|
||||
import { useChatStore } from "../store/chatStore";
|
||||
|
||||
type CreateMode = "private" | "group" | "channel";
|
||||
type CreateMode = "group" | "channel";
|
||||
|
||||
export function NewChatPanel() {
|
||||
const [mode, setMode] = useState<CreateMode>("private");
|
||||
const [mode, setMode] = useState<CreateMode>("group");
|
||||
const [query, setQuery] = useState("");
|
||||
const [title, setTitle] = useState("");
|
||||
const [results, setResults] = useState<UserSearchItem[]>([]);
|
||||
@@ -57,9 +57,6 @@ export function NewChatPanel() {
|
||||
|
||||
async function createByType(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
if (mode === "private") {
|
||||
return;
|
||||
}
|
||||
if (!title.trim()) {
|
||||
setError("Title is required");
|
||||
return;
|
||||
@@ -80,9 +77,6 @@ export function NewChatPanel() {
|
||||
return (
|
||||
<div className="border-b border-slate-700 p-3">
|
||||
<div className="mb-2 flex gap-2 text-xs">
|
||||
<button className={`rounded px-2 py-1 ${mode === "private" ? "bg-accent text-black" : "bg-slate-700"}`} onClick={() => setMode("private")}>
|
||||
Private
|
||||
</button>
|
||||
<button className={`rounded px-2 py-1 ${mode === "group" ? "bg-accent text-black" : "bg-slate-700"}`} onClick={() => setMode("group")}>
|
||||
Group
|
||||
</button>
|
||||
@@ -91,40 +85,38 @@ export function NewChatPanel() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{mode === "private" ? (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
className="w-full rounded bg-slate-800 px-2 py-1 text-sm"
|
||||
placeholder="@username"
|
||||
value={query}
|
||||
onChange={(e) => void handleSearch(e.target.value)}
|
||||
/>
|
||||
<div className="max-h-32 overflow-auto">
|
||||
{results.map((user) => (
|
||||
<button
|
||||
className="mb-1 block w-full rounded bg-slate-800 px-2 py-1 text-left text-sm hover:bg-slate-700"
|
||||
key={user.id}
|
||||
onClick={() => void createPrivate(user.id)}
|
||||
>
|
||||
@{user.username}
|
||||
</button>
|
||||
))}
|
||||
{normalizedQuery && results.length === 0 ? <p className="text-xs text-slate-400">No users</p> : null}
|
||||
</div>
|
||||
<div className="mb-3 space-y-2">
|
||||
<p className="text-xs text-slate-400">Новый диалог</p>
|
||||
<input
|
||||
className="w-full rounded bg-slate-800 px-2 py-1 text-sm"
|
||||
placeholder="@username"
|
||||
value={query}
|
||||
onChange={(e) => void handleSearch(e.target.value)}
|
||||
/>
|
||||
<div className="max-h-32 overflow-auto">
|
||||
{results.map((user) => (
|
||||
<button
|
||||
className="mb-1 block w-full rounded bg-slate-800 px-2 py-1 text-left text-sm hover:bg-slate-700"
|
||||
key={user.id}
|
||||
onClick={() => void createPrivate(user.id)}
|
||||
>
|
||||
@{user.username}
|
||||
</button>
|
||||
))}
|
||||
{normalizedQuery && results.length === 0 ? <p className="text-xs text-slate-400">No users</p> : null}
|
||||
</div>
|
||||
) : (
|
||||
<form className="space-y-2" onSubmit={(e) => void createByType(e)}>
|
||||
<input
|
||||
className="w-full rounded bg-slate-800 px-2 py-1 text-sm"
|
||||
placeholder={mode === "group" ? "Group title" : "Channel title"}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<button className="w-full rounded bg-slate-700 px-2 py-1 text-sm hover:bg-slate-600" disabled={loading} type="submit">
|
||||
Create {mode}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
<form className="space-y-2" onSubmit={(e) => void createByType(e)}>
|
||||
<input
|
||||
className="w-full rounded bg-slate-800 px-2 py-1 text-sm"
|
||||
placeholder={mode === "group" ? "Group title" : "Channel title"}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<button className="w-full rounded bg-slate-700 px-2 py-1 text-sm hover:bg-slate-600" disabled={loading} type="submit">
|
||||
Create {mode}
|
||||
</button>
|
||||
</form>
|
||||
{error ? <p className="mt-2 text-xs text-red-400">{error}</p> : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -14,6 +14,8 @@ export function useRealtime() {
|
||||
const accessToken = useAuthStore((s) => s.accessToken);
|
||||
const me = useAuthStore((s) => s.me);
|
||||
const prependMessage = useChatStore((s) => s.prependMessage);
|
||||
const loadChats = useChatStore((s) => s.loadChats);
|
||||
const chats = useChatStore((s) => s.chats);
|
||||
const typingByChat = useRef<Record<number, Set<number>>>({});
|
||||
|
||||
const wsUrl = useMemo(() => {
|
||||
@@ -32,6 +34,9 @@ export function useRealtime() {
|
||||
const chatId = Number(event.payload.chat_id);
|
||||
const message = event.payload.message as Message;
|
||||
prependMessage(chatId, message);
|
||||
if (!chats.some((chat) => chat.id === chatId)) {
|
||||
void loadChats();
|
||||
}
|
||||
}
|
||||
if (event.event === "typing_start") {
|
||||
const chatId = Number(event.payload.chat_id);
|
||||
@@ -54,7 +59,7 @@ export function useRealtime() {
|
||||
};
|
||||
|
||||
return () => ws.close();
|
||||
}, [wsUrl, prependMessage, me?.id]);
|
||||
}, [wsUrl, prependMessage, loadChats, chats, me?.id]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"root":["./src/main.tsx","./src/vite-env.d.ts","./src/api/auth.ts","./src/api/chats.ts","./src/api/http.ts","./src/app/app.tsx","./src/chat/types.ts","./src/components/authpanel.tsx","./src/components/chatlist.tsx","./src/components/messagecomposer.tsx","./src/components/messagelist.tsx","./src/hooks/userealtime.ts","./src/pages/authpage.tsx","./src/pages/chatspage.tsx","./src/store/authstore.ts","./src/store/chatstore.ts","./src/utils/format.ts","./src/utils/ws.ts"],"version":"5.9.2"}
|
||||
{"root":["./src/main.tsx","./src/vite-env.d.ts","./src/api/auth.ts","./src/api/chats.ts","./src/api/http.ts","./src/api/users.ts","./src/app/app.tsx","./src/chat/types.ts","./src/components/authpanel.tsx","./src/components/chatlist.tsx","./src/components/messagecomposer.tsx","./src/components/messagelist.tsx","./src/components/newchatpanel.tsx","./src/hooks/userealtime.ts","./src/pages/authpage.tsx","./src/pages/chatspage.tsx","./src/store/authstore.ts","./src/store/chatstore.ts","./src/utils/format.ts","./src/utils/ws.ts"],"version":"5.9.2"}
|
||||
Reference in New Issue
Block a user