fix and update
This commit is contained in:
@@ -5,6 +5,7 @@ import { useRouter } from 'next/navigation';
|
||||
import { Car, ChevronRight, FileKey2, FileText, Loader2, Mail, Phone, Trash2, UserRound } from 'lucide-react';
|
||||
import { AddressQuickSection } from '@/components/addresses/address-quick-section';
|
||||
import { DocumentFormDialog } from '@/components/documents/document-form-dialog';
|
||||
import { DocumentPhotosInline } from '@/components/documents/document-photo-gallery';
|
||||
import { ActionTile } from '@/components/id/action-tile';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { IdShell } from '@/components/id/shell';
|
||||
@@ -19,6 +20,8 @@ import { useRequireAuth } from '@/hooks/use-require-auth';
|
||||
import {
|
||||
getDocumentType,
|
||||
indexDocumentsByType,
|
||||
parseDocumentPhotos,
|
||||
parseMetadata,
|
||||
type DocumentTypeCode
|
||||
} from '@/lib/document-catalog';
|
||||
import { apiFetch, getApiErrorMessage, cancelAccountDeletion, fetchAccountDeletionStatus, requestAccountDeletion, type AccountDeletionStatus, UserDocument, UserProfileResponse } from '@/lib/api';
|
||||
@@ -320,14 +323,21 @@ export default function DataPage() {
|
||||
) : (
|
||||
documents.map((document) => {
|
||||
const config = getDocumentType(document.type);
|
||||
const photoKeys = parseDocumentPhotos(parseMetadata(document.metadataJson));
|
||||
return (
|
||||
<div key={document.id}>
|
||||
<Row
|
||||
key={document.id}
|
||||
icon={FileText}
|
||||
title={config?.label ?? document.type}
|
||||
text={document.number}
|
||||
onClick={() => openDocument(document.type as DocumentTypeCode)}
|
||||
/>
|
||||
{photoKeys.length > 0 && userId && token ? (
|
||||
<div className="border-b border-[#eceef4] px-1 pb-4">
|
||||
<DocumentPhotosInline userId={userId} token={token} storageKeys={photoKeys} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ChevronRight, Plus } from 'lucide-react';
|
||||
import { DocumentFormDialog } from '@/components/documents/document-form-dialog';
|
||||
import { DocumentPhotosInline } from '@/components/documents/document-photo-gallery';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { IdShell } from '@/components/id/shell';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
@@ -11,6 +12,8 @@ import {
|
||||
DOCUMENT_CATEGORIES,
|
||||
DOCUMENT_TYPES,
|
||||
getDocumentType,
|
||||
parseDocumentPhotos,
|
||||
parseMetadata,
|
||||
QUICK_DOCUMENT_TYPES,
|
||||
indexDocumentsByType,
|
||||
type DocumentTypeCode
|
||||
@@ -93,12 +96,13 @@ export default function DocumentsPage() {
|
||||
{DOCUMENT_TYPES.filter((item) => item.category === category.id).map((item) => {
|
||||
const Icon = item.icon;
|
||||
const existing = documentsByType.get(item.type);
|
||||
const photoKeys = existing ? parseDocumentPhotos(parseMetadata(existing.metadataJson)) : [];
|
||||
return (
|
||||
<div key={item.type} className="border-b border-white/70 last:border-b-0">
|
||||
<button
|
||||
key={item.type}
|
||||
type="button"
|
||||
onClick={() => openCreate(item.type)}
|
||||
className="flex w-full items-center gap-4 border-b border-white/70 px-4 py-4 text-left last:border-b-0 hover:bg-white/60"
|
||||
className="flex w-full items-center gap-4 px-4 py-4 text-left hover:bg-white/60"
|
||||
>
|
||||
<div className={cn('flex h-11 w-11 items-center justify-center rounded-2xl', item.accent)}>
|
||||
<Icon className="h-5 w-5" />
|
||||
@@ -109,6 +113,12 @@ export default function DocumentsPage() {
|
||||
</div>
|
||||
{existing ? <ChevronRight className="h-5 w-5 text-[#a8adbc]" /> : <Plus className="h-5 w-5 text-[#a8adbc]" />}
|
||||
</button>
|
||||
{existing && photoKeys.length > 0 && user && token ? (
|
||||
<div className="px-4 pb-4">
|
||||
<DocumentPhotosInline userId={user.id} token={token} storageKeys={photoKeys} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Loader2, Trash2 } from 'lucide-react';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { fetchDocumentPhotoUrl } from '@/lib/api';
|
||||
import { resolveBrowserMediaUrl } from '@/lib/resilient-media-fetch';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { DocumentFullscreenViewer, DocumentPhotoThumbnail } from './document-photo-viewer';
|
||||
|
||||
interface DocumentPhotoGalleryProps {
|
||||
@@ -13,9 +14,19 @@ interface DocumentPhotoGalleryProps {
|
||||
storageKeys: string[];
|
||||
readOnly?: boolean;
|
||||
onRemove?: (storageKey: string) => void;
|
||||
layout?: 'grid' | 'strip';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function DocumentPhotoGallery({ userId, token, storageKeys, readOnly, onRemove }: DocumentPhotoGalleryProps) {
|
||||
export function DocumentPhotoGallery({
|
||||
userId,
|
||||
token,
|
||||
storageKeys,
|
||||
readOnly,
|
||||
onRemove,
|
||||
layout = 'grid',
|
||||
className
|
||||
}: DocumentPhotoGalleryProps) {
|
||||
const { isPinLocked } = useAuth();
|
||||
const [urls, setUrls] = React.useState<Record<string, string>>({});
|
||||
const [loadingKeys, setLoadingKeys] = React.useState<Set<string>>(new Set());
|
||||
@@ -58,28 +69,42 @@ export function DocumentPhotoGallery({ userId, token, storageKeys, readOnly, onR
|
||||
.map((storageKey) => ({ storageKey, url: urls[storageKey] }))
|
||||
.filter((item) => Boolean(item.url));
|
||||
|
||||
if (storageKeys.length === 0) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{storageKeys.map((storageKey) => (
|
||||
<div key={storageKey} className="relative">
|
||||
<DocumentPhotoThumbnail
|
||||
url={urls[storageKey]}
|
||||
loading={loadingKeys.has(storageKey)}
|
||||
onClick={() => {
|
||||
function openViewer(storageKey: string) {
|
||||
const resolvedIndex = resolvedImages.findIndex((item) => item.storageKey === storageKey);
|
||||
if (resolvedIndex >= 0) {
|
||||
setViewerIndex(resolvedIndex);
|
||||
setViewerOpen(true);
|
||||
}
|
||||
}}
|
||||
}
|
||||
|
||||
if (storageKeys.length === 0) return null;
|
||||
|
||||
const isStrip = layout === 'strip';
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={cn(
|
||||
isStrip ? 'flex gap-2 overflow-x-auto pb-1' : 'grid grid-cols-2 gap-3',
|
||||
className
|
||||
)}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
{storageKeys.map((storageKey) => (
|
||||
<div key={storageKey} className={cn('relative', isStrip && 'w-20 shrink-0')}>
|
||||
<DocumentPhotoThumbnail
|
||||
url={urls[storageKey]}
|
||||
loading={loadingKeys.has(storageKey)}
|
||||
className={isStrip ? 'aspect-square rounded-xl' : undefined}
|
||||
onClick={() => openViewer(storageKey)}
|
||||
/>
|
||||
{!readOnly && onRemove ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemove(storageKey)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onRemove(storageKey);
|
||||
}}
|
||||
className="absolute right-2 top-2 rounded-full bg-black/60 p-1.5 text-white hover:bg-black/80"
|
||||
aria-label="Удалить фото"
|
||||
>
|
||||
@@ -104,3 +129,25 @@ export function DocumentPhotoGallery({ userId, token, storageKeys, readOnly, onR
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface DocumentPhotosInlineProps {
|
||||
userId: string;
|
||||
token: string | null;
|
||||
storageKeys: string[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Горизонтальная полоска фото документа для списков (страница «Документы», «Данные»). */
|
||||
export function DocumentPhotosInline({ userId, token, storageKeys, className }: DocumentPhotosInlineProps) {
|
||||
if (!storageKeys.length) return null;
|
||||
return (
|
||||
<DocumentPhotoGallery
|
||||
userId={userId}
|
||||
token={token}
|
||||
storageKeys={storageKeys}
|
||||
readOnly
|
||||
layout="strip"
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { ChevronLeft, ChevronRight, X, ZoomIn } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { MediaImageSkeleton } from '@/components/ui/media-image-skeleton';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface DocumentFullscreenViewerProps {
|
||||
@@ -13,6 +16,11 @@ interface DocumentFullscreenViewerProps {
|
||||
|
||||
export function DocumentFullscreenViewer({ images, initialIndex = 0, open, onOpenChange }: DocumentFullscreenViewerProps) {
|
||||
const [index, setIndex] = React.useState(initialIndex);
|
||||
const [mounted, setMounted] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) setIndex(initialIndex);
|
||||
@@ -29,50 +37,101 @@ export function DocumentFullscreenViewer({ images, initialIndex = 0, open, onOpe
|
||||
return () => window.removeEventListener('keydown', onKeyDown);
|
||||
}, [images.length, onOpenChange, open]);
|
||||
|
||||
if (!open || images.length === 0) return null;
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
const previous = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
document.body.style.overflow = previous;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
if (!open || images.length === 0 || !mounted) return null;
|
||||
|
||||
const current = images[index];
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[300] flex flex-col bg-black/95">
|
||||
return createPortal(
|
||||
<div className="fixed inset-0 z-[250] flex flex-col bg-[#0f1117]/96">
|
||||
<div className="flex items-center justify-between px-4 py-3 text-white">
|
||||
<span className="text-sm text-white/80">
|
||||
{index + 1} / {images.length}
|
||||
</span>
|
||||
<button type="button" onClick={() => onOpenChange(false)} className="rounded-full p-2 hover:bg-white/10" aria-label="Закрыть">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium">Фото документа</p>
|
||||
<p className="text-xs text-white/60">
|
||||
{index + 1} из {images.length}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="text-white hover:bg-white/10"
|
||||
aria-label="Закрыть"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
<X className="h-5 w-5" />
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="relative flex flex-1 items-center justify-center px-4 pb-6">
|
||||
<div className="relative flex flex-1 items-center justify-center px-3 pb-4">
|
||||
{images.length > 1 ? (
|
||||
<button
|
||||
<Button
|
||||
type="button"
|
||||
disabled={index === 0}
|
||||
onClick={() => setIndex((value) => Math.max(0, value - 1))}
|
||||
className="absolute left-4 z-10 rounded-full bg-white/10 p-2 text-white disabled:opacity-30"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'absolute left-3 z-10 h-11 w-11 rounded-full text-white hover:bg-white/10',
|
||||
index <= 0 && 'pointer-events-none opacity-30'
|
||||
)}
|
||||
aria-label="Предыдущее фото"
|
||||
onClick={() => setIndex((value) => Math.max(0, value - 1))}
|
||||
>
|
||||
<ChevronLeft className="h-6 w-6" />
|
||||
</button>
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={current.url} alt="Фото документа" className="max-h-[calc(100vh-120px)] max-w-full object-contain" />
|
||||
<img
|
||||
src={current.url}
|
||||
alt="Фото документа"
|
||||
className="max-h-[calc(100vh-140px)] max-w-full object-contain"
|
||||
/>
|
||||
|
||||
{images.length > 1 ? (
|
||||
<button
|
||||
<Button
|
||||
type="button"
|
||||
disabled={index === images.length - 1}
|
||||
onClick={() => setIndex((value) => Math.min(images.length - 1, value + 1))}
|
||||
className="absolute right-4 z-10 rounded-full bg-white/10 p-2 text-white disabled:opacity-30"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'absolute right-3 z-10 h-11 w-11 rounded-full text-white hover:bg-white/10',
|
||||
index >= images.length - 1 && 'pointer-events-none opacity-30'
|
||||
)}
|
||||
aria-label="Следующее фото"
|
||||
onClick={() => setIndex((value) => Math.min(images.length - 1, value + 1))}
|
||||
>
|
||||
<ChevronRight className="h-6 w-6" />
|
||||
</button>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{images.length > 1 ? (
|
||||
<div className="flex gap-2 overflow-x-auto px-4 pb-4">
|
||||
{images.map((image, imageIndex) => (
|
||||
<button
|
||||
key={image.storageKey}
|
||||
type="button"
|
||||
className={cn(
|
||||
'h-14 w-14 shrink-0 overflow-hidden rounded-lg border-2',
|
||||
imageIndex === index ? 'border-[#3390ec]' : 'border-transparent opacity-70'
|
||||
)}
|
||||
onClick={() => setIndex(imageIndex)}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={image.url} alt="" className="h-full w-full object-cover" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>,
|
||||
document.body
|
||||
);
|
||||
}
|
||||
|
||||
@@ -93,7 +152,7 @@ export function DocumentPhotoThumbnail({ url, loading, className, onClick }: Doc
|
||||
className
|
||||
)}
|
||||
>
|
||||
{loading ? <div className="h-full w-full animate-pulse bg-[#eceef4]" /> : null}
|
||||
{loading ? <MediaImageSkeleton className="h-full w-full min-h-0" rounded="none" /> : null}
|
||||
{!loading && url ? (
|
||||
<>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { FileText } from 'lucide-react';
|
||||
import { DocumentFormDialog } from '@/components/documents/document-form-dialog';
|
||||
import { DocumentPhotosInline } from '@/components/documents/document-photo-gallery';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { getDocumentType, indexDocumentsByType, type DocumentTypeCode } from '@/lib/document-catalog';
|
||||
import { getDocumentType, indexDocumentsByType, parseDocumentPhotos, parseMetadata, type DocumentTypeCode } from '@/lib/document-catalog';
|
||||
import { apiFetch, UserDocument } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -68,9 +69,10 @@ export function UserDocumentsDialog({
|
||||
const config = getDocumentType(document.type);
|
||||
if (!config) return null;
|
||||
const Icon = config.icon;
|
||||
const photoKeys = parseDocumentPhotos(parseMetadata(document.metadataJson));
|
||||
return (
|
||||
<div key={document.id}>
|
||||
<button
|
||||
key={document.id}
|
||||
type="button"
|
||||
onClick={() => openDocument(document.type as DocumentTypeCode)}
|
||||
className="flex w-full items-center gap-3 rounded-2xl bg-[#f4f5f8] px-4 py-3 text-left transition hover:bg-[#eceef4]"
|
||||
@@ -84,6 +86,12 @@ export function UserDocumentsDialog({
|
||||
</div>
|
||||
<FileText className="h-4 w-4 text-[#a8adbc]" />
|
||||
</button>
|
||||
{photoKeys.length > 0 && token ? (
|
||||
<div className="mt-2 px-1">
|
||||
<DocumentPhotosInline userId={targetUserId} token={token} storageKeys={photoKeys} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
extractFilesFromDataTransfer,
|
||||
useChatMediaComposer
|
||||
} from '@/components/chat/chat-media-compose-dialog';
|
||||
import { ChatImageLightbox } from '@/components/chat/chat-image-lightbox';
|
||||
import { ChatEmojiContent } from '@/components/chat/chat-emoji-content';
|
||||
import { ChatMessageContextMenu, ChatSelectionContextMenu, SelectableMessageWrapper } from '@/components/chat/chat-message-context-menu';
|
||||
import { ChatPinnedMessageBanner } from '@/components/chat/chat-pinned-message-banner';
|
||||
@@ -28,6 +29,7 @@ import { scrollToChatMessage } from '@/components/chat/replied-message-preview';
|
||||
import { useFamilyOverlay } from '@/components/family/family-overlay-provider';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { UserAvatar } from '@/components/id/user-avatar';
|
||||
import { MediaImageSkeleton } from '@/components/ui/media-image-skeleton';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { useRealtime } from '@/components/notifications/realtime-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -74,6 +76,8 @@ import { shouldShowChatDateSeparator } from '@/lib/chat-date-utils';
|
||||
import { encryptE2EBlob, e2eKindFromMessageType } from '@/lib/e2e-chat';
|
||||
import { findMemberRoom, findOrCreateMemberChat, roomDisplayLabel } from '@/lib/family-chat';
|
||||
import { getE2EMessageText, useE2EChat } from '@/hooks/use-e2e-chat';
|
||||
import { useChatRoomMedia } from '@/hooks/use-chat-room-media';
|
||||
import { collectChatImageMessages } from '@/lib/chat-media-album';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface PresignedUploadResponse {
|
||||
@@ -87,7 +91,7 @@ function formatMessageTime(value: string) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(new Date(value));
|
||||
}
|
||||
|
||||
function MiniChatImageMessage({ message, token }: { message: ChatMessage; token: string }) {
|
||||
function MiniChatEncryptedImageMessage({ message, token, onOpen }: { message: ChatMessage; token: string; onOpen?: () => void }) {
|
||||
const [src, setSrc] = useState<string | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const metadata = parseMessageMetadata(message.metadataJson) as { fileName?: string; width?: number; height?: number };
|
||||
@@ -146,12 +150,19 @@ function MiniChatImageMessage({ message, token }: { message: ChatMessage; token:
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="block overflow-hidden rounded-2xl shadow-sm"
|
||||
onClick={onOpen}
|
||||
disabled={!onOpen}
|
||||
>
|
||||
<img
|
||||
src={src}
|
||||
alt={message.content?.trim() || metadata.fileName || 'Фото в чате'}
|
||||
className="max-h-[260px] w-[190px] rounded-2xl object-cover shadow-sm"
|
||||
className="max-h-[260px] w-[190px] object-cover"
|
||||
style={{ aspectRatio: metadata.width && metadata.height ? `${metadata.width} / ${metadata.height}` : undefined }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -202,6 +213,7 @@ export function MiniFamilyChat() {
|
||||
const [chatToolsOpen, setChatToolsOpen] = useState(false);
|
||||
const [chatToolsTab, setChatToolsTab] = useState<ChatToolsTab>('search');
|
||||
const [mediaDropVisible, setMediaDropVisible] = useState(false);
|
||||
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
|
||||
const mediaComposer = useChatMediaComposer();
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const autoScrollStateRef = useRef<{ id: string | null; count: number }>({ id: null, count: 0 });
|
||||
@@ -213,6 +225,13 @@ export function MiniFamilyChat() {
|
||||
() => messages.filter((message) => !message.isDeleted),
|
||||
[messages]
|
||||
);
|
||||
const chatImageMessages = useMemo(() => collectChatImageMessages(visibleMessages), [visibleMessages]);
|
||||
const { mediaUrls } = useChatRoomMedia(token, activeRoom?.id ?? null, visibleMessages);
|
||||
|
||||
function openImageLightbox(message: ChatMessage) {
|
||||
const index = chatImageMessages.findIndex((item) => item.id === message.id);
|
||||
if (index >= 0) setLightboxIndex(index);
|
||||
}
|
||||
const pinnedMessage = useMemo(
|
||||
() =>
|
||||
visibleMessages
|
||||
@@ -361,6 +380,7 @@ export function MiniFamilyChat() {
|
||||
setMessages([]);
|
||||
setBotMessages([]);
|
||||
setDraft('');
|
||||
setLightboxIndex(null);
|
||||
exitSelectionMode();
|
||||
setEmojiOpen(false);
|
||||
setPollOpen(false);
|
||||
@@ -1173,9 +1193,58 @@ export function MiniFamilyChat() {
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : message.storageKey && message.type === 'IMAGE' && message.isEncrypted && token ? (
|
||||
<div className="space-y-1">
|
||||
<MiniChatEncryptedImageMessage
|
||||
message={message}
|
||||
token={token}
|
||||
onOpen={() => openImageLightbox(message)}
|
||||
/>
|
||||
{visibleText?.trim() ? (
|
||||
<div className="whitespace-pre-wrap break-words text-sm leading-relaxed">
|
||||
<ChatEmojiContent content={visibleText} size={18} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : message.storageKey && message.type === 'IMAGE' && token ? (
|
||||
<div className="space-y-1">
|
||||
<MiniChatImageMessage message={message} token={token} />
|
||||
{(() => {
|
||||
const media = message.storageKey ? mediaUrls[message.storageKey] : undefined;
|
||||
const meta = parseMessageMetadata(message.metadataJson) as {
|
||||
fileName?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
if (!media?.blobUrl || media.status === 'loading') {
|
||||
const ratio =
|
||||
meta.width && meta.height
|
||||
? Math.max(0.65, Math.min(1.35, meta.height / meta.width))
|
||||
: 0.72;
|
||||
return (
|
||||
<div className="w-[190px]" style={{ height: Math.round(190 * ratio) }}>
|
||||
<MediaImageSkeleton className="h-full w-full min-h-0" rounded="2xl" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="block overflow-hidden rounded-2xl shadow-sm"
|
||||
onClick={() => openImageLightbox(message)}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={media.blobUrl}
|
||||
alt={message.content?.trim() || meta.fileName || 'Фото в чате'}
|
||||
className="max-h-[260px] w-[190px] object-cover"
|
||||
style={{
|
||||
aspectRatio:
|
||||
meta.width && meta.height ? `${meta.width} / ${meta.height}` : undefined
|
||||
}}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})()}
|
||||
{visibleText?.trim() ? (
|
||||
<div className="whitespace-pre-wrap break-words text-sm leading-relaxed">
|
||||
<ChatEmojiContent content={visibleText} size={18} />
|
||||
@@ -1494,6 +1563,14 @@ export function MiniFamilyChat() {
|
||||
authToken={token}
|
||||
onClose={() => setMiniAppUrl(null)}
|
||||
/>
|
||||
<ChatImageLightbox
|
||||
open={lightboxIndex !== null}
|
||||
images={chatImageMessages}
|
||||
index={lightboxIndex ?? 0}
|
||||
mediaUrls={mediaUrls}
|
||||
onClose={() => setLightboxIndex(null)}
|
||||
onIndexChange={setLightboxIndex}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
95
apps/frontend/hooks/use-chat-room-media.ts
Normal file
95
apps/frontend/hooks/use-chat-room-media.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { ChatMessage } from '@/lib/api';
|
||||
import { fetchChatMediaUrl } from '@/lib/api';
|
||||
import { createBlobObjectUrl, fetchAuthenticatedMediaBlob, revokeBlobObjectUrl } from '@/lib/authenticated-media';
|
||||
import { parseChatMediaMetadata } from '@/lib/chat-media-album';
|
||||
|
||||
export type ChatRoomMediaEntry = {
|
||||
blobUrl?: string;
|
||||
fileName?: string;
|
||||
mimeType?: string;
|
||||
status?: 'loading' | 'ready' | 'error';
|
||||
errorMessage?: string;
|
||||
};
|
||||
|
||||
export function useChatRoomMedia(token: string | null, roomId: string | null, messages: ChatMessage[]) {
|
||||
const [mediaUrls, setMediaUrls] = useState<Record<string, ChatRoomMediaEntry>>({});
|
||||
const mediaUrlsRef = useRef<Record<string, ChatRoomMediaEntry>>({});
|
||||
const inFlightRef = useRef(new Set<string>());
|
||||
|
||||
useEffect(() => {
|
||||
mediaUrlsRef.current = mediaUrls;
|
||||
}, [mediaUrls]);
|
||||
|
||||
const loadMedia = useCallback(
|
||||
async (message: ChatMessage, force = false) => {
|
||||
if (!token || !roomId || !message.storageKey || message.isDeleted || message.isEncrypted) return;
|
||||
const storageKey = message.storageKey;
|
||||
const existing = mediaUrlsRef.current[storageKey];
|
||||
if (!force && existing?.status === 'ready' && existing.blobUrl) {
|
||||
return;
|
||||
}
|
||||
if (inFlightRef.current.has(storageKey) && !force) {
|
||||
return;
|
||||
}
|
||||
|
||||
inFlightRef.current.add(storageKey);
|
||||
setMediaUrls((current) => ({
|
||||
...current,
|
||||
[storageKey]: { ...current[storageKey], status: 'loading', errorMessage: undefined }
|
||||
}));
|
||||
|
||||
const meta = parseChatMediaMetadata(message.metadataJson);
|
||||
const fileName = meta.fileName || message.content || undefined;
|
||||
|
||||
try {
|
||||
const access = await fetchChatMediaUrl(roomId, storageKey, token, fileName);
|
||||
const blob = await fetchAuthenticatedMediaBlob(access.accessUrl, token, message.mimeType);
|
||||
const blobUrl = createBlobObjectUrl(blob);
|
||||
setMediaUrls((current) => {
|
||||
revokeBlobObjectUrl(current[storageKey]?.blobUrl);
|
||||
return {
|
||||
...current,
|
||||
[storageKey]: {
|
||||
blobUrl,
|
||||
fileName,
|
||||
mimeType: message.mimeType,
|
||||
status: 'ready'
|
||||
}
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
setMediaUrls((current) => ({
|
||||
...current,
|
||||
[storageKey]: {
|
||||
...current[storageKey],
|
||||
status: 'error',
|
||||
errorMessage: error instanceof Error ? error.message : 'Не удалось загрузить файл'
|
||||
}
|
||||
}));
|
||||
} finally {
|
||||
inFlightRef.current.delete(storageKey);
|
||||
}
|
||||
},
|
||||
[roomId, token]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !roomId) return;
|
||||
messages.forEach((message) => {
|
||||
if (message.storageKey && message.type === 'IMAGE') {
|
||||
void loadMedia(message);
|
||||
}
|
||||
});
|
||||
}, [loadMedia, messages, roomId, token]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
Object.values(mediaUrlsRef.current).forEach((entry) => revokeBlobObjectUrl(entry.blobUrl));
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { mediaUrls, loadMedia };
|
||||
}
|
||||
Reference in New Issue
Block a user