chore: initial import of CoHaiSe Cloud
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:
2026-10-14 15:24:06 +02:00
commit cc397e96d8
113 changed files with 12678 additions and 0 deletions
+14
View File
@@ -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>
+27
View File
@@ -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"
}
}
+10
View File
@@ -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;
}
})();
+73
View File
@@ -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>
);
+154
View File
@@ -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>
);
+381
View File
@@ -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>
);
};
+136
View File
@@ -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>
);
+160
View File
@@ -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>
);
+370
View File
@@ -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" }) : "—";
+58
View File
@@ -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;
};
+22
View File
@@ -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>,
);
+753
View File
@@ -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>
);
};
+449
View File
@@ -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>
);
};
+108
View File
@@ -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>
);
};
+81
View File
@@ -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>
);
};
+142
View File
@@ -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>
);
};
+91
View File
@@ -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>
);
};
+316
View File
@@ -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>
);
};
+106
View File
@@ -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>
);
};
+138
View File
@@ -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>
);
};
+185
View File
@@ -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>
);
};
+4
View File
@@ -0,0 +1,4 @@
@import "tailwindcss";
@import "@cohaise/ui/styles";
@source "../../../../frontend/shared/src";
+11
View File
@@ -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"]
}
+19
View File
@@ -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,
},
},
},
});
+186
View File
@@ -0,0 +1,186 @@
# @cohaise/ui
Design system du Cloud. Point d'entrée unique des jetons de style
utilisés par `frontend/cloud`, garantissant une identité visuelle
homogène et la thématisation dynamique clair/sombre.
## Couche de jetons
Ce paquet expose une chaîne CSS en trois fichiers, du plus primitif au plus dérivé.
| Fichier | Rôle |
|---|---|
| `src/styles/tokens.css` | Variables CSS brutes (`--cohaise-*`). Échelle de gris en `oklch`, jetons sémantiques, ombres, typographie, rayons, courbes et durées de mouvement. |
| `src/styles/theme.css` | Directive `@theme inline` mappant les variables brutes vers les utilitaires Tailwind (`bg-surface`, `text-muted-foreground`, `border-border`...). |
| `src/styles/index.css` | Point d'entrée, importe les deux fichiers ci-dessus. |
### Mouvement
Tailwind v4 ne réserve pas de namespace de thème aux durées : `duration-*` est un
utilitaire à valeur nue. Les trois durées sont donc exposées via `@utility` dans
`theme.css`, adossées aux jetons `--cohaise-duration-*`.
`--default-transition-duration` et `--default-transition-timing-function` sont
également déclarés, si bien que toute classe `transition-*` hérite du mouvement du
design system sans avoir à le répéter :
```css
.transition-colors {
transition-timing-function: var(--tw-ease, var(--cohaise-ease-out-soft));
transition-duration: var(--tw-duration, var(--cohaise-duration-base));
}
```
Les utilitaires `duration-fast`, `duration-base`, `duration-slow` et `ease-out-soft`
surchargent ces valeurs au cas par cas.
### Chaîne de résolution
```mermaid
flowchart TD
A["tokens.css<br/>--cohaise-gray-*, --cohaise-crimson-*"] --> B["tokens.css<br/>--cohaise-background, --cohaise-border, ..."]
B --> C["theme.css<br/>@theme inline"]
C --> D["Tailwind CSS<br/>compile les utilitaires"]
D --> E["frontend/cloud"]
F["Classe .dark sur &lt;html&gt;"] -.->|surcharge les jetons sémantiques| B
```
L'échelle de gris et l'échelle carmin sont les seules sources de vérité des couleurs
brutes. Les jetons sémantiques n'y font référence que par `var()`, jamais par une valeur
littérale, sauf pour les statuts (`success`, `warning`, `info`) et l'ombre carmin, qui
n'existent que dans le mode sombre.
La source de vérité du rouge est `--clr-accent` du site, soit `#b71c1c`, et non le
carmin `#c3073f` qui apparaît davantage dans la feuille de style compilée. Les deux
valeurs ont été retenues à un moment de la construction du thème : le carmin est plus
vif, la valeur déclarée plus profonde et moins magenta. Sur un outil de gestion de
fichiers, c'est la seconde qui tient le mieux sur de grandes surfaces.
## Couleurs
Les valeurs viennent de `esiah.dev`. Le fond sombre est un noir à dominante rouge
(`#050000`), pas un gris neutre, et l'accent est le carmin `#b71c1c`.
| Rôle | Clair | Sombre |
|---|---|---|
| Fond | `#f7f5f4` | `#050000` |
| Surface | `#ffffff` | `#1a0505` |
| Surface surélevée | `#ffffff` | `#1e1e22` |
| Texte | `#1a1a1a` | `#f4f4f2` |
| Texte atténué | `#5c5656` | `#a8a0a0` |
| Primaire | `#b71c1c` | `#b71c1c` |
| Accent graphique | `#b71c1c` | `#c92a2a` |
| Filet de séparation | `#e8dcdc` | `#2e1c1c` |
Un seul rouge de marque dans les deux modes, ce qui rend les captures et les
comparaisons d'écran reproductibles. Il n'est appliqué qu'en aplat plein, avec du texte
blanc dessus, où il atteint 6,57:1.
`accent-graphic` est un ton séparé, réservé aux **petits éléments posés sur** une
surface : filet de carte, carré de liste, anneau de focus. Ces éléments sont lus comme
interface et relèvent du seuil de 3:1, or le rouge de marque ne donne que 2,65:1 sur la
surface sombre. Le même raisonnement impose une bordure de champ distincte, à 3,57:1 en
sombre et 3,73:1 en clair.
**Le destructif est ambre, pas rouge.** C'est une décision de lisibilité, pas un goût :
l'accent du site est un rouge, donc un bouton « supprimer » rouge serait confondu avec un
bouton d'accent. `destructive` occupe donc le ton `oklch(0.768 0.188 70)`, déjà présent
dans la palette, et `warning` garde le jaune plus clair. Le prix à payer est que
« supprimer » et « attention » sont proches en teinte ; ils ne se croisent jamais dans le
même écran, et c'est un choix à revoir si l'interface grossit.
**Les bordures de champs de formulaire ont leur propre jeton.** Les bordures
décoratives restent très discrètes, `1.2:1` sur le fond en mode sombre, pour respecter le
grain du site. Un champ de formulaire doit en revanche pouvoir être identifié sans le
remplir ni le survoler, ce que la WCAG 1.4.11 chiffre à `3:1`. `border-control` est
donc nettement plus clair, `3.5:1` en sombre et `3.7:1` en clair, et c'est lui que
`Input` utilise. Les deux valeurs ont été retenues en mesurant le contraste réel plutôt
qu'à l'œil.
## Polices
| Usage | Police | Variable |
|---|---|---|
| Titres, libellés, boutons | Orbitron | `--cohaise-font-display` |
| Texte courant et paragraphes | Poppins | `--cohaise-font-sans` |
| Marque | Orbitron | `--cohaise-font-logo` |
| Accroche courte, registre éditorial | Cinzel | `--cohaise-font-serif` |
| Code | JetBrains Mono et replis | `--cohaise-font-mono` |
Le partage vient du site, où `body` est en Orbitron. Orbitron a une chasse très large : à
32 px, un titre paraît écrit à la main, et un mot-symbole doit être resserré pour ne pas
s'éparpiller. D'où quatre jetons d'interlettrage dédiés, dont un négatif pour les titres.
Orbitron est donc cantonnée aux **chaînes courtes** — titres jusqu'à `h3`, libellés en
capitales, boutons — avec `tracking-label` en positif. Au-delà de `h3`, la chasse est trop
large pour la taille du texte. Le flux est en Poppins. C'est pourquoi `font-display` est
appliqué dans la couche `base` plutôt que laissé au soin de chaque composant : c'est la
seule façon d'éviter qu'un titre revienne en Poppins parce qu'un écran l'a oublié.
Cinzel est conservée en réserve. C'est un bon caractère, mais une serif d'inscription
romaine sur des libellés d'interface ou un paragraphe devient vite illisible, et c'est
précisément ce qui donnait au premier jet de ce thème son aspect de thème généré.
Les trois faces sont **auto-hébergées** dans `frontend/shared/fonts`, 53,6 Ko au total,
soit 30 Ko de moins que Roboto seul. Un appel à Google Fonts aurait fait fuiter l'adresse
IP de chaque visiteur de ton NAS vers un tiers, ce qui n'a pas sa place dans une
application privée.
## Modes clair et sombre
Le mode est piloté par la classe `.dark` appliquée sur `<html>`. `:root` porte le mode
clair, `.dark` surcharge l'ensemble des jetons sémantiques. `color-scheme` est défini
sur les deux blocs pour aligner les contrôles natifs et les barres de défilement.
```mermaid
flowchart LR
subgraph Light["`:root` — mode clair"]
LA["--cohaise-background<br/>#f7f5f4"]
LB["--cohaise-foreground<br/>#1a1a1a"]
LC["--cohaise-primary<br/>#b71c1c"]
end
subgraph Dark["`.dark` — mode sombre"]
DA["--cohaise-background<br/>#050000"]
DB["--cohaise-foreground<br/>#f4f4f2"]
DC["--cohaise-primary<br/>#b71c1c"]
end
Light -->|bascule de classe| Dark
```
Aucune règle `@media (prefers-color-scheme)` n'est déclarée : la bascule est
explicite, ce qui garantit un comportement unique quelle que soit la préférence
système.
## Forme
Les rayons sont quasi nuls, de 2 à 6 px, contre 4 à 12 px pour les valeurs par défaut de
Tailwind. Les tuiles à coins arrondis sont la signature la plus immédiate d'une interface
sans intention, et un registre d'instrument se lit dans l'angle autant que dans la
couleur.
Trois marques complètent le registre : un filet carmin d'un pixel en tête de `Card`, un
carré plein de 6 px devant chaque élément de liste au lieu d'une puce ronde, et des
libellés en capitales espacées. Aucune n'est décorative au sens strict : elles servent à
séparer des blocs sans ajouter de bordure lourde, et à rendre les métriques denses
scannables.
## Consommation
```css
@import "tailwindcss";
@import "@cohaise/ui/styles";
```
L'application conserve la main sur la directive `tailwindcss` et sur sa configuration ;
ce paquet ne fournit que les jetons. Le build Vite résout l'entrée via le champ
`exports` du `package.json`.
## Contraintes
- Aucune valeur de couleur littérale n'est autorisée dans les composants : uniquement
des utilitaires derivés des jetons sémantiques, sinon la thématisation casse.
- `@theme inline` est obligatoire plutôt que `@theme`, car les utilitaires doivent
référencer la variable pour résoudre la valeur au changement de mode.
- Aucune durée ne doit être écrite en dur dans un composant (`duration-150` est
interdit) : passer par `duration-fast`, `duration-base` ou `duration-slow`.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
{
"name": "@cohaise/ui",
"version": "0.0.0",
"private": true,
"type": "module",
"sideEffects": ["**/*.css"],
"style": "./src/styles/index.css",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./styles": "./src/styles/index.css",
"./styles/tokens": "./src/styles/tokens.css",
"./styles/theme": "./src/styles/theme.css"
},
"files": ["dist", "src/styles"],
"scripts": {
"build": "tsc --build",
"clean": "node --eval \"import('node:fs').then(fs => { fs.rmSync('dist', { recursive: true, force: true }); fs.rmSync('tsconfig.tsbuildinfo', { force: true }); })\"",
"typecheck": "tsc --noEmit"
},
"peerDependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"typescript": "^7.0.2"
},
"dependencies": {
"clsx": "^2.1.1",
"tailwind-merge": "^3.7.0"
}
}
+72
View File
@@ -0,0 +1,72 @@
import type { ButtonHTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn.js";
import { Spinner } from "./Spinner.js";
import type { SpinnerSize } from "./Spinner.js";
const variantClasses = {
primary: "bg-primary text-primary-foreground hover:bg-primary-hover",
secondary: "border border-border-strong bg-surface text-foreground hover:bg-surface-hover",
ghost: "text-foreground hover:bg-surface-hover",
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive-hover",
} as const;
const sizeClasses = {
sm: "h-8 gap-1.5 rounded-sm px-3 text-[0.6875rem]",
md: "h-10 gap-2 rounded-md px-4 text-xs",
lg: "h-12 gap-2.5 rounded-lg px-6 text-sm",
} as const;
const spinnerBySize: Record<keyof typeof sizeClasses, SpinnerSize> = {
sm: "xs",
md: "sm",
lg: "md",
};
export type ButtonVariant = keyof typeof variantClasses;
export type ButtonSize = keyof typeof sizeClasses;
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
size?: ButtonSize;
isLoading?: boolean;
showTextWhileLoading?: boolean;
iconLeading?: ReactNode;
iconTrailing?: ReactNode;
fullWidth?: boolean;
}
export const Button = ({
variant = "primary",
size = "md",
isLoading = false,
showTextWhileLoading = true,
iconLeading,
iconTrailing,
fullWidth = false,
disabled,
type = "button",
className,
children,
...props
}: ButtonProps) => (
<button
type={type}
disabled={disabled === true || isLoading}
aria-busy={isLoading}
className={cn(
"inline-flex select-none items-center justify-center whitespace-nowrap font-display font-semibold uppercase tracking-label",
"focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"transition-[background-color,border-color,color,box-shadow,opacity]",
"disabled:pointer-events-none disabled:opacity-50",
variantClasses[variant],
sizeClasses[size],
fullWidth && "w-full",
className,
)}
{...props}
>
{isLoading ? <Spinner size={spinnerBySize[size]} /> : iconLeading}
{isLoading && !showTextWhileLoading ? null : children}
{isLoading ? null : iconTrailing}
</button>
);
+49
View File
@@ -0,0 +1,49 @@
import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn.js";
export const Card = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"relative overflow-hidden rounded-lg border border-border bg-surface text-foreground shadow-sm",
"transition-colors duration-base ease-out-soft",
className,
)}
{...props}
/>
);
/* Signature du produit : un filet carmin d'un pixel en tete de carte. Invisible sur
une grille dense, mais c'est lui qui donne aux cartes leur epaisseur et evite
l'aspect de tuiles interchangeables. */
export const CardHeader = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"relative flex flex-col gap-1.5 p-5",
"before:absolute before:inset-x-0 before:top-0 before:h-px before:bg-accent-graphic",
className,
)}
{...props}
/>
);
export const CardTitle = ({ className, ...props }: HTMLAttributes<HTMLHeadingElement>) => (
<h3
className={cn(
"font-display text-sm font-semibold uppercase leading-tight tracking-label",
className,
)}
{...props}
/>
);
export const CardDescription = ({ className, ...props }: HTMLAttributes<HTMLParagraphElement>) => (
<p className={cn("text-sm leading-relaxed text-muted-foreground", className)} {...props} />
);
export const CardContent = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (
<div className={cn("p-5 pt-0", className)} {...props} />
);
export const CardFooter = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex items-center gap-2 p-5 pt-0", className)} {...props} />
);
+72
View File
@@ -0,0 +1,72 @@
import { useId } from "react";
import type { InputHTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn.js";
export interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "size"> {
label?: ReactNode;
hint?: ReactNode;
error?: ReactNode;
sizeVariant?: "sm" | "md" | "lg";
}
const inputSize = {
sm: "h-8 px-2.5 text-xs",
md: "h-10 px-3 text-sm",
lg: "h-12 px-4 text-base",
} as const;
export const Input = ({
label,
hint,
error,
sizeVariant = "md",
id,
className,
disabled,
...props
}: InputProps) => {
const generatedId = useId();
const inputId = id ?? generatedId;
const messageId = `${inputId}-message`;
const isInvalid = error !== undefined && error !== null && error !== "";
return (
<div className="flex w-full flex-col gap-1.5">
{label ? (
<label
htmlFor={inputId}
className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground"
>
{label}
</label>
) : null}
<input
id={inputId}
disabled={disabled}
aria-invalid={isInvalid}
aria-describedby={isInvalid || hint ? messageId : undefined}
className={cn(
"w-full rounded-sm border bg-surface text-foreground placeholder:text-subtle-foreground",
"transition-[background-color,border-color,box-shadow] duration-fast ease-out-soft",
"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",
"disabled:cursor-not-allowed disabled:bg-surface-muted disabled:opacity-60",
isInvalid ? "border-destructive focus-visible:ring-destructive" : "border-border-control",
inputSize[sizeVariant],
className,
)}
{...props}
/>
{isInvalid || hint ? (
<p
id={messageId}
role={isInvalid ? "alert" : undefined}
className={cn("text-xs leading-relaxed", isInvalid ? "text-destructive" : "text-muted-foreground")}
>
{isInvalid ? error : hint}
</p>
) : null}
</div>
);
};
@@ -0,0 +1,32 @@
import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn.js";
export type SkeletonProps = HTMLAttributes<HTMLDivElement> & {
width?: string;
height?: string;
radius?: "sm" | "md" | "lg" | "xl" | "full";
};
const skeletonRadius = {
sm: "rounded-sm",
md: "rounded-md",
lg: "rounded-lg",
xl: "rounded-xl",
full: "rounded-full",
} as const;
export const Skeleton = ({
width,
height,
radius = "md",
className,
style,
...props
}: SkeletonProps) => (
<div
aria-hidden="true"
style={{ width, height, ...style }}
className={cn("animate-pulse bg-skeleton-base motion-reduce:animate-none", skeletonRadius[radius], className)}
{...props}
/>
);
@@ -0,0 +1,36 @@
import type { SVGProps } from "react";
import { cn } from "../lib/cn.js";
const spinnerSize = {
xs: "size-3",
sm: "size-3.5",
md: "size-4",
lg: "size-4.5",
} as const;
export type SpinnerSize = keyof typeof spinnerSize;
export interface SpinnerProps extends Omit<SVGProps<SVGSVGElement>, "children"> {
size?: SpinnerSize;
label?: string;
}
export const Spinner = ({ size = "md", label, className, ...props }: SpinnerProps) => (
<svg
viewBox="0 0 24 24"
fill="none"
role={label ? "status" : undefined}
aria-label={label}
aria-hidden={label ? undefined : true}
className={cn("shrink-0 animate-spin motion-reduce:animate-none", spinnerSize[size], className)}
{...props}
>
<circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2.5" opacity="0.25" />
<path
d="M21 12a9 9 0 0 0-9-9"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
/>
</svg>
);
+10
View File
@@ -0,0 +1,10 @@
export { cn } from "./lib/cn.js";
export type { SpinnerProps, SpinnerSize } from "./components/Spinner.js";
export { Spinner } from "./components/Spinner.js";
export type { ButtonProps, ButtonSize, ButtonVariant } from "./components/Button.js";
export { Button } from "./components/Button.js";
export type { SkeletonProps } from "./components/Skeleton.js";
export { Skeleton } from "./components/Skeleton.js";
export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "./components/Card.js";
export type { InputProps } from "./components/Input.js";
export { Input } from "./components/Input.js";
+5
View File
@@ -0,0 +1,5 @@
import { clsx } from "clsx";
import type { ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export const cn = (...inputs: ClassValue[]): string => twMerge(clsx(inputs));
+61
View File
@@ -0,0 +1,61 @@
/*
Poppins n'existe qu'en graisses statiques chez Google Fonts, deux fichiers sont donc
necessaires. Elle couvre 300 Ko de plus que Cinzel et Orbitron reunis, d'ou l'arbitrage
suivant : Poppins porte le texte courant, Cinzel et Orbitron restent deux faces de
caractere Reserves aux chaines courtes.
*/
@font-face {
font-family: "Poppins";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("../../fonts/poppins-400.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193,
U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: "Poppins";
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("../../fonts/poppins-600.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193,
U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: "JetBrains Mono";
font-style: normal;
font-weight: 400 700;
font-display: swap;
src: url("../../fonts/jetbrains-mono-latin.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193,
U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: "Orbitron";
font-style: normal;
font-weight: 400 900;
font-display: swap;
src: url("../../fonts/orbitron-latin.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193,
U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: "Cinzel";
font-style: normal;
font-weight: 400 900;
font-display: swap;
src: url("../../fonts/cinzel-latin.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193,
U+2212, U+2215, U+FEFF, U+FFFD;
}
+3
View File
@@ -0,0 +1,3 @@
@import "./fonts.css";
@import "./tokens.css";
@import "./theme.css";
+105
View File
@@ -0,0 +1,105 @@
@theme inline {
--color-background: var(--cohaise-background);
--color-foreground: var(--cohaise-foreground);
--color-surface: var(--cohaise-surface);
--color-surface-raised: var(--cohaise-surface-raised);
--color-surface-sunken: var(--cohaise-surface-sunken);
--color-surface-muted: var(--cohaise-surface-muted);
--color-surface-hover: var(--cohaise-surface-hover);
--color-surface-overlay: var(--cohaise-surface-overlay);
--color-muted-foreground: var(--cohaise-muted-foreground);
--color-subtle-foreground: var(--cohaise-subtle-foreground);
--color-border: var(--cohaise-border);
--color-border-strong: var(--cohaise-border-strong);
--color-border-control: var(--cohaise-border-control);
--color-primary: var(--cohaise-primary);
--color-primary-foreground: var(--cohaise-primary-foreground);
--color-primary-hover: var(--cohaise-primary-hover);
--color-accent: var(--cohaise-accent);
--color-accent-foreground: var(--cohaise-accent-foreground);
--color-accent-hover: var(--cohaise-accent-hover);
--color-accent-graphic: var(--cohaise-accent-graphic);
--color-ring: var(--cohaise-ring);
--color-destructive: var(--cohaise-destructive);
--color-destructive-foreground: var(--cohaise-destructive-foreground);
--color-destructive-hover: var(--cohaise-destructive-hover);
--color-success: var(--cohaise-success);
--color-success-foreground: var(--cohaise-success-foreground);
--color-warning: var(--cohaise-warning);
--color-warning-foreground: var(--cohaise-warning-foreground);
--color-info: var(--cohaise-info);
--color-info-foreground: var(--cohaise-info-foreground);
--color-skeleton-base: var(--cohaise-skeleton-base);
--color-skeleton-highlight: var(--cohaise-skeleton-highlight);
--shadow-sm: var(--cohaise-shadow-sm);
--shadow-md: var(--cohaise-shadow-md);
--shadow-lg: var(--cohaise-shadow-lg);
--shadow-crimson: var(--cohaise-shadow-crimson, 0 0 0 0 transparent);
--font-display: var(--cohaise-font-display);
--font-logo: var(--cohaise-font-logo);
--font-sans: var(--cohaise-font-sans);
--font-serif: var(--cohaise-font-serif);
--font-mono: var(--cohaise-font-mono);
--tracking-display: var(--cohaise-tracking-display);
--tracking-logo: var(--cohaise-tracking-logo);
--tracking-label: var(--cohaise-tracking-label);
--tracking-body: var(--cohaise-tracking-body);
--radius-sm: var(--cohaise-radius-sm);
--radius-md: var(--cohaise-radius-md);
--radius-lg: var(--cohaise-radius-lg);
--radius-xl: var(--cohaise-radius-xl);
--radius-full: var(--cohaise-radius-full);
--ease-out-soft: var(--cohaise-ease-out-soft);
--ease-in-out-soft: var(--cohaise-ease-in-out-soft);
--default-transition-duration: var(--cohaise-duration-base);
--default-transition-timing-function: var(--cohaise-ease-out-soft);
}
@layer base {
html,
body {
background-color: var(--cohaise-background);
}
body {
color: var(--cohaise-foreground);
font-family: var(--cohaise-font-sans);
letter-spacing: var(--cohaise-tracking-body);
}
/* Orbitron sur les titres seulement, jusqu'a h3. Au-dela la chasse est trop large
pour la taille du texte et le titre devient illisible. */
h1,
h2,
h3 {
font-family: var(--cohaise-font-display);
letter-spacing: var(--cohaise-tracking-display);
}
}
@utility duration-fast {
transition-duration: var(--cohaise-duration-fast);
}
@utility duration-base {
transition-duration: var(--cohaise-duration-base);
}
@utility duration-slow {
transition-duration: var(--cohaise-duration-slow);
}
+176
View File
@@ -0,0 +1,176 @@
:root {
color-scheme: light;
--cohaise-gray-50: #f7f5f4;
--cohaise-gray-100: #f0eeee;
--cohaise-gray-200: #e4e0e0;
--cohaise-gray-300: #d6d1d1;
--cohaise-gray-400: #a8a0a0;
--cohaise-gray-500: #7a7373;
--cohaise-gray-600: #5c5656;
--cohaise-gray-700: #423d3d;
--cohaise-gray-800: #2a2626;
--cohaise-gray-900: #1a1616;
--cohaise-gray-950: #0d0909;
/* Echelle organisee autour de #b71c1c, la valeur reelle de --clr-accent du site.
Les tons plus sombres servent au survol en mode clair, les plus clairs au
survol et au focus en mode sombre. */
--cohaise-crimson-950: #3d070e;
--cohaise-crimson-900: #5e0a14;
--cohaise-crimson-800: #8f1116;
--cohaise-crimson-700: #b71c1c;
--cohaise-crimson-600: #c92a2a;
--cohaise-crimson-500: #d32f2f;
--cohaise-yellow-500: oklch(0.828 0.189 84);
--cohaise-background: var(--cohaise-gray-50);
--cohaise-foreground: #1a1a1a;
--cohaise-surface: #ffffff;
--cohaise-surface-raised: #ffffff;
--cohaise-surface-sunken: #f0eeee;
--cohaise-surface-muted: #f4f2f2;
--cohaise-surface-hover: #ece8e8;
--cohaise-surface-overlay: #ffffff;
--cohaise-muted-foreground: #5c5656;
--cohaise-subtle-foreground: #7a7373;
/* Les separateurs sont des filets carmin tres desatures, pas du gris. C'est ce
qui donne au produit son teinte plutot que celle d'une carte bancaire. */
--cohaise-border: #e8dcdc;
--cohaise-border-strong: #d4bfbf;
--cohaise-border-control: #8f8181;
--cohaise-primary: var(--cohaise-crimson-700);
--cohaise-primary-foreground: #ffffff;
--cohaise-primary-hover: var(--cohaise-crimson-800);
--cohaise-accent: var(--cohaise-crimson-700);
--cohaise-accent-foreground: #ffffff;
--cohaise-accent-hover: var(--cohaise-crimson-800);
/* Ton dedie aux petits elements qui sont poses SUR une surface, donc lus
comme element d'interface et non comme aplat de marque : filet de carte,
carre de liste, anneau de focus. Le rouge de marque n'y atteint que
2.65:1 sur la surface sombre. */
--cohaise-accent-graphic: var(--cohaise-crimson-700);
--cohaise-ring: var(--cohaise-crimson-700);
--cohaise-destructive: #d32f2f;
--cohaise-destructive-foreground: #ffffff;
--cohaise-destructive-hover: #a31818;
--cohaise-success: oklch(0.52 0.128 155);
--cohaise-success-foreground: #ffffff;
--cohaise-warning: var(--cohaise-yellow-500);
--cohaise-warning-foreground: #1a0505;
--cohaise-info: #0f6d78;
--cohaise-info-foreground: #ffffff;
--cohaise-skeleton-base: #e4e0e0;
--cohaise-skeleton-highlight: #f7f5f4;
--cohaise-shadow-sm: 0 1px 2px 0 oklch(0.1 0.02 20 / 0.06);
--cohaise-shadow-md: 0 4px 12px -2px oklch(0.1 0.02 20 / 0.1);
--cohaise-shadow-lg: 0 12px 32px -8px oklch(0.1 0.02 20 / 0.16);
/* Orbitron porte les chaines courtes, la marque et les titres. Poppins porte le
texte courant : Orbitron est trop large pour etre lu en flux. Cinzel reste
disponible pour une accroche courte ou Editorial, jamais pour un paragraphe. */
--cohaise-font-display: "Orbitron", "Cinzel", sans-serif;
--cohaise-font-logo: "Orbitron", "Cinzel", sans-serif;
--cohaise-font-sans: "Poppins", ui-sans-serif, system-ui, -apple-system, "Segoe UI",
sans-serif;
--cohaise-font-serif: "Cinzel", "Times New Roman", serif;
/* Auto-hebergee comme les trois autres. En repli systeme, la meme taille de
chiffres se rendait differemment sur le P330, le portable et le telephone. */
--cohaise-font-mono: "JetBrains Mono", ui-monospace, "SFMono-Regular", "Menlo",
"Consolas", monospace;
/* Orbitron a des chassees tres larges : sans correction, un titre de 32 px
parait avoir ete espace a la main et un mot-symlose des caracteres. */
--cohaise-tracking-display: -0.015em;
--cohaise-tracking-logo: 0.16em;
--cohaise-tracking-label: 0.09em;
--cohaise-tracking-body: 0;
/* Deux echelles et non une seule. Un conteneur qui enveloppe du contenu
merite d'etre plus doux qu'un bouton qu'on presse : c'est ce decalage qui
donne la hierarchie, la ou un rayon unique uniforme rend tout interchangeable. */
--cohaise-radius-sm: 0.375rem;
--cohaise-radius-md: 0.5rem;
--cohaise-radius-lg: 0.75rem;
--cohaise-radius-xl: 1rem;
--cohaise-radius-full: 9999px;
--cohaise-ease-out-soft: cubic-bezier(0.22, 1, 0.36, 1);
--cohaise-ease-in-out-soft: cubic-bezier(0.65, 0, 0.35, 1);
--cohaise-duration-fast: 150ms;
--cohaise-duration-base: 250ms;
--cohaise-duration-slow: 400ms;
}
.dark {
color-scheme: dark;
--cohaise-background: #050000;
--cohaise-foreground: #f4f4f2;
/* Surfaces neutres comme sur le site, le fond porte seul la dominante rouge. */
--cohaise-surface: #1a1a1a;
--cohaise-surface-raised: #242424;
--cohaise-surface-sunken: #0a0a0a;
--cohaise-surface-muted: #1f1f1f;
--cohaise-surface-hover: #2a2a2a;
--cohaise-surface-overlay: #242424;
--cohaise-muted-foreground: #a8a0a0;
--cohaise-subtle-foreground: #7a7373;
--cohaise-border: #2e1c1c;
--cohaise-border-strong: #46262a;
--cohaise-border-control: #a85a62;
/* #b71c1c reste lisible dans les deux modes : texte blanc a 6.57:1, et
3.18:1 sur le fond, au-dessus du seuil de 3:1 pour un element d'interface. */
--cohaise-primary: var(--cohaise-crimson-700);
--cohaise-primary-foreground: #ffffff;
--cohaise-primary-hover: var(--cohaise-crimson-600);
--cohaise-accent: var(--cohaise-crimson-700);
--cohaise-accent-foreground: #ffffff;
--cohaise-accent-hover: var(--cohaise-crimson-600);
--cohaise-accent-graphic: var(--cohaise-crimson-600);
--cohaise-ring: var(--cohaise-crimson-600);
--cohaise-destructive: #ef4444;
--cohaise-destructive-foreground: #1a0505;
--cohaise-destructive-hover: #f87171;
--cohaise-success: oklch(0.792 0.152 155);
--cohaise-success-foreground: #050000;
--cohaise-warning: var(--cohaise-yellow-500);
--cohaise-warning-foreground: #1a0505;
--cohaise-info: oklch(0.752 0.112 194);
--cohaise-info-foreground: #050000;
--cohaise-skeleton-base: #2a1a1a;
--cohaise-skeleton-highlight: #3a2222;
--cohaise-shadow-sm: 0 1px 2px 0 oklch(0 0 0 / 0.4);
--cohaise-shadow-md: 0 4px 12px -2px oklch(0 0 0 / 0.5);
--cohaise-shadow-lg: 0 12px 32px -8px oklch(0 0 0 / 0.6);
--cohaise-shadow-crimson: 0 0 0 1px oklch(0.55 0.22 15 / 0.28),
0 8px 30px -12px oklch(0.55 0.22 15 / 0.55);
}
+15
View File
@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"rootDir": "src",
"outDir": "dist",
"composite": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*.ts", "src/**/*.tsx"]
}