Files
CoHaiSe-CLOUD/frontend/src/components/dialogs.tsx
T
Esiah 5e612653da feat(frontend): i18n, theming and account/browser/admin UI updates
- add French-keyed i18n with an English dictionary, plus theme and locale
  helpers, applied across all pages and components
- account page: theme and language selectors and a two-column layout
- browser: per-folder media type filters and unread chat badges
- admin: audit log filtered by user and action through dropdowns
- global API and type updates to match the new backend endpoints
2026-10-17 14:33:21 +02:00

413 lines
14 KiB
TypeScript

import { useEffect, useState, type FormEvent } from "react";
import { Button, Input, cn } from "../ui/index.js";
import {
ApiError,
api,
formatDate,
type DirectoryUser,
type Folder,
type FolderPermission,
} from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { Alert, Modal } from "./feedback.js";
import { TrashIcon } from "./icons.js";
const LEVELS = ["read", "write", "admin"] as const;
const LEVEL_LABEL: Record<string, string> = {
read: "Lecture",
write: "Écriture",
admin: "Administration",
};
const messageOf = (caught: unknown, fallback: string): string =>
caught instanceof ApiError ? caught.message : fallback;
interface Target {
type: "folder" | "file";
id: string;
name: string;
}
export const CreateFolderDialog = ({
parentId,
onClose,
onCreated,
}: {
parentId: string | null;
onClose: () => void;
onCreated: () => void;
}) => {
const { t } = useI18n();
const [name, setName] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setBusy(true);
setError(null);
try {
await api.createFolder(name, parentId);
onCreated();
} catch (caught) {
setError(messageOf(caught, t("Création impossible.")));
} finally {
setBusy(false);
}
};
return (
<Modal open title={t("Nouveau dossier")} onClose={onClose}>
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
<Input
label={t("Nom")}
required
maxLength={255}
autoFocus
placeholder={t("Contrats 2026")}
value={name}
onChange={(event) => setName(event.target.value)}
/>
{error ? <Alert>{error}</Alert> : null}
<div className="flex justify-end gap-2">
<Button variant="ghost" size="md" onClick={onClose}>
{t("Annuler")}
</Button>
<Button type="submit" size="md" isLoading={busy}>
{t("Créer")}
</Button>
</div>
</form>
</Modal>
);
};
export const RenameDialog = ({
target,
onClose,
onDone,
}: {
target: Target;
onClose: () => void;
onDone: () => void;
}) => {
const { t } = useI18n();
const [name, setName] = useState(target.name);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setBusy(true);
setError(null);
try {
if (target.type === "folder") await api.updateFolder(target.id, name);
else await api.renameFile(target.id, name);
onDone();
} catch (caught) {
setError(messageOf(caught, t("Renommage impossible.")));
} finally {
setBusy(false);
}
};
return (
<Modal open title={t("Renommer")} onClose={onClose}>
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
<Input
label={t("Nom")}
required
maxLength={255}
autoFocus
value={name}
onChange={(event) => setName(event.target.value)}
/>
{error ? <Alert>{error}</Alert> : null}
<div className="flex justify-end gap-2">
<Button variant="ghost" size="md" onClick={onClose}>
{t("Annuler")}
</Button>
<Button type="submit" size="md" isLoading={busy}>
{t("Enregistrer")}
</Button>
</div>
</form>
</Modal>
);
};
interface TreeEntry {
id: string;
label: string;
}
const loadTree = async (): Promise<TreeEntry[]> => {
const entries: TreeEntry[] = [];
const walk = async (parentId: string | null, prefix: string, depth: number): Promise<void> => {
if (depth > 6) return;
const { folders } = await api.folders(parentId);
for (const folder of folders) {
entries.push({ id: folder.id, label: `${prefix}${folder.name}` });
await walk(folder.id, `${prefix}${folder.name} / `, depth + 1);
}
};
await walk(null, "", 0);
return entries;
};
export const MoveDialog = ({
target,
onClose,
onDone,
}: {
target: Target;
onClose: () => void;
onDone: () => void;
}) => {
const { t } = useI18n();
const [entries, setEntries] = useState<TreeEntry[] | null>(null);
const [destination, setDestination] = useState<string>("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
loadTree()
.then(setEntries)
.catch((caught: unknown) => setError(messageOf(caught, t("Chargement des dossiers impossible."))));
}, []);
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setBusy(true);
setError(null);
const parentId = destination === "" ? null : destination;
try {
if (target.type === "folder") await api.moveFolder(target.id, parentId);
else await api.moveFile(target.id, parentId);
onDone();
} catch (caught) {
setError(messageOf(caught, t("Déplacement impossible.")));
} finally {
setBusy(false);
}
};
return (
<Modal open title={t("Déplacer")} onClose={onClose}>
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
<p className="text-sm text-muted-foreground">
{t("Destination de {name}.", { name: target.name })}
</p>
{entries === null && !error ? (
<Alert tone="info">{t("Chargement des dossiers…")}</Alert>
) : (
<label className="flex flex-col gap-1.5">
<span className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground">
{t("Destination")}
</span>
<select
value={destination}
onChange={(event) => setDestination(event.target.value)}
className={cn(
"h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground",
"focus-visible:ring-ring focus-visible:border-border-strong focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none",
)}
>
<option value="">{t("Racine")}</option>
{(entries ?? [])
.filter((entry) => entry.id !== target.id)
.map((entry) => (
<option key={entry.id} value={entry.id}>
{entry.label}
</option>
))}
</select>
</label>
)}
{error ? <Alert>{error}</Alert> : null}
<div className="flex justify-end gap-2">
<Button variant="ghost" size="md" onClick={onClose}>
{t("Annuler")}
</Button>
<Button type="submit" size="md" isLoading={busy} disabled={entries === null}>
{t("Déplacer")}
</Button>
</div>
</form>
</Modal>
);
};
export const ShareDialog = ({
folder,
onClose,
}: {
folder: Folder;
onClose: () => void;
}) => {
const { t } = useI18n();
const [permissions, setPermissions] = useState<FolderPermission[] | null>(null);
const [members, setMembers] = useState<DirectoryUser[] | null>(null);
const [email, setEmail] = useState("");
const [level, setLevel] = useState<string>("read");
const [expiresAt, setExpiresAt] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const load = async () => {
try {
const [{ permissions: list }, { users }] = await Promise.all([
api.folderPermissions(folder.id),
api.directory(),
]);
setPermissions(list);
setMembers(users);
setError(null);
} catch (caught) {
setError(messageOf(caught, t("Chargement des partages impossible.")));
setPermissions([]);
setMembers([]);
}
};
useEffect(() => {
void load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [folder.id]);
const candidates = (members ?? []).filter(
(member) => !(permissions ?? []).some((permission) => permission.user_id === member.id),
);
const grant = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setBusy(true);
setError(null);
try {
const iso = expiresAt ? new Date(expiresAt).toISOString() : null;
await api.grantPermission(folder.id, email, level, expiresAt ? iso : null);
setEmail("");
setExpiresAt("");
await load();
} catch (caught) {
setError(messageOf(caught, t("Partage impossible.")));
} finally {
setBusy(false);
}
};
const revoke = async (userId: string) => {
setError(null);
try {
await api.revokePermission(folder.id, userId);
await load();
} catch (caught) {
setError(messageOf(caught, t("Révocation impossible.")));
}
};
return (
<Modal open title={t("Partager « {name} »", { name: folder.name })} onClose={onClose}>
<div className="flex flex-col gap-5">
<form className="flex flex-col gap-3" onSubmit={(event) => void grant(event)}>
<label className="flex flex-col gap-1.5">
<span className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground">
{t("Membre")}
</span>
<select
value={email}
autoFocus
required
disabled={candidates.length === 0}
onChange={(event) => setEmail(event.target.value)}
className="h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground focus-visible:ring-ring focus-visible:border-border-strong focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none"
>
<option value="" disabled>
{t("Choisir un membre")}
</option>
{candidates.map((member) => (
<option key={member.id} value={member.email}>
{member.first_name} {member.last_name} ({member.email})
</option>
))}
</select>
</label>
{members !== null && candidates.length === 0 && permissions !== null ? (
<p className="text-xs text-muted-foreground">{t("Aucun autre membre à ajouter.")}</p>
) : null}
<div className="grid grid-cols-2 gap-3">
<label className="flex flex-col gap-1.5">
<span className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground">
{t("Niveau")}
</span>
<select
value={level}
onChange={(event) => setLevel(event.target.value)}
className="h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground focus-visible:ring-ring focus-visible:border-border-strong focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none"
>
{LEVELS.map((value) => (
<option key={value} value={value}>
{t(LEVEL_LABEL[value] ?? value)}
</option>
))}
</select>
</label>
<Input
label={t("Expire le")}
type="date"
value={expiresAt}
onChange={(event) => setExpiresAt(event.target.value)}
/>
</div>
{error ? <Alert>{error}</Alert> : null}
<div className="flex justify-end">
<Button type="submit" size="md" isLoading={busy} disabled={candidates.length === 0}>
{t("Autoriser")}
</Button>
</div>
</form>
<div>
<h3 className="mb-2 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
{t("Accès accordés")}
</h3>
{permissions === null ? (
<Alert tone="info">{t("Chargement…")}</Alert>
) : permissions.length === 0 ? (
<p className="text-xs text-muted-foreground">{t("Aucun partage pour ce dossier.")}</p>
) : (
<ul className="flex flex-col divide-y divide-border rounded-md border border-border">
{permissions.map((permission) => (
<li key={permission.user_id} className="flex items-center gap-3 px-3 py-2">
<span className="min-w-0 flex-1">
<span className="block truncate text-xs font-medium text-foreground">
{permission.first_name} {permission.last_name}
</span>
<span className="block truncate text-[0.6875rem] text-subtle-foreground">
{permission.email} ·{" "}
{permission.expires_at
? t("{level} · jusqu'au {date}", {
level: t(LEVEL_LABEL[permission.level] ?? permission.level),
date: formatDate(permission.expires_at),
})
: t(LEVEL_LABEL[permission.level] ?? permission.level)}
</span>
</span>
<button
type="button"
aria-label={t("Révoquer {email}", { email: permission.email })}
onClick={() => void revoke(permission.user_id)}
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:text-destructive"
>
<TrashIcon className="h-4 w-4" />
</button>
</li>
))}
</ul>
)}
</div>
</div>
</Modal>
);
};