family update
This commit is contained in:
@@ -6,36 +6,57 @@ import {
|
||||
ArrowLeft,
|
||||
BarChart3,
|
||||
Camera,
|
||||
Check,
|
||||
CheckCheck,
|
||||
FileText,
|
||||
Loader2,
|
||||
Mic,
|
||||
MoreVertical,
|
||||
Paperclip,
|
||||
Pencil,
|
||||
Plus,
|
||||
Send,
|
||||
Smile,
|
||||
Trash2,
|
||||
UserPlus,
|
||||
Users,
|
||||
Volume2,
|
||||
VolumeX
|
||||
} from 'lucide-react';
|
||||
import { VoiceMessagePlayer } from '@/components/chat/voice-message-player';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { useRealtime } from '@/components/notifications/realtime-provider';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useRequireAuth } from '@/hooks/use-require-auth';
|
||||
import {
|
||||
addChatRoomMember,
|
||||
apiFetch,
|
||||
ChatMessage,
|
||||
ChatRoom,
|
||||
createChatRoom,
|
||||
deleteChatMessage,
|
||||
editChatMessage,
|
||||
FamilyGroup,
|
||||
FamilyInviteCandidate,
|
||||
FamilyPresenceMember,
|
||||
fetchChatMessages,
|
||||
fetchChatRooms,
|
||||
fetchFamilyGroup,
|
||||
fetchFamilyPresence,
|
||||
getApiErrorMessage,
|
||||
markChatRoomRead,
|
||||
removeChatRoomMember,
|
||||
removeFamilyMember,
|
||||
searchFamilyInviteUsers,
|
||||
sendChatMessage,
|
||||
sendFamilyInvite,
|
||||
@@ -74,12 +95,54 @@ interface LoadedChatMedia {
|
||||
blobUrl: string;
|
||||
expiresAt: number;
|
||||
fileName?: string;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
function formatMessageTime(value: string) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(new Date(value));
|
||||
}
|
||||
|
||||
function formatLastSeen(value?: string) {
|
||||
if (!value) return 'Не в сети';
|
||||
const date = new Date(value);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMinutes = Math.floor(diffMs / 60_000);
|
||||
if (diffMinutes < 1) return 'был(а) только что';
|
||||
if (diffMinutes < 60) return `был(а) ${diffMinutes} мин. назад`;
|
||||
const diffHours = Math.floor(diffMinutes / 60);
|
||||
if (diffHours < 24) return `был(а) ${diffHours} ч. назад`;
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }).format(date);
|
||||
}
|
||||
|
||||
function formatPresenceStatus(member: FamilyPresenceMember) {
|
||||
if (member.online) return 'В сети';
|
||||
return formatLastSeen(member.lastSeenAt);
|
||||
}
|
||||
|
||||
function messagePreview(message?: ChatMessage) {
|
||||
if (!message) return '';
|
||||
if (message.isDeleted) return 'Сообщение удалено';
|
||||
if (message.type === 'POLL') return '📊 Опрос';
|
||||
if (message.type === 'VOICE') return '🎤 Голосовое';
|
||||
if (message.type === 'AUDIO') return '🎵 Аудио';
|
||||
if (message.type === 'IMAGE') return '📷 Фото';
|
||||
if (message.type === 'FILE') return '📄 Файл';
|
||||
return message.content ?? '';
|
||||
}
|
||||
|
||||
function OnlineDot({ online, className }: { online?: boolean; className?: string }) {
|
||||
if (!online) return null;
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-white bg-emerald-500 shadow-sm',
|
||||
className
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FamilyAvatar({ groupId, name, hasAvatar, token }: { groupId: string; name: string; hasAvatar?: boolean; token: string | null }) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
@@ -96,12 +159,38 @@ function FamilyAvatar({ groupId, name, hasAvatar, token }: { groupId: string; na
|
||||
);
|
||||
}
|
||||
|
||||
function ChatRoomAvatar({ roomId, name, hasAvatar, token }: { roomId: string; name: string; hasAvatar?: boolean; token: string | null }) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!hasAvatar || !token) return;
|
||||
apiFetch<{ accessUrl: string }>(`/media/chat/${roomId}/avatar/url`, {}, token)
|
||||
.then((response) => setUrl(response.accessUrl))
|
||||
.catch(() => setUrl(null));
|
||||
}, [hasAvatar, roomId, token]);
|
||||
return (
|
||||
<Avatar className="h-11 w-11">
|
||||
{url ? <AvatarImage src={url} alt={name} /> : null}
|
||||
<AvatarFallback>{name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
|
||||
function memberRoleLabel(member: { familyRole?: string; isChatCreator?: boolean }) {
|
||||
if (member.familyRole === 'owner') return 'Создатель семьи';
|
||||
if (member.isChatCreator) return 'Создатель чата';
|
||||
return 'Участник';
|
||||
}
|
||||
|
||||
function familyMemberRoleLabel(role: string) {
|
||||
return role === 'owner' ? 'Создатель семьи' : 'Участник';
|
||||
}
|
||||
|
||||
export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
const router = useRouter();
|
||||
const { user, token } = useAuth();
|
||||
const { isReady, isPinLocked } = useRequireAuth();
|
||||
const { showToast } = useToast();
|
||||
const { subscribe } = useRealtime();
|
||||
const { subscribe, connected } = useRealtime();
|
||||
|
||||
const [group, setGroup] = useState<FamilyGroup | null>(null);
|
||||
const [rooms, setRooms] = useState<ChatRoom[]>([]);
|
||||
@@ -113,6 +202,9 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
const [inviteOpen, setInviteOpen] = useState(false);
|
||||
const [createRoomOpen, setCreateRoomOpen] = useState(false);
|
||||
const [pollOpen, setPollOpen] = useState(false);
|
||||
const [membersOpen, setMembersOpen] = useState(false);
|
||||
const [familyMembersOpen, setFamilyMembersOpen] = useState(false);
|
||||
const [addMembersOpen, setAddMembersOpen] = useState(false);
|
||||
const [inviteQuery, setInviteQuery] = useState('');
|
||||
const [inviteResults, setInviteResults] = useState<FamilyInviteCandidate[]>([]);
|
||||
const [selectedInviteUser, setSelectedInviteUser] = useState<FamilyInviteCandidate | null>(null);
|
||||
@@ -126,12 +218,17 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
const [recording, setRecording] = useState(false);
|
||||
const [mediaUrls, setMediaUrls] = useState<Record<string, LoadedChatMedia>>({});
|
||||
const [downloadingKey, setDownloadingKey] = useState<string | null>(null);
|
||||
const [editingMessageId, setEditingMessageId] = useState<string | null>(null);
|
||||
const [editDraft, setEditDraft] = useState('');
|
||||
const [presenceMembers, setPresenceMembers] = useState<FamilyPresenceMember[]>([]);
|
||||
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const readReceiptTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
|
||||
const recordingStartedAtRef = useRef<number | null>(null);
|
||||
const mediaUrlsRef = useRef<Record<string, LoadedChatMedia>>({});
|
||||
const avatarInputRef = useRef<HTMLInputElement>(null);
|
||||
const roomAvatarInputRef = useRef<HTMLInputElement>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -144,6 +241,20 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
|
||||
const activeRoom = useMemo(() => rooms.find((room) => room.id === activeRoomId) ?? null, [activeRoomId, rooms]);
|
||||
const myMembership = activeRoom?.members.find((member) => member.userId === user?.id);
|
||||
const isFamilyOwner = group?.ownerId === user?.id;
|
||||
const isChatCreator = activeRoom?.createdById === user?.id;
|
||||
const canManageChatMembers = Boolean(isFamilyOwner || isChatCreator);
|
||||
const familyMembersNotInRoom = useMemo(() => {
|
||||
if (!group?.members || !activeRoom) return [];
|
||||
const inRoom = new Set(activeRoom.members.map((member) => member.userId));
|
||||
return group.members.filter((member) => !inRoom.has(member.userId));
|
||||
}, [activeRoom, group?.members]);
|
||||
|
||||
const presenceByUserId = useMemo(
|
||||
() => new Map(presenceMembers.map((member) => [member.userId, member])),
|
||||
[presenceMembers]
|
||||
);
|
||||
const onlineCount = useMemo(() => presenceMembers.filter((member) => member.online).length, [presenceMembers]);
|
||||
|
||||
const loadGroup = useCallback(async () => {
|
||||
if (!token || isPinLocked) return;
|
||||
@@ -161,34 +272,85 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
setMessages(response.messages ?? []);
|
||||
}, [isPinLocked, token]);
|
||||
|
||||
const loadPresence = useCallback(async () => {
|
||||
if (!token || isPinLocked) return;
|
||||
try {
|
||||
const response = await fetchFamilyPresence(groupId, token);
|
||||
setPresenceMembers(response.members ?? []);
|
||||
} catch {
|
||||
// ignore background presence errors
|
||||
}
|
||||
}, [groupId, isPinLocked, token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isReady || !token || isPinLocked) return;
|
||||
setLoading(true);
|
||||
loadGroup()
|
||||
.catch((error) => showToast(getApiErrorMessage(error, 'Не удалось загрузить семью') ?? 'Ошибка'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [isPinLocked, isReady, loadGroup, showToast, token]);
|
||||
void loadPresence();
|
||||
}, [isPinLocked, isReady, loadGroup, loadPresence, showToast, token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || isPinLocked) return;
|
||||
void loadPresence();
|
||||
const timer = window.setInterval(() => void loadPresence(), 25_000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [connected, isPinLocked, loadPresence, token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeRoomId) return;
|
||||
void loadMessages(activeRoomId);
|
||||
setEditingMessageId(null);
|
||||
setEditDraft('');
|
||||
}, [activeRoomId, loadMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeRoomId || !token || !messages.length) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
const last = messages[messages.length - 1];
|
||||
void markChatRoomRead(activeRoomId, last.id, token).catch(() => {});
|
||||
}, 500);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [activeRoomId, messages, token]);
|
||||
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
}, [messages]);
|
||||
|
||||
useEffect(() => {
|
||||
return subscribe((event) => {
|
||||
if (event.type !== 'chat_message') return;
|
||||
const payload = event.payload;
|
||||
if (!payload?.roomId || payload.roomId !== activeRoomId) return;
|
||||
if (payload.message) {
|
||||
appendMessage(payload.message);
|
||||
} else {
|
||||
void loadMessages(activeRoomId!);
|
||||
if (payload?.roomId && payload.roomId !== activeRoomId) {
|
||||
if (event.type === 'chat_message') void loadGroup();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'chat_message') {
|
||||
if (payload?.message) {
|
||||
appendMessage(payload.message);
|
||||
} else if (activeRoomId) {
|
||||
void loadMessages(activeRoomId);
|
||||
}
|
||||
void loadGroup();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'chat_message_updated' || event.type === 'chat_message_deleted') {
|
||||
const updated = payload?.message;
|
||||
if (updated) {
|
||||
setMessages((current) => current.map((item) => (item.id === updated.id ? updated : item)));
|
||||
} else if (activeRoomId) {
|
||||
void loadMessages(activeRoomId);
|
||||
}
|
||||
void loadGroup();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'chat_read_receipt' && activeRoomId) {
|
||||
if (readReceiptTimerRef.current) clearTimeout(readReceiptTimerRef.current);
|
||||
readReceiptTimerRef.current = setTimeout(() => void loadMessages(activeRoomId), 400);
|
||||
}
|
||||
void loadGroup();
|
||||
});
|
||||
}, [activeRoomId, appendMessage, loadGroup, loadMessages, subscribe]);
|
||||
|
||||
@@ -201,6 +363,7 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
|
||||
const meta = parseMessageMetadata(message.metadataJson);
|
||||
const fileName = meta.fileName || message.content || undefined;
|
||||
const mimeType = message.mimeType || (message.type === 'VOICE' ? 'audio/webm' : message.type === 'AUDIO' ? 'audio/mpeg' : undefined);
|
||||
const query = new URLSearchParams({ storageKey });
|
||||
if (fileName) query.set('fileName', fileName);
|
||||
|
||||
@@ -210,7 +373,7 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
{},
|
||||
token
|
||||
);
|
||||
const blob = await fetchAuthenticatedMediaBlob(access.accessUrl, token);
|
||||
const blob = await fetchAuthenticatedMediaBlob(access.accessUrl, token, mimeType);
|
||||
const blobUrl = createBlobObjectUrl(blob);
|
||||
setMediaUrls((current) => {
|
||||
revokeBlobObjectUrl(current[storageKey]?.blobUrl);
|
||||
@@ -219,7 +382,8 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
[storageKey]: {
|
||||
blobUrl,
|
||||
expiresAt: mediaExpiresAtMs(access.expiresAt),
|
||||
fileName
|
||||
fileName,
|
||||
mimeType
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -289,6 +453,70 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadRoomAvatar(file: File) {
|
||||
if (!token || !activeRoomId) return;
|
||||
try {
|
||||
const presigned = await apiFetch<PresignedUploadResponse>(
|
||||
`/media/chat/${activeRoomId}/avatar/upload-url`,
|
||||
{ method: 'POST', body: JSON.stringify({ contentType: file.type }) },
|
||||
token
|
||||
);
|
||||
await uploadMediaObject(presigned, file, file.type);
|
||||
await apiFetch(`/media/chat/${activeRoomId}/avatar/confirm`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ storageKey: presigned.storageKey })
|
||||
}, token);
|
||||
await loadGroup();
|
||||
showToast('Фото чата обновлено');
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось загрузить фото чата') ?? 'Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
function applyRoomUpdate(room: ChatRoom) {
|
||||
setRooms((current) => current.map((item) => (item.id === room.id ? room : item)));
|
||||
}
|
||||
|
||||
async function handleAddRoomMember(memberUserId: string) {
|
||||
if (!token || !activeRoomId) return;
|
||||
try {
|
||||
const room = await addChatRoomMember(activeRoomId, memberUserId, token);
|
||||
applyRoomUpdate(room);
|
||||
setAddMembersOpen(false);
|
||||
showToast('Участник добавлен в чат');
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось добавить участника') ?? 'Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveFromChat(memberUserId: string) {
|
||||
if (!token || !activeRoomId) return;
|
||||
try {
|
||||
const room = await removeChatRoomMember(activeRoomId, memberUserId, token);
|
||||
applyRoomUpdate(room);
|
||||
if (memberUserId === user?.id) {
|
||||
setActiveRoomId(null);
|
||||
setMembersOpen(false);
|
||||
}
|
||||
showToast('Участник удалён из чата');
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось удалить участника из чата') ?? 'Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveFromFamily(memberId: string) {
|
||||
if (!token) return;
|
||||
try {
|
||||
await removeFamilyMember(memberId, token);
|
||||
await loadGroup();
|
||||
setMembersOpen(false);
|
||||
setFamilyMembersOpen(false);
|
||||
showToast('Участник удалён из семьи');
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось удалить участника из семьи') ?? 'Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
async function saveRename() {
|
||||
if (!token || !renameValue.trim()) return;
|
||||
try {
|
||||
@@ -368,6 +596,51 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function startEditMessage(message: ChatMessage) {
|
||||
if (message.isDeleted) return;
|
||||
setEditingMessageId(message.id);
|
||||
setEditDraft(message.content ?? '');
|
||||
}
|
||||
|
||||
async function submitEditMessage() {
|
||||
if (!token || !editingMessageId) return;
|
||||
const content = editDraft.trim();
|
||||
if (!content) {
|
||||
showToast('Сообщение не может быть пустым');
|
||||
return;
|
||||
}
|
||||
setSending(true);
|
||||
try {
|
||||
const updated = await editChatMessage(editingMessageId, content, token);
|
||||
setMessages((current) => current.map((item) => (item.id === updated.id ? updated : item)));
|
||||
setEditingMessageId(null);
|
||||
setEditDraft('');
|
||||
void loadGroup();
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось изменить сообщение') ?? 'Ошибка');
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteMessage(messageId: string) {
|
||||
if (!token) return;
|
||||
setSending(true);
|
||||
try {
|
||||
const updated = await deleteChatMessage(messageId, token);
|
||||
setMessages((current) => current.map((item) => (item.id === updated.id ? updated : item)));
|
||||
if (editingMessageId === messageId) {
|
||||
setEditingMessageId(null);
|
||||
setEditDraft('');
|
||||
}
|
||||
void loadGroup();
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось удалить сообщение') ?? 'Ошибка');
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendText(type: string = 'TEXT') {
|
||||
if (!token || !activeRoomId || sending) return;
|
||||
const content = draft.trim();
|
||||
@@ -544,6 +817,22 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
<Camera className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setFamilyMembersOpen(true)}
|
||||
className="mt-3 flex w-full items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3 text-left transition hover:bg-[#eceef4]"
|
||||
>
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[#3390ec]/10 text-[#3390ec]">
|
||||
<Users className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium">Участники семьи</p>
|
||||
<p className="text-xs text-[#667085]">
|
||||
{onlineCount > 0 ? `${onlineCount} в сети · ` : ''}
|
||||
{group?.members?.length ?? 0} человек
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4 py-3">
|
||||
<p className="text-sm font-semibold text-[#667085]">Чаты</p>
|
||||
@@ -562,9 +851,7 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
activeRoomId === room.id && 'bg-[#3390ec]/10'
|
||||
)}
|
||||
>
|
||||
<div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-[#3390ec] text-sm font-semibold text-white">
|
||||
{room.name.slice(0, 2).toUpperCase()}
|
||||
</div>
|
||||
<ChatRoomAvatar roomId={room.id} name={room.name} hasAvatar={room.hasAvatar} token={token} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="truncate font-medium">{room.name}</p>
|
||||
@@ -573,7 +860,7 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
) : null}
|
||||
</div>
|
||||
<p className="truncate text-sm text-[#667085]">
|
||||
{room.lastMessage?.content ?? (room.type === 'GENERAL' ? 'Общий чат семьи' : 'Нет сообщений')}
|
||||
{messagePreview(room.lastMessage) || (room.type === 'GENERAL' ? 'Общий чат семьи' : 'Нет сообщений')}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
@@ -585,28 +872,105 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
{activeRoom ? (
|
||||
<>
|
||||
<div className="flex items-center justify-between border-b border-[#dce3ec] bg-white px-4 py-3">
|
||||
<div>
|
||||
<h2 className="font-semibold">{activeRoom.name}</h2>
|
||||
<p className="text-xs text-[#667085]">{activeRoom.members.length} участников</p>
|
||||
<button type="button" className="flex min-w-0 items-center gap-3 text-left" onClick={() => setMembersOpen(true)}>
|
||||
<div className="shrink-0 overflow-hidden rounded-full">
|
||||
<ChatRoomAvatar roomId={activeRoom.id} name={activeRoom.name} hasAvatar={activeRoom.hasAvatar} token={token} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h2 className="font-semibold">{activeRoom.name}</h2>
|
||||
<p className="text-xs text-[#667085]">
|
||||
{onlineCount > 0 ? (
|
||||
<span className="text-emerald-600">{onlineCount} в сети</span>
|
||||
) : (
|
||||
'Никого нет в сети'
|
||||
)}
|
||||
{' · '}
|
||||
{activeRoom.members.length} участников
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
{activeRoom.type === 'GROUP' ? (
|
||||
<Button size="sm" variant="secondary" className="rounded-xl" onClick={() => roomAvatarInputRef.current?.click()}>
|
||||
<Camera className="h-4 w-4" />
|
||||
</Button>
|
||||
) : null}
|
||||
<Button size="sm" variant="secondary" className="rounded-xl" onClick={() => setMembersOpen(true)}>
|
||||
<Users className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button size="sm" variant="secondary" className="rounded-xl" onClick={() => void toggleMute()}>
|
||||
{myMembership?.notificationsMuted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
<Button size="sm" variant="secondary" className="rounded-xl" onClick={() => void toggleMute()}>
|
||||
{myMembership?.notificationsMuted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 space-y-2 overflow-y-auto px-4 py-4">
|
||||
{messages.map((message) => {
|
||||
const mine = message.senderId === user?.id;
|
||||
const isEditing = editingMessageId === message.id;
|
||||
const canEdit = mine && !message.isDeleted && (message.type === 'TEXT' || message.type === 'EMOJI');
|
||||
return (
|
||||
<div key={message.id} className={cn('flex', mine ? 'justify-end' : 'justify-start')}>
|
||||
<div key={message.id} className={cn('group flex', mine ? 'justify-end' : 'justify-start')}>
|
||||
<div
|
||||
className={cn(
|
||||
'max-w-[78%] rounded-[18px] px-3 py-2 shadow-sm',
|
||||
mine ? 'rounded-br-md bg-[#effdde] text-[#1f2430]' : 'rounded-bl-md bg-white text-[#1f2430]'
|
||||
'relative max-w-[78%] rounded-[18px] px-3 py-2 shadow-sm',
|
||||
mine ? 'rounded-br-md bg-[#effdde] text-[#1f2430]' : 'rounded-bl-md bg-white text-[#1f2430]',
|
||||
message.isDeleted && 'bg-[#eef1f6]/90 text-[#667085] italic'
|
||||
)}
|
||||
>
|
||||
{canEdit ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'absolute -right-2 -top-2 flex h-7 w-7 items-center justify-center rounded-full bg-white text-[#667085] opacity-0 shadow-sm transition group-hover:opacity-100',
|
||||
mine ? '-left-2 right-auto' : ''
|
||||
)}
|
||||
aria-label="Действия с сообщением"
|
||||
>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align={mine ? 'end' : 'start'} className="rounded-xl">
|
||||
<DropdownMenuItem onClick={() => void startEditMessage(message)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Изменить
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-red-600 focus:text-red-600"
|
||||
onClick={() => void handleDeleteMessage(message.id)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Удалить
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : null}
|
||||
{!mine ? <p className="mb-1 text-xs font-semibold text-[#3390ec]">{message.senderName}</p> : null}
|
||||
{message.type === 'POLL' && message.poll ? (
|
||||
{message.isDeleted ? (
|
||||
<p className="text-[15px] italic text-[#8b93a7]">Сообщение удалено</p>
|
||||
) : isEditing ? (
|
||||
<div className="space-y-2">
|
||||
<textarea
|
||||
value={editDraft}
|
||||
onChange={(event) => setEditDraft(event.target.value)}
|
||||
rows={2}
|
||||
className="w-full resize-none rounded-xl border border-[#dce3ec] bg-white px-3 py-2 text-[15px] outline-none focus:border-[#3390ec]"
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button size="sm" variant="secondary" className="h-8 rounded-xl" onClick={() => {
|
||||
setEditingMessageId(null);
|
||||
setEditDraft('');
|
||||
}}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button size="sm" className="h-8 rounded-xl" disabled={sending} onClick={() => void submitEditMessage()}>
|
||||
Сохранить
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : message.type === 'POLL' && message.poll ? (
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">{message.poll.question}</p>
|
||||
{message.poll.options.map((option) => {
|
||||
@@ -650,18 +1014,14 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
);
|
||||
}
|
||||
if (message.type === 'VOICE' || message.type === 'AUDIO') {
|
||||
const metaDuration = parseMessageMetadata(message.metadataJson).durationMs;
|
||||
return (
|
||||
<div className="flex min-w-[220px] items-center gap-3 rounded-xl bg-black/5 px-3 py-2">
|
||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[#3390ec] text-white">
|
||||
{message.type === 'VOICE' ? <Mic className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-xs font-medium text-[#667085]">
|
||||
{message.type === 'VOICE' ? 'Голосовое сообщение' : 'Аудиофайл'}
|
||||
</p>
|
||||
<audio controls preload="metadata" src={media.blobUrl} className="mt-1 h-8 w-full max-w-[240px]" />
|
||||
</div>
|
||||
</div>
|
||||
<VoiceMessagePlayer
|
||||
src={media.blobUrl}
|
||||
seed={message.storageKey ?? message.id}
|
||||
durationMs={typeof metaDuration === 'number' ? metaDuration : undefined}
|
||||
variant={mine ? 'mine' : 'theirs'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
@@ -689,9 +1049,17 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
) : (
|
||||
<p className="whitespace-pre-wrap break-words text-[15px] leading-relaxed">{message.content}</p>
|
||||
)}
|
||||
<p className={cn('mt-1 text-[11px]', mine ? 'text-[#7ea06a]' : 'text-[#a8adbc]')}>
|
||||
{formatMessageTime(message.createdAt)}
|
||||
</p>
|
||||
<div className={cn('mt-1 flex items-center justify-end gap-1 text-[11px]', mine ? 'text-[#7ea06a]' : 'text-[#a8adbc]')}>
|
||||
{message.editedAt ? <span className="mr-1">изменено</span> : null}
|
||||
<span>{formatMessageTime(message.createdAt)}</span>
|
||||
{mine && !message.isDeleted ? (
|
||||
message.readByAll ? (
|
||||
<CheckCheck className="h-3.5 w-3.5 text-[#3390ec]" aria-label="Прочитано" />
|
||||
) : (
|
||||
<Check className="h-3.5 w-3.5" aria-label="Отправлено" />
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -766,6 +1134,11 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
if (file) void uploadFamilyAvatar(file);
|
||||
event.target.value = '';
|
||||
}} />
|
||||
<input ref={roomAvatarInputRef} type="file" accept="image/*" className="hidden" onChange={(event) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (file) void uploadRoomAvatar(file);
|
||||
event.target.value = '';
|
||||
}} />
|
||||
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (file) void uploadChatFile(file);
|
||||
@@ -841,6 +1214,149 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={familyMembersOpen} onOpenChange={setFamilyMembersOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[480px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Участники семьи</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-[#667085]">
|
||||
{group?.name} · {group?.members?.length ?? 0} {group?.members?.length === 1 ? 'участник' : 'участников'}
|
||||
</p>
|
||||
<div className="mt-3 max-h-[420px] space-y-2 overflow-y-auto">
|
||||
{(group?.members ?? []).map((member) => {
|
||||
const isSelf = member.userId === user?.id;
|
||||
const canRemove =
|
||||
member.role !== 'owner' && (isFamilyOwner || isSelf);
|
||||
const presence = presenceByUserId.get(member.userId);
|
||||
|
||||
return (
|
||||
<div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3">
|
||||
<div className="relative shrink-0">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<OnlineDot online={presence?.online} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium">
|
||||
{member.displayName}
|
||||
{isSelf ? <span className="ml-1 text-xs font-normal text-[#667085]">(Вы)</span> : null}
|
||||
</p>
|
||||
<p className="text-xs text-[#667085]">{familyMemberRoleLabel(member.role)}</p>
|
||||
<p className={cn('text-xs', presence?.online ? 'font-medium text-emerald-600' : 'text-[#a8adbc]')}>
|
||||
{presence ? formatPresenceStatus(presence) : 'Статус неизвестен'}
|
||||
</p>
|
||||
</div>
|
||||
{canRemove ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 shrink-0 rounded-xl text-xs text-red-600 hover:text-red-700"
|
||||
onClick={() => void handleRemoveFromFamily(member.id)}
|
||||
>
|
||||
{isSelf ? 'Выйти' : 'Удалить'}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Button className="mt-4 w-full rounded-xl" variant="secondary" onClick={() => {
|
||||
setFamilyMembersOpen(false);
|
||||
setInviteOpen(true);
|
||||
}}>
|
||||
<UserPlus className="mr-2 h-4 w-4" />
|
||||
Пригласить в семью
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={membersOpen} onOpenChange={setMembersOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[480px]">
|
||||
<DialogHeader><DialogTitle>Участники чата</DialogTitle></DialogHeader>
|
||||
<div className="max-h-[420px] space-y-2 overflow-y-auto">
|
||||
{activeRoom?.members.map((member) => {
|
||||
const familyMember = group?.members?.find((item) => item.userId === member.userId);
|
||||
const presence = presenceByUserId.get(member.userId);
|
||||
const canRemoveFromChat =
|
||||
canManageChatMembers &&
|
||||
activeRoom.type === 'GROUP' &&
|
||||
member.userId !== user?.id &&
|
||||
!(member.isChatCreator && !isFamilyOwner);
|
||||
const canRemoveFromFamily = isFamilyOwner && member.familyRole !== 'owner' && familyMember;
|
||||
|
||||
return (
|
||||
<div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3">
|
||||
<div className="relative shrink-0">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<OnlineDot online={presence?.online} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium">{member.displayName}</p>
|
||||
<p className="text-xs text-[#667085]">{memberRoleLabel(member)}</p>
|
||||
<p className={cn('text-xs', presence?.online ? 'font-medium text-emerald-600' : 'text-[#a8adbc]')}>
|
||||
{presence ? formatPresenceStatus(presence) : 'Статус неизвестен'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col gap-1">
|
||||
{canRemoveFromChat ? (
|
||||
<Button size="sm" variant="secondary" className="h-8 rounded-xl text-xs" onClick={() => void handleRemoveFromChat(member.userId)}>
|
||||
<Trash2 className="mr-1 h-3.5 w-3.5" />
|
||||
Из чата
|
||||
</Button>
|
||||
) : null}
|
||||
{canRemoveFromFamily ? (
|
||||
<Button size="sm" variant="ghost" className="h-8 rounded-xl text-xs text-red-600 hover:text-red-700" onClick={() => void handleRemoveFromFamily(familyMember!.id)}>
|
||||
Из семьи
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{activeRoom?.type === 'GROUP' && familyMembersNotInRoom.length > 0 ? (
|
||||
<Button className="mt-4 w-full rounded-xl" onClick={() => {
|
||||
setMembersOpen(false);
|
||||
setAddMembersOpen(true);
|
||||
}}>
|
||||
<UserPlus className="mr-2 h-4 w-4" />
|
||||
Добавить участника
|
||||
</Button>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={addMembersOpen} onOpenChange={setAddMembersOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[420px]">
|
||||
<DialogHeader><DialogTitle>Добавить в чат</DialogTitle></DialogHeader>
|
||||
<div className="space-y-2">
|
||||
{familyMembersNotInRoom.length ? (
|
||||
familyMembersNotInRoom.map((member) => (
|
||||
<button
|
||||
key={member.id}
|
||||
type="button"
|
||||
className="flex w-full items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3 text-left transition hover:bg-[#eceef4]"
|
||||
onClick={() => void handleAddRoomMember(member.userId)}
|
||||
>
|
||||
<Avatar className="h-9 w-9">
|
||||
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="font-medium">{member.displayName}</p>
|
||||
<p className="text-xs text-[#667085]">{member.role === 'owner' ? 'Создатель семьи' : 'Участник семьи'}</p>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<p className="py-6 text-center text-sm text-[#667085]">Все участники семьи уже в этом чате</p>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={createRoomOpen} onOpenChange={setCreateRoomOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[480px]">
|
||||
<DialogHeader><DialogTitle>Новый групповой чат</DialogTitle></DialogHeader>
|
||||
|
||||
Reference in New Issue
Block a user