Files
CoHaiSe-CLOUD/frontend/src/pages/Browser.tsx
T
Esiah 6664677562
PR — Ouverture automatique / create-pr (push) Successful in 3s
feat(ui): visionneuse et vignettes, retrait du popup identifiants, en-tete fige
- MediaViewer (image/video/audio/pdf/texte) et MediaThumb (vignette video 1re frame, icones audio/archive)
- Gallery/Browser cables sur le viewer et les vignettes ; lib/media.ts + previewUrl
- Admin: bandeau de succes au lieu du popup "Identifiants generes"
- AppShell/PageHeader: hauteur fixe du viewport + en-tete de page sticky (filtres, recherche, stats figes)
2026-10-16 15:11:25 +02:00

481 lines
18 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from "react";
import { Button, Card, Spinner } from "../ui/index.js";
import {
ApiError,
api,
formatBytes,
type Folder,
type UploadedFile,
} from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { Alert, Badge, 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 {
CreateFolderDialog,
MoveDialog,
RenameDialog,
ShareDialog,
} from "../components/dialogs.js";
import {
ArrowLeftIcon,
DownloadIcon,
FolderIcon,
MoveIcon,
PenIcon,
PlusIcon,
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: "share"; folder: Folder }
| null;
export const Browser = () => {
const { user, refresh } = useSession();
const confirm = useConfirm();
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 [error, setError] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const [removing, setRemoving] = useState<string | null>(null);
const [dialog, setDialog] = useState<Dialog>(null);
const [viewer, setViewer] = useState<number | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const current = path[path.length - 1] ?? { id: null, name: "Racine" };
const load = useCallback(async (parentId: string | null) => {
setLoading(true);
setError(null);
try {
const [folderResult, fileResult] = await Promise.all([
api.folders(parentId),
api.files(parentId),
]);
setFolders(folderResult.folders);
setFiles(fileResult.files);
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
setFolders([]);
setFiles([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load(current.id);
}, [current.id, load]);
const reload = useCallback(() => load(current.id), [current.id, load]);
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 (selected: FileList | null) => {
if (!selected || selected.length === 0) return;
setUploading(true);
setError(null);
try {
for (const file of Array.from(selected)) {
await api.uploadFile(file, current.id);
}
void refresh();
await reload();
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : "Envoi impossible.");
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
};
const removeTarget = async (target: Target) => {
const label = target.type === "folder" ? "ce dossier" : "ce fichier";
const ok = await confirm({
title: "Mettre à la corbeille",
message: (
<>
Placer <span className="font-semibold text-foreground">{target.name}</span> ({label}) dans la
corbeille ?
</>
),
confirmLabel: "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) {
setError(caught instanceof ApiError ? caught.message : "Suppression impossible.");
} finally {
setRemoving(null);
}
};
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) {
setError(caught instanceof ApiError ? caught.message : "Action impossible.");
}
};
const canWrite = user?.role_slug === "admin" || user?.role_slug === "user";
const empty = folders.length === 0 && files.length === 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">
<PageHeader
title={current.name}
description="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 px-2.5 py-1.5 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground transition-colors duration-fast hover:bg-surface-hover focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none"
>
<ArrowLeftIcon className="h-3.5 w-3.5" />
Retour
</button>
) : null}
<nav aria-label="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">
{crumb.name}
</span>
) : (
<button
type="button"
onClick={() => goTo(index)}
className="text-muted-foreground underline-offset-2 transition-colors hover:text-foreground hover:underline"
>
{crumb.name}
</button>
)}
</li>
))}
</ol>
</nav>
</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">Espace utilisé</span>
<span className="text-xs text-muted-foreground">
{formatBytes(user?.used_bytes ?? 0)} sur {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>
{canWrite ? (
<div className="flex gap-2">
<input
ref={fileInputRef}
type="file"
multiple
className="sr-only"
onChange={(event) => void upload(event.target.files)}
/>
<Button
variant="secondary"
size="sm"
iconLeading={<UploadIcon className="h-3.5 w-3.5" />}
isLoading={uploading}
onClick={() => fileInputRef.current?.click()}
>
Envoyer
</Button>
<Button
variant="secondary"
size="sm"
iconLeading={<PlusIcon className="h-3.5 w-3.5" />}
onClick={() => setDialog({ kind: "create" })}
>
Nouveau dossier
</Button>
</div>
) : null}
</div>
</Card>
{error ? <Alert>{error}</Alert> : null}
{loading ? (
<div className="flex justify-center py-16">
<Spinner size="md" />
</div>
) : empty ? (
<EmptyState
icon={<FolderIcon className="h-8 w-8" />}
title="Emplacement vide"
description="Créez un sous-dossier ou envoyez un fichier pour commencer."
/>
) : (
<div className="flex flex-col gap-6">
{folders.length > 0 ? (
<section aria-label="Dossiers">
<h2 className="mb-2 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
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}
className="flex items-center gap-1 rounded-lg border border-border bg-surface p-2 transition-colors hover:border-border-strong hover:bg-surface-hover"
>
<button
type="button"
onClick={() => 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">
<FolderIcon className="h-5 w-5" />
</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 flex items-center gap-2">
{folder.is_system ? <Badge>Système</Badge> : null}
{folder.access_type === "public" ? (
<Badge tone="accent">Public</Badge>
) : null}
<span className="text-[0.6875rem] text-subtle-foreground">
{new Date(folder.created_at).toLocaleDateString("fr-FR")}
</span>
</span>
</span>
</button>
{canWrite ? (
<div className="flex shrink-0 items-center gap-0.5">
<IconAction
label={`Partager ${folder.name}`}
icon={<ShareIcon className="h-4 w-4" />}
onClick={() => setDialog({ kind: "share", folder })}
/>
<IconAction
label={`Renommer ${folder.name}`}
icon={<PenIcon className="h-4 w-4" />}
onClick={() =>
setDialog({
kind: "rename",
target: { type: "folder", id: folder.id, name: folder.name },
})
}
/>
<IconAction
label={`Déplacer ${folder.name}`}
icon={<MoveIcon className="h-4 w-4" />}
onClick={() =>
setDialog({
kind: "move",
target: { type: "folder", id: folder.id, name: folder.name },
})
}
/>
<IconAction
label={`Supprimer ${folder.name}`}
icon={<TrashIcon className="h-4 w-4" />}
isLoading={removing === folder.id}
tone="danger"
onClick={() =>
void removeTarget({ type: "folder", id: folder.id, name: folder.name })
}
/>
</div>
) : null}
</li>
))}
</ul>
</section>
) : null}
{files.length > 0 ? (
<section aria-label="Fichiers">
<h2 className="mb-2 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
Fichiers
</h2>
<ul className="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
{files.map((file, index) => (
<li key={file.id} className="flex items-center gap-2 px-3 py-2.5">
<button
type="button"
onClick={() => 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={`Aperçu de ${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("fr-FR")}
</span>
</span>
<IconAction
label={file.is_starred ? `Retirer l'étoile de ${file.name}` : `Étoiler ${file.name}`}
icon={
<StarIcon className="h-4 w-4" {...(file.is_starred ? { filled: true } : {})} />
}
onClick={() => void toggleStar(file)}
/>
<a
href={api.downloadUrl(file.id)}
download={file.name}
className="inline-flex h-8 items-center gap-1.5 rounded-sm border border-border-strong bg-surface px-3 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground transition-colors hover:bg-surface-hover"
>
<DownloadIcon className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Télécharger</span>
</a>
{canWrite ? (
<>
<IconAction
label={`Renommer ${file.name}`}
icon={<PenIcon className="h-4 w-4" />}
onClick={() =>
setDialog({
kind: "rename",
target: { type: "file", id: file.id, name: file.name },
})
}
/>
<IconAction
label={`Déplacer ${file.name}`}
icon={<MoveIcon className="h-4 w-4" />}
onClick={() =>
setDialog({
kind: "move",
target: { type: "file", id: file.id, name: file.name },
})
}
/>
<IconAction
label={`Supprimer ${file.name}`}
icon={<TrashIcon className="h-4 w-4" />}
isLoading={removing === file.id}
tone="danger"
onClick={() =>
void removeTarget({ type: "file", id: file.id, name: file.name })
}
/>
</>
) : null}
</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 === "move" ? (
<MoveDialog
target={dialog.target}
onClose={() => setDialog(null)}
onDone={() => {
setDialog(null);
void reload();
}}
/>
) : null}
{dialog?.kind === "share" ? (
<ShareDialog folder={dialog.folder} onClose={() => setDialog(null)} />
) : null}
{viewer !== null ? (
<MediaViewer
items={files.map((item) => ({ id: item.id, name: item.name, mime_type: item.mime_type }))}
startIndex={viewer}
onClose={() => setViewer(null)}
/>
) : null}
</div>
);
};