Files
CoHaiSe-CLOUD/frontend/src/pages/Browser.tsx
T
Esiah 68d4d5dea0
PR — Ouverture automatique / create-pr (push) Successful in 3s
refactor: restructure frontend and backend by domain services
Split the monolithic backend (lib/, routes/, access.ts, storage.ts, media.ts)
into a layered structure inspired by JeanXXIII-CRM:
- config/: appConfig, db
- middleware/: auth (session, roles, cookies)
- models/: shared types
- routes/: *Routes.ts (thin HTTP handlers)
- services/: *Service.ts (business logic, one per domain)
- utils/: errors, http, migrate, ratelimit, validators, service bootstrap

Frontend likewise: services/*Service.ts + apiClient, contexts/, types/, utils/format.
Route files now carry the "Routes" suffix; service files are named
authService.ts, ratelimit.ts, etc. and live in their own files, frontend and
backend separated.

Updated docs and READMEs to reflect the new layout. Typecheck and builds pass.
2026-11-13 09:45:21 +01:00

1017 lines
38 KiB
TypeScript

import {
useCallback,
useEffect,
useRef,
useState,
type DragEvent,
} from "react";
import { Card, Spinner, cn } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { chatService } from "../services/chatService.js";
import { fileService } from "../services/fileService.js";
import { folderService } from "../services/folderService.js";
import { formatBytes } from "../utils/format.js";
import type { Folder, UploadedFile } from "../types/index.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import { getLocale } from "../lib/locale.js";
import { mediaKind } from "../lib/media.js";
import { EmptyState, PageHeader } from "../components/feedback.js";
import { useConfirm } from "../components/confirm.js";
import { MediaViewer } from "../components/MediaViewer.js";
import { MediaThumb } from "../components/MediaThumb.js";
import { IconAction } from "../components/IconAction.js";
import { FolderChat, type ChatFolder } from "../components/FolderChat.js";
import { useToast } from "../components/toast.js";
import {
CreateFolderDialog,
MoveDialog,
RenameDialog,
ShareDialog,
} from "../components/dialogs.js";
import {
ArrowLeftIcon,
ChatIcon,
CloseIcon,
DownloadIcon,
MoveIcon,
OpenedFolderIcon,
PenIcon,
PlusIcon,
RefreshIcon,
ShareIcon,
StarIcon,
TrashIcon,
UploadIcon,
} from "../components/icons.js";
interface Crumb {
id: string | null;
name: string;
}
type Target = { type: "folder" | "file"; id: string; name: string };
type Dialog =
| { kind: "create" }
| { kind: "rename"; target: Target }
| { kind: "move"; target: Target }
| { kind: "moveMany"; targets: Target[] }
| { kind: "share"; folder: Folder }
| null;
const KINDS = [
{ value: "", label: "Tout" },
{ value: "image", label: "Images" },
{ value: "video", label: "Vidéos" },
{ value: "audio", label: "Audio" },
{ value: "document", label: "Documents" },
{ value: "archive", label: "Archives" },
{ value: "other", label: "Autres" },
] as const;
const REFRESH_FOLDER_MS = 60_000;
export const Browser = () => {
const { user, refresh } = useSession();
const { t } = useI18n();
const confirm = useConfirm();
const toast = useToast();
const [path, setPath] = useState<Crumb[]>([{ id: null, name: "Racine" }]);
const [folders, setFolders] = useState<Folder[]>([]);
const [files, setFiles] = useState<UploadedFile[]>([]);
const [loading, setLoading] = useState(true);
const [, setError] = useState<string | null>(null);
const [, setNotice] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [removing, setRemoving] = useState<string | null>(null);
const [dialog, setDialog] = useState<Dialog>(null);
const [viewer, setViewer] = useState<number | null>(null);
const [chat, setChat] = useState<ChatFolder | null>(null);
const [unread, setUnread] = useState<Record<string, number>>({});
const [kind, setKind] = useState<string>("");
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragDepth, setDragDepth] = useState(0);
const [dropTargetId, setDropTargetId] = useState<string | null>(null);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [uploadProgress, setUploadProgress] = useState<{
current: number;
total: number;
uploadedBytes: number;
totalBytes: number;
} | null>(null);
const current = path[path.length - 1] ?? { id: null, name: "Racine" };
const dragActive = dragDepth > 0;
const loadSeq = useRef(0);
const load = useCallback(
async (parentId: string | null, options?: { silent?: boolean }) => {
const sequence = ++loadSeq.current;
if (!options?.silent) setLoading(true);
setError(null);
try {
const [folderResult, fileResult] = await Promise.all([
folderService.folders(parentId),
fileService.files(parentId),
]);
if (sequence !== loadSeq.current) return;
setFolders(folderResult.folders);
setFiles(fileResult.files);
} catch (caught) {
if (sequence !== loadSeq.current) return;
const msg =
caught instanceof ApiError
? caught.message
: t("Chargement impossible.");
if (!options?.silent) {
setError(msg);
toast.error(msg);
setFolders([]);
setFiles([]);
}
} finally {
if (!options?.silent) setLoading(false);
}
},
[t, toast.error],
);
const refreshUnread = useCallback(async () => {
try {
const { unread: counts } = await chatService.chatUnread();
setUnread(counts);
} catch {
}
}, []);
useEffect(() => {
void load(current.id);
}, [current.id, load]);
useEffect(() => {
void refreshUnread();
}, [current.id, refreshUnread]);
useEffect(() => {
const timer = window.setInterval(() => {
if (document.hidden) return;
if (uploading || viewer !== null || dialog !== null || chat !== null) return;
void load(current.id, { silent: true });
void refreshUnread();
}, REFRESH_FOLDER_MS);
return () => window.clearInterval(timer);
}, [chat, current.id, dialog, load, refreshUnread, uploading, viewer]);
useEffect(() => {
setKind("");
}, [current.id]);
const reload = useCallback(() => load(current.id), [current.id, load]);
const manualRefresh = useCallback(async () => {
if (refreshing) return;
setRefreshing(true);
try {
await load(current.id);
await refreshUnread();
} finally {
setRefreshing(false);
}
}, [current.id, load, refreshUnread, refreshing]);
const open = (folder: Folder) => {
setPath((previous) => [...previous, { id: folder.id, name: folder.name }]);
};
const goTo = (index: number) =>
setPath((previous) => previous.slice(0, index + 1));
const upload = async (selectedFiles: FileList | null) => {
if (!selectedFiles || selectedFiles.length === 0) return;
setUploading(true);
setError(null);
setNotice(null);
const filesArr = Array.from(selectedFiles);
const total = filesArr.length;
const totalBytes = filesArr.reduce((sum, file) => sum + file.size, 0);
let completedBytes = 0;
const update = (current: number, loaded: number) =>
setUploadProgress({ current, total, uploadedBytes: completedBytes + loaded, totalBytes });
update(0, 0);
try {
for (let i = 0; i < filesArr.length; i++) {
const f = filesArr[i] as File;
update(i + 1, 0);
await fileService.uploadFile(f, current.id, (loaded) => update(i + 1, loaded));
completedBytes += f.size;
}
void refresh();
await reload();
} catch (caught) {
const msg =
caught instanceof ApiError ? caught.message : t("Envoi impossible.");
setError(msg);
toast.error(msg);
} finally {
setUploading(false);
setUploadProgress(null);
if (fileInputRef.current) fileInputRef.current.value = "";
}
};
const uploadInto = async (
selectedFiles: FileList | null,
folderId: string | null,
label?: string,
) => {
if (!selectedFiles || selectedFiles.length === 0) return;
setUploading(true);
setError(null);
setNotice(null);
const filesArr = Array.from(selectedFiles);
const total = filesArr.length;
const totalBytes = filesArr.reduce((sum, file) => sum + file.size, 0);
let completedBytes = 0;
const update = (current: number, loaded: number) =>
setUploadProgress({ current, total, uploadedBytes: completedBytes + loaded, totalBytes });
update(0, 0);
try {
for (let i = 0; i < filesArr.length; i++) {
const f = filesArr[i] as File;
update(i + 1, 0);
await fileService.uploadFile(f, folderId, (loaded) => update(i + 1, loaded));
completedBytes += f.size;
}
void refresh();
if (folderId === current.id) await reload();
const msg = label
? t("{count} fichier(s) déposé(s) dans {name}.", {
count: filesArr.length,
name: label,
})
: t("{count} fichier(s) déposé(s) dans ce dossier.", {
count: filesArr.length,
});
setNotice(msg);
toast.success(msg);
} catch (caught) {
const msg =
caught instanceof ApiError ? caught.message : t("Envoi impossible.");
setError(msg);
toast.error(msg);
} finally {
setUploading(false);
setUploadProgress(null);
}
};
const carriesFiles = (event: DragEvent): boolean =>
Array.from(event.dataTransfer.types).includes("Files");
const stillInside = (event: DragEvent): boolean => {
const related = event.relatedTarget as Node | null;
return related !== null && event.currentTarget.contains(related);
};
const onDragEnter = (event: DragEvent) => {
if (!carriesFiles(event)) return;
event.preventDefault();
if (stillInside(event)) return;
setDragDepth((depth) => depth + 1);
};
const onDragOver = (event: DragEvent) => {
if (!carriesFiles(event)) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
};
const onDragLeave = (event: DragEvent) => {
if (!carriesFiles(event)) return;
event.preventDefault();
if (stillInside(event)) return;
setDragDepth((depth) => Math.max(0, depth - 1));
};
const onDrop = (event: DragEvent) => {
if (!carriesFiles(event)) return;
event.preventDefault();
setDragDepth(0);
setDropTargetId(null);
void uploadInto(event.dataTransfer.files, current.id);
};
const onFolderDragOver = (event: DragEvent, folderId: string) => {
if (!carriesFiles(event)) return;
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = "copy";
setDropTargetId(folderId);
};
const onFolderDragLeave = (event: DragEvent, folderId: string) => {
if (!carriesFiles(event)) return;
event.preventDefault();
event.stopPropagation();
if (stillInside(event)) return;
setDropTargetId((current) => (current === folderId ? null : current));
};
const onFolderDrop = (event: DragEvent, folder: Folder) => {
if (!carriesFiles(event)) return;
event.preventDefault();
event.stopPropagation();
setDragDepth(0);
setDropTargetId(null);
void uploadInto(event.dataTransfer.files, folder.id, folder.name);
};
const removeTarget = async (target: Target) => {
const kind = target.type === "folder" ? t("ce dossier") : t("ce fichier");
const ok = await confirm({
title: t("Mettre à la corbeille"),
message: t("Placer {name} ({kind}) dans la corbeille ?", {
name: target.name,
kind,
}),
confirmLabel: t("Corbeille"),
tone: "danger",
});
if (!ok) return;
setRemoving(target.id);
setError(null);
try {
if (target.type === "folder") {
await folderService.deleteFolder(target.id);
} else {
await fileService.deleteFile(target.id);
void refresh();
}
await reload();
} catch (caught) {
const msg =
caught instanceof ApiError
? caught.message
: t("Suppression impossible.");
setError(msg);
toast.error(msg);
} finally {
setRemoving(null);
}
};
const removeSelected = async () => {
const ok = await confirm({
title: t("Mettre à la corbeille"),
message: t("{count} élément(s) seront placés dans la corbeille.", {
count: selectedItems.length,
}),
confirmLabel: t("Corbeille"),
tone: "danger",
});
if (!ok) return;
setError(null);
try {
for (const target of selectedItems) {
if (target.type === "folder") await folderService.deleteFolder(target.id);
else await fileService.deleteFile(target.id);
}
clearSelection();
await reload();
void refresh();
} catch (caught) {
const msg =
caught instanceof ApiError
? caught.message
: t("Suppression impossible.");
setError(msg);
toast.error(msg);
}
};
const toggleStar = async (file: UploadedFile) => {
setError(null);
try {
const { file: updated } = await fileService.starFile(file.id);
setFiles((previous) =>
previous.map((item) => (item.id === updated.id ? updated : item)),
);
} catch (caught) {
const msg =
caught instanceof ApiError ? caught.message : t("Action impossible.");
setError(msg);
toast.error(msg);
}
};
const closeChat = () => {
setChat(null);
void refreshUnread();
};
const toggleSelection = (key: string) => {
setSelected((previous) => {
const next = new Set(previous);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
};
const clearSelection = () => setSelected(new Set());
const selectedItems: Target[] = [];
for (const folder of folders) {
if (selected.has(`f:${folder.id}`))
selectedItems.push({ type: "folder", id: folder.id, name: folder.name });
}
for (const file of files) {
if (selected.has(`i:${file.id}`))
selectedItems.push({ type: "file", id: file.id, name: file.name });
}
const empty = folders.length === 0 && files.length === 0;
const canWrite = true;
const visibleFiles = kind
? files.filter((file) => mediaKind(file.mime_type) === kind)
: files;
const currentUnread = current.id ? (unread[current.id] ?? 0) : 0;
const quotaPercent =
user && user.quota_bytes > 0
? Math.min(100, Math.round((user.used_bytes / user.quota_bytes) * 100))
: 0;
return (
<div
className="flex flex-col gap-5"
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
>
{dragActive ? (
<div
className="pointer-events-none fixed inset-0 z-30 flex items-center justify-center bg-background/70"
aria-hidden="true"
>
<p className="rounded-md border border-accent/50 bg-accent/10 px-4 py-3 text-sm font-medium text-accent">
{t("Déposez vos fichiers ici")}
</p>
</div>
) : null}
<PageHeader
title={current.name}
description={t(
"Vos dossiers et fichiers. Envoyez un fichier ou créez un dossier.",
)}
toolbar={
<div className="flex flex-wrap items-center gap-3">
{path.length > 1 ? (
<button
type="button"
onClick={() => goTo(path.length - 2)}
className="inline-flex items-center gap-1.5 rounded-sm border border-border-control bg-surface/60 px-2.5 py-1.5 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground backdrop-blur-sm transition-colors duration-fast hover:bg-surface/80 focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none"
>
<ArrowLeftIcon className="h-3.5 w-3.5" />
{t("Retour")}
</button>
) : null}
<nav aria-label={t("Fil d'Ariane")} className="min-w-0">
<ol className="flex flex-wrap items-center gap-1.5 text-xs">
{path.map((crumb, index) => (
<li
key={`${crumb.id ?? "root"}-${index}`}
className="flex items-center gap-1.5"
>
{index > 0 ? (
<span className="text-border" aria-hidden="true">
/
</span>
) : null}
{index === path.length - 1 ? (
<span
className="font-medium text-foreground"
aria-current="page"
>
{t(crumb.name)}
</span>
) : (
<button
type="button"
onClick={() => goTo(index)}
className="text-muted-foreground underline-offset-2 transition-colors hover:text-foreground hover:underline"
>
{t(crumb.name)}
</button>
)}
</li>
))}
</ol>
</nav>
<IconAction
label={t("Rafraîchir")}
icon={<RefreshIcon className="h-4 w-4" />}
isLoading={refreshing}
onClick={() => void manualRefresh()}
/>
{current.id ? (
<IconAction
label={t("Discussion")}
icon={<ChatIcon className="h-4 w-4" />}
badge={currentUnread}
onClick={() =>
setChat({ id: current.id as string, name: current.name })
}
/>
) : null}
</div>
}
/>
<Card>
<div className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 flex-1">
<div className="flex items-baseline justify-between gap-3">
<span className="text-xs font-medium text-foreground">
{t("Espace utilisé")}
</span>
<span className="text-xs text-muted-foreground">
{t("{used} sur {quota}", {
used: formatBytes(user?.used_bytes ?? 0),
quota: formatBytes(user?.quota_bytes ?? 0),
})}
</span>
</div>
<div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-surface-muted">
<div
className="h-full rounded-full bg-accent-graphic transition-[width] duration-300"
style={{ width: `${Math.max(quotaPercent, 1)}%` }}
/>
</div>
</div>
{uploading && uploadProgress ? (
<div className="w-full px-4">
<div className="flex items-baseline justify-between gap-2 mb-1">
<span className="text-xs font-medium text-foreground">
{t("Envoi en cours")}
</span>
<span className="text-xs text-muted-foreground">
{t("{current}/{total}", uploadProgress)} ·{" "}
{formatBytes(uploadProgress.uploadedBytes)} / {formatBytes(uploadProgress.totalBytes)}
</span>
</div>
<div className="h-1.5 w-full overflow-hidden rounded-full bg-surface-muted">
<div
className="h-full rounded-full bg-accent transition-[width] duration-200"
style={{
width: `${Math.min(
100,
Math.round(
(uploadProgress.uploadedBytes / Math.max(1, uploadProgress.totalBytes)) * 100,
),
)}%`,
}}
/>
</div>
</div>
) : null}
{canWrite ? (
<div className="flex gap-1">
<input
ref={fileInputRef}
type="file"
multiple
className="sr-only"
onChange={(event) => void upload(event.target.files)}
/>
<IconAction
label={uploading && uploadProgress ? t("Envoi {current}/{total}…", uploadProgress) : t("Envoyer")}
icon={<UploadIcon className="h-5 w-5" />}
className="h-10 w-10 bg-accent text-accent-foreground hover:bg-accent"
isLoading={uploading}
onClick={() => fileInputRef.current?.click()}
/>
<IconAction
label={t("Nouveau dossier")}
icon={<PlusIcon className="h-5 w-5" />}
className="h-10 w-10 bg-accent text-accent-foreground hover:bg-accent"
onClick={() => setDialog({ kind: "create" })}
/>
</div>
) : null}
</div>
</Card>
{files.length > 0 ? (
<div
className="flex flex-wrap gap-1.5"
role="tablist"
aria-label={t("Filtrer par type")}
>
{KINDS.map((option) => (
<button
key={option.value}
type="button"
role="tab"
aria-selected={kind === option.value}
onClick={() => setKind(option.value)}
className={cn(
"rounded-sm border px-3 py-1.5 font-display text-[0.6875rem] font-semibold uppercase tracking-label transition-colors",
kind === option.value
? "border-accent/50 bg-accent/10 text-accent"
: "border-border-control text-muted-foreground hover:bg-surface-hover hover:text-foreground",
)}
>
{t(option.label)}
</button>
))}
</div>
) : null}
{canWrite && selectedItems.length > 0 ? (
<div className="fixed bottom-3 left-1/2 z-40 w-[calc(100%-1rem)] max-w-xl -translate-x-1/2 px-1 sm:bottom-4 sm:w-auto">
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-border-strong bg-surface/80 px-3 py-2 shadow-lg backdrop-blur-md sm:flex-row sm:flex-wrap sm:items-center sm:justify-center">
<p className="text-center text-sm font-medium text-foreground">
{t("{count} élément(s) sélectionné(s).", {
count: selectedItems.length,
})}
</p>
<div className="flex flex-wrap items-center justify-center gap-1">
<IconAction
label={t("Déplacer")}
icon={<MoveIcon className="h-4 w-4 object-contain" />}
onClick={() => setDialog({ kind: "moveMany", targets: selectedItems })}
/>
<IconAction
label={t("Télécharger")}
icon={<DownloadIcon className="h-4 w-4" />}
onClick={() => {
const files = selectedItems.filter((t) => t.type === "file");
if (files.length === 0) {
toast.info(t("Seuls les fichiers peuvent être téléchargés."));
return;
}
for (const target of files) {
const link = document.createElement("a");
link.href = fileService.downloadUrl(target.id);
link.download = target.name;
link.click();
}
if (files.length < selectedItems.length) {
toast.info(t("Les dossiers n'ont pas été téléchargés."));
}
}}
/>
<IconAction
label={t("Supprimer")}
icon={<TrashIcon className="h-4 w-4" />}
tone="danger"
onClick={() => void removeSelected()}
/>
<IconAction
label={t("Annuler la sélection")}
icon={<CloseIcon className="h-4 w-4" />}
onClick={clearSelection}
/>
</div>
</div>
</div>
) : null}
{loading ? (
<div className="flex justify-center py-16">
<Spinner size="md" />
</div>
) : empty ? (
<EmptyState
icon={<OpenedFolderIcon className="h-8 w-8 object-contain" />}
title={t("Emplacement vide")}
description={t(
"Créez un sous-dossier ou envoyez un fichier pour commencer.",
)}
/>
) : (
<div className="flex flex-col gap-6">
{folders.length > 0 ? (
<section aria-label={t("Dossiers")}>
<h2 className="mb-2 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
{t("Dossiers")}
</h2>
<ul className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{folders.map((folder) => (
<li
key={folder.id}
onDragOver={(event) => onFolderDragOver(event, folder.id)}
onDragLeave={(event) => onFolderDragLeave(event, folder.id)}
onDrop={(event) => onFolderDrop(event, folder)}
onClick={() => toggleSelection(`f:${folder.id}`)}
className={cn(
"group relative flex items-center gap-1 rounded-xl border border-border/50 bg-surface/60 p-2 backdrop-blur-md transition-all hover:-translate-y-1 hover:border-border-strong hover:bg-surface/80 hover:shadow-lg cursor-pointer",
dropTargetId === folder.id &&
"border-accent bg-accent/10 ring-1 ring-accent/50",
selected.has(`f:${folder.id}`) &&
"border-accent/60 ring-1 ring-accent/40",
)}
>
<input
type="checkbox"
className={cn(
"ml-1 h-4 w-4 rounded border-border-control transition-opacity",
selected.has(`f:${folder.id}`) ||
selectedItems.length > 0
? "opacity-100"
: "opacity-100 md:opacity-0 md:group-hover:opacity-100 md:focus:opacity-100",
)}
checked={selected.has(`f:${folder.id}`)}
aria-label={t("Sélectionner {name}", {
name: folder.name,
})}
onClick={(event) => event.stopPropagation()}
onChange={() => toggleSelection(`f:${folder.id}`)}
/>
<button
type="button"
onClick={(event) => {
event.stopPropagation();
if (selectedItems.length > 0) {
toggleSelection(`f:${folder.id}`);
return;
}
open(folder);
}}
className="flex min-w-0 flex-1 items-center gap-3 rounded-sm p-1 text-left focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none"
>
<span className="shrink-0 text-accent">
<OpenedFolderIcon className="h-5 w-5 object-contain" />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-foreground">
{folder.name}
</span>
<span className="mt-0.5 block text-[0.6875rem] text-subtle-foreground">
{new Date(folder.created_at).toLocaleDateString(
getLocale(),
)}
</span>
</span>
</button>
<div className="flex shrink-0 items-center gap-0.5 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100 md:focus-within:opacity-100">
<IconAction
label={t("Discussion {name}", { name: folder.name })}
icon={<ChatIcon className="h-4 w-4" />}
badge={unread[folder.id] ?? 0}
onClick={(event) => {
event.stopPropagation();
setChat({ id: folder.id, name: folder.name });
}}
/>
{canWrite ? (
<>
<IconAction
label={t("Partager {name}", { name: folder.name })}
icon={<ShareIcon className="h-4 w-4" />}
onClick={(event) => {
event.stopPropagation();
setDialog({ kind: "share", folder });
}}
/>
<IconAction
label={t("Renommer {name}", { name: folder.name })}
icon={<PenIcon className="h-4 w-4" />}
onClick={(event) => {
event.stopPropagation();
setDialog({
kind: "rename",
target: {
type: "folder",
id: folder.id,
name: folder.name,
},
});
}}
/>
<IconAction
label={t("Supprimer {name}", { name: folder.name })}
icon={<TrashIcon className="h-4 w-4" />}
isLoading={removing === folder.id}
tone="danger"
onClick={(event) => {
event.stopPropagation();
void removeTarget({
type: "folder",
id: folder.id,
name: folder.name,
});
}}
/>
</>
) : null}
</div>
</li>
))}
</ul>
</section>
) : null}
{files.length > 0 ? (
<section aria-label={t("Fichiers")}>
<h2 className="mb-2 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
{t("Fichiers")}
</h2>
{visibleFiles.length === 0 ? (
<p className="text-xs text-muted-foreground">
{t("Rien à afficher pour ce filtre.")}
</p>
) : (
<ul className="flex flex-col divide-y divide-border rounded-xl border border-border/50 bg-surface/60 backdrop-blur-md">
{visibleFiles.map((file, index) => (
<li
key={file.id}
onClick={() => toggleSelection(`i:${file.id}`)}
className={cn(
"group flex items-center gap-2 px-3 py-2.5 cursor-pointer",
selected.has(`i:${file.id}`) && "bg-accent/5",
)}
>
<input
type="checkbox"
className={cn(
"h-4 w-4 rounded border-border-control transition-opacity",
selected.has(`i:${file.id}`) ||
selectedItems.length > 0
? "opacity-100"
: "opacity-100 md:opacity-0 md:group-hover:opacity-100 md:focus:opacity-100",
)}
checked={selected.has(`i:${file.id}`)}
aria-label={t("Sélectionner {name}", {
name: file.name,
})}
onClick={(event) => event.stopPropagation()}
onChange={() => toggleSelection(`i:${file.id}`)}
/>
<button
type="button"
onClick={(event) => {
event.stopPropagation();
setViewer(index);
}}
className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-sm border border-border bg-surface-muted text-muted-foreground transition-colors hover:border-border-strong focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none"
aria-label={t("Aperçu de {name}", { name: file.name })}
>
<MediaThumb
id={file.id}
mime={file.mime_type}
name={file.name}
/>
</button>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-foreground">
{file.name}
</span>
<span className="block text-[0.6875rem] text-subtle-foreground">
{formatBytes(file.size_bytes)} ·{" "}
{new Date(file.created_at).toLocaleDateString(
getLocale(),
)}
</span>
</span>
<div className="flex items-center gap-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100 md:focus-within:opacity-100">
<IconAction
label={
file.is_starred
? t("Retirer l'étoile de {name}", {
name: file.name,
})
: t("Étoiler {name}", { name: file.name })
}
icon={
<StarIcon
className={`h-4 w-4 ${file.is_starred ? "text-accent" : "opacity-60"}`}
/>
}
onClick={(event) => {
event.stopPropagation();
void toggleStar(file);
}}
/>
<a
href={fileService.downloadUrl(file.id)}
download={file.name}
aria-label={t("Télécharger {name}", { name: file.name })}
title={t("Télécharger {name}", { name: file.name })}
className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-border/50 bg-surface/60 text-muted-foreground backdrop-blur-sm transition-all hover:-translate-y-0.5 hover:bg-surface/80 hover:text-foreground hover:shadow-sm"
onClick={(event) => event.stopPropagation()}
>
<DownloadIcon className="h-4 w-4" />
</a>
{canWrite ? (
<>
<IconAction
label={t("Renommer {name}", { name: file.name })}
icon={<PenIcon className="h-4 w-4" />}
onClick={(event) => {
event.stopPropagation();
setDialog({
kind: "rename",
target: {
type: "file",
id: file.id,
name: file.name,
},
});
}}
/>
<IconAction
label={t("Supprimer {name}", { name: file.name })}
icon={<TrashIcon className="h-4 w-4" />}
isLoading={removing === file.id}
tone="danger"
onClick={(event) => {
event.stopPropagation();
void removeTarget({
type: "file",
id: file.id,
name: file.name,
});
}}
/>
</>
) : null}
</div>
</li>
))}
</ul>
)}
</section>
) : null}
</div>
)}
{dialog?.kind === "create" ? (
<CreateFolderDialog
parentId={current.id}
onClose={() => setDialog(null)}
onCreated={() => {
setDialog(null);
void reload();
}}
/>
) : null}
{dialog?.kind === "rename" ? (
<RenameDialog
target={dialog.target}
onClose={() => setDialog(null)}
onDone={() => {
setDialog(null);
void reload();
}}
/>
) : null}
{dialog?.kind === "moveMany" ? (
<MoveDialog
targets={dialog.targets}
onClose={() => setDialog(null)}
onDone={() => {
setDialog(null);
clearSelection();
void reload();
void refresh();
}}
/>
) : null}
{dialog?.kind === "share" ? (
<ShareDialog folder={dialog.folder} onClose={() => setDialog(null)} />
) : null}
{viewer !== null ? (
<MediaViewer
items={visibleFiles.map((item) => ({
id: item.id,
name: item.name,
mime_type: item.mime_type,
}))}
startIndex={viewer}
onClose={() => setViewer(null)}
/>
) : null}
{chat ? (
<FolderChat key={chat.id} folder={chat} onClose={closeChat} />
) : null}
</div>
);
};