chore: initial import of CoHaiSe Cloud
PR — Ouverture automatique / create-pr (push) Failing after 1s
PR — Ouverture automatique / create-pr (push) Failing after 1s
Standalone files & media application: React/Vite frontend with the @cohaise/ui design system, Hono + MariaDB backend, nginx reverse proxy, Docker Compose stack, migrations 000-006, and project docs. Adds Gitea Actions workflows for deployment, automatic pull requests, and Renovate dependency updates.
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<title>CoHaiSe Cloud</title>
|
||||
<script src="/theme.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@cohaise/cloud-web",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cohaise/ui": "*",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router-dom": "^7.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^7.0.2",
|
||||
"vite": "^8.3.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
(function () {
|
||||
try {
|
||||
var stored = localStorage.getItem("cohaise-theme");
|
||||
var prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
var theme = stored || (prefersDark ? "dark" : "light");
|
||||
if (theme === "dark") document.documentElement.classList.add("dark");
|
||||
} catch (error) {
|
||||
void error;
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Navigate, Outlet, Route, Routes } from "react-router-dom";
|
||||
import { Spinner } from "@cohaise/ui";
|
||||
import { useSession } from "./lib/session.js";
|
||||
import { AppShell } from "./components/AppShell.js";
|
||||
import { Login } from "./pages/Login.js";
|
||||
import { ForgotPassword } from "./pages/ForgotPassword.js";
|
||||
import { ResetPassword } from "./pages/ResetPassword.js";
|
||||
import { ConfirmEmail } from "./pages/ConfirmEmail.js";
|
||||
import { ChangePassword } from "./pages/ChangePassword.js";
|
||||
import { Browser } from "./pages/Browser.js";
|
||||
import { Search } from "./pages/Search.js";
|
||||
import { Gallery } from "./pages/Gallery.js";
|
||||
import { Trash } from "./pages/Trash.js";
|
||||
import { Profile } from "./pages/Profile.js";
|
||||
import { AdminUsers, AdminStorage, AdminAudit } from "./pages/Admin.js";
|
||||
|
||||
const RequireAuth = () => {
|
||||
const { user, loading } = useSession();
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center bg-background">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!user) return <Navigate to="/login" replace />;
|
||||
return <Outlet />;
|
||||
};
|
||||
|
||||
const RequireReady = () => {
|
||||
const { user } = useSession();
|
||||
if (user?.must_change_password) return <Navigate to="/change-password" replace />;
|
||||
return <Outlet />;
|
||||
};
|
||||
|
||||
const RequireAdmin = () => {
|
||||
const { user } = useSession();
|
||||
if (!user || user.role_slug !== "admin") return <Navigate to="/files" replace />;
|
||||
return <Outlet />;
|
||||
};
|
||||
|
||||
export const App = () => (
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/forgot-password" element={<ForgotPassword />} />
|
||||
<Route path="/reset-password" element={<ResetPassword />} />
|
||||
<Route path="/confirm-email" element={<ConfirmEmail />} />
|
||||
|
||||
<Route element={<RequireAuth />}>
|
||||
<Route path="/change-password" element={<ChangePassword />} />
|
||||
|
||||
<Route element={<RequireReady />}>
|
||||
<Route element={<AppShell />}>
|
||||
<Route path="/files" element={<Browser />} />
|
||||
<Route path="/search" element={<Search />} />
|
||||
<Route path="/gallery" element={<Gallery />} />
|
||||
<Route path="/trash" element={<Trash />} />
|
||||
<Route path="/profile" element={<Profile />} />
|
||||
</Route>
|
||||
|
||||
<Route element={<RequireAdmin />}>
|
||||
<Route element={<AppShell />}>
|
||||
<Route path="/admin/comptes" element={<AdminUsers />} />
|
||||
<Route path="/admin/stockage" element={<AdminStorage />} />
|
||||
<Route path="/admin/audit" element={<AdminAudit />} />
|
||||
</Route>
|
||||
</Route>
|
||||
</Route>
|
||||
</Route>
|
||||
|
||||
<Route path="*" element={<Navigate to="/files" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useState } from "react";
|
||||
import { NavLink, Outlet } from "react-router-dom";
|
||||
import { Button, cn } from "@cohaise/ui";
|
||||
import { useSession } from "../lib/session.js";
|
||||
import {
|
||||
ActivityIcon,
|
||||
CloseIcon,
|
||||
FolderIcon,
|
||||
HardDriveIcon,
|
||||
ImageIcon,
|
||||
LogoutIcon,
|
||||
MenuIcon,
|
||||
SearchNavIcon,
|
||||
SettingsIcon,
|
||||
ShieldIcon,
|
||||
TrashIcon,
|
||||
} from "./icons.js";
|
||||
|
||||
interface NavItem {
|
||||
to: string;
|
||||
label: string;
|
||||
icon: typeof FolderIcon;
|
||||
}
|
||||
|
||||
const NAV: NavItem[] = [
|
||||
{ to: "/files", label: "Fichiers", icon: FolderIcon },
|
||||
{ to: "/search", label: "Recherche", icon: SearchNavIcon },
|
||||
{ to: "/gallery", label: "Galerie", icon: ImageIcon },
|
||||
{ to: "/trash", label: "Corbeille", icon: TrashIcon },
|
||||
];
|
||||
|
||||
const ADMIN_NAV: NavItem[] = [
|
||||
{ to: "/admin/comptes", label: "Comptes", icon: ShieldIcon },
|
||||
{ to: "/admin/stockage", label: "Stockage", icon: HardDriveIcon },
|
||||
{ to: "/admin/audit", label: "Journal", icon: ActivityIcon },
|
||||
];
|
||||
|
||||
const ACCOUNT_NAV: NavItem = { to: "/profile", label: "Mon compte", icon: SettingsIcon };
|
||||
|
||||
const initials = (first: string, last: string): string =>
|
||||
`${first.charAt(0)}${last.charAt(0)}`.toUpperCase() || "?";
|
||||
|
||||
const navClass = ({ isActive }: { isActive: boolean }) =>
|
||||
cn(
|
||||
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
|
||||
isActive
|
||||
? "bg-accent/10 text-accent"
|
||||
: "text-muted-foreground hover:bg-surface-hover hover:text-foreground",
|
||||
);
|
||||
|
||||
export const AppShell = () => {
|
||||
const { user, logout } = useSession();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
if (!user) return null;
|
||||
|
||||
const isAdmin = user.role_slug === "admin";
|
||||
const allNav = [...NAV, ...(isAdmin ? ADMIN_NAV : []), ACCOUNT_NAV];
|
||||
|
||||
const brand = (
|
||||
<NavLink to="/files" className="flex items-center gap-2" onClick={() => setMenuOpen(false)}>
|
||||
<span className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
</span>
|
||||
<span className="text-border" aria-hidden="true">
|
||||
/
|
||||
</span>
|
||||
<span className="font-display text-xs font-semibold uppercase tracking-label text-foreground">
|
||||
Cloud
|
||||
</span>
|
||||
</NavLink>
|
||||
);
|
||||
|
||||
const renderLink = (item: NavItem) => {
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<NavLink key={item.to} to={item.to} className={navClass} onClick={() => setMenuOpen(false)}>
|
||||
<Icon className="h-4 w-4" />
|
||||
{item.label}
|
||||
</NavLink>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-dvh bg-background">
|
||||
<aside className="hidden w-60 shrink-0 flex-col gap-1 border-r border-border bg-surface p-3 lg:flex">
|
||||
<div className="px-1 py-2">{brand}</div>
|
||||
{NAV.map(renderLink)}
|
||||
{isAdmin ? (
|
||||
<>
|
||||
<p className="mt-3 px-3 py-1 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
|
||||
Administration
|
||||
</p>
|
||||
{ADMIN_NAV.map(renderLink)}
|
||||
</>
|
||||
) : null}
|
||||
<div className="mt-auto pt-3">{renderLink(ACCOUNT_NAV)}</div>
|
||||
</aside>
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<header className="sticky top-0 z-20 border-b border-border bg-surface">
|
||||
<div className="mx-auto flex w-full max-w-5xl items-center justify-between gap-4 px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground lg:hidden"
|
||||
aria-label={menuOpen ? "Fermer le menu" : "Ouvrir le menu"}
|
||||
aria-expanded={menuOpen}
|
||||
onClick={() => setMenuOpen((value) => !value)}
|
||||
>
|
||||
{menuOpen ? <CloseIcon className="h-5 w-5" /> : <MenuIcon className="h-5 w-5" />}
|
||||
</button>
|
||||
<span className="lg:hidden">{brand}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="hidden text-right sm:block">
|
||||
<p className="text-xs font-medium text-foreground">
|
||||
{user.first_name} {user.last_name}
|
||||
</p>
|
||||
<p className="text-[0.6875rem] uppercase tracking-label text-subtle-foreground">
|
||||
{user.role_name}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-border bg-surface text-xs font-semibold text-foreground"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{initials(user.first_name, user.last_name)}
|
||||
</span>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
iconLeading={<LogoutIcon className="h-3.5 w-3.5" />}
|
||||
onClick={() => void logout()}
|
||||
>
|
||||
<span className="hidden sm:inline">Déconnexion</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{menuOpen ? (
|
||||
<nav className="flex flex-col gap-1 border-t border-border px-3 py-2 lg:hidden">
|
||||
{allNav.map(renderLink)}
|
||||
</nav>
|
||||
) : null}
|
||||
</header>
|
||||
|
||||
<main className="mx-auto w-full max-w-5xl flex-1 px-4 py-6">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Spinner, cn } from "@cohaise/ui";
|
||||
|
||||
export const IconAction = ({
|
||||
label,
|
||||
icon,
|
||||
onClick,
|
||||
isLoading = false,
|
||||
tone = "neutral",
|
||||
}: {
|
||||
label: string;
|
||||
icon: ReactNode;
|
||||
onClick: () => void;
|
||||
isLoading?: boolean;
|
||||
tone?: "neutral" | "danger";
|
||||
}) => (
|
||||
<button
|
||||
type="button"
|
||||
title={label}
|
||||
aria-label={label}
|
||||
disabled={isLoading}
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors",
|
||||
"hover:bg-surface-hover hover:text-foreground disabled:pointer-events-none disabled:opacity-50",
|
||||
tone === "danger" && "hover:text-destructive",
|
||||
)}
|
||||
>
|
||||
{isLoading ? <Spinner size="xs" /> : icon}
|
||||
</button>
|
||||
);
|
||||
@@ -0,0 +1,381 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { Button, Input, cn } from "@cohaise/ui";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatDate,
|
||||
type Folder,
|
||||
type FolderPermission,
|
||||
} from "../lib/api.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 [name, setName] = useState("");
|
||||
const [description, setDescription] = 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, description.trim() || undefined);
|
||||
onCreated();
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Création impossible."));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open title="Nouveau dossier" onClose={onClose}>
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Nom"
|
||||
required
|
||||
maxLength={255}
|
||||
autoFocus
|
||||
placeholder="Contrats 2026"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Description (optionnelle)"
|
||||
maxLength={2000}
|
||||
value={description}
|
||||
onChange={(event) => setDescription(event.target.value)}
|
||||
/>
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="ghost" size="md" onClick={onClose}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button type="submit" size="md" isLoading={busy}>
|
||||
Créer
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export const RenameDialog = ({
|
||||
target,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
target: Target;
|
||||
onClose: () => void;
|
||||
onDone: () => void;
|
||||
}) => {
|
||||
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, "Renommage impossible."));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open title="Renommer" onClose={onClose}>
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="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}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button type="submit" size="md" isLoading={busy}>
|
||||
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 [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, "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, "Déplacement impossible."));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open title="Déplacer" onClose={onClose}>
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Destination de <span className="font-medium text-foreground">{target.name}</span>.
|
||||
</p>
|
||||
{entries === null && !error ? (
|
||||
<Alert tone="info">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">
|
||||
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="">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}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button type="submit" size="md" isLoading={busy} disabled={entries === null}>
|
||||
Déplacer
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export const ShareDialog = ({
|
||||
folder,
|
||||
onClose,
|
||||
}: {
|
||||
folder: Folder;
|
||||
onClose: () => void;
|
||||
}) => {
|
||||
const [permissions, setPermissions] = useState<FolderPermission[] | 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 } = await api.folderPermissions(folder.id);
|
||||
setPermissions(list);
|
||||
setError(null);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Chargement des partages impossible."));
|
||||
setPermissions([]);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [folder.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, "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, "Révocation impossible."));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open title={`Partager « ${folder.name} »`} onClose={onClose}>
|
||||
<div className="flex flex-col gap-5">
|
||||
<form className="flex flex-col gap-3" onSubmit={(event) => void grant(event)}>
|
||||
<Input
|
||||
label="Adresse e-mail du membre"
|
||||
type="email"
|
||||
required
|
||||
autoFocus
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
/>
|
||||
<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">
|
||||
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}>
|
||||
{LEVEL_LABEL[value]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<Input
|
||||
label="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}>
|
||||
Autoriser
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div>
|
||||
<h3 className="mb-2 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
|
||||
Accès accordés
|
||||
</h3>
|
||||
{permissions === null ? (
|
||||
<Alert tone="info">Chargement…</Alert>
|
||||
) : permissions.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">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} · {LEVEL_LABEL[permission.level] ?? permission.level}
|
||||
{permission.expires_at ? ` · jusqu'au ${formatDate(permission.expires_at)}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Révoquer ${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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { cn } from "@cohaise/ui";
|
||||
import { CloseIcon } from "./icons.js";
|
||||
|
||||
export const Modal = ({
|
||||
open,
|
||||
title,
|
||||
onClose,
|
||||
children,
|
||||
}: {
|
||||
open: boolean;
|
||||
title: string;
|
||||
onClose: () => void;
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||
<div
|
||||
className="absolute inset-0 bg-black/40"
|
||||
onClick={onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
className="relative w-full max-w-md rounded-lg border border-border bg-surface p-4 shadow-lg"
|
||||
>
|
||||
<div className="mb-4 flex items-center justify-between gap-4">
|
||||
<h2 className="font-display text-xs font-semibold uppercase tracking-label text-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Fermer"
|
||||
className="text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<CloseIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
export const Alert = ({
|
||||
children,
|
||||
tone = "error",
|
||||
className,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
tone?: "error" | "success" | "info";
|
||||
className?: string;
|
||||
}) => (
|
||||
<p
|
||||
role="alert"
|
||||
className={cn(
|
||||
"rounded-md border px-3 py-2 text-xs leading-relaxed",
|
||||
tone === "error" && "border-destructive/40 bg-destructive/10 text-destructive",
|
||||
tone === "success" && "border-accent/40 bg-accent/10 text-accent",
|
||||
tone === "info" && "border-border bg-surface text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</p>
|
||||
);
|
||||
|
||||
export const PageHeader = ({
|
||||
title,
|
||||
description,
|
||||
actions,
|
||||
}: {
|
||||
title: string;
|
||||
description?: string;
|
||||
actions?: ReactNode;
|
||||
}) => (
|
||||
<header className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div>
|
||||
<h1 className="font-display text-base font-semibold uppercase tracking-label text-foreground">
|
||||
{title}
|
||||
</h1>
|
||||
{description ? (
|
||||
<p className="mt-1 max-w-2xl text-sm leading-relaxed text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
{actions ? <div className="flex flex-wrap items-center gap-2">{actions}</div> : null}
|
||||
</header>
|
||||
);
|
||||
|
||||
export const EmptyState = ({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
}: {
|
||||
icon?: ReactNode;
|
||||
title: string;
|
||||
description?: string;
|
||||
action?: ReactNode;
|
||||
}) => (
|
||||
<div className="flex flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border-control py-16 text-center">
|
||||
{icon ? <span className="text-subtle-foreground">{icon}</span> : null}
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-label text-foreground">
|
||||
{title}
|
||||
</p>
|
||||
{description ? (
|
||||
<p className="max-w-xs text-sm leading-relaxed text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
|
||||
export const Badge = ({
|
||||
children,
|
||||
tone = "neutral",
|
||||
}: {
|
||||
children: ReactNode;
|
||||
tone?: "neutral" | "accent" | "warning" | "danger";
|
||||
}) => (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-sm border px-1.5 py-0.5 font-display text-[0.625rem] font-semibold uppercase tracking-label",
|
||||
tone === "neutral" && "border-border-strong text-muted-foreground",
|
||||
tone === "accent" && "border-accent/50 bg-accent/10 text-accent",
|
||||
tone === "warning" && "border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400",
|
||||
tone === "danger" && "border-destructive/40 bg-destructive/10 text-destructive",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
@@ -0,0 +1,160 @@
|
||||
import type { SVGProps } from "react";
|
||||
|
||||
type IconProps = SVGProps<SVGSVGElement>;
|
||||
|
||||
const base = (props: IconProps) => ({
|
||||
viewBox: "0 0 24 24",
|
||||
fill: "none",
|
||||
stroke: "currentColor",
|
||||
strokeWidth: 1.6,
|
||||
strokeLinecap: "round" as const,
|
||||
strokeLinejoin: "round" as const,
|
||||
"aria-hidden": true,
|
||||
...props,
|
||||
});
|
||||
|
||||
export const FolderIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M3 7.5A1.5 1.5 0 0 1 4.5 6h4l2 2.5h7A1.5 1.5 0 0 1 19 10v7.5A1.5 1.5 0 0 1 17.5 19h-13A1.5 1.5 0 0 1 3 17.5Z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const FileIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M6 3.5h7l5 5v12A1.5 1.5 0 0 1 16.5 22h-10A1.5 1.5 0 0 1 5 20.5v-16A1.5 1.5 0 0 1 6 3Z" />
|
||||
<path d="M13 3.5v5h5" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const ImageIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<rect x="3" y="4" width="18" height="16" rx="2" />
|
||||
<circle cx="8.5" cy="9.5" r="1.5" />
|
||||
<path d="m4 17 4.5-4.5a1.5 1.5 0 0 1 2.1 0L15 17m1.5-2 1.2-1.2a1.5 1.5 0 0 1 2.1 0L21 15" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const UploadIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5M4 17v1.5A1.5 1.5 0 0 0 5.5 20h13a1.5 1.5 0 0 0 1.5-1.5V17" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const DownloadIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M12 4v12m0 0-4.5-4.5M12 16l4.5-4.5M4 17v1.5A1.5 1.5 0 0 0 5.5 20h13a1.5 1.5 0 0 0 1.5-1.5V17" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const PlusIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M12 5v14M5 12h14" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const TrashIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M4 7h16M9 7V5.5A1.5 1.5 0 0 1 10.5 4h3A1.5 1.5 0 0 1 15 5.5V7m-8 0 .7 11.1A1.5 1.5 0 0 0 9.2 19.6h5.6a1.5 1.5 0 0 0 1.5-1.5L17 7" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const RestoreIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const StarIcon = ({ filled, ...props }: IconProps & { filled?: boolean }) => (
|
||||
<svg {...base(props)} fill={filled ? "currentColor" : "none"}>
|
||||
<path d="m12 3.5 2.6 5.3 5.9.9-4.2 4.1 1 5.8L12 20.8l-5.3 2.8 1-5.8L3.5 14l5.9-.9Z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const SearchIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<circle cx="11" cy="11" r="7" />
|
||||
<path d="m20 20-3.5-3.5" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const UsersIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<circle cx="9" cy="8" r="3.5" />
|
||||
<path d="M3.5 20a5.5 5.5 0 0 1 11 0M16 5.5a3 3 0 0 1 0 6M16.5 20a5.5 1.5 0 0 0-2.2-4.3" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const SettingsIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2 2 2 0 1 1-4 0 1.7 1.7 0 0 0-2.9-1.2l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.7 1.7 0 0 0 2.6 15a2 2 0 1 1 0-4 1.7 1.7 0 0 0 1.2-2.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.7 1.7 0 0 0 9 4.6a2 2 0 1 1 4 0 1.7 1.7 0 0 0 2.9 1.2l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0 1.2 2.9 2 2 0 1 1 0 4 1.7 1.7 0 0 0-1.5 1Z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const LogoutIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M15 4h2.5A1.5 1.5 0 0 1 19 5.5v13a1.5 1.5 0 0 1-1.5 1.5H15M10 8l-4 4 4 4M6 12h9" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const ShieldIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M12 3 5 6v5c0 4.3 3 8.2 7 9.5 4-1.3 7-5.2 7-9.5V6Z" />
|
||||
<path d="m9 12 2 2 4-4" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const HardDriveIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<rect x="3" y="4" width="18" height="16" rx="2" />
|
||||
<path d="M3 14h18M7 17h.01M11 17h.01" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const ActivityIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M3 12h4l3 8 4-16 3 8h4" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const SearchNavIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<circle cx="11" cy="11" r="7" />
|
||||
<path d="m20 20-3.5-3.5" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const ShareIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<circle cx="18" cy="5" r="2.5" />
|
||||
<circle cx="6" cy="12" r="2.5" />
|
||||
<circle cx="18" cy="19" r="2.5" />
|
||||
<path d="m8.2 10.8 7.6-4.6M8.2 13.2l7.6 4.6" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const MenuIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M4 7h16M4 12h16M4 17h16" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const CloseIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M6 6l12 12M18 6 6 18" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const PenIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M4 20h4L18.5 9.5a2.1 2.1 0 0 0-3-3L5 17v3Z" />
|
||||
<path d="m13.5 6.5 3 3" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const MoveIcon = (props: IconProps) => (
|
||||
<svg {...base(props)}>
|
||||
<path d="M12 4v16M4 12h16" />
|
||||
<path d="m9 7 3-3 3 3M9 17l3 3 3-3M7 9l-3 3 3 3M17 9l3 3-3 3" />
|
||||
</svg>
|
||||
);
|
||||
@@ -0,0 +1,370 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
role_name: string;
|
||||
quota_bytes: number;
|
||||
used_bytes: number;
|
||||
max_file_bytes: number;
|
||||
must_change_password: boolean;
|
||||
}
|
||||
|
||||
export interface Folder {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
is_system: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface UploadedFile {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
checksum_sha256: string | null;
|
||||
owner_id: string | null;
|
||||
is_starred: boolean;
|
||||
download_count: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface FolderPermission {
|
||||
user_id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
level: string;
|
||||
expires_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface SessionInfo {
|
||||
id: string;
|
||||
ip_address: string | null;
|
||||
user_agent: string | null;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
expires_at: string;
|
||||
current: boolean;
|
||||
}
|
||||
|
||||
export interface TrashFolder {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string;
|
||||
}
|
||||
|
||||
export interface TrashFile {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string;
|
||||
}
|
||||
|
||||
export interface MediaItem {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
is_starred: boolean;
|
||||
kind: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
created_at: string;
|
||||
has_thumbnail: boolean;
|
||||
}
|
||||
|
||||
export interface AdminUser {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
quota_bytes: number;
|
||||
used_bytes: number;
|
||||
max_file_bytes: number;
|
||||
is_active: boolean;
|
||||
must_change_password: boolean;
|
||||
last_login_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface StorageLocation {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
mount_path: string;
|
||||
quota_bytes: number | null;
|
||||
used_bytes: number;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AdminStats {
|
||||
users: number;
|
||||
folders: number;
|
||||
files: number;
|
||||
usedBytes: number;
|
||||
trashFiles: number;
|
||||
locations: { id: number; name: string; used_bytes: number; quota_bytes: number | null }[];
|
||||
}
|
||||
|
||||
export interface AuditEntry {
|
||||
id: number;
|
||||
user_id: string | null;
|
||||
user_email: string | null;
|
||||
action: string;
|
||||
resource: string;
|
||||
resource_id: string | null;
|
||||
details: string | null;
|
||||
ip_address: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
const BASE = "/api/cloud";
|
||||
|
||||
const messageOf = (body: unknown, fallback: string): string =>
|
||||
(body as { error?: { message?: string } } | null)?.error?.message ?? fallback;
|
||||
|
||||
/**
|
||||
* Un seul point d'entree HTTP. Le cookie de session est envoye
|
||||
* automatiquement (same-origin), et toute erreur non-2xx devient une
|
||||
* ApiError portant le message serveur, jamais un corps brut.
|
||||
*/
|
||||
const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${BASE}${path}`, {
|
||||
credentials: "same-origin",
|
||||
...init,
|
||||
headers: {
|
||||
...(init?.body ? { "content-type": "application/json" } : {}),
|
||||
...init?.headers,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
|
||||
}
|
||||
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new ApiError(response.status, messageOf(body, "Une erreur est survenue."));
|
||||
return body as T;
|
||||
};
|
||||
|
||||
const post = <T>(path: string, payload?: unknown): Promise<T> =>
|
||||
request<T>(path, {
|
||||
method: "POST",
|
||||
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
||||
});
|
||||
|
||||
const patch = <T>(path: string, payload: unknown): Promise<T> =>
|
||||
request<T>(path, { method: "PATCH", body: JSON.stringify(payload) });
|
||||
|
||||
const del = <T>(path: string): Promise<T> => request<T>(path, { method: "DELETE" });
|
||||
|
||||
const query = (params: Record<string, string | number | null | undefined>): string => {
|
||||
const search = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value !== null && value !== undefined && value !== "") search.set(key, String(value));
|
||||
}
|
||||
const suffix = search.toString();
|
||||
return suffix ? `?${suffix}` : "";
|
||||
};
|
||||
|
||||
/** Envoi d'un corps brut (fichier, image), hors JSON. */
|
||||
const putBinary = async <T>(path: string, body: BodyInit, type: string): Promise<T> => {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${BASE}${path}`, {
|
||||
method: "PUT",
|
||||
credentials: "same-origin",
|
||||
headers: type ? { "content-type": type } : {},
|
||||
body,
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
|
||||
}
|
||||
const parsed: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new ApiError(response.status, messageOf(parsed, "L'envoi a echoue."));
|
||||
return parsed as T;
|
||||
};
|
||||
|
||||
export const api = {
|
||||
// --- Session -----------------------------------------------------------
|
||||
me: () => request<{ user: User }>("/auth/me"),
|
||||
login: (email: string, password: string) =>
|
||||
post<{ user: User }>("/auth/login", { email, password }),
|
||||
logout: () => post<{ ok: boolean }>("/auth/logout"),
|
||||
changePassword: (current: string, next: string) =>
|
||||
post<{ ok: boolean }>("/auth/change-password", { current, next }),
|
||||
forgotPassword: (email: string) => post<{ ok: boolean }>("/account/forgot-password", { email }),
|
||||
resetPassword: (token: string, password: string) =>
|
||||
post<{ ok: boolean }>("/account/reset-password", { token, password }),
|
||||
requestEmailChange: (password: string, new_email: string) =>
|
||||
post<{ ok: boolean }>("/account/email-change", { password, new_email }),
|
||||
confirmEmailChange: (token: string) =>
|
||||
post<{ ok: boolean; email: string }>("/account/email-change/confirm", { token }),
|
||||
|
||||
// --- Compte ------------------------------------------------------------
|
||||
updateProfile: (first_name: string, last_name: string) =>
|
||||
patch<{ ok: boolean }>("/account/profile", { first_name, last_name }),
|
||||
sessions: () => request<{ sessions: SessionInfo[] }>("/account/sessions"),
|
||||
revokeSession: (id: string) => del<{ ok: boolean }>(`/account/sessions/${encodeURIComponent(id)}`),
|
||||
revokeOtherSessions: () => del<{ ok: boolean }>("/account/sessions"),
|
||||
avatarUrl: (userId: string) => `${BASE}/account/avatar/${encodeURIComponent(userId)}`,
|
||||
uploadAvatar: (file: File) => putBinary<{ ok: boolean }>("/account/avatar", file, file.type),
|
||||
deleteAvatar: () => del<{ ok: boolean }>("/account/avatar"),
|
||||
|
||||
// --- Dossiers ----------------------------------------------------------
|
||||
folders: (parentId?: string | null) =>
|
||||
request<{ parentId: string | null; folders: Folder[] }>(
|
||||
`/folders${query({ parentId })}`,
|
||||
),
|
||||
createFolder: (name: string, parentId?: string | null, description?: string) =>
|
||||
post<{ folder: Folder }>("/folders", { name, parentId: parentId ?? null, description }),
|
||||
updateFolder: (id: string, payload: { name?: string; description?: string | null }) =>
|
||||
patch<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}`, payload),
|
||||
moveFolder: (id: string, parentId: string | null) =>
|
||||
post<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}/move`, { parentId }),
|
||||
deleteFolder: (id: string) => del<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}`),
|
||||
folderPermissions: (id: string) =>
|
||||
request<{ permissions: FolderPermission[] }>(
|
||||
`/folders/${encodeURIComponent(id)}/permissions`,
|
||||
),
|
||||
grantPermission: (id: string, email: string, level: string, expiresAt: string | null) =>
|
||||
post<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}/permissions`, {
|
||||
email,
|
||||
level,
|
||||
expiresAt,
|
||||
}),
|
||||
revokePermission: (id: string, userId: string) =>
|
||||
del<{ ok: boolean }>(
|
||||
`/folders/${encodeURIComponent(id)}/permissions/${encodeURIComponent(userId)}`,
|
||||
),
|
||||
|
||||
// --- Fichiers ----------------------------------------------------------
|
||||
files: (folderId?: string | null) =>
|
||||
request<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`),
|
||||
uploadFile: (file: File, folderId: string | null) =>
|
||||
putBinary<{ file: UploadedFile }>(
|
||||
`/files${query({ name: file.name, folderId })}`,
|
||||
file,
|
||||
file.type,
|
||||
),
|
||||
renameFile: (id: string, name: string) =>
|
||||
patch<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}`, { name }),
|
||||
moveFile: (id: string, folderId: string | null) =>
|
||||
post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }),
|
||||
starFile: (id: string) =>
|
||||
request<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`, { method: "PUT" }),
|
||||
deleteFile: (id: string) => del<{ ok: boolean }>(`/files/${encodeURIComponent(id)}`),
|
||||
downloadUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/download`,
|
||||
thumbnailUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/thumbnail`,
|
||||
|
||||
// --- Corbeille, recherche, galerie ------------------------------------
|
||||
trash: () =>
|
||||
request<{ retentionDays: number; folders: TrashFolder[]; files: TrashFile[] }>("/trash"),
|
||||
restoreFolder: (id: string) =>
|
||||
post<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}/restore`),
|
||||
restoreFile: (id: string) =>
|
||||
post<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}/restore`),
|
||||
purgeFolder: (id: string) => del<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}`),
|
||||
purgeFile: (id: string) => del<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}`),
|
||||
emptyTrash: () => del<{ ok: boolean }>("/trash"),
|
||||
|
||||
search: (q: string) =>
|
||||
request<{ query: string; folders: Folder[]; files: UploadedFile[] }>(`/search${query({ q })}`),
|
||||
gallery: (kind: string, limit = 60, offset = 0) =>
|
||||
request<{ kind: string | null; items: MediaItem[] }>(
|
||||
`/media${query({ kind, limit, offset })}`,
|
||||
),
|
||||
|
||||
// --- Administration ----------------------------------------------------
|
||||
adminStats: () => request<AdminStats>("/admin/stats"),
|
||||
adminUsers: (q?: string) =>
|
||||
request<{ users: AdminUser[] }>(`/admin/users${query({ q })}`),
|
||||
adminCreateUser: (payload: {
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
quota_bytes?: number | null;
|
||||
max_file_bytes?: number | null;
|
||||
}) => post<{ user: AdminUser; password: string }>("/admin/users", payload),
|
||||
adminUpdateUser: (
|
||||
id: string,
|
||||
payload: Partial<{
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
quota_bytes: number;
|
||||
max_file_bytes: number;
|
||||
is_active: boolean;
|
||||
}>,
|
||||
) => patch<{ user: AdminUser }>(`/admin/users/${encodeURIComponent(id)}`, payload),
|
||||
adminDeleteUser: (id: string) => del<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}`),
|
||||
adminResetPassword: (id: string) =>
|
||||
post<{ password: string }>(`/admin/users/${encodeURIComponent(id)}/reset-password`),
|
||||
adminStorageLocations: () =>
|
||||
request<{ locations: StorageLocation[] }>("/admin/storage-locations"),
|
||||
adminCreateStorageLocation: (payload: {
|
||||
name: string;
|
||||
slug: string;
|
||||
mount_path: string;
|
||||
quota_bytes?: number | null;
|
||||
}) => post<{ ok: boolean }>("/admin/storage-locations", payload),
|
||||
adminUpdateStorageLocation: (
|
||||
id: number,
|
||||
payload: { name?: string; quota_bytes?: number | null; is_active?: boolean },
|
||||
) => patch<{ ok: boolean }>(`/admin/storage-locations/${id}`, payload),
|
||||
adminAudit: (limit = 100, offset = 0, action?: string) =>
|
||||
request<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action })}`),
|
||||
};
|
||||
|
||||
/** Octets en lecture humaine, sans precision inutile. */
|
||||
export const formatBytes = (bytes: number): string => {
|
||||
if (bytes < 1024) return `${bytes} o`;
|
||||
const units = ["Ko", "Mo", "Go", "To"];
|
||||
let value = bytes;
|
||||
let index = -1;
|
||||
do {
|
||||
value /= 1024;
|
||||
index += 1;
|
||||
} while (value >= 1024 && index < units.length - 1);
|
||||
return `${value.toLocaleString("fr-FR", { maximumFractionDigits: value < 10 ? 1 : 0 })} ${units[index]}`;
|
||||
};
|
||||
|
||||
export const formatDate = (value: string | null): string =>
|
||||
value ? new Date(value).toLocaleString("fr-FR", { dateStyle: "medium", timeStyle: "short" }) : "—";
|
||||
@@ -0,0 +1,58 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { api, type User } from "./api.js";
|
||||
|
||||
interface SessionValue {
|
||||
user: User | null;
|
||||
loading: boolean;
|
||||
refresh: () => Promise<void>;
|
||||
setUser: (user: User | null) => void;
|
||||
logout: () => Promise<void>;
|
||||
}
|
||||
|
||||
const SessionContext = createContext<SessionValue | null>(null);
|
||||
|
||||
export const SessionProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const { user: current } = await api.me();
|
||||
setUser(current);
|
||||
} catch {
|
||||
setUser(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await api.logout().catch(() => undefined);
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
const value = useMemo<SessionValue>(
|
||||
() => ({ user, loading, refresh, setUser, logout }),
|
||||
[user, loading, refresh, logout],
|
||||
);
|
||||
|
||||
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
|
||||
};
|
||||
|
||||
export const useSession = (): SessionValue => {
|
||||
const value = useContext(SessionContext);
|
||||
if (!value) throw new Error("useSession doit etre utilise dans un SessionProvider.");
|
||||
return value;
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import { App } from "./App.js";
|
||||
import { SessionProvider } from "./lib/session.js";
|
||||
import "./styles/index.css";
|
||||
|
||||
const container = document.getElementById("root");
|
||||
|
||||
if (!container) {
|
||||
throw new Error("Element racine introuvable");
|
||||
}
|
||||
|
||||
createRoot(container).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<SessionProvider>
|
||||
<App />
|
||||
</SessionProvider>
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,753 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||
import { Button, Input, Spinner } from "@cohaise/ui";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatDate,
|
||||
type AdminStats,
|
||||
type AdminUser,
|
||||
type AuditEntry,
|
||||
type StorageLocation,
|
||||
} from "../lib/api.js";
|
||||
import { Alert, Badge, EmptyState, Modal, PageHeader } from "../components/feedback.js";
|
||||
import { IconAction } from "../components/IconAction.js";
|
||||
import {
|
||||
ActivityIcon,
|
||||
HardDriveIcon,
|
||||
PlusIcon,
|
||||
TrashIcon,
|
||||
UsersIcon,
|
||||
} from "../components/icons.js";
|
||||
|
||||
const GB = 1024 ** 3;
|
||||
const MB = 1024 ** 2;
|
||||
|
||||
const messageOf = (caught: unknown, fallback: string): string =>
|
||||
caught instanceof ApiError ? caught.message : fallback;
|
||||
|
||||
const toGb = (bytes: number): string =>
|
||||
(bytes / GB).toLocaleString("fr-FR", { maximumFractionDigits: 1 });
|
||||
|
||||
const StatCard = ({ label, value }: { label: string; value: string }) => (
|
||||
<div className="rounded-lg border border-border bg-surface p-3">
|
||||
<p className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
|
||||
{label}
|
||||
</p>
|
||||
<p className="mt-1 text-lg font-semibold text-foreground">{value}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const AdminUsers = () => {
|
||||
const [users, setUsers] = useState<AdminUser[] | null>(null);
|
||||
const [stats, setStats] = useState<AdminStats | null>(null);
|
||||
const [q, setQ] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [edit, setEdit] = useState<AdminUser | null>(null);
|
||||
const [credentials, setCredentials] = useState<{ email: string; password: string } | null>(null);
|
||||
const termRef = useRef("");
|
||||
|
||||
const load = async (term: string) => {
|
||||
termRef.current = term;
|
||||
setError(null);
|
||||
try {
|
||||
const { users: list } = await api.adminUsers(term || undefined);
|
||||
setUsers(list);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Chargement impossible."));
|
||||
setUsers([]);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void load("");
|
||||
api
|
||||
.adminStats()
|
||||
.then(setStats)
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const toggleActive = async (user: AdminUser) => {
|
||||
setBusy(user.id);
|
||||
setError(null);
|
||||
try {
|
||||
await api.adminUpdateUser(user.id, { is_active: !user.is_active });
|
||||
await load(termRef.current);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Mise à jour impossible."));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const resetPassword = async (user: AdminUser) => {
|
||||
setBusy(user.id);
|
||||
setError(null);
|
||||
try {
|
||||
const { password } = await api.adminResetPassword(user.id);
|
||||
setCredentials({ email: user.email, password });
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Réinitialisation impossible."));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const removeUser = async (user: AdminUser) => {
|
||||
if (!window.confirm(`Supprimer définitivement ${user.email} ?`)) return;
|
||||
setBusy(user.id);
|
||||
setError(null);
|
||||
try {
|
||||
await api.adminDeleteUser(user.id);
|
||||
await load(termRef.current);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Suppression impossible."));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<PageHeader
|
||||
title="Comptes"
|
||||
description="Créez des membres, ajustez leurs quotas et gérez les accès."
|
||||
actions={
|
||||
<Button
|
||||
size="sm"
|
||||
iconLeading={<PlusIcon className="h-3.5 w-3.5" />}
|
||||
onClick={() => setCreateOpen(true)}
|
||||
>
|
||||
Nouveau membre
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{stats ? (
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<StatCard label="Membres" value={String(stats.users)} />
|
||||
<StatCard label="Fichiers" value={String(stats.files)} />
|
||||
<StatCard label="Stockage" value={`${toGb(stats.usedBytes)} Go`} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<form
|
||||
className="flex items-end gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void load(q);
|
||||
}}
|
||||
>
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
label="Rechercher"
|
||||
type="search"
|
||||
placeholder="nom ou e-mail"
|
||||
value={q}
|
||||
onChange={(event) => setQ(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" size="md" variant="secondary">
|
||||
Filtrer
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
|
||||
{users === null ? (
|
||||
<div className="flex justify-center py-16">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
) : users.length === 0 ? (
|
||||
<EmptyState icon={<UsersIcon className="h-8 w-8" />} title="Aucun membre" />
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{users.map((user) => (
|
||||
<li key={user.id} className="flex flex-wrap items-center gap-3 px-3 py-3">
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-medium text-foreground">
|
||||
{user.first_name} {user.last_name}
|
||||
</span>
|
||||
{user.role_slug === "admin" ? <Badge tone="accent">Admin</Badge> : null}
|
||||
{!user.is_active ? <Badge tone="danger">Inactif</Badge> : null}
|
||||
{user.must_change_password ? <Badge tone="warning">À changer</Badge> : null}
|
||||
</span>
|
||||
<span className="block truncate text-[0.6875rem] text-subtle-foreground">
|
||||
{user.email} · {toGb(user.used_bytes)} / {toGb(user.quota_bytes)} Go ·{" "}
|
||||
{user.last_login_at
|
||||
? `vu le ${formatDate(user.last_login_at)}`
|
||||
: "jamais connecté"}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<Button variant="ghost" size="sm" onClick={() => setEdit(user)}>
|
||||
Modifier
|
||||
</Button>
|
||||
<IconAction
|
||||
label={user.is_active ? "Désactiver" : "Réactiver"}
|
||||
icon={<HardDriveIcon className="h-4 w-4" />}
|
||||
isLoading={busy === user.id}
|
||||
onClick={() => void toggleActive(user)}
|
||||
/>
|
||||
<IconAction
|
||||
label="Réinitialiser le mot de passe"
|
||||
icon={<ActivityIcon className="h-4 w-4" />}
|
||||
isLoading={busy === user.id}
|
||||
onClick={() => void resetPassword(user)}
|
||||
/>
|
||||
<IconAction
|
||||
label="Supprimer"
|
||||
icon={<TrashIcon className="h-4 w-4" />}
|
||||
tone="danger"
|
||||
isLoading={busy === user.id}
|
||||
onClick={() => void removeUser(user)}
|
||||
/>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{createOpen ? (
|
||||
<CreateUserDialog
|
||||
onClose={() => setCreateOpen(false)}
|
||||
onCreated={(email, password) => {
|
||||
setCreateOpen(false);
|
||||
setCredentials({ email, password });
|
||||
void load(termRef.current);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{edit ? (
|
||||
<EditUserDialog
|
||||
user={edit}
|
||||
onClose={() => setEdit(null)}
|
||||
onSaved={() => {
|
||||
setEdit(null);
|
||||
void load(termRef.current);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<CredentialsModal credentials={credentials} onClose={() => setCredentials(null)} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const CredentialsModal = ({
|
||||
credentials,
|
||||
onClose,
|
||||
}: {
|
||||
credentials: { email: string; password: string } | null;
|
||||
onClose: () => void;
|
||||
}) => {
|
||||
if (!credentials) return null;
|
||||
return (
|
||||
<Modal open title="Identifiants générés" onClose={onClose}>
|
||||
<div className="flex flex-col gap-4">
|
||||
<Alert tone="success">
|
||||
Transmettez ces informations par un canal sûr : le mot de passe ne sera plus affiché.
|
||||
</Alert>
|
||||
<dl className="flex flex-col gap-2 text-xs">
|
||||
<div>
|
||||
<dt className="text-subtle-foreground">Adresse</dt>
|
||||
<dd className="font-medium text-foreground">{credentials.email}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-subtle-foreground">Mot de passe</dt>
|
||||
<dd className="break-all font-mono text-foreground">{credentials.password}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className="flex justify-end">
|
||||
<Button size="md" onClick={onClose}>
|
||||
Terminé
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
const CreateUserDialog = ({
|
||||
onClose,
|
||||
onCreated,
|
||||
}: {
|
||||
onClose: () => void;
|
||||
onCreated: (email: string, password: string) => void;
|
||||
}) => {
|
||||
const [email, setEmail] = useState("");
|
||||
const [firstName, setFirstName] = useState("");
|
||||
const [lastName, setLastName] = useState("");
|
||||
const [role, setRole] = useState("user");
|
||||
const [quotaGb, setQuotaGb] = useState("");
|
||||
const [maxFileMb, setMaxFileMb] = 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 {
|
||||
const { user, password } = await api.adminCreateUser({
|
||||
email: email.trim(),
|
||||
first_name: firstName.trim(),
|
||||
last_name: lastName.trim(),
|
||||
role_slug: role,
|
||||
quota_bytes: quotaGb ? Math.round(Number(quotaGb) * GB) : null,
|
||||
max_file_bytes: maxFileMb ? Math.round(Number(maxFileMb) * MB) : null,
|
||||
});
|
||||
onCreated(user.email, password);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Création impossible."));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open title="Nouveau membre" onClose={onClose}>
|
||||
<form className="flex flex-col gap-3" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Adresse e-mail"
|
||||
type="email"
|
||||
required
|
||||
autoFocus
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Input
|
||||
label="Prénom"
|
||||
required
|
||||
value={firstName}
|
||||
onChange={(event) => setFirstName(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Nom"
|
||||
required
|
||||
value={lastName}
|
||||
onChange={(event) => setLastName(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<label className="flex flex-col gap-1.5">
|
||||
<span className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground">
|
||||
Rôle
|
||||
</span>
|
||||
<select
|
||||
value={role}
|
||||
onChange={(event) => setRole(event.target.value)}
|
||||
className="h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground"
|
||||
>
|
||||
<option value="user">Utilisateur</option>
|
||||
<option value="admin">Administrateur</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Input
|
||||
label="Quota (Go, optionnel)"
|
||||
type="number"
|
||||
min={1}
|
||||
value={quotaGb}
|
||||
onChange={(event) => setQuotaGb(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Fichier max (Mo)"
|
||||
type="number"
|
||||
min={1}
|
||||
value={maxFileMb}
|
||||
onChange={(event) => setMaxFileMb(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="ghost" size="md" onClick={onClose}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button type="submit" size="md" isLoading={busy}>
|
||||
Créer
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
const EditUserDialog = ({
|
||||
user,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
user: AdminUser;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}) => {
|
||||
const [firstName, setFirstName] = useState(user.first_name);
|
||||
const [lastName, setLastName] = useState(user.last_name);
|
||||
const [role, setRole] = useState(user.role_slug);
|
||||
const [quotaGb, setQuotaGb] = useState(String(Math.round(user.quota_bytes / GB)));
|
||||
const [maxFileMb, setMaxFileMb] = useState(String(Math.round(user.max_file_bytes / MB)));
|
||||
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.adminUpdateUser(user.id, {
|
||||
first_name: firstName.trim(),
|
||||
last_name: lastName.trim(),
|
||||
role_slug: role,
|
||||
quota_bytes: Math.round(Number(quotaGb) * GB),
|
||||
max_file_bytes: Math.round(Number(maxFileMb) * MB),
|
||||
});
|
||||
onSaved();
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Enregistrement impossible."));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open title="Modifier le membre" onClose={onClose}>
|
||||
<form className="flex flex-col gap-3" onSubmit={(event) => void submit(event)}>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Input
|
||||
label="Prénom"
|
||||
required
|
||||
value={firstName}
|
||||
onChange={(event) => setFirstName(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Nom"
|
||||
required
|
||||
value={lastName}
|
||||
onChange={(event) => setLastName(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<label className="flex flex-col gap-1.5">
|
||||
<span className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground">
|
||||
Rôle
|
||||
</span>
|
||||
<select
|
||||
value={role}
|
||||
onChange={(event) => setRole(event.target.value)}
|
||||
className="h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground"
|
||||
>
|
||||
<option value="user">Utilisateur</option>
|
||||
<option value="admin">Administrateur</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Input
|
||||
label="Quota (Go)"
|
||||
type="number"
|
||||
min={1}
|
||||
value={quotaGb}
|
||||
onChange={(event) => setQuotaGb(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Fichier max (Mo)"
|
||||
type="number"
|
||||
min={1}
|
||||
value={maxFileMb}
|
||||
onChange={(event) => setMaxFileMb(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="ghost" size="md" onClick={onClose}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button type="submit" size="md" isLoading={busy}>
|
||||
Enregistrer
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export const AdminStorage = () => {
|
||||
const [locations, setLocations] = useState<StorageLocation[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
|
||||
const load = async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const { locations: list } = await api.adminStorageLocations();
|
||||
setLocations(list);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Chargement impossible."));
|
||||
setLocations([]);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
const toggle = async (location: StorageLocation) => {
|
||||
setError(null);
|
||||
try {
|
||||
await api.adminUpdateStorageLocation(location.id, { is_active: !location.is_active });
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Mise à jour impossible."));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<PageHeader
|
||||
title="Emplacements de stockage"
|
||||
description="Volumes montés utilisés pour stocker les fichiers."
|
||||
actions={
|
||||
<Button
|
||||
size="sm"
|
||||
iconLeading={<PlusIcon className="h-3.5 w-3.5" />}
|
||||
onClick={() => setCreateOpen(true)}
|
||||
>
|
||||
Nouvel emplacement
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
|
||||
{locations === null ? (
|
||||
<div className="flex justify-center py-16">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
) : locations.length === 0 ? (
|
||||
<EmptyState icon={<HardDriveIcon className="h-8 w-8" />} title="Aucun emplacement" />
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{locations.map((location) => (
|
||||
<li key={location.id} className="flex flex-wrap items-center gap-3 px-3 py-3">
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-medium text-foreground">
|
||||
{location.name}
|
||||
</span>
|
||||
{!location.is_active ? <Badge tone="danger">Inactif</Badge> : null}
|
||||
</span>
|
||||
<span className="block truncate text-[0.6875rem] text-subtle-foreground">
|
||||
{location.slug} · {location.mount_path} ·{" "}
|
||||
{location.quota_bytes
|
||||
? `${toGb(location.used_bytes)} / ${toGb(location.quota_bytes)} Go`
|
||||
: `${toGb(location.used_bytes)} Go utilisés`}
|
||||
</span>
|
||||
</span>
|
||||
<Button variant="ghost" size="sm" onClick={() => void toggle(location)}>
|
||||
{location.is_active ? "Désactiver" : "Réactiver"}
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{createOpen ? (
|
||||
<CreateLocationDialog
|
||||
onClose={() => setCreateOpen(false)}
|
||||
onCreated={() => {
|
||||
setCreateOpen(false);
|
||||
void load();
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const CreateLocationDialog = ({
|
||||
onClose,
|
||||
onCreated,
|
||||
}: {
|
||||
onClose: () => void;
|
||||
onCreated: () => void;
|
||||
}) => {
|
||||
const [name, setName] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const [mountPath, setMountPath] = useState("");
|
||||
const [quotaGb, setQuotaGb] = 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.adminCreateStorageLocation({
|
||||
name: name.trim(),
|
||||
slug: slug.trim(),
|
||||
mount_path: mountPath.trim(),
|
||||
quota_bytes: quotaGb ? Math.round(Number(quotaGb) * GB) : null,
|
||||
});
|
||||
onCreated();
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Création impossible."));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open title="Nouvel emplacement" onClose={onClose}>
|
||||
<form className="flex flex-col gap-3" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Nom"
|
||||
required
|
||||
autoFocus
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Identifiant technique"
|
||||
required
|
||||
placeholder="principal"
|
||||
pattern="[a-z0-9][a-z0-9-]*"
|
||||
value={slug}
|
||||
onChange={(event) => setSlug(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Chemin de montage"
|
||||
required
|
||||
placeholder="/data/cloud"
|
||||
value={mountPath}
|
||||
onChange={(event) => setMountPath(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Quota (Go, optionnel)"
|
||||
type="number"
|
||||
min={1}
|
||||
value={quotaGb}
|
||||
onChange={(event) => setQuotaGb(event.target.value)}
|
||||
/>
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="ghost" size="md" onClick={onClose}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button type="submit" size="md" isLoading={busy}>
|
||||
Créer
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export const AdminAudit = () => {
|
||||
const [entries, setEntries] = useState<AuditEntry[] | null>(null);
|
||||
const [action, setAction] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
|
||||
const load = async (term: string) => {
|
||||
setError(null);
|
||||
try {
|
||||
const { entries: list } = await api.adminAudit(100, 0, term || undefined);
|
||||
setEntries(list);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Chargement impossible."));
|
||||
setEntries([]);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void load("");
|
||||
}, []);
|
||||
|
||||
const loadMore = async () => {
|
||||
if (!entries) return;
|
||||
setLoadingMore(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { entries: more } = await api.adminAudit(100, entries.length, action || undefined);
|
||||
setEntries((previous) => [...(previous ?? []), ...more]);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, "Chargement impossible."));
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<PageHeader title="Journal d'activité" description="Dernières actions enregistrées." />
|
||||
|
||||
<form
|
||||
className="flex items-end gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void load(action);
|
||||
}}
|
||||
>
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
label="Filtrer par action"
|
||||
placeholder="auth.login, file.upload…"
|
||||
value={action}
|
||||
onChange={(event) => setAction(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" variant="secondary" size="md">
|
||||
Filtrer
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
|
||||
{entries === null ? (
|
||||
<div className="flex justify-center py-16">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
) : entries.length === 0 ? (
|
||||
<EmptyState icon={<ActivityIcon className="h-8 w-8" />} title="Aucune entrée" />
|
||||
) : (
|
||||
<>
|
||||
<ul className="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{entries.map((entry) => (
|
||||
<li key={entry.id} className="flex flex-wrap items-center gap-3 px-3 py-2.5">
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium text-foreground">
|
||||
{entry.action}
|
||||
<span className="ml-2 font-normal text-subtle-foreground">
|
||||
{entry.resource}
|
||||
{entry.resource_id ? ` · ${entry.resource_id}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
<span className="block truncate text-[0.6875rem] text-subtle-foreground">
|
||||
{entry.user_email ?? "système"} · {formatDate(entry.created_at)}
|
||||
{entry.ip_address ? ` · ${entry.ip_address}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{entries.length >= 100 ? (
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="md"
|
||||
isLoading={loadingMore}
|
||||
onClick={() => void loadMore()}
|
||||
>
|
||||
Charger plus
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,449 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button, Card, Spinner } from "@cohaise/ui";
|
||||
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 { IconAction } from "../components/IconAction.js";
|
||||
import {
|
||||
CreateFolderDialog,
|
||||
MoveDialog,
|
||||
RenameDialog,
|
||||
ShareDialog,
|
||||
} from "../components/dialogs.js";
|
||||
import {
|
||||
DownloadIcon,
|
||||
FileIcon,
|
||||
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;
|
||||
|
||||
const isImage = (file: UploadedFile): boolean =>
|
||||
(file.mime_type ?? "").toLowerCase().startsWith("image/");
|
||||
|
||||
export const Browser = () => {
|
||||
const { user, refresh } = useSession();
|
||||
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 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";
|
||||
if (!window.confirm(`Placer ${label} dans la corbeille ?`)) 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."
|
||||
/>
|
||||
|
||||
<nav aria-label="Fil d'Ariane">
|
||||
<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>
|
||||
|
||||
<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) => (
|
||||
<li key={file.id} className="flex items-center gap-2 px-3 py-2.5">
|
||||
<span 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">
|
||||
{isImage(file) ? (
|
||||
<img
|
||||
src={api.thumbnailUrl(file.id)}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<FileIcon className="h-5 w-5" />
|
||||
)}
|
||||
</span>
|
||||
<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}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui";
|
||||
import { Alert } from "../components/feedback.js";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
|
||||
export const ChangePassword = () => {
|
||||
const { user, refresh, logout } = useSession();
|
||||
const navigate = useNavigate();
|
||||
const [current, setCurrent] = useState("");
|
||||
const [next, setNext] = useState("");
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (next !== confirm) {
|
||||
setError("Les deux mots de passe ne correspondent pas.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.changePassword(current, next);
|
||||
await refresh();
|
||||
navigate("/files", { replace: true });
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Changement impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<header className="mb-6 text-center">
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
</p>
|
||||
<h1 className="font-display mt-2 text-lg font-semibold uppercase tracking-label text-foreground">
|
||||
Nouveau mot de passe
|
||||
</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||
Bienvenue {user?.first_name ?? ""}. Ce mot de passe a été défini par un
|
||||
administrateur : choisissez le vôtre.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Changement requis</CardTitle>
|
||||
<CardDescription>
|
||||
Les autres sessions ouvertes sur ce compte seront fermées.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Mot de passe actuel"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
autoFocus
|
||||
value={current}
|
||||
onChange={(event) => setCurrent(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Nouveau mot de passe"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
minLength={8}
|
||||
hint="8 caractères minimum."
|
||||
value={next}
|
||||
onChange={(event) => setNext(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Confirmation"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
minLength={8}
|
||||
value={confirm}
|
||||
onChange={(event) => setConfirm(event.target.value)}
|
||||
/>
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
<Button type="submit" size="lg" fullWidth isLoading={busy}>
|
||||
Enregistrer
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="md"
|
||||
fullWidth
|
||||
onClick={() => void logout()}
|
||||
>
|
||||
Se déconnecter
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardHeader, CardTitle, Spinner } from "@cohaise/ui";
|
||||
import { Alert } from "../components/feedback.js";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
|
||||
export const ConfirmEmail = () => {
|
||||
const [params] = useSearchParams();
|
||||
const token = params.get("token") ?? "";
|
||||
const { refresh } = useSession();
|
||||
const [state, setState] = useState<"loading" | "success" | "error">("loading");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const started = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (started.current) return;
|
||||
started.current = true;
|
||||
if (!token) {
|
||||
setState("error");
|
||||
setError("Ce lien est incomplet ou invalide.");
|
||||
return;
|
||||
}
|
||||
api
|
||||
.confirmEmailChange(token)
|
||||
.then(() => {
|
||||
setState("success");
|
||||
void refresh();
|
||||
})
|
||||
.catch((caught: unknown) => {
|
||||
setState("error");
|
||||
setError(caught instanceof ApiError ? caught.message : "Confirmation impossible.");
|
||||
});
|
||||
}, [token, refresh]);
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<header className="mb-6 text-center">
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
</p>
|
||||
<h1 className="font-display mt-2 text-lg font-semibold uppercase tracking-label text-foreground">
|
||||
Changement d'adresse
|
||||
</h1>
|
||||
</header>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Confirmation</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{state === "loading" ? (
|
||||
<div className="flex justify-center py-4">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
) : state === "success" ? (
|
||||
<>
|
||||
<Alert tone="success">Votre adresse e-mail a été mise à jour.</Alert>
|
||||
<Link to="/files">
|
||||
<Button size="lg" fullWidth>
|
||||
Accéder à mes fichiers
|
||||
</Button>
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Alert>{error}</Alert>
|
||||
<Link to="/profile">
|
||||
<Button size="lg" fullWidth>
|
||||
Mon compte
|
||||
</Button>
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui";
|
||||
import { Alert } from "../components/feedback.js";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
|
||||
export const ForgotPassword = () => {
|
||||
const [email, setEmail] = useState("");
|
||||
const [sent, setSent] = useState(false);
|
||||
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.forgotPassword(email);
|
||||
setSent(true);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Demande impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<header className="mb-6 text-center">
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
</p>
|
||||
<h1 className="font-display mt-2 text-lg font-semibold uppercase tracking-label text-foreground">
|
||||
Mot de passe oublié
|
||||
</h1>
|
||||
</header>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Réinitialisation</CardTitle>
|
||||
<CardDescription>
|
||||
Nous vous enverrons un lien valable une heure.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{sent ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Alert tone="success">
|
||||
Si cette adresse correspond à un compte, un message contenant le lien de
|
||||
réinitialisation vient d'être envoyé.
|
||||
</Alert>
|
||||
<Link
|
||||
to="/login"
|
||||
className="text-center text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
|
||||
>
|
||||
Retour à la connexion
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(event) => void submit(event)}
|
||||
>
|
||||
<Input
|
||||
label="Adresse e-mail"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
autoFocus
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
/>
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
<Button type="submit" size="lg" fullWidth isLoading={busy}>
|
||||
Envoyer le lien
|
||||
</Button>
|
||||
<Link
|
||||
to="/login"
|
||||
className="text-center text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
|
||||
>
|
||||
Retour à la connexion
|
||||
</Link>
|
||||
</form>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,142 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Button, Spinner, cn } from "@cohaise/ui";
|
||||
import { ApiError, api, formatBytes, type MediaItem } from "../lib/api.js";
|
||||
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
|
||||
import { FileIcon, ImageIcon } from "../components/icons.js";
|
||||
|
||||
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 PAGE = 60;
|
||||
|
||||
export const Gallery = () => {
|
||||
const [kind, setKind] = useState<string>("image");
|
||||
const [items, setItems] = useState<MediaItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
void api
|
||||
.gallery(kind, PAGE, 0)
|
||||
.then(({ items: first }) => {
|
||||
setItems(first);
|
||||
setError(null);
|
||||
})
|
||||
.catch((caught: unknown) => {
|
||||
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
|
||||
setItems([]);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [kind]);
|
||||
|
||||
const loadMore = useCallback(async () => {
|
||||
setLoadingMore(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { items: more } = await api.gallery(kind, PAGE, items.length);
|
||||
setItems((previous) => [...previous, ...more]);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}, [kind, items.length]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<PageHeader
|
||||
title="Galerie"
|
||||
description="Parcourez les médias auxquels vous avez accès."
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap gap-1.5" role="tablist" aria-label="Filtrer par type">
|
||||
{KINDS.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={kind === option.value}
|
||||
onClick={() => {
|
||||
setKind(option.value);
|
||||
setItems([]);
|
||||
}}
|
||||
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",
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-16">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
) : items.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={<ImageIcon className="h-8 w-8" />}
|
||||
title="Aucun média"
|
||||
description="Rien à afficher pour ce filtre."
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||||
{items.map((item) => (
|
||||
<li key={item.id}>
|
||||
<a
|
||||
href={api.downloadUrl(item.id)}
|
||||
download={item.name}
|
||||
className="group flex flex-col overflow-hidden rounded-lg border border-border bg-surface transition-colors hover:border-border-strong"
|
||||
>
|
||||
<span className="flex aspect-square items-center justify-center overflow-hidden bg-surface-muted text-muted-foreground">
|
||||
{item.kind === "image" && item.has_thumbnail ? (
|
||||
<img
|
||||
src={api.thumbnailUrl(item.id)}
|
||||
alt={item.name}
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover transition-transform duration-fast group-hover:scale-[1.02]"
|
||||
/>
|
||||
) : (
|
||||
<FileIcon className="h-8 w-8" />
|
||||
)}
|
||||
</span>
|
||||
<span className="flex flex-col gap-0.5 p-2">
|
||||
<span className="truncate text-xs font-medium text-foreground">
|
||||
{item.name}
|
||||
</span>
|
||||
<span className="text-[0.6875rem] text-subtle-foreground">
|
||||
{formatBytes(item.size_bytes)}
|
||||
</span>
|
||||
</span>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{items.length >= PAGE ? (
|
||||
<div className="flex justify-center">
|
||||
<Button variant="secondary" size="md" isLoading={loadingMore} onClick={() => void loadMore()}>
|
||||
Charger plus
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Link, Navigate, useNavigate } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
|
||||
export const Login = () => {
|
||||
const { user, setUser } = useSession();
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
if (user) return <Navigate to="/files" replace />;
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { user: current } = await api.login(email, password);
|
||||
setUser(current);
|
||||
navigate(current.must_change_password ? "/change-password" : "/files", { replace: true });
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Connexion impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<header className="mb-6 text-center">
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
</p>
|
||||
<h1 className="font-display mt-2 text-lg font-semibold uppercase tracking-label text-foreground">
|
||||
Cloud
|
||||
</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||
Connectez-vous pour accéder à vos fichiers.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Connexion</CardTitle>
|
||||
<CardDescription>Votre session reste ouverte 14 jours.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Adresse e-mail"
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
required
|
||||
autoFocus
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Mot de passe"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
{...(error ? { error } : {})}
|
||||
/>
|
||||
|
||||
<Button type="submit" size="lg" fullWidth isLoading={busy}>
|
||||
Se connecter
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<p className="mt-4 text-center text-xs text-muted-foreground">
|
||||
<Link
|
||||
to="/forgot-password"
|
||||
className="underline-offset-2 hover:text-foreground hover:underline"
|
||||
>
|
||||
Mot de passe oublié ?
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,316 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Spinner } from "@cohaise/ui";
|
||||
import { ApiError, api, formatDate, type SessionInfo } from "../lib/api.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
import { Alert, Badge, PageHeader } from "../components/feedback.js";
|
||||
import { TrashIcon } from "../components/icons.js";
|
||||
|
||||
export const Profile = () => {
|
||||
const { user, refresh } = useSession();
|
||||
|
||||
const [firstName, setFirstName] = useState(user?.first_name ?? "");
|
||||
const [lastName, setLastName] = useState(user?.last_name ?? "");
|
||||
const [profileMessage, setProfileMessage] = useState<string | null>(null);
|
||||
const [profileError, setProfileError] = useState<string | null>(null);
|
||||
const [savingProfile, setSavingProfile] = useState(false);
|
||||
|
||||
const [avatarNonce, setAvatarNonce] = useState(0);
|
||||
const [avatarError, setAvatarError] = useState<string | null>(null);
|
||||
const avatarInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [password, setPassword] = useState("");
|
||||
const [newEmail, setNewEmail] = useState("");
|
||||
const [emailMessage, setEmailMessage] = useState<string | null>(null);
|
||||
const [emailError, setEmailError] = useState<string | null>(null);
|
||||
const [sendingEmail, setSendingEmail] = useState(false);
|
||||
|
||||
const [sessions, setSessions] = useState<SessionInfo[] | null>(null);
|
||||
const [sessionsError, setSessionsError] = useState<string | null>(null);
|
||||
const [revoking, setRevoking] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setFirstName((current) => (current === "" ? user.first_name : current));
|
||||
setLastName((current) => (current === "" ? user.last_name : current));
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const loadSessions = async () => {
|
||||
setSessionsError(null);
|
||||
try {
|
||||
const { sessions: list } = await api.sessions();
|
||||
setSessions(list);
|
||||
} catch (caught) {
|
||||
setSessionsError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
|
||||
setSessions([]);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void loadSessions();
|
||||
}, []);
|
||||
|
||||
const saveProfile = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setSavingProfile(true);
|
||||
setProfileError(null);
|
||||
setProfileMessage(null);
|
||||
try {
|
||||
await api.updateProfile(firstName.trim(), lastName.trim());
|
||||
await refresh();
|
||||
setProfileMessage("Informations enregistrées.");
|
||||
} catch (caught) {
|
||||
setProfileError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
|
||||
} finally {
|
||||
setSavingProfile(false);
|
||||
}
|
||||
};
|
||||
|
||||
const requestEmail = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setSendingEmail(true);
|
||||
setEmailError(null);
|
||||
setEmailMessage(null);
|
||||
try {
|
||||
await api.requestEmailChange(password, newEmail.trim());
|
||||
setPassword("");
|
||||
setNewEmail("");
|
||||
setEmailMessage("Un e-mail de confirmation a été envoyé à la nouvelle adresse.");
|
||||
} catch (caught) {
|
||||
setEmailError(caught instanceof ApiError ? caught.message : "Demande impossible.");
|
||||
} finally {
|
||||
setSendingEmail(false);
|
||||
}
|
||||
};
|
||||
|
||||
const changeAvatar = async (file: File | undefined) => {
|
||||
if (!file) return;
|
||||
setAvatarError(null);
|
||||
try {
|
||||
await api.uploadAvatar(file);
|
||||
setAvatarNonce((value) => value + 1);
|
||||
} catch (caught) {
|
||||
setAvatarError(caught instanceof ApiError ? caught.message : "Envoi impossible.");
|
||||
} finally {
|
||||
if (avatarInput.current) avatarInput.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
const removeAvatar = async () => {
|
||||
setAvatarError(null);
|
||||
try {
|
||||
await api.deleteAvatar();
|
||||
setAvatarNonce((value) => value + 1);
|
||||
} catch (caught) {
|
||||
setAvatarError(caught instanceof ApiError ? caught.message : "Suppression impossible.");
|
||||
}
|
||||
};
|
||||
|
||||
const revokeSession = async (session: SessionInfo) => {
|
||||
if (session.current && !window.confirm("Fermer la session en cours ?")) return;
|
||||
setRevoking(session.id);
|
||||
setSessionsError(null);
|
||||
try {
|
||||
await api.revokeSession(session.id);
|
||||
if (session.current) {
|
||||
await refresh();
|
||||
return;
|
||||
}
|
||||
setSessions((previous) => (previous ?? []).filter((item) => item.id !== session.id));
|
||||
} catch (caught) {
|
||||
setSessionsError(caught instanceof ApiError ? caught.message : "Révocation impossible.");
|
||||
} finally {
|
||||
setRevoking(null);
|
||||
}
|
||||
};
|
||||
|
||||
const revokeOthers = async () => {
|
||||
setSessionsError(null);
|
||||
try {
|
||||
await api.revokeOtherSessions();
|
||||
setSessions((previous) => (previous ?? []).filter((item) => item.current));
|
||||
} catch (caught) {
|
||||
setSessionsError(caught instanceof ApiError ? caught.message : "Révocation impossible.");
|
||||
}
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<div className="flex justify-center py-16">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<PageHeader title="Mon compte" description="Profil, photo, adresse e-mail et sessions ouvertes." />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Identité</CardTitle>
|
||||
<CardDescription>Informations affichées dans l'interface.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void saveProfile(event)}>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<Input
|
||||
label="Prénom"
|
||||
required
|
||||
maxLength={255}
|
||||
value={firstName}
|
||||
onChange={(event) => setFirstName(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Nom"
|
||||
required
|
||||
maxLength={255}
|
||||
value={lastName}
|
||||
onChange={(event) => setLastName(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{profileError ? <Alert>{profileError}</Alert> : null}
|
||||
{profileMessage ? <Alert tone="success">{profileMessage}</Alert> : null}
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" size="md" isLoading={savingProfile}>
|
||||
Enregistrer
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Photo de profil</CardTitle>
|
||||
<CardDescription>Image carrée, format PNG ou JPEG.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-surface-muted">
|
||||
<img
|
||||
src={`${api.avatarUrl(user.id)}?v=${avatarNonce}`}
|
||||
alt=""
|
||||
className="h-full w-full object-cover"
|
||||
onError={(event) => {
|
||||
event.currentTarget.style.display = "none";
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
<div className="flex flex-col gap-2">
|
||||
<input
|
||||
ref={avatarInput}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp"
|
||||
className="sr-only"
|
||||
onChange={(event) => void changeAvatar(event.target.files?.[0])}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="secondary" size="sm" onClick={() => avatarInput.current?.click()}>
|
||||
Choisir une image
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => void removeAvatar()}>
|
||||
Retirer
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-[0.6875rem] text-subtle-foreground">
|
||||
Si aucune image n'est définie, vos initiales sont affichées.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{avatarError ? <Alert>{avatarError}</Alert> : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Adresse e-mail</CardTitle>
|
||||
<CardDescription>Adresse actuelle : {user.email}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void requestEmail(event)}>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Input
|
||||
label="Nouvelle adresse"
|
||||
type="email"
|
||||
required
|
||||
value={newEmail}
|
||||
onChange={(event) => setNewEmail(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Mot de passe actuel"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{emailError ? <Alert>{emailError}</Alert> : null}
|
||||
{emailMessage ? <Alert tone="success">{emailMessage}</Alert> : null}
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" size="md" isLoading={sendingEmail}>
|
||||
Demander le changement
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Sessions ouvertes</CardTitle>
|
||||
<CardDescription>Appareils actuellement connectés à votre compte.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{sessionsError ? <Alert>{sessionsError}</Alert> : null}
|
||||
{sessions === null ? (
|
||||
<div className="flex justify-center py-6">
|
||||
<Spinner size="sm" />
|
||||
</div>
|
||||
) : sessions.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">Aucune session active.</p>
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-border rounded-md border border-border">
|
||||
{sessions.map((session) => (
|
||||
<li key={session.id} className="flex items-center gap-3 px-3 py-2.5">
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="truncate text-xs font-medium text-foreground">
|
||||
{session.user_agent ? session.user_agent.slice(0, 60) : "Appareil inconnu"}
|
||||
</span>
|
||||
{session.current ? <Badge tone="accent">Cette session</Badge> : null}
|
||||
</span>
|
||||
<span className="block truncate text-[0.6875rem] text-subtle-foreground">
|
||||
{session.ip_address ?? "IP inconnue"} · vue le {formatDate(session.last_seen_at)}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Fermer cette session"
|
||||
disabled={revoking === session.id}
|
||||
onClick={() => void revokeSession(session)}
|
||||
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:text-destructive disabled:opacity-50"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
iconLeading={<TrashIcon className="h-3.5 w-3.5" />}
|
||||
disabled={sessions === null || sessions.length <= 1}
|
||||
onClick={() => void revokeOthers()}
|
||||
>
|
||||
Fermer les autres sessions
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui";
|
||||
import { Alert } from "../components/feedback.js";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
|
||||
export const ResetPassword = () => {
|
||||
const [params] = useSearchParams();
|
||||
const token = params.get("token") ?? "";
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [done, setDone] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (password !== confirm) {
|
||||
setError("Les deux mots de passe ne correspondent pas.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.resetPassword(token, password);
|
||||
setDone(true);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Réinitialisation impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<header className="mb-6 text-center">
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
</p>
|
||||
<h1 className="font-display mt-2 text-lg font-semibold uppercase tracking-label text-foreground">
|
||||
Nouveau mot de passe
|
||||
</h1>
|
||||
</header>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Réinitialisation</CardTitle>
|
||||
<CardDescription>Choisissez un mot de passe robuste.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!token ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Alert>Ce lien est incomplet ou invalide.</Alert>
|
||||
<Link
|
||||
to="/forgot-password"
|
||||
className="text-center text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
|
||||
>
|
||||
Demander un nouveau lien
|
||||
</Link>
|
||||
</div>
|
||||
) : done ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Alert tone="success">
|
||||
Votre mot de passe a été réinitialisé. Vous pouvez vous connecter.
|
||||
</Alert>
|
||||
<Link to="/login">
|
||||
<Button size="lg" fullWidth>
|
||||
Se connecter
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Nouveau mot de passe"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
minLength={8}
|
||||
autoFocus
|
||||
hint="8 caractères minimum."
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Confirmation"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
minLength={8}
|
||||
value={confirm}
|
||||
onChange={(event) => setConfirm(event.target.value)}
|
||||
/>
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
<Button type="submit" size="lg" fullWidth isLoading={busy}>
|
||||
Réinitialiser
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Button, Input, Spinner } from "@cohaise/ui";
|
||||
import { ApiError, api, formatBytes, type Folder, type UploadedFile } from "../lib/api.js";
|
||||
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
|
||||
import { DownloadIcon, FileIcon, FolderIcon, SearchIcon } from "../components/icons.js";
|
||||
|
||||
interface Results {
|
||||
folders: Folder[];
|
||||
files: UploadedFile[];
|
||||
}
|
||||
|
||||
export const Search = () => {
|
||||
const [q, setQ] = useState("");
|
||||
const [results, setResults] = useState<Results | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const query = q.trim();
|
||||
if (query.length < 2) {
|
||||
setError("Saisissez au moins deux caractères.");
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { folders, files } = await api.search(query);
|
||||
setResults({ folders, files });
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Recherche impossible.");
|
||||
setResults(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const total = results ? results.folders.length + results.files.length : 0;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<PageHeader
|
||||
title="Recherche"
|
||||
description="Recherchez par nom dans les dossiers et fichiers auxquels vous avez accès."
|
||||
/>
|
||||
|
||||
<form className="flex items-end gap-2" onSubmit={(event) => void submit(event)}>
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
label="Terme recherché"
|
||||
type="search"
|
||||
autoFocus
|
||||
placeholder="facture, rapport…"
|
||||
value={q}
|
||||
onChange={(event) => setQ(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
size="md"
|
||||
isLoading={loading}
|
||||
iconLeading={<SearchIcon className="h-3.5 w-3.5" />}
|
||||
>
|
||||
Rechercher
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-16">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
) : results === null ? null : total === 0 ? (
|
||||
<EmptyState
|
||||
icon={<SearchIcon className="h-8 w-8" />}
|
||||
title="Aucun résultat"
|
||||
description={`Rien ne correspond à « ${q.trim()} ».`}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col gap-6">
|
||||
{results.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="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{results.folders.map((folder) => (
|
||||
<li key={folder.id} className="flex items-center gap-3 px-3 py-2.5">
|
||||
<span className="shrink-0 text-accent">
|
||||
<FolderIcon className="h-5 w-5" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
|
||||
{folder.name}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{results.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">
|
||||
{results.files.map((file) => (
|
||||
<li key={file.id} className="flex items-center gap-3 px-3 py-2.5">
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
<FileIcon className="h-5 w-5" />
|
||||
</span>
|
||||
<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)}
|
||||
</span>
|
||||
</span>
|
||||
<a
|
||||
href={api.downloadUrl(file.id)}
|
||||
download={file.name}
|
||||
aria-label={`Télécharger ${file.name}`}
|
||||
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground"
|
||||
>
|
||||
<DownloadIcon className="h-4 w-4" />
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,185 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Button, Spinner } from "@cohaise/ui";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatBytes,
|
||||
formatDate,
|
||||
type TrashFile,
|
||||
type TrashFolder,
|
||||
} from "../lib/api.js";
|
||||
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
|
||||
import { IconAction } from "../components/IconAction.js";
|
||||
import { FileIcon, FolderIcon, RestoreIcon, TrashIcon } from "../components/icons.js";
|
||||
|
||||
interface TrashData {
|
||||
retentionDays: number;
|
||||
folders: TrashFolder[];
|
||||
files: TrashFile[];
|
||||
}
|
||||
|
||||
export const Trash = () => {
|
||||
const [data, setData] = useState<TrashData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
setData(await api.trash());
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
|
||||
setData(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const run = async (key: string, action: () => Promise<unknown>) => {
|
||||
setBusy(key);
|
||||
setError(null);
|
||||
try {
|
||||
await action();
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Action impossible.");
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const emptyTrash = () => {
|
||||
if (!window.confirm("Vider définitivement la corbeille ?")) return;
|
||||
void run("empty", () => api.emptyTrash());
|
||||
};
|
||||
|
||||
const empty = data !== null && data.folders.length === 0 && data.files.length === 0;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<PageHeader
|
||||
title="Corbeille"
|
||||
description={
|
||||
data
|
||||
? `Les éléments sont définitivement supprimés après ${data.retentionDays} jours.`
|
||||
: "Éléments supprimés récemment."
|
||||
}
|
||||
actions={
|
||||
data && !empty ? (
|
||||
<Button variant="destructive" size="sm" isLoading={busy === "empty"} onClick={emptyTrash}>
|
||||
Vider la corbeille
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
{error ? <Alert>{error}</Alert> : null}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-16">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
) : empty ? (
|
||||
<EmptyState
|
||||
icon={<TrashIcon className="h-8 w-8" />}
|
||||
title="Corbeille vide"
|
||||
description="Aucun élément supprimé pour le moment."
|
||||
/>
|
||||
) : data ? (
|
||||
<div className="flex flex-col gap-6">
|
||||
{data.folders.length > 0 ? (
|
||||
<section aria-label="Dossiers supprimés">
|
||||
<h2 className="mb-2 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
|
||||
Dossiers
|
||||
</h2>
|
||||
<ul className="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{data.folders.map((folder) => (
|
||||
<li key={folder.id} className="flex items-center gap-3 px-3 py-2.5">
|
||||
<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="block text-[0.6875rem] text-subtle-foreground">
|
||||
Supprimé le {formatDate(folder.deleted_at)}
|
||||
</span>
|
||||
</span>
|
||||
<IconAction
|
||||
label={`Restaurer ${folder.name}`}
|
||||
icon={<RestoreIcon className="h-4 w-4" />}
|
||||
isLoading={busy === `restore-${folder.id}`}
|
||||
onClick={() =>
|
||||
void run(`restore-${folder.id}`, () => api.restoreFolder(folder.id))
|
||||
}
|
||||
/>
|
||||
<IconAction
|
||||
label={`Supprimer définitivement ${folder.name}`}
|
||||
icon={<TrashIcon className="h-4 w-4" />}
|
||||
tone="danger"
|
||||
isLoading={busy === `purge-${folder.id}`}
|
||||
onClick={() => {
|
||||
if (window.confirm(`Supprimer définitivement « ${folder.name} » ?`)) {
|
||||
void run(`purge-${folder.id}`, () => api.purgeFolder(folder.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{data.files.length > 0 ? (
|
||||
<section aria-label="Fichiers supprimés">
|
||||
<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">
|
||||
{data.files.map((file) => (
|
||||
<li key={file.id} className="flex items-center gap-3 px-3 py-2.5">
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
<FileIcon className="h-5 w-5" />
|
||||
</span>
|
||||
<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)} · supprimé le {formatDate(file.deleted_at)}
|
||||
</span>
|
||||
</span>
|
||||
<IconAction
|
||||
label={`Restaurer ${file.name}`}
|
||||
icon={<RestoreIcon className="h-4 w-4" />}
|
||||
isLoading={busy === `restore-${file.id}`}
|
||||
onClick={() =>
|
||||
void run(`restore-${file.id}`, () => api.restoreFile(file.id))
|
||||
}
|
||||
/>
|
||||
<IconAction
|
||||
label={`Supprimer définitivement ${file.name}`}
|
||||
icon={<TrashIcon className="h-4 w-4" />}
|
||||
isLoading={busy === `purge-${file.id}`}
|
||||
tone="danger"
|
||||
onClick={() =>
|
||||
void run(`purge-${file.id}`, () => api.purgeFile(file.id))
|
||||
}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
@import "tailwindcss";
|
||||
@import "@cohaise/ui/styles";
|
||||
|
||||
@source "../../../../frontend/shared/src";
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/tsconfig",
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"jsx": "react-jsx",
|
||||
"types": ["vite/client"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx"]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
host: true,
|
||||
port: 5174,
|
||||
// En developpement, l'API tourne sur 3001 ; en production nginx
|
||||
// intercepte /api/ lui-meme. Meme chemin des deux cotes.
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://127.0.0.1:3101",
|
||||
changeOrigin: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user