Files
CoHaiSe-CLOUD/frontend/src/pages/Browser.tsx
T
Gitea ActionsandEsiah a82711c9b1
CD — Deployment / deploy (push) Successful in 16s
refactor(ui): switch icons to WebP and standardize icon-only actions (#22)
- Replace PNG icon assets with WebP in public/icons
- Route every icon through icons.tsx and add missing exports
  (Clear, Save, OpenedFolder, Deactivate, PasswordReset, TrashEmpty, Filter)
- Replace text buttons with icon-only actions backed by tooltips
- Unify confirm/delete/primary dialog buttons on the accent red
- Use liquid glass hover on chat messages

---------

Co-authored-by: xEsiah <[email protected]>
Reviewed-on: #22
Reviewed-by: Esiah <[email protected]>
Co-authored-by: Gitea Actions <-[email protected]>
2026-11-04 10:44:43 +00:00

1047 lines
39 KiB
TypeScript

import {
useCallback,
useEffect,
useRef,
useState,
type DragEvent,
} from "react";
import { Card, Spinner, cn } from "../ui/index.js";
import {
ApiError,
api,
formatBytes,
type Folder,
type UploadedFile,
} from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.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;
// Rafraichissement de l'explorateur : un autre compte peut deposer ou
// supprimer un fichier dans un dossier partage sans prevenir.
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);
// Depot par glisser-deposer : `dragDepth` compte les entrees et sorties
// successives. La garde `stillInside` evite en plus que la zone clignote
// quand le pointeur passe d'un element enfant a un autre.
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([
api.folders(parentId),
api.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.");
// Un rafraichissement automatique echoue en silence : pas de toast
// toutes les minutes si le reseau tombe pendant la consultation.
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 api.chatUnread();
setUnread(counts);
} catch {
/* les pastilles sont un confort : un echec ne bloque pas l'explorateur */
}
}, []);
useEffect(() => {
void load(current.id);
}, [current.id, load]);
useEffect(() => {
void refreshUnread();
}, [current.id, refreshUnread]);
// Un autre compte peut deposer ou supprimer un fichier dans un dossier
// partage : la vue se resynchronise d'elle-meme tant que l'onglet est actif.
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]);
// Le filtre de type n'est propre qu'au dossier affiche : on repart sur
// « Tout » a chaque navigation, faute de voir un dossier vide pour rien.
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 api.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 = "";
}
};
/**
* Depot d'un lot de fichiers dans un dossier precis. Le dossier peut etre le
* dossier affiche ou l'un des sous-dossiers listes ; le serveur revalide les
* droits d'ecriture dans tous les cas.
*/
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 api.uploadFile(f, folderId, (loaded) => update(i + 1, loaded));
completedBytes += f.size;
}
void refresh();
// Seule la vue courante est rechargée : un depot dans un sous-dossier ne
// change rien a l'ecran tant qu'on ne l'ouvre pas.
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);
}
};
/** Le glisser porte-t-il des fichiers (et non du texte ou une URL) ? */
const carriesFiles = (event: DragEvent): boolean =>
Array.from(event.dataTransfer.types).includes("Files");
/**
* Le pointeur est-il reste dans la zone qui recoit l'evenement ? Vrai quand
* le pointeur passe d'un enfant a un autre : sans cette garde, la zone
* clignoterait a chaque changement d element.
*/
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;
// Sans preventDefault le navigateur refuse le depot.
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);
};
/** Cible precise : un sous-dossier de la liste courante. */
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 api.deleteFolder(target.id);
} else {
await api.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 api.deleteFolder(target.id);
else await api.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 api.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}
{/* Alerts replaced by toasts */}
{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 = api.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={api.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>
);
};