Up And Down : première version

This commit is contained in:
cedric committed 2026-11-19 10:30:47 +01:00
commit 89c5430308
76 files changed
+20730

No files matched your search

+1
View File
@@ -0,0 +1 @@
node_modules/
+23
View File
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#2f6fed" />
<meta name="robots" content="noindex" />
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%232f6fed' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M7 18a4.5 4.5 0 0 1-.5-9 6 6 0 0 1 11.4 1.5A3.5 3.5 0 0 1 17.5 18'/%3E%3Cpath d='M9 14l3-3 3 3M12 11v9'/%3E%3C/svg%3E" />
<title>Up And Down</title>
<script>
// Thème appliqué avant le premier rendu (évite un flash clair).
try {
var t = localStorage.getItem("udTheme");
if (t === "dark" || t === "light") document.documentElement.dataset.theme = t;
else if (matchMedia("(prefers-color-scheme: dark)").matches) document.documentElement.dataset.theme = "dark";
} catch (e) {}
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1877
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "upandown-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@vitejs/plugin-react": "^5.0.0",
"typescript": "^5.8.0",
"vite": "^7.0.0"
}
}
+92
View File
@@ -0,0 +1,92 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { createPortal } from "react-dom";
interface Props {
/** Bouton « … » qui a ouvert le menu : le menu s'aligne sur lui. */
anchor: HTMLElement;
onClose: () => void;
children: ReactNode;
}
const MARGIN = 8; // écart minimal avec les bords de la fenêtre
/**
* Menu déroulant des actions d'un élément, ouvert sous le bouton « … » et aligné
* sur son bord droit (au-dessus s'il manque de place en bas). Rendu dans <body>
* pour ne pas être rogné par le défilement de la liste ; refermé par un clic
* ailleurs, Échap, un défilement, un redimensionnement ou le choix d'une action.
*/
export function ActionMenu({ anchor, onClose, children }: Props) {
const ref = useRef<HTMLDivElement>(null);
const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
useLayoutEffect(() => {
const menu = ref.current;
if (!menu) return;
const a = anchor.getBoundingClientRect();
const { offsetWidth: w, offsetHeight: h } = menu;
let top = a.bottom + 4;
if (top + h > innerHeight - MARGIN) top = Math.max(MARGIN, a.top - 4 - h);
const left = Math.min(Math.max(MARGIN, a.right - w), innerWidth - w - MARGIN);
setPos({ top, left });
}, [anchor]);
// Focus sur la première action une fois le menu placé (masqué, il ne le prend pas).
useEffect(() => {
if (pos) ref.current?.querySelector<HTMLElement>("button, a")?.focus({ preventScroll: true });
}, [pos]);
useEffect(() => {
const inside = (t: EventTarget | null) => t instanceof Node && (ref.current?.contains(t) || anchor.contains(t));
const onDown = (ev: PointerEvent) => {
if (!inside(ev.target)) onClose();
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key === "Escape") {
// Ni désélection, ni fermeture du panneau flottant : seulement le menu.
ev.preventDefault();
ev.stopPropagation();
onClose();
anchor.focus();
} else if (ev.key === "ArrowDown" || ev.key === "ArrowUp") {
const items = [...(ref.current?.querySelectorAll<HTMLElement>("button, a") ?? [])];
if (!items.length) return;
ev.preventDefault();
const i = items.indexOf(document.activeElement as HTMLElement);
const next = ev.key === "ArrowDown" ? (i + 1) % items.length : (i - 1 + items.length) % items.length;
items[next].focus();
}
};
const onScroll = (ev: Event) => {
if (!(ev.target instanceof Node && ref.current?.contains(ev.target))) onClose();
};
document.addEventListener("pointerdown", onDown, true);
document.addEventListener("keydown", onKey, true);
document.addEventListener("scroll", onScroll, true);
window.addEventListener("resize", onClose);
return () => {
document.removeEventListener("pointerdown", onDown, true);
document.removeEventListener("keydown", onKey, true);
document.removeEventListener("scroll", onScroll, true);
window.removeEventListener("resize", onClose);
};
}, [anchor, onClose]);
return createPortal(
<div
ref={ref}
className="actions menu-popup"
role="menu"
style={pos ?? { top: 0, left: 0, visibility: "hidden" }}
// Une action choisie referme le menu (après coup, pour laisser un lien de
// téléchargement aboutir).
onClick={(ev) => {
if ((ev.target as HTMLElement).closest("button, a")) setTimeout(onClose);
}}
>
{children}
</div>,
document.body,
);
}
+316
View File
@@ -0,0 +1,316 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { api, FAVORIS, PERSO, POUBELLE, type Entry, type Me } from "./api";
import { ActionMenu } from "./ActionMenu";
import { Explorer } from "./Explorer";
import { Login } from "./Login";
import { SettingsDialog } from "./SettingsDialog";
import { Splitter } from "./Splitter";
import { UploadPanel } from "./UploadPanel";
import { fmtSize, initials } from "./format";
import {
CloudUpIcon,
FolderIcon,
KeyIcon,
LogoutIcon,
MenuIcon,
MoonIcon,
SettingsIcon,
ShareIcon,
ShieldIcon,
StarFilledIcon,
SunIcon,
TrashFullIcon,
TrashIcon,
UserIcon,
UsersIcon,
} from "./icons";
type Theme = "light" | "dark";
const initialTheme = (): Theme => (document.documentElement.dataset.theme === "dark" ? "dark" : "light");
const SIDEBAR_MIN = 200;
const SIDEBAR_MAX = 420;
const SIDEBAR_DEFAULT = 248;
const hashDir = () => {
const h = location.hash.replace(/^#\/?/, "");
try {
return decodeURIComponent(h);
} catch {
return "";
}
};
export default function App() {
const [me, setMe] = useState<Me | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const loadMe = useCallback(
() =>
api
.me()
.then((m) => {
setMe(m);
setLoadError(null);
document.title = m.title || "Up And Down";
})
.catch((e) => setLoadError(e instanceof Error ? e.message : String(e))),
[],
);
useEffect(() => {
loadMe();
}, [loadMe]);
// OIDC seul : pas de page de connexion locale, direction le fournisseur.
const redirecting = !!me && !me.user && me.oidc && !me.local;
useEffect(() => {
if (redirecting) location.replace(`/auth/login?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`);
}, [redirecting]);
if (loadError) {
return (
<main className="login">
<div className="login-card center">
<p className="error">{loadError}</p>
<button className="primary" onClick={loadMe}>
Réessayer
</button>
</div>
</main>
);
}
if (!me || redirecting) return <div className="splash muted">Chargement…</div>;
if (!me.user) return <Login me={me} onLoggedIn={loadMe} />;
return <Shell me={me} reloadMe={loadMe} />;
}
function Shell({ me, reloadMe }: { me: Me; reloadMe: () => Promise<unknown> }) {
const [theme, setTheme] = useState<Theme>(initialTheme);
const [dir, setDir] = useState("");
const [goto, setGoto] = useState<{ dir: string; seq: number }>({ dir: hashDir(), seq: 0 });
const [refreshKey, setRefreshKey] = useState(0);
const [places, setPlaces] = useState<Entry[]>([]);
const [drawer, setDrawer] = useState(false);
const [settings, setSettings] = useState<"account" | "tokens" | "shares" | "general" | "users" | null>(null);
const [userMenu, setUserMenu] = useState<HTMLElement | null>(null);
const [sidebarW, setSidebarW] = useState(() => {
try {
const n = Number(localStorage.getItem("udSidebar"));
return n >= SIDEBAR_MIN && n <= SIDEBAR_MAX ? n : SIDEBAR_DEFAULT;
} catch {
return SIDEBAR_DEFAULT;
}
});
const [resizing, setResizing] = useState(false);
const dirRef = useRef("");
const title = me.title || "Up And Down";
useEffect(() => {
document.documentElement.dataset.theme = theme;
try {
localStorage.setItem("udTheme", theme);
} catch {
/* stockage indisponible */
}
}, [theme]);
// Dossier courant dans l'adresse (#/dossier/sous) : liens directs et bouton « précédent ».
const onDirChange = useCallback((d: string) => {
dirRef.current = d;
setDir(d);
const want = d ? `#/${d.split("/").map(encodeURIComponent).join("/")}` : "";
if (decodeURIComponent(location.hash.replace(/^#\/?/, "")) !== d) {
if (want) location.hash = want;
else history.pushState(null, "", location.pathname + location.search);
}
}, []);
useEffect(() => {
const onHash = () => {
const d = hashDir();
if (d !== dirRef.current) setGoto((g) => ({ dir: d, seq: g.seq + 1 }));
};
window.addEventListener("hashchange", onHash);
window.addEventListener("popstate", onHash);
return () => {
window.removeEventListener("hashchange", onHash);
window.removeEventListener("popstate", onHash);
};
}, []);
const go = (d: string) => {
setGoto((g) => ({ dir: d, seq: g.seq + 1 }));
setDrawer(false);
};
// Dossiers virtuels (Favoris, Personnel, Poubelle) et leurs compteurs.
const loadPlaces = useCallback(() => {
api
.list("")
.then((es) => setPlaces(es.filter((e) => e.special)))
.catch(() => setPlaces([]));
}, []);
useEffect(loadPlaces, [loadPlaces, refreshKey]);
const onMutated = useCallback(() => {
loadPlaces();
reloadMe();
}, [loadPlaces, reloadMe]);
const trash = places.find((p) => p.special === "poubelle");
const user = me.user!;
const root = dir.split("/")[0];
const current = root === PERSO || root === FAVORIS || root === POUBELLE ? root : "";
const navItem = (id: string, text: string, icon: React.ReactNode, active: boolean, badge?: number) => (
<button className={`nav-item ${active ? "on" : ""}`} onClick={() => go(id)} aria-current={active ? "page" : undefined}>
{icon}
<span>{text}</span>
{!!badge && <small className="badge">{badge}</small>}
</button>
);
const usage = me.usage;
const pct = usage && usage.quota > 0 ? Math.min(100, Math.round((usage.used / usage.quota) * 100)) : 0;
return (
<div className={`app ${resizing ? "resizing" : ""}`} style={{ ["--sidebar-w" as string]: `${sidebarW}px` }}>
<header className="topbar">
<button className="icon-btn menu-btn" onClick={() => setDrawer(!drawer)} aria-label="Menu" title="Menu">
<MenuIcon />
</button>
<a className="brand" href="/" onClick={(e) => (e.preventDefault(), go(""))} title={title}>
{me.logo ? <img className="logo" src={api.logoUrl(me.logo)} alt="" /> : <CloudUpIcon size={26} />}
<span>{title}</span>
</a>
<span className="spacer" />
<button className="icon-btn" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label={theme === "dark" ? "Thème clair" : "Thème sombre"} title={theme === "dark" ? "Thème clair" : "Thème sombre"}>
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
</button>
<button className="user-btn" onClick={(e) => setUserMenu(userMenu ? null : e.currentTarget)} aria-haspopup="menu" aria-expanded={!!userMenu} title={`${user.name} (${user.id})`}>
<span className="avatar">{initials(user.name)}</span>
<span className="user-name">{user.name}</span>
{me.admin && me.mode !== "none" && <ShieldIcon size={14} />}
{!!me.pending && <small className="badge">{me.pending}</small>}
</button>
</header>
<div className="layout">
{drawer && <div className="scrim" onClick={() => setDrawer(false)} />}
<aside className={`sidebar ${drawer ? "open" : ""}`}>
<nav>
{navItem("", "Fichiers", <FolderIcon />, current === "")}
{navItem(PERSO, "Personnel", <UserIcon />, current === PERSO)}
{navItem(FAVORIS, "Favoris", <StarFilledIcon />, current === FAVORIS)}
{navItem(POUBELLE, "Poubelle", trash?.count ? <TrashFullIcon /> : <TrashIcon />, current === POUBELLE, trash?.count)}
</nav>
<div className="sidebar-foot">
{usage && (
<div className="usage" title="Occupation de votre espace personnel">
<div className="usage-text">
<span>Espace personnel</span>
<small className="muted">
{fmtSize(usage.used)}
{usage.quota > 0 ? ` / ${fmtSize(usage.quota)}` : ""}
</small>
</div>
{usage.quota > 0 && (
<div className="bar" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
<span style={{ width: `${pct}%` }} className={pct >= 90 ? "err" : ""} />
</div>
)}
</div>
)}
{me.version && me.version !== "dev" && <small className="muted">v{me.version}</small>}
</div>
</aside>
<Splitter width={sidebarW} min={SIDEBAR_MIN} max={SIDEBAR_MAX} onResize={(w) => {
const v = Math.min(SIDEBAR_MAX, Math.max(SIDEBAR_MIN, w));
setSidebarW(v);
try {
localStorage.setItem("udSidebar", String(v));
} catch {
/* stockage indisponible */
}
}} onDragging={setResizing} onReset={() => setSidebarW(SIDEBAR_DEFAULT)} />
<main className="main">
<Explorer
me={me}
refreshKey={refreshKey}
goto={goto}
onDirChange={onDirChange}
onMutated={onMutated}
toolbarStart={
<button className="icon-btn menu-btn-inline" onClick={() => setDrawer(true)} aria-label="Menu" title="Menu">
<MenuIcon />
</button>
}
/>
</main>
</div>
<UploadPanel />
{userMenu && (
<ActionMenu anchor={userMenu} onClose={() => setUserMenu(null)}>
<div className="menu-head">
<strong>{user.name}</strong>
<small className="muted">{user.email || user.id}</small>
<small className="muted">{me.admin && me.mode !== "none" ? "Administrateur" : ""}</small>
</div>
<hr />
<button role="menuitem" onClick={() => setSettings("account")}>
<SettingsIcon />
Paramètres
</button>
<button role="menuitem" onClick={() => setSettings("tokens")}>
<KeyIcon />
Jetons d'API
</button>
<button role="menuitem" onClick={() => setSettings("shares")}>
<ShareIcon />
Mes partages
</button>
{me.admin && me.mode !== "none" && (
<>
<hr />
<button role="menuitem" onClick={() => setSettings("users")}>
<UsersIcon />
Utilisateurs{!!me.pending && ` (${me.pending} en attente)`}
</button>
</>
)}
{me.admin && (
<button role="menuitem" onClick={() => setSettings("general")}>
<ShieldIcon />
Administration
</button>
)}
{me.logout && (
<>
<hr />
<a role="menuitem" href={me.logout}>
<LogoutIcon />
Se déconnecter
</a>
</>
)}
</ActionMenu>
)}
{settings && (
<SettingsDialog
me={me}
initialTab={settings}
onClose={() => setSettings(null)}
onChanged={() => {
reloadMe();
setRefreshKey((k) => k + 1);
}}
/>
)}
</div>
);
}
+183
View File
@@ -0,0 +1,183 @@
import { useEffect, useState } from "react";
import { api, dirname, displayPath, type Entry } from "./api";
import { CloseIcon, DownloadIcon, EyeIcon, FolderIcon, HistoryIcon, ShareIcon, StarFilledIcon, StarIcon } from "./icons";
import { FolderGlyph } from "./folderIcons";
import { FileGlyph, Thumb, thumbSource } from "./FileGlyph";
import { previewable, typeLabel } from "./filetypes";
import { fmtDate, fmtSize, plural, who } from "./format";
interface Props {
entry: Entry;
onClose: () => void;
onOpen: (e: Entry) => void;
onShare: (e: Entry) => void;
onHistory: (e: Entry) => void;
onFavorite: (e: Entry) => void;
onTag: (t: string) => void;
onLocate: (dir: string) => void;
}
const Row = ({ label, children }: { label: string; children: React.ReactNode }) => (
<div className="detail-row">
<dt>{label}</dt>
<dd>{children}</dd>
</div>
);
/** Panneau Détails : propriétés d'un fichier ou d'un dossier, actions rapides. */
export function DetailsPanel({ entry: e, onClose, onOpen, onShare, onHistory, onFavorite, onTag, onLocate }: Props) {
const d = e.details ?? {};
const [hash, setHash] = useState<string | null>(null);
const [hashing, setHashing] = useState(false);
const [hashError, setHashError] = useState<string | null>(null);
const by = who(e.editedBy);
useEffect(() => {
setHash(null);
setHashError(null);
}, [e.path, e.modTime]);
useEffect(() => {
const onKey = (ev: KeyboardEvent) => ev.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const computeHash = async () => {
setHashing(true);
setHashError(null);
try {
setHash(await api.hash(e.path));
} catch (err) {
setHashError(err instanceof Error ? err.message : String(err));
} finally {
setHashing(false);
}
};
return (
<aside className="details" aria-label={`Détails de ${e.name}`}>
<header>
<strong title={e.name}>{e.name}</strong>
<button className="icon-btn" onClick={onClose} aria-label="Fermer les détails" title="Fermer (Échap)">
<CloseIcon />
</button>
</header>
<div className="details-preview">
{e.isDir ? (
<span className="icon folder big">
<FolderGlyph name={e.icon} size={64} />
</span>
) : (
<Thumb
name={e.name}
glyph={64}
src={thumbSource(
e.name,
e.size,
() => api.thumbUrl(e.path, e.modTime),
() => api.downloadUrl(e.path, true),
)}
/>
)}
</div>
<div className="details-actions">
{e.isDir ? (
<>
<button onClick={() => onOpen(e)}>
<FolderIcon />
<span>Ouvrir</span>
</button>
<a className="ex-btn" href={api.zipUrl(e.path)} title="Télécharger le dossier en ZIP">
<DownloadIcon />
<span>ZIP</span>
</a>
</>
) : (
<>
{previewable(e.name) && (
<button onClick={() => onOpen(e)}>
<EyeIcon />
<span>Aperçu</span>
</button>
)}
<a className="ex-btn" href={api.downloadUrl(e.path)} download={e.name}>
<DownloadIcon />
<span>Télécharger</span>
</a>
</>
)}
<button onClick={() => onShare(e)}>
<ShareIcon />
<span>Partager</span>
</button>
{!e.isDir && (
<button onClick={() => onHistory(e)}>
<HistoryIcon />
<span>Historique</span>
</button>
)}
<button onClick={() => onFavorite(e)} aria-pressed={!!e.favorite}>
{e.favorite ? <StarFilledIcon /> : <StarIcon />}
<span>{e.favorite ? "Favori" : "Ajouter aux favoris"}</span>
</button>
</div>
<dl>
<Row label="Type">{e.isDir ? "Dossier" : typeLabel(e.name)}</Row>
{!e.isDir && <Row label="Taille">{`${fmtSize(e.size)}${e.size >= 1024 ? ` (${e.size.toLocaleString()} octets)` : ""}`}</Row>}
{e.isDir && d.total !== undefined && (
<Row label="Contenu">
{plural(d.count ?? 0, "fichier")} · {fmtSize(d.total)}
{!!d.dirs && ` · ${plural(d.dirs, "sous-dossier")}`}
</Row>
)}
{!!d.width && <Row label="Dimensions">{`${d.width} × ${d.height} px`}</Row>}
<Row label="Modifié">{fmtDate(e.modTime)}{by && ` par ${by}`}</Row>
{d.created && (
<Row label="Créé">
{fmtDate(d.created)}
{who(d.createdBy) && ` par ${who(d.createdBy)}`}
</Row>
)}
<Row label="Emplacement">
<button className="link" onClick={() => onLocate(dirname(e.path))}>
{displayPath(dirname(e.path)) || "Racine"}
</button>
</Row>
{!e.isDir && !!d.versions && <Row label="Versions">{d.versions}</Row>}
{!!d.shares && <Row label="Partages actifs">{d.shares}</Row>}
{!!e.tags?.length && (
<Row label="Tags">
<span className="chips">
{e.tags.map((t) => (
<button key={t} className="chip" onClick={() => onTag(t)} title={`Filtrer sur « ${t} »`}>
{t}
</button>
))}
</span>
</Row>
)}
{!e.isDir && (
<Row label="SHA-256">
{hash ? (
<code className="hash">{hash}</code>
) : (
<button className="link" disabled={hashing} onClick={computeHash}>
{hashing ? "Calcul…" : "Calculer"}
</button>
)}
{hashError && <span className="error-text"> {hashError}</span>}
</Row>
)}
</dl>
{!e.isDir && (
<div className="details-foot muted">
<FileGlyph name={e.name} size={14} /> {e.path.startsWith(".perso") ? "Espace personnel" : "Arborescence commune"}
</div>
)}
</aside>
);
}
+98
View File
@@ -0,0 +1,98 @@
import { useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
function useEscape(onClose: () => void) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
}
interface PromptProps {
title: string;
label?: string;
initial?: string;
placeholder?: string;
submit?: string;
/** Sélectionne seulement le nom, sans l'extension (renommage d'un fichier). */
stem?: boolean;
onSubmit: (value: string) => void;
onClose: () => void;
}
/** Saisie d'un nom (nouveau dossier, renommage), à la place de prompt(). */
export function PromptDialog({ title, label, initial = "", placeholder, submit = "Valider", stem, onSubmit, onClose }: PromptProps) {
const [value, setValue] = useState(initial);
const ref = useRef<HTMLInputElement>(null);
useEscape(onClose);
useEffect(() => {
const el = ref.current;
if (!el) return;
el.focus();
const dot = initial.lastIndexOf(".");
el.setSelectionRange(0, stem && dot > 0 ? dot : initial.length);
}, [initial, stem]);
const trimmed = value.trim();
return (
<div className="modal-backdrop" onClick={onClose}>
<form
className="modal small"
role="dialog"
aria-modal="true"
aria-label={title}
onClick={(e) => e.stopPropagation()}
onSubmit={(e) => {
e.preventDefault();
if (trimmed) onSubmit(trimmed);
}}
>
<h3>{title}</h3>
<label className="field">
{label && <span>{label}</span>}
<input ref={ref} value={value} placeholder={placeholder} maxLength={255} onChange={(e) => setValue(e.target.value)} />
</label>
<div className="modal-actions">
<span className="spacer" />
<button type="button" onClick={onClose}>
Annuler
</button>
<button type="submit" className="primary" disabled={!trimmed || trimmed === initial}>
{submit}
</button>
</div>
</form>
</div>
);
}
interface ConfirmProps {
title: string;
children: ReactNode;
confirm: string;
danger?: boolean;
onConfirm: () => void;
onClose: () => void;
}
/** Confirmation d'une action destructrice, à la place de confirm(). */
export function ConfirmDialog({ title, children, confirm, danger, onConfirm, onClose }: ConfirmProps) {
useEscape(onClose);
return (
<div className="modal-backdrop" onClick={onClose}>
<div className="modal small" role="alertdialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
<h3>{title}</h3>
<div className="modal-text">{children}</div>
<div className="modal-actions">
<span className="spacer" />
<button onClick={onClose}>Annuler</button>
<button autoFocus className={danger ? "primary danger-fill" : "primary"} onClick={onConfirm}>
{confirm}
</button>
</div>
</div>
</div>
);
}
File diff suppressed because it is too large. Load diff
+64
View File
@@ -0,0 +1,64 @@
import { useState } from "react";
import {
FileCodeIcon,
FileIcon,
FileImageIcon,
FileMusicIcon,
FilePdfIcon,
FileSheetIcon,
FileSlidesIcon,
FileTextIcon,
FileVideoIcon,
FileZipIcon,
} from "./icons";
import { browserImage, kindOf, serverThumb, type Kind } from "./filetypes";
const glyphs: Record<Kind, ReturnType<typeof FileIcon>["type"] | ((p: { size?: number }) => React.ReactElement)> = {
image: FileImageIcon,
video: FileVideoIcon,
audio: FileMusicIcon,
pdf: FilePdfIcon,
text: FileTextIcon,
code: FileCodeIcon,
archive: FileZipIcon,
doc: FileTextIcon,
sheet: FileSheetIcon,
slides: FileSlidesIcon,
other: FileIcon,
};
/** Icône d'un fichier d'après son type, colorée par famille (classe k-<type>). */
export function FileGlyph({ name, size = 20 }: { name: string; size?: number }) {
const kind = kindOf(name);
const Icon = glyphs[kind] as (p: { size?: number }) => React.ReactElement;
return (
<span className={`fileglyph k-${kind}`} aria-hidden>
<Icon size={size} />
</span>
);
}
/** Taille au-delà de laquelle une image n'est pas chargée telle quelle comme miniature. */
const MAX_DIRECT = 12 << 20;
/**
* Adresse d'une miniature : miniature du serveur pour JPEG, PNG et GIF, l'image
* elle-même pour les autres formats du navigateur (WebP, SVG...) si elle est
* raisonnable, sinon rien (icône de type).
*/
export const thumbSource = (name: string, size: number, thumb: () => string, direct: () => string): string | null => {
if (serverThumb(name)) return thumb();
if (browserImage(name) && size <= MAX_DIRECT) return direct();
return null;
};
/** Miniature d'image avec repli sur l'icône du type (format illisible, erreur de chargement). */
export function Thumb({ name, src, glyph = 40, className = "" }: { name: string; src: string | null; glyph?: number; className?: string }) {
const [failed, setFailed] = useState<string | null>(null);
const ok = src && failed !== src;
return (
<span className={`thumb ${ok ? "" : "ph"} ${className}`} aria-hidden>
{ok ? <img src={src} alt="" loading="lazy" decoding="async" draggable={false} onError={() => setFailed(src)} /> : <FileGlyph name={name} size={glyph} />}
</span>
);
}
+99
View File
@@ -0,0 +1,99 @@
import { useCallback, useEffect, useState } from "react";
import { api, type Version } from "./api";
import { DownloadIcon, HistoryIcon, RestoreIcon } from "./icons";
import { fmtDate, fmtRelative, fmtSize } from "./format";
interface Props {
path: string;
name: string;
onClose: () => void;
/** Appelé après une restauration (le fichier a changé). */
onChanged: () => void;
}
/** Versions antérieures d'un fichier : téléchargement, restauration, création d'une version à la demande. */
export function HistoryDialog({ path, name, onClose, onChanged }: Props) {
const [versions, setVersions] = useState<Version[] | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const load = useCallback(() => api.history(path).then(setVersions).catch((e) => setError(e.message)), [path]);
useEffect(() => {
load();
}, [load]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const run = async (fn: () => Promise<unknown>, done?: string) => {
setBusy(true);
setError(null);
setNotice(null);
try {
await fn();
await load();
if (done) setNotice(done);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};
return (
<div className="modal-backdrop" onClick={onClose}>
<div className="modal" role="dialog" aria-modal="true" aria-label={`Historique de ${name}`} onClick={(e) => e.stopPropagation()}>
<h3>Historique · {name}</h3>
<p className="muted small-text">
Quand un fichier est remplacé, son contenu précédent est conservé ici. Restaurer une version garde l'état actuel dans l'historique : l'opération s'annule.
</p>
{error && <div className="error">{error}</div>}
{notice && <div className="notice">{notice}</div>}
<ul className="versions">
{versions?.map((v) => (
<li key={v.id}>
<HistoryIcon size={16} />
<div className="grow">
<span title={fmtDate(v.time)}>{fmtRelative(v.time)}</span>
<small className="muted">
{" "}
· {fmtDate(v.time)} · {fmtSize(v.size)}
</small>
</div>
<a className="icon-btn" href={api.versionUrl(path, v.id)} download={name} title="Télécharger cette version" aria-label="Télécharger cette version">
<DownloadIcon />
</a>
<button
disabled={busy}
title="Remplacer le fichier par cette version"
onClick={() =>
run(async () => {
await api.restore(path, v.id);
onChanged();
}, "Version restaurée.")
}
>
<RestoreIcon />
<span>Restaurer</span>
</button>
</li>
))}
{versions && versions.length === 0 && <li className="muted empty">Aucune version antérieure.</li>}
{!versions && !error && <li className="muted empty">Chargement…</li>}
</ul>
<div className="modal-actions">
<button disabled={busy} onClick={() => run(() => api.snapshot(path), "Version créée.")} title="Fixer l'état actuel comme version">
<HistoryIcon />
<span>Créer une version</span>
</button>
<span className="spacer" />
<button onClick={onClose}>Fermer</button>
</div>
</div>
</div>
);
}
+76
View File
@@ -0,0 +1,76 @@
import { useEffect, useState } from "react";
import { api, type Entry } from "./api";
import { FOLDER_ICONS, FolderGlyph } from "./folderIcons";
interface Props {
/** Dossiers concernés. */
items: Entry[];
/** Appelé après le changement pour rafraîchir l'explorateur. */
onChanged: () => Promise<void>;
onClose: () => void;
}
/** Choix de l'icône d'un ou plusieurs dossiers (partagée par tous les utilisateurs). */
export function IconDialog({ items, onChanged, onClose }: Props) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Icône commune aux dossiers (sinon aucune n'est marquée).
const current = items.every((e) => (e.icon ?? "") === (items[0].icon ?? "")) ? (items[0].icon ?? "") : null;
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const choose = async (name: string) => {
setBusy(true);
setError(null);
try {
await api.setIcon(
items.map((e) => e.path),
name,
);
await onChanged();
onClose();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
setBusy(false);
}
};
const title = items.length === 1 ? `Icône · ${items[0].name}` : `Icône · ${items.length} dossiers`;
const choice = (name: string, label: string) => (
<button
key={name || "default"}
className={`folder-icon-choice${current === name ? " current" : ""}`}
disabled={busy}
onClick={() => choose(name)}
title={label}
aria-label={label}
aria-pressed={current === name}
>
<span className="folder">
<FolderGlyph name={name} size={24} />
</span>
<small>{label}</small>
</button>
);
return (
<div className="modal-backdrop" onClick={onClose}>
<div className="modal icon-dialog" role="dialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
<h3>{title}</h3>
<div className="folder-icon-grid">
{choice("", "Par défaut")}
{FOLDER_ICONS.map((i) => choice(i.name, i.label))}
</div>
{error && <div className="error">{error}</div>}
<div className="modal-actions">
<span className="spacer" />
<button onClick={onClose}>Fermer</button>
</div>
</div>
</div>
);
}
+126
View File
@@ -0,0 +1,126 @@
import { useState } from "react";
import { api, ApiError, type Me } from "./api";
import { CloudUpIcon } from "./icons";
interface Props {
me: Me;
/** Connexion ou inscription réussie (session ouverte) : recharge l'application. */
onLoggedIn: () => void;
}
/** Page de connexion : compte local, inscription (selon le mode choisi par l'administrateur) et bouton OIDC. */
export function Login({ me, onLoggedIn }: Props) {
const canRegister = me.local && (me.registration !== "closed" || !!me.setup);
const [mode, setMode] = useState<"login" | "register">(me.setup ? "register" : "login");
const [f, setF] = useState({ username: "", name: "", email: "", password: "", confirm: "" });
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [info, setInfo] = useState<string | null>(null);
const title = me.title || "Up And Down";
const next = encodeURIComponent(location.pathname + location.search + location.hash);
const set = (k: keyof typeof f) => (e: React.ChangeEvent<HTMLInputElement>) => setF({ ...f, [k]: e.target.value });
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setInfo(null);
if (mode === "register" && f.password !== f.confirm) {
setError("Les deux mots de passe sont différents.");
return;
}
setBusy(true);
try {
if (mode === "login") {
await api.login(f.username, f.password);
onLoggedIn();
} else {
const status = await api.register({ username: f.username, name: f.name, email: f.email, password: f.password });
if (status === "pending") {
setInfo("Compte créé. Un administrateur doit le valider avant votre première connexion.");
setMode("login");
setF({ ...f, password: "", confirm: "" });
} else onLoggedIn();
}
} catch (err) {
if (err instanceof ApiError && err.code === "pending") setInfo("Votre compte est en attente de validation par un administrateur.");
else setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
};
return (
<main className="login">
<div className="login-card">
<div className="login-brand">
{me.logo ? <img src={api.logoUrl(me.logo)} alt="" className="logo" /> : <CloudUpIcon size={36} />}
<h1>{title}</h1>
<p className="muted">Envoyez, rangez et partagez vos fichiers.</p>
</div>
{me.setup && (
<div className="notice">
<strong>Première utilisation.</strong> Le compte créé ici devient l'administrateur.
</div>
)}
{info && <div className="notice">{info}</div>}
{error && <div className="error">{error}</div>}
{me.local && (
<form onSubmit={submit} className="form">
{canRegister && !me.setup && (
<div className="tabs" role="tablist">
<button type="button" role="tab" aria-selected={mode === "login"} className={mode === "login" ? "on" : ""} onClick={() => setMode("login")}>
Connexion
</button>
<button type="button" role="tab" aria-selected={mode === "register"} className={mode === "register" ? "on" : ""} onClick={() => setMode("register")}>
Créer un compte
</button>
</div>
)}
<label className="field">
<span>Identifiant</span>
<input autoFocus autoComplete="username" autoCapitalize="none" spellCheck={false} required value={f.username} onChange={set("username")} />
</label>
{mode === "register" && (
<>
<label className="field">
<span>Nom affiché (facultatif)</span>
<input autoComplete="name" maxLength={80} value={f.name} onChange={set("name")} />
</label>
<label className="field">
<span>Adresse e-mail (facultatif)</span>
<input type="email" autoComplete="email" maxLength={120} value={f.email} onChange={set("email")} />
</label>
</>
)}
<label className="field">
<span>{mode === "register" ? "Mot de passe (10 caractères minimum)" : "Mot de passe"}</span>
<input type="password" required minLength={mode === "register" ? 10 : undefined} autoComplete={mode === "login" ? "current-password" : "new-password"} value={f.password} onChange={set("password")} />
</label>
{mode === "register" && (
<label className="field">
<span>Confirmer le mot de passe</span>
<input type="password" required autoComplete="new-password" value={f.confirm} onChange={set("confirm")} />
</label>
)}
<button className="primary big" type="submit" disabled={busy}>
{mode === "login" ? "Se connecter" : me.setup ? "Créer l'administrateur" : "Créer mon compte"}
</button>
{mode === "register" && me.registration === "approval" && !me.setup && <p className="muted small-text">Votre compte devra être validé par un administrateur.</p>}
</form>
)}
{me.oidc && (
<>
{me.local && <div className="or">ou</div>}
<a className="ex-btn big" href={`/auth/login?next=${next}`}>
Se connecter avec {me.oidcName || "SSO"}
</a>
</>
)}
</div>
</main>
);
}
+100
View File
@@ -0,0 +1,100 @@
import { useEffect, useState } from "react";
import { api, basename, dirname, join, label, type Entry } from "./api";
import { FolderIcon, FolderPlusIcon } from "./icons";
import { PromptDialog } from "./Dialogs";
interface Props {
/** Éléments à déplacer. */
paths: string[];
startDir: string;
onCancel: () => void;
onConfirm: (dir: string) => void;
}
/** Sélecteur de dossier de destination (utilisable au doigt comme à la souris). */
export function MoveDialog({ paths, startDir, onCancel, onConfirm }: Props) {
const [dir, setDir] = useState(startDir);
const [folders, setFolders] = useState<Entry[]>([]);
const [error, setError] = useState<string | null>(null);
const [naming, setNaming] = useState(false);
useEffect(() => {
let live = true;
setError(null);
api
.list(dir)
.then((es) => live && setFolders(es.filter((e) => e.isDir && e.special !== "favoris" && e.special !== "poubelle")))
.catch((e) => live && setError(e.message));
return () => {
live = false;
};
}, [dir]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && !naming && onCancel();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onCancel, naming]);
// Un dossier déplacé ne peut pas recevoir son propre contenu.
const blocked = (p: string) => paths.some((m) => p === m || p.startsWith(m + "/"));
const crumbs = dir ? dir.split("/") : [];
const newFolder = async (name: string) => {
setNaming(false);
try {
const e = await api.mkdir(join(dir, name));
setDir(e.path);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
};
const title = paths.length === 1 ? `Déplacer « ${basename(paths[0])} »` : `Déplacer ${paths.length} éléments`;
return (
<div className="modal-backdrop" onClick={onCancel}>
<div className="modal" role="dialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
<h3>{title}</h3>
<nav className="crumbs">
<button onClick={() => setDir("")}>Racine</button>
{crumbs.map((c, i) => {
const p = crumbs.slice(0, i + 1).join("/");
return (
<span key={p}>
<span className="muted"> / </span>
<button onClick={() => setDir(p)}>{label(c)}</button>
</span>
);
})}
</nav>
{error && <div className="error">{error}</div>}
<ul className="folders">
{folders.map((f) => (
<li key={f.path}>
<button disabled={blocked(f.path)} onClick={() => setDir(f.path)}>
<span className="folder">
<FolderIcon />
</span>
{f.name}
</button>
</li>
))}
{folders.length === 0 && <li className="muted empty">Aucun sous-dossier</li>}
</ul>
<div className="modal-actions">
<button onClick={() => setNaming(true)}>
<FolderPlusIcon />
<span>Dossier</span>
</button>
<span className="spacer" />
<button onClick={onCancel}>Annuler</button>
<button className="primary" disabled={blocked(dir) || paths.every((p) => dirname(p) === dir)} onClick={() => onConfirm(dir)}>
Déplacer ici
</button>
</div>
</div>
{naming && <PromptDialog title="Nouveau dossier" label="Nom du dossier" submit="Créer" onSubmit={newFolder} onClose={() => setNaming(false)} />}
</div>
);
}
+163
View File
@@ -0,0 +1,163 @@
import { useEffect, useState } from "react";
import type { ReactNode } from "react";
import { createPortal } from "react-dom";
import { ChevronLeftIcon, ChevronRightIcon, CloseIcon, DownloadIcon, ExpandIcon } from "./icons";
import { FileGlyph } from "./FileGlyph";
import { kindOf, monospace, previewable, typeLabel } from "./filetypes";
import { fmtDate, fmtSize } from "./format";
/** Fichier à prévisualiser : adresses d'affichage et de téléchargement fournies par l'appelant. */
export interface PreviewFile {
name: string;
size: number;
modTime: string;
/** Adresse d'affichage en ligne (images, vidéo, PDF). */
src: string;
download: string;
/** Lit le début du contenu texte. */
text: () => Promise<{ text: string; truncated: boolean }>;
}
interface Props {
files: PreviewFile[];
index: number;
onIndex: (i: number) => void;
onClose: () => void;
/** Boutons supplémentaires de la barre (partage, détails...). */
actions?: (file: PreviewFile) => ReactNode;
}
/** Visionneuse plein écran : image, vidéo, audio, PDF, texte ; navigation ←/→ entre les fichiers du dossier. */
export function Preview({ files, index, onIndex, onClose, actions }: Props) {
const file = files[index];
const many = files.length > 1;
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.target as HTMLElement).tagName === "INPUT") return;
if (e.key === "Escape") onClose();
else if (e.key === "ArrowLeft" && index > 0) onIndex(index - 1);
else if (e.key === "ArrowRight" && index < files.length - 1) onIndex(index + 1);
else return;
e.preventDefault();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [index, files.length, onIndex, onClose]);
if (!file) return null;
return createPortal(
<div className="preview" role="dialog" aria-modal="true" aria-label={`Aperçu de ${file.name}`}>
<header className="preview-bar">
<button className="icon-btn" onClick={onClose} aria-label="Fermer l'aperçu" title="Fermer (Échap)">
<CloseIcon />
</button>
<FileGlyph name={file.name} size={18} />
<div className="preview-title">
<strong title={file.name}>{file.name}</strong>
<small className="muted">
{typeLabel(file.name)} · {fmtSize(file.size)} · {fmtDate(file.modTime)}
{many && ` · ${index + 1}/${files.length}`}
</small>
</div>
<span className="spacer" />
{actions?.(file)}
<a className="ex-btn" href={file.download} download={file.name} title="Télécharger">
<DownloadIcon />
<span>Télécharger</span>
</a>
</header>
<div className="preview-body" onClick={(e) => e.target === e.currentTarget && onClose()}>
{many && index > 0 && (
<button className="nav prev" onClick={() => onIndex(index - 1)} aria-label="Fichier précédent" title="Précédent (←)">
<ChevronLeftIcon size={24} />
</button>
)}
<Viewer key={file.src} file={file} />
{many && index < files.length - 1 && (
<button className="nav next" onClick={() => onIndex(index + 1)} aria-label="Fichier suivant" title="Suivant (→)">
<ChevronRightIcon size={24} />
</button>
)}
</div>
</div>,
document.body,
);
}
function Viewer({ file }: { file: PreviewFile }) {
const kind = kindOf(file.name);
const [zoom, setZoom] = useState(false);
const [error, setError] = useState(false);
if (!previewable(file.name) || error) {
return (
<div className="preview-none">
<FileGlyph name={file.name} size={72} />
<p>
<strong>{file.name}</strong>
</p>
<p className="muted">{error ? "Impossible d'afficher ce fichier dans le navigateur." : "Pas d'aperçu pour ce type de fichier."}</p>
<a className="ex-btn primary" href={file.download} download={file.name}>
<DownloadIcon />
<span>Télécharger ({fmtSize(file.size)})</span>
</a>
</div>
);
}
switch (kind) {
case "image":
return (
<div className={`viewer-image ${zoom ? "zoom" : ""}`}>
<img src={file.src} alt={file.name} onClick={() => setZoom((z) => !z)} onError={() => setError(true)} draggable={false} />
<button className="icon-btn zoom-btn" onClick={() => setZoom((z) => !z)} title={zoom ? "Ajuster à la fenêtre" : "Taille réelle"} aria-label="Zoom">
<ExpandIcon />
</button>
</div>
);
case "video":
return <video className="viewer-media" src={file.src} controls autoPlay playsInline onError={() => setError(true)} />;
case "audio":
return (
<div className="viewer-audio">
<FileGlyph name={file.name} size={64} />
<p>{file.name}</p>
<audio src={file.src} controls autoPlay onError={() => setError(true)} />
</div>
);
case "pdf":
return <iframe className="viewer-pdf" src={file.src} title={file.name} />;
default:
return <TextViewer file={file} onError={() => setError(true)} />;
}
}
function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void }) {
const [state, setState] = useState<{ text: string; truncated: boolean } | null>(null);
useEffect(() => {
let live = true;
file
.text()
.then((t) => live && setState(t))
.catch(() => live && onError());
return () => {
live = false;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [file.src]);
if (!state) return <div className="preview-none muted">Chargement…</div>;
const lines = state.text.split("\n");
return (
<div className="viewer-text">
<pre className={monospace(file.name) ? "mono" : ""}>
{lines.map((l, i) => (
<span key={i} className="ln" data-n={i + 1}>
{l || " "}
{"\n"}
</span>
))}
</pre>
{state.truncated && <div className="notice">Aperçu limité au début du fichier ({fmtSize(512 * 1024)}) : télécharger pour le lire en entier.</div>}
</div>
);
}
+718
View File
@@ -0,0 +1,718 @@
import { useCallback, useEffect, useState } from "react";
import type { ReactNode } from "react";
import { api, displayPath, type Account, type ApiToken, type Me, type Role, type Settings, type Share, type Status } from "./api";
import { CheckIcon, CloseIcon, CopyLinkIcon, KeyIcon, LockIcon, ShareIcon, ShieldIcon, TrashIcon, UserIcon, UsersIcon } from "./icons";
import { ConfirmDialog } from "./Dialogs";
import { fmtDate, fmtSize, plural } from "./format";
type Tab = "account" | "tokens" | "shares" | "general" | "users";
interface Props {
me: Me;
initialTab?: Tab;
onClose: () => void;
/** Titre, logo ou comptes modifiés : le parent recharge /api/me. */
onChanged: () => void;
}
const copyText = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
return false;
}
};
const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));
/** Paramètres : compte, jetons d'API, partages ; pour les administrateurs, réglages généraux et utilisateurs. */
export function SettingsDialog({ me, initialTab = "account", onClose, onChanged }: Props) {
const [tab, setTab] = useState<Tab>(initialTab);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const tabs: { id: Tab; label: string; icon: ReactNode; admin?: boolean; badge?: number }[] = [
{ id: "account", label: "Mon compte", icon: <UserIcon /> },
{ id: "tokens", label: "Jetons d'API", icon: <KeyIcon /> },
{ id: "shares", label: "Partages", icon: <ShareIcon /> },
{ id: "general", label: "Général", icon: <ShieldIcon />, admin: true },
{ id: "users", label: "Utilisateurs", icon: <UsersIcon />, admin: true, badge: me.pending },
];
return (
<div className="modal-backdrop" onClick={onClose}>
<div className="modal settings" role="dialog" aria-modal="true" aria-label="Paramètres" onClick={(e) => e.stopPropagation()}>
<header className="settings-head">
<h3>Paramètres</h3>
<button className="icon-btn" onClick={onClose} aria-label="Fermer" title="Fermer (Échap)">
<CloseIcon />
</button>
</header>
<nav className="tabs" role="tablist">
{tabs
.filter((t) => !t.admin || me.admin)
.map((t) => (
<button
key={t.id}
role="tab"
aria-selected={tab === t.id}
className={tab === t.id ? "on" : ""}
onClick={() => {
setError(null);
setTab(t.id);
}}
>
{t.icon}
<span>{t.label}</span>
{!!t.badge && <small className="badge">{t.badge}</small>}
</button>
))}
</nav>
{error && (
<div className="error" onClick={() => setError(null)}>
{error}
</div>
)}
<div className="settings-body">
{tab === "account" && <AccountTab me={me} onError={setError} onChanged={onChanged} />}
{tab === "tokens" && <TokensTab onError={setError} />}
{tab === "shares" && <SharesTab me={me} onError={setError} />}
{tab === "general" && me.admin && <GeneralTab onError={setError} onChanged={onChanged} />}
{tab === "users" && me.admin && <UsersTab me={me} onError={setError} onChanged={onChanged} />}
</div>
</div>
</div>
);
}
// --- Mon compte ----------------------------------------------------------------------
function AccountTab({ me, onError, onChanged }: { me: Me; onError: (m: string | null) => void; onChanged: () => void }) {
const u = me.user;
const [name, setName] = useState(u?.name ?? "");
const [email, setEmail] = useState(u?.email ?? "");
const [current, setCurrent] = useState("");
const [next, setNext] = useState("");
const [ok, setOk] = useState<string | null>(null);
const local = me.canChangePassword;
const run = async (fn: () => Promise<unknown>, done: string) => {
onError(null);
setOk(null);
try {
await fn();
setOk(done);
} catch (e) {
onError(msg(e));
}
};
return (
<div className="section">
<dl className="kv">
<dt>Identifiant</dt>
<dd>
<code>{u?.id}</code>
</dd>
<dt>Rôle</dt>
<dd>{u?.role === "admin" ? "Administrateur" : "Utilisateur"}</dd>
<dt>Connexion</dt>
<dd>{u?.provider === "oidc" ? "Fournisseur d'identité (OIDC)" : u?.provider === "local" ? "Compte local" : "Sans authentification intégrée"}</dd>
{me.usage && (
<>
<dt>Espace personnel</dt>
<dd>
{fmtSize(me.usage.used)}
{me.usage.quota > 0 ? ` sur ${fmtSize(me.usage.quota)}` : " (illimité)"}
</dd>
</>
)}
</dl>
{ok && <div className="notice">{ok}</div>}
{local ? (
<>
<form
className="form"
onSubmit={(e) => {
e.preventDefault();
run(async () => {
await api.patchAccount({ name, email });
onChanged();
}, "Profil enregistré.");
}}
>
<h4>Profil</h4>
<label className="field">
<span>Nom affiché</span>
<input value={name} maxLength={80} onChange={(e) => setName(e.target.value)} />
</label>
<label className="field">
<span>Adresse e-mail</span>
<input type="email" value={email} maxLength={120} onChange={(e) => setEmail(e.target.value)} />
</label>
<div>
<button className="primary" type="submit">
Enregistrer
</button>
</div>
</form>
<form
className="form"
onSubmit={(e) => {
e.preventDefault();
run(async () => {
await api.changePassword(current, next);
setCurrent("");
setNext("");
}, "Mot de passe modifié.");
}}
>
<h4>Mot de passe</h4>
<label className="field">
<span>Mot de passe actuel</span>
<input type="password" autoComplete="current-password" value={current} onChange={(e) => setCurrent(e.target.value)} />
</label>
<label className="field">
<span>Nouveau mot de passe (10 caractères minimum)</span>
<input type="password" autoComplete="new-password" minLength={10} value={next} onChange={(e) => setNext(e.target.value)} />
</label>
<div>
<button className="primary" type="submit" disabled={!current || next.length < 10}>
Changer le mot de passe
</button>
</div>
</form>
</>
) : (
<p className="muted">Le nom, l'adresse et le mot de passe de ce compte sont gérés par votre fournisseur d'identité.</p>
)}
</div>
);
}
// --- Jetons d'API ----------------------------------------------------------------------
function TokensTab({ onError }: { onError: (m: string | null) => void }) {
const [tokens, setTokens] = useState<ApiToken[] | null>(null);
const [name, setName] = useState("");
const [created, setCreated] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const load = useCallback(() => api.tokens().then(setTokens).catch((e) => onError(msg(e))), [onError]);
useEffect(() => {
load();
}, [load]);
const create = async () => {
onError(null);
try {
const t = await api.createToken(name);
setCreated(t.token);
setName("");
load();
} catch (e) {
onError(msg(e));
}
};
const revoke = async (t: ApiToken) => {
onError(null);
try {
await api.revokeToken(t.id);
load();
} catch (e) {
onError(msg(e));
}
};
const o = location.origin;
return (
<div className="section">
<p className="muted">
Un jeton permet d'envoyer et de télécharger des fichiers depuis un script ou un outil (curl, sauvegardes...) sans passer par le navigateur. Il donne accès à vos fichiers, comme votre session, mais pas aux comptes ni aux jetons.
</p>
<form
className="inline-form"
onSubmit={(e) => {
e.preventDefault();
create();
}}
>
<input value={name} maxLength={80} placeholder="Nom du jeton (ex. sauvegarde NAS)" onChange={(e) => setName(e.target.value)} />
<button className="primary" type="submit" disabled={!name.trim()}>
Créer un jeton
</button>
</form>
{created && (
<div className="secret">
<strong>Copier ce jeton maintenant : il ne sera plus affiché.</strong>
<code>{created}</code>
<button
onClick={async () => {
setCopied(await copyText(created));
setTimeout(() => setCopied(false), 1500);
}}
>
<CopyLinkIcon />
<span>{copied ? "Copié" : "Copier"}</span>
</button>
<pre className="example">{`# Envoyer un fichier dans « Personnel »
curl -T rapport.pdf -H "Authorization: Bearer ${created}" \\
"${o}/api/file?path=.perso/rapport.pdf&conflict=overwrite"
# Télécharger
curl -OJ -H "Authorization: Bearer ${created}" \\
"${o}/api/file?path=.perso/rapport.pdf"`}</pre>
</div>
)}
<ul className="rows">
{tokens?.map((t) => (
<li key={t.id}>
<KeyIcon />
<div className="grow">
<strong>{t.name}</strong>
<small className="muted">
{" "}
créé le {fmtDate(t.created)} · {t.lastUsed ? `utilisé le ${fmtDate(t.lastUsed)}` : "jamais utilisé"}
</small>
</div>
<button className="icon-btn danger" onClick={() => revoke(t)} title="Révoquer" aria-label={`Révoquer ${t.name}`}>
<TrashIcon />
</button>
</li>
))}
{tokens && tokens.length === 0 && <li className="muted empty">Aucun jeton.</li>}
</ul>
</div>
);
}
// --- Partages ----------------------------------------------------------------------------
function SharesTab({ me, onError }: { me: Me; onError: (m: string | null) => void }) {
const [shares, setShares] = useState<Share[] | null>(null);
const [confirmAll, setConfirmAll] = useState(false);
const load = useCallback(() => api.shares().then(setShares).catch((e) => onError(msg(e))), [onError]);
useEffect(() => {
load();
}, [load]);
const revoke = async (id: string) => {
onError(null);
try {
await api.revokeShare(id);
load();
} catch (e) {
onError(msg(e));
}
};
return (
<div className="section">
<ul className="rows">
{shares?.map((s) => (
<li key={s.id}>
<ShareIcon />
<div className="grow">
<strong title={displayPath(s.path)}>{displayPath(s.path)}</strong>
{s.protected && (
<span className="pill" title="Protégé par un mot de passe">
<LockIcon size={12} /> mot de passe
</span>
)}
<small className="muted">
{" "}
{s.isDir ? "dossier" : "fichier"} · {s.expires ? `expire le ${fmtDate(s.expires)}` : "sans expiration"}
{!!s.downloads && ` · ${plural(s.downloads, "téléchargement")}`}
</small>
</div>
<button
onClick={async () => {
if (!(await copyText(api.shareUrl(s.token)))) prompt("Copier le lien :", api.shareUrl(s.token));
}}
>
<CopyLinkIcon />
<span>Copier</span>
</button>
<button className="icon-btn danger" onClick={() => revoke(s.id)} title="Révoquer ce lien" aria-label="Révoquer ce lien">
<CloseIcon />
</button>
</li>
))}
{shares && shares.length === 0 && <li className="muted empty">Aucun lien de partage actif.</li>}
</ul>
{me.admin && (
<div>
<button className="danger-outline" disabled={!shares?.length} onClick={() => setConfirmAll(true)}>
<TrashIcon />
<span>Tout révoquer (tous les utilisateurs)</span>
</button>
</div>
)}
{confirmAll && (
<ConfirmDialog
title="Révoquer tous les liens"
confirm="Tout révoquer"
danger
onClose={() => setConfirmAll(false)}
onConfirm={async () => {
setConfirmAll(false);
try {
await api.revokeAllShares();
load();
} catch (e) {
onError(msg(e));
}
}}
>
<p>Tous les liens de partage de tous les utilisateurs deviennent invalides.</p>
</ConfirmDialog>
)}
</div>
);
}
// --- Général (administrateur) ------------------------------------------------------------
function GeneralTab({ onError, onChanged }: { onError: (m: string | null) => void; onChanged: () => void }) {
const [st, setSt] = useState<Settings | null>(null);
const [title, setTitle] = useState("");
const [quota, setQuota] = useState("0");
const [trash, setTrash] = useState("0");
const [saved, setSaved] = useState<string | null>(null);
const load = useCallback(
() =>
api
.settings()
.then((s) => {
setSt(s);
setTitle(s.title);
setQuota(String(s.quotaMB));
setTrash(String(s.trashDays));
})
.catch((e) => onError(msg(e))),
[onError],
);
useEffect(() => {
load();
}, [load]);
const apply = async (patch: Parameters<typeof api.setSettings>[0], done = "Enregistré.") => {
onError(null);
setSaved(null);
try {
setSt(await api.setSettings(patch));
setSaved(done);
onChanged();
} catch (e) {
onError(msg(e));
}
};
const logo = async (f?: File) => {
if (!f) return;
onError(null);
try {
setSt(await api.uploadLogo(f));
setSaved("Logo enregistré.");
onChanged();
} catch (e) {
onError(msg(e));
}
};
if (!st) return <p className="muted">Chargement…</p>;
return (
<div className="section">
{saved && (
<div className="notice">
<CheckIcon size={14} /> {saved}
</div>
)}
<h4>Apparence</h4>
<form
className="inline-form"
onSubmit={(e) => {
e.preventDefault();
apply({ title });
}}
>
<input value={title} maxLength={80} placeholder="Up And Down" onChange={(e) => setTitle(e.target.value)} />
<button type="submit" disabled={title === st.title}>
Enregistrer le titre
</button>
</form>
<div className="logo-row">
{st.logo ? <img className="logo-preview" src={api.logoUrl(st.logo)} alt="Logo" /> : <span className="muted">Aucun logo</span>}
<label className="ex-btn">
<input type="file" accept="image/png" hidden onChange={(e) => logo(e.target.files?.[0])} />
<span>Choisir un logo PNG</span>
</label>
{st.logo && (
<button
onClick={async () => {
try {
setSt(await api.removeLogo());
onChanged();
} catch (e) {
onError(msg(e));
}
}}
>
Retirer
</button>
)}
</div>
<h4>Inscription</h4>
<label className="field">
<span>Les visiteurs peuvent créer un compte local</span>
<select value={st.registration} onChange={(e) => apply({ registration: e.target.value as Settings["registration"] })}>
<option value="closed">Non : l'administrateur crée les comptes</option>
<option value="approval">Oui, après validation par un administrateur</option>
<option value="open">Oui, immédiatement</option>
</select>
</label>
<p className="muted small-text">S'applique aux comptes locaux ; les comptes OIDC sont créés à la première connexion réussie.</p>
<h4>Stockage</h4>
<form
className="inline-form"
onSubmit={(e) => {
e.preventDefault();
apply({ quotaMB: Math.max(0, Math.floor(Number(quota) || 0)) });
}}
>
<label className="field grow">
<span>Quota de l'espace personnel par utilisateur (Mo, 0 : illimité)</span>
<input type="number" min={0} value={quota} onChange={(e) => setQuota(e.target.value)} />
</label>
<button type="submit" disabled={Number(quota) === st.quotaMB}>
Enregistrer
</button>
</form>
<label className="check-row">
<input type="checkbox" checked={st.commonReadonly} onChange={(e) => apply({ commonReadonly: e.target.checked })} />
<span>Arborescence commune en lecture seule pour les utilisateurs (seuls les administrateurs y écrivent)</span>
</label>
<form
className="inline-form"
onSubmit={(e) => {
e.preventDefault();
apply({ trashDays: Math.max(0, Math.floor(Number(trash) || 0)) });
}}
>
<label className="field grow">
<span>Purge de la poubelle après (jours, 0 : jamais)</span>
<input type="number" min={0} max={3650} value={trash} onChange={(e) => setTrash(e.target.value)} />
</label>
<button type="submit" disabled={Number(trash) === st.trashDays}>
Enregistrer
</button>
</form>
</div>
);
}
// --- Utilisateurs (administrateur) ---------------------------------------------------------
const statusLabel: Record<Status, string> = { active: "Actif", pending: "En attente", disabled: "Désactivé" };
function UsersTab({ me, onError, onChanged }: { me: Me; onError: (m: string | null) => void; onChanged: () => void }) {
const [users, setUsers] = useState<Account[] | null>(null);
const [form, setForm] = useState({ username: "", name: "", email: "", password: "", role: "user" as Role });
const [creating, setCreating] = useState(false);
const [removing, setRemoving] = useState<Account | null>(null);
const [resetting, setResetting] = useState<Account | null>(null);
const [newPassword, setNewPassword] = useState("");
const load = useCallback(() => api.users().then(setUsers).catch((e) => onError(msg(e))), [onError]);
useEffect(() => {
load();
}, [load]);
const patch = async (u: Account, v: Parameters<typeof api.patchUser>[1]) => {
onError(null);
try {
await api.patchUser(u.id, v);
await load();
onChanged();
} catch (e) {
onError(msg(e));
}
};
const create = async () => {
onError(null);
try {
await api.createUser(form);
setForm({ username: "", name: "", email: "", password: "", role: "user" });
setCreating(false);
await load();
} catch (e) {
onError(msg(e));
}
};
return (
<div className="section">
<div className="row-between">
<span className="muted">{users ? plural(users.length, "compte") : ""}</span>
<button className="primary" onClick={() => setCreating(!creating)}>
{creating ? "Annuler" : "Créer un compte local"}
</button>
</div>
{creating && (
<form
className="form card"
onSubmit={(e) => {
e.preventDefault();
create();
}}
>
<div className="grid2">
<label className="field">
<span>Identifiant</span>
<input value={form.username} autoComplete="off" onChange={(e) => setForm({ ...form, username: e.target.value })} />
</label>
<label className="field">
<span>Nom affiché</span>
<input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
</label>
<label className="field">
<span>Adresse e-mail</span>
<input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
</label>
<label className="field">
<span>Mot de passe (10 caractères minimum)</span>
<input type="password" autoComplete="new-password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
</label>
<label className="field">
<span>Rôle</span>
<select value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value as Role })}>
<option value="user">Utilisateur</option>
<option value="admin">Administrateur</option>
</select>
</label>
</div>
<div>
<button className="primary" type="submit" disabled={form.username.length < 3 || form.password.length < 10}>
Créer
</button>
</div>
</form>
)}
<div className="table-wrap">
<table className="users">
<thead>
<tr>
<th>Compte</th>
<th>Origine</th>
<th>Rôle</th>
<th>État</th>
<th>Dernière connexion</th>
<th />
</tr>
</thead>
<tbody>
{users?.map((u) => (
<tr key={u.id} className={u.status}>
<td>
<strong>{u.name}</strong>
<small className="muted"> {u.id}</small>
{u.email && u.email !== u.id && <small className="muted block">{u.email}</small>}
</td>
<td>{u.provider === "oidc" ? "OIDC" : "Local"}</td>
<td>
<select value={u.role} onChange={(e) => patch(u, { role: e.target.value as Role })} aria-label={`Rôle de ${u.id}`}>
<option value="user">Utilisateur</option>
<option value="admin">Administrateur</option>
</select>
</td>
<td>
<span className={`status ${u.status}`}>{statusLabel[u.status]}</span>
</td>
<td className="muted">{u.lastLogin ? fmtDate(u.lastLogin) : "jamais"}</td>
<td className="actions-cell">
{u.status === "pending" && (
<button className="primary" onClick={() => patch(u, { status: "active" })}>
<CheckIcon />
<span>Valider</span>
</button>
)}
{u.status === "active" && u.id !== me.user?.id && <button onClick={() => patch(u, { status: "disabled" })}>Désactiver</button>}
{u.status === "disabled" && <button onClick={() => patch(u, { status: "active" })}>Réactiver</button>}
{u.provider === "local" && (
<button className="icon-btn" onClick={() => setResetting(u)} title="Nouveau mot de passe" aria-label={`Nouveau mot de passe pour ${u.id}`}>
<KeyIcon />
</button>
)}
{u.id !== me.user?.id && (
<button className="icon-btn danger" onClick={() => setRemoving(u)} title="Supprimer le compte" aria-label={`Supprimer ${u.id}`}>
<TrashIcon />
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{resetting && (
<ConfirmDialog
title={`Nouveau mot de passe pour ${resetting.id}`}
confirm="Changer"
onClose={() => {
setResetting(null);
setNewPassword("");
}}
onConfirm={async () => {
const u = resetting;
setResetting(null);
await patch(u, { password: newPassword });
setNewPassword("");
}}
>
<label className="field">
<span>Mot de passe (10 caractères minimum)</span>
<input type="password" autoFocus autoComplete="new-password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />
</label>
</ConfirmDialog>
)}
{removing && (
<ConfirmDialog
title="Supprimer le compte"
confirm="Supprimer"
danger
onClose={() => setRemoving(null)}
onConfirm={async () => {
const u = removing;
setRemoving(null);
onError(null);
try {
await api.deleteUser(u.id);
await load();
onChanged();
} catch (e) {
onError(msg(e));
}
}}
>
<p>
Supprimer le compte de <strong>{removing.name}</strong> ({removing.id}) ? Ses jetons et ses sessions sont révoqués. Ses fichiers personnels sont mis de côté sur le serveur
(<code>.users-removed</code>), pas supprimés.
</p>
</ConfirmDialog>
)}
</div>
);
}
+152
View File
@@ -0,0 +1,152 @@
import { useCallback, useEffect, useState } from "react";
import { api, displayPath, type Share } from "./api";
import { CloseIcon, CopyLinkIcon, DownloadIcon, LockIcon } from "./icons";
import { fmtDate, plural } from "./format";
interface Props {
/** Fichier ou dossier à partager. */
path: string;
name: string;
isDir: boolean;
onClose: () => void;
/** Appelé après création ou révocation (compteurs de l'explorateur). */
onChanged: () => void;
}
const DURATIONS = [
{ days: 1, label: "1 jour" },
{ days: 7, label: "7 jours" },
{ days: 30, label: "30 jours" },
{ days: 90, label: "90 jours" },
{ days: 0, label: "Sans expiration" },
];
/** Liens de partage d'un fichier ou d'un dossier : création (durée, mot de passe), copie, révocation. */
export function ShareDialog({ path, name, isDir, onClose, onChanged }: Props) {
const [links, setLinks] = useState<Share[]>([]);
const [days, setDays] = useState(7);
const [password, setPassword] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState<string | null>(null);
const load = useCallback(() => api.shares(path).then(setLinks).catch((e) => setError(e.message)), [path]);
useEffect(() => {
load();
}, [load]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const copy = async (token: string) => {
const url = api.shareUrl(token);
try {
await navigator.clipboard.writeText(url);
setCopied(token);
setTimeout(() => setCopied((c) => (c === token ? null : c)), 2000);
} catch {
prompt("Copier le lien :", url); // presse-papiers indisponible (HTTP, navigateur restreint)
}
};
const create = async () => {
setBusy(true);
setError(null);
try {
const sh = await api.createShare(path, days, password);
setPassword("");
await load();
onChanged();
await copy(sh.token);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};
const revoke = async (id: string) => {
setError(null);
try {
await api.revokeShare(id);
await load();
onChanged();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
};
return (
<div className="modal-backdrop" onClick={onClose}>
<div className="modal share-dialog" role="dialog" aria-modal="true" aria-label={`Partager ${name}`} onClick={(e) => e.stopPropagation()}>
<h3>Partager « {name} »</h3>
<p className="muted small-text">
Toute personne qui a le lien {password ? "et le mot de passe " : ""}peut {isDir ? "parcourir et télécharger ce dossier" : "télécharger ce fichier"}, sans compte.
</p>
<div className="share-form">
<label className="field">
<span>Validité</span>
<select value={days} onChange={(e) => setDays(Number(e.target.value))}>
{DURATIONS.map((d) => (
<option key={d.days} value={d.days}>
{d.label}
</option>
))}
</select>
</label>
<label className="field grow">
<span>Mot de passe (facultatif)</span>
<input type="text" autoComplete="off" value={password} maxLength={200} placeholder="Aucun" onChange={(e) => setPassword(e.target.value)} />
</label>
<button className="primary" disabled={busy} onClick={create}>
<CopyLinkIcon />
<span>Créer et copier</span>
</button>
</div>
{error && <div className="error">{error}</div>}
<ul className="share-list">
{links.map((l) => (
<li key={l.id}>
<div className="share-info">
<code className="share-token">/s/{l.token.slice(0, 10)}…</code>
{l.protected && (
<span className="pill" title="Protégé par un mot de passe">
<LockIcon size={12} /> mot de passe
</span>
)}
<small className="muted">
créé le {fmtDate(l.created)} · {l.expires ? `expire le ${fmtDate(l.expires)}` : "sans expiration"}
{!!l.downloads && (
<>
{" "}
· <DownloadIcon size={12} /> {plural(l.downloads, "téléchargement")}
</>
)}
</small>
</div>
<button onClick={() => copy(l.token)}>
<CopyLinkIcon />
<span>{copied === l.token ? "Copié" : "Copier"}</span>
</button>
<button className="icon-btn danger" onClick={() => revoke(l.id)} title="Révoquer ce lien" aria-label="Révoquer ce lien">
<CloseIcon />
</button>
</li>
))}
{links.length === 0 && <li className="muted empty">Aucun lien actif pour {displayPath(path)}.</li>}
</ul>
<div className="modal-actions">
<span className="spacer" />
<button onClick={onClose}>Fermer</button>
</div>
</div>
</div>
);
}
+227
View File
@@ -0,0 +1,227 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { api, ApiError, type PublicInfo } from "./api";
import { CloudUpIcon, DownloadIcon, EyeIcon, FolderIcon, LockIcon, UpIcon } from "./icons";
import { FileGlyph, Thumb, thumbSource } from "./FileGlyph";
import { kindOf, previewable, typeLabel } from "./filetypes";
import { fmtDate, fmtSize, plural } from "./format";
import { Preview, type PreviewFile } from "./Preview";
const join = (a: string, b: string) => (a ? `${a}/${b}` : b);
/** Page d'un lien de partage (/s/<jeton>) : fichier ou dossier, sans compte ; mot de passe si le lien en a un. */
export function ShareView({ token }: { token: string }) {
const [sub, setSub] = useState("");
const [info, setInfo] = useState<PublicInfo | null>(null);
const [error, setError] = useState<string | null>(null);
const [password, setPassword] = useState("");
const [busy, setBusy] = useState(false);
const [preview, setPreview] = useState<string | null>(null);
const load = useCallback(
(s: string) => {
setError(null);
return api
.publicInfo(token, s)
.then((i) => {
setInfo(i);
setSub(s);
})
.catch((e) => setError(e instanceof ApiError && e.status === 404 ? "Ce lien est invalide, expiré ou a été révoqué." : (e as Error).message));
},
[token],
);
useEffect(() => {
load("");
}, [load]);
useEffect(() => {
document.title = info?.name ? `${info.name} - ${info.title || "Up And Down"}` : info?.title || "Up And Down";
}, [info]);
const unlock = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setError(null);
try {
await api.publicUnlock(token, password);
await load(sub);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
};
const files = useMemo(() => (info?.entries ?? []).filter((e) => !e.isDir), [info]);
const previews: PreviewFile[] = useMemo(
() =>
info?.isDir
? files.map((f) => ({
name: f.name,
size: f.size,
modTime: f.modTime,
src: api.publicFileUrl(token, join(sub, f.name), true),
download: api.publicFileUrl(token, join(sub, f.name)),
text: async () => ({ text: await api.publicText(token, join(sub, f.name)), truncated: f.size > 512 * 1024 }),
}))
: info?.name
? [
{
name: info.name,
size: info.size,
modTime: info.modTime,
src: api.publicFileUrl(token, "", true),
download: api.publicFileUrl(token, ""),
text: async () => ({ text: await api.publicText(token, ""), truncated: info.size > 512 * 1024 }),
},
]
: [],
[info, files, token, sub],
);
const previewIndex = preview === null ? -1 : previews.findIndex((p) => p.name === preview);
const header = (
<header className="share-top">
{info?.logo ? <img src={api.logoUrl(info.logo)} alt="" className="logo" /> : <CloudUpIcon size={26} />}
<strong>{info?.title || "Up And Down"}</strong>
</header>
);
if (error && !info?.protected) {
return (
<main className="share-page">
{header}
<div className="share-card center">
<p className="error">{error}</p>
</div>
</main>
);
}
if (!info) {
return (
<main className="share-page">
{header}
<p className="muted center">Chargement…</p>
</main>
);
}
if (info.protected) {
return (
<main className="share-page">
{header}
<form className="share-card form center" onSubmit={unlock}>
<LockIcon size={32} />
<h2>Ce lien est protégé</h2>
<p className="muted">Saisissez le mot de passe communiqué par la personne qui a partagé ce contenu.</p>
<input type="password" autoFocus autoComplete="off" value={password} placeholder="Mot de passe" onChange={(e) => setPassword(e.target.value)} />
{error && <div className="error">{error}</div>}
<button className="primary big" type="submit" disabled={busy || !password}>
Accéder
</button>
</form>
</main>
);
}
const crumbs = sub ? sub.split("/") : [];
const thumb = (name: string, size: number, path: string) => (
<Thumb name={name} glyph={36} src={thumbSource(name, size, () => api.publicThumbUrl(token, path), () => api.publicFileUrl(token, path, true))} />
);
return (
<main className="share-page">
{header}
<div className="share-card">
{info.isDir ? (
<>
<div className="share-title">
<h2>
<FolderIcon size={22} /> {info.name}
</h2>
<a className="ex-btn primary" href={api.publicZipUrl(token, sub)}>
<DownloadIcon />
<span>Tout télécharger (ZIP)</span>
</a>
</div>
<nav className="crumbs">
<button onClick={() => load("")}>{(info.sub ? "" : info.name) || "Dossier partagé"}</button>
{crumbs.map((c, i) => {
const p = crumbs.slice(0, i + 1).join("/");
return (
<span key={p}>
<span className="muted"> / </span>
<button onClick={() => load(p)}>{c}</button>
</span>
);
})}
</nav>
<ul className="share-list-files">
{sub && (
<li>
<button className="name" onClick={() => load(crumbs.slice(0, -1).join("/"))}>
<span className="icon">
<UpIcon size={22} />
</span>
<span className="label">..</span>
</button>
</li>
)}
{info.entries?.map((e) => (
<li key={e.name}>
{e.isDir ? (
<button className="name" onClick={() => load(join(sub, e.name))}>
<span className="icon folder">
<FolderIcon size={22} />
</span>
<span className="label">{e.name}</span>
</button>
) : (
<>
<button className="name" onClick={() => setPreview(e.name)}>
{kindOf(e.name) === "image" ? thumb(e.name, e.size, join(sub, e.name)) : <FileGlyph name={e.name} size={22} />}
<span className="label">{e.name}</span>
</button>
<span className="meta muted">{fmtSize(e.size)}</span>
<span className="meta muted">{fmtDate(e.modTime)}</span>
<a className="icon-btn" href={api.publicFileUrl(token, join(sub, e.name))} download={e.name} title="Télécharger" aria-label={`Télécharger ${e.name}`}>
<DownloadIcon />
</a>
</>
)}
</li>
))}
{info.entries?.length === 0 && <li className="muted empty">Dossier vide</li>}
</ul>
<p className="muted small-text">
{plural(files.length, "fichier")} {info.expires && `· lien valable jusqu'au ${fmtDate(info.expires)}`}
</p>
</>
) : (
<div className="share-file">
{info.name && thumb(info.name, info.size, "")}
<h2>{info.name}</h2>
<p className="muted">
{info.name && typeLabel(info.name)} · {fmtSize(info.size)} · {fmtDate(info.modTime)}
</p>
<div className="share-actions">
<a className="ex-btn primary big" href={api.publicFileUrl(token, "")} download={info.name}>
<DownloadIcon />
<span>Télécharger</span>
</a>
{info.name && previewable(info.name) && (
<button className="big" onClick={() => setPreview(info.name!)}>
<EyeIcon />
<span>Aperçu</span>
</button>
)}
</div>
{info.expires && <p className="muted small-text">Lien valable jusqu'au {fmtDate(info.expires)}</p>}
</div>
)}
</div>
{previewIndex >= 0 && <Preview files={previews} index={previewIndex} onIndex={(i) => setPreview(previews[i].name)} onClose={() => setPreview(null)} />}
{error && <div className="error floating">{error}</div>}
</main>
);
}
+61
View File
@@ -0,0 +1,61 @@
import { useRef } from "react";
interface Props {
width: number;
min: number;
max: number;
onResize: (width: number) => void;
/** Début / fin de glissement (désactive l'animation de la grille). */
onDragging: (dragging: boolean) => void;
onReset: () => void;
}
/** Poignée verticale entre l'explorateur et le canevas : souris, doigt ou clavier. */
export function Splitter({ width, min, max, onResize, onDragging, onReset }: Props) {
const start = useRef<{ x: number; w: number } | null>(null);
return (
<div
className="splitter"
role="separator"
aria-orientation="vertical"
aria-label="Largeur de l'explorateur"
aria-valuenow={width}
aria-valuemin={min}
aria-valuemax={max}
tabIndex={0}
title="Glisser pour redimensionner, double-clic pour la largeur par défaut"
onPointerDown={(e) => {
if (e.button !== 0) return;
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
start.current = { x: e.clientX, w: width };
onDragging(true);
}}
onPointerMove={(e) => {
if (start.current) onResize(start.current.w + e.clientX - start.current.x);
}}
onPointerUp={(e) => {
e.currentTarget.releasePointerCapture(e.pointerId);
start.current = null;
onDragging(false);
}}
onLostPointerCapture={() => {
if (start.current) {
start.current = null;
onDragging(false);
}
}}
onDoubleClick={onReset}
onKeyDown={(e) => {
const step = e.shiftKey ? 64 : 16;
if (e.key === "ArrowLeft") onResize(width - step);
else if (e.key === "ArrowRight") onResize(width + step);
else if (e.key === "Home") onResize(min);
else if (e.key === "End") onResize(max);
else return;
e.preventDefault();
}}
/>
);
}
+144
View File
@@ -0,0 +1,144 @@
import { useEffect, useState } from "react";
import { api, basename, type Entry, type TagCount } from "./api";
import { CloseIcon, TagIcon } from "./icons";
interface Props {
/** Éléments concernés, avec leurs tags actuels. */
items: Entry[];
/** Tags déjà utilisés (suggestions). */
known: TagCount[];
/** Appelé après chaque modification pour rafraîchir l'explorateur. */
onChanged: () => Promise<void>;
onClose: () => void;
}
const key = (t: string) => t.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
/** Ajout et retrait de tags sur un ou plusieurs éléments. */
export function TagsDialog({ items, known, onChanged, onClose }: Props) {
const [input, setInput] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const paths = items.map((e) => e.path);
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
// Tags présents et nombre d'éléments qui les portent.
const present = new Map<string, { name: string; count: number }>();
for (const e of items)
for (const t of e.tags ?? []) {
const p = present.get(key(t));
if (p) p.count++;
else present.set(key(t), { name: t, count: 1 });
}
const suggestions = known.filter((t) => !present.has(key(t.name)) || present.get(key(t.name))!.count < items.length);
const run = async (add: string[], remove: string[]) => {
setBusy(true);
setError(null);
try {
await api.editTags(paths, add, remove);
await onChanged();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};
const add = (raw: string) => {
const tags = raw
.split(",")
.map((t) => t.trim())
.filter(Boolean);
if (tags.length === 0) return;
setInput("");
run(tags, []);
};
const title =
items.length === 1
? `Tags · ${items[0].isDir ? items[0].name : basename(items[0].path)}`
: `Tags · ${items.length} éléments`;
return (
<div className="modal-backdrop" onClick={onClose}>
<div className="modal tags-dialog" role="dialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
<h3>{title}</h3>
<div className="chips">
{[...present.values()].map((t) => (
<span key={t.name} className="chip">
{t.name}
{items.length > 1 && t.count < items.length && (
<small className="muted">
{" "}
{t.count}/{items.length}
</small>
)}
<button
className="icon-btn"
disabled={busy}
onClick={() => run([], [t.name])}
title={`Retirer « ${t.name} »`}
aria-label={`Retirer ${t.name}`}
>
<CloseIcon size={12} />
</button>
</span>
))}
{present.size === 0 && <span className="muted">Aucun tag.</span>}
</div>
<form
className="tag-add"
onSubmit={(e) => {
e.preventDefault();
add(input);
}}
>
<label className="search">
<TagIcon />
<input
autoFocus
value={input}
list="known-tags"
maxLength={200}
placeholder="Ajouter des tags (séparés par des virgules)"
onChange={(e) => setInput(e.target.value)}
/>
</label>
<datalist id="known-tags">
{known.map((t) => (
<option key={t.name} value={t.name} />
))}
</datalist>
<button type="submit" className="primary" disabled={busy || !input.trim()}>
Ajouter
</button>
</form>
{suggestions.length > 0 && (
<div className="chips suggestions">
{suggestions.slice(0, 30).map((t) => (
<button key={t.name} className="chip" disabled={busy} onClick={() => run([t.name], [])} title={`Ajouter « ${t.name} »`}>
+ {t.name}
</button>
))}
</div>
)}
{error && <div className="error">{error}</div>}
<div className="modal-actions">
<span className="spacer" />
<button onClick={onClose}>Fermer</button>
</div>
</div>
</div>
);
}
+124
View File
@@ -0,0 +1,124 @@
import { useEffect, useRef, useState } from "react";
import { CheckIcon, ChevronDownIcon, CloseIcon, RefreshIcon, WarningIcon } from "./icons";
import { fmtRate, fmtSize } from "./format";
import { uploads, useUploads, type OnExists } from "./uploads";
/** Panneau flottant des envois : progression globale et par fichier, annulation, nouvel essai. */
export function UploadPanel() {
const items = useUploads();
const [collapsed, setCollapsed] = useState(false);
const [rate, setRate] = useState(0);
const last = useRef({ loaded: 0, at: Date.now() });
const active = items.filter((i) => i.status === "uploading" || i.status === "queued");
const done = items.filter((i) => i.status === "done");
const failed = items.filter((i) => i.status === "error");
const total = items.reduce((n, i) => n + i.size, 0);
const loaded = items.reduce((n, i) => n + (i.status === "done" ? i.size : i.loaded), 0);
// Débit moyen sur la dernière seconde.
useEffect(() => {
if (active.length === 0) {
setRate(0);
last.current = { loaded, at: Date.now() };
return;
}
const t = setInterval(() => {
const now = Date.now();
const bytes = items.reduce((n, i) => n + (i.status === "done" ? i.size : i.loaded), 0);
const dt = (now - last.current.at) / 1000;
if (dt > 0) setRate(Math.max(0, (bytes - last.current.loaded) / dt));
last.current = { loaded: bytes, at: now };
}, 1000);
return () => clearInterval(t);
});
if (items.length === 0) return null;
const pct = total ? Math.round((loaded / total) * 100) : 100;
const eta = rate > 0 && total > loaded ? Math.ceil((total - loaded) / rate) : 0;
const status =
active.length > 0
? `Envoi de ${active.length} fichier${active.length > 1 ? "s" : ""} · ${pct} %${rate > 0 ? ` · ${fmtRate(rate)}` : ""}${eta > 1 ? ` · ${eta < 90 ? `${eta} s` : `${Math.ceil(eta / 60)} min`}` : ""}`
: failed.length > 0
? `${done.length} envoyé${done.length > 1 ? "s" : ""}, ${failed.length} en échec`
: `${done.length} fichier${done.length > 1 ? "s" : ""} envoyé${done.length > 1 ? "s" : ""}`;
return (
<section className="uploads" aria-label="Envois">
<header>
{active.length === 0 && failed.length === 0 ? <CheckIcon size={16} /> : failed.length > 0 && active.length === 0 ? <WarningIcon size={16} /> : null}
<strong>{status}</strong>
<span className="spacer" />
<button className="icon-btn" onClick={() => setCollapsed(!collapsed)} title={collapsed ? "Développer" : "Réduire"} aria-label={collapsed ? "Développer" : "Réduire"}>
<ChevronDownIcon className={collapsed ? "flip" : ""} />
</button>
<button
className="icon-btn"
onClick={() => (active.length ? uploads.cancelAll() : uploads.clearFinished())}
title={active.length ? "Annuler tous les envois" : "Fermer"}
aria-label={active.length ? "Annuler tous les envois" : "Fermer"}
>
<CloseIcon />
</button>
</header>
<div className="bar total" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
<span style={{ width: `${pct}%` }} className={failed.length ? "err" : ""} />
</div>
{!collapsed && (
<>
<ul>
{items.map((i) => (
<li key={i.id} className={i.status}>
<div className="upinfo">
<span className="upname" title={i.path}>
{i.rel}
</span>
<small className="muted">
{i.status === "uploading" && `${fmtSize(i.loaded)} / ${fmtSize(i.size)}`}
{i.status === "queued" && `en attente · ${fmtSize(i.size)}`}
{i.status === "done" && (i.result && i.result !== i.path ? `envoyé sous « ${i.result.split("/").pop()} »` : `envoyé · ${fmtSize(i.size)}`)}
{i.status === "error" && <span className="error-text">{i.error}</span>}
{i.status === "canceled" && "annulé"}
</small>
{(i.status === "uploading" || i.status === "queued") && (
<div className="bar">
<span style={{ width: `${i.size ? (i.loaded / i.size) * 100 : 0}%` }} />
</div>
)}
</div>
{(i.status === "error" || i.status === "canceled") && (
<button className="icon-btn" onClick={() => uploads.retry(i.id)} title="Réessayer" aria-label="Réessayer">
<RefreshIcon />
</button>
)}
{(i.status === "uploading" || i.status === "queued") && (
<button className="icon-btn" onClick={() => uploads.cancel(i.id)} title="Annuler" aria-label="Annuler">
<CloseIcon />
</button>
)}
</li>
))}
</ul>
<footer>
<label>
<span className="muted">Si le fichier existe :</span>
<select value={uploads.onExists} onChange={(e) => uploads.setOnExists(e.target.value as OnExists)} aria-label="Si le fichier existe déjà">
<option value="rename">garder les deux</option>
<option value="overwrite">remplacer</option>
<option value="fail">ignorer</option>
</select>
</label>
<span className="spacer" />
{failed.length > 0 && (
<button onClick={() => uploads.retryFailed()}>
<RefreshIcon />
<span>Réessayer</span>
</button>
)}
{active.length === 0 && <button onClick={() => uploads.clearFinished()}>Effacer</button>}
</footer>
</>
)}
</section>
);
}
+450
View File
@@ -0,0 +1,450 @@
// Client de l'API Go (voir internal/api/api.go).
export interface Entry {
name: string;
path: string;
isDir: boolean;
size: number;
modTime: string;
tags?: string[];
favorite?: boolean;
/** Dossier : icône choisie (voir folderIcons.tsx). */
icon?: string;
/** Entrée virtuelle de la racine : "favoris", "perso" (espace personnel) ou "poubelle". */
special?: "favoris" | "perso" | "poubelle";
/** Entrée « poubelle » de la racine : nombre d'éléments qu'elle contient. */
count?: number;
/** Élément de la poubelle : chemin d'origine (modTime = date de suppression). */
origin?: string;
/** Élément de la poubelle : supprimé par (vide si inconnu). */
by?: string;
/** Dans le dossier Favoris : nom du lien (le chemin est celui de l'original). */
link?: string;
/** Favori dont l'original a disparu (chemin .favoris/<lien>, à retirer). */
broken?: boolean;
/** Fichier : dernier utilisateur à l'avoir déposé. */
editedBy?: string;
/** Vue Galerie : détails demandés à la liste ou à la recherche (details=1). */
details?: Details;
}
/** Détails d'une entrée (internal/storage/details.go) ; compteurs absents = 0. */
export interface Details {
/** Image : dimensions en pixels. */
width?: number;
height?: number;
versions?: number;
/** Liens de partage actifs. */
shares?: number;
created?: string;
createdBy?: string;
/** Dossier : éléments directs, puis taille et nombre de fichiers de tout le contenu. */
dirs?: number;
files?: number;
total?: number;
count?: number;
}
export interface TagCount {
name: string;
count: number;
}
/** Filtres de recherche : tag exact et/ou favoris seulement. */
export interface SearchFilter {
tag?: string | null;
fav?: boolean;
}
/** Résultat de recherche ; snippet = extrait du contenu qui correspond. */
export interface Hit extends Entry {
snippet?: string;
}
export interface MoveResult {
from: string;
to?: string;
error?: string;
}
export type Registration = "closed" | "approval" | "open";
/** Paramètres partagés ; logo = "" sans logo, sinon sa version. */
export interface Settings {
title: string;
logo: string;
trashDays: number;
registration: Registration;
quotaMB: number;
commonReadonly: boolean;
}
/** Version enregistrée d'un fichier (time : date de ce contenu). */
export interface Version {
id: string;
time: string;
size: number;
}
/** Lien de partage (token : à placer dans /s/<token>). */
export interface Share {
id: string;
token: string;
path: string;
isDir: boolean;
created: string;
expires?: string;
protected?: boolean;
downloads?: number;
}
/** Jeton d'accès personnel à l'API. */
export interface ApiToken {
id: string;
name: string;
created: string;
lastUsed?: string;
}
export interface Usage {
used: number;
/** 0 : illimité. */
quota: number;
}
/** Session courante et réglages publics (GET /api/me, accessible sans connexion). */
export interface Me {
mode: "none" | "local" | "oidc" | "both";
local: boolean;
oidc: boolean;
oidcName?: string;
registration: Registration;
/** Aucun administrateur : le premier compte créé le devient. */
setup?: boolean;
title: string;
logo?: string;
version?: string;
user?: { id: string; name: string; email?: string; role: "admin" | "user"; provider?: "local" | "oidc" };
admin: boolean;
canChangePassword?: boolean;
logout?: string;
usage?: Usage;
commonReadonly: boolean;
/** Administrateur : inscriptions à valider. */
pending?: number;
}
export type Role = "admin" | "user";
export type Status = "active" | "pending" | "disabled";
export interface Account {
id: string;
username?: string;
name: string;
email?: string;
provider: "local" | "oidc";
role: Role;
status: Status;
created: string;
lastLogin?: string;
}
export interface PublicEntry {
name: string;
isDir: boolean;
size: number;
modTime: string;
}
/** Lien de partage tel que servi sans authentification. */
export interface PublicInfo {
title: string;
logo?: string;
protected?: boolean;
name?: string;
isDir: boolean;
size: number;
modTime: string;
sub?: string;
entries?: PublicEntry[];
expires?: string;
}
export class ApiError extends Error {
constructor(
public status: number,
message: string,
public code?: string,
) {
super(message);
}
}
async function request(url: string, init?: RequestInit): Promise<Response> {
const res = await fetch(url, init);
if (!res.ok) {
// Session OIDC expirée : reconnexion, puis retour sur la page courante.
const login = res.status === 401 ? res.headers.get("X-Auth-Login") : null;
if (login) location.assign(`${login}?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`);
let msg = res.statusText;
let code: string | undefined;
try {
const j = await res.json();
msg = j.error ?? msg;
code = j.code;
} catch {
/* corps non JSON */
}
throw new ApiError(res.status, msg, code);
}
return res;
}
const q = (p: string) => encodeURIComponent(p);
const json = (body: unknown, method = "POST"): RequestInit => ({
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
export const api = {
me: async (): Promise<Me> => (await request("/api/me")).json(),
// --- Connexion ---------------------------------------------------------------
login: async (username: string, password: string): Promise<void> => {
await request("/auth/local/login", json({ username, password }));
},
/** Renvoie « active » (connecté d'office) ou « pending » (à valider par un administrateur). */
register: async (v: { username: string; name: string; email: string; password: string }): Promise<"active" | "pending"> => {
const res = await request("/auth/local/register", json(v));
return (await res.json()).status;
},
// --- Fichiers ----------------------------------------------------------------
/** details : détails des entrées pour la vue Galerie. */
list: async (dir: string, details = false): Promise<Entry[]> =>
(await request(`/api/list?path=${q(dir)}${details ? "&details=1" : ""}`)).json(),
search: async (text: string, f: SearchFilter = {}, details = false): Promise<Hit[]> =>
(
await request(
`/api/search?q=${q(text)}${f.tag ? `&tag=${q(f.tag)}` : ""}${f.fav ? "&fav=true" : ""}${details ? "&details=1" : ""}`,
)
).json(),
tags: async (): Promise<TagCount[]> => (await request("/api/tags")).json(),
setFavorite: async (paths: string[], favorite: boolean): Promise<void> => {
await request("/api/meta/favorite", json({ paths, favorite }));
},
editTags: async (paths: string[], add: string[], remove: string[]): Promise<void> => {
await request("/api/meta/tags", json({ paths, add, remove }));
},
/** icon = "" : dossier classique. */
setIcon: async (paths: string[], icon: string): Promise<void> => {
await request("/api/meta/icon", json({ paths, icon }));
},
mkdir: async (path: string): Promise<Entry> => (await request("/api/folder", json({ path }))).json(),
move: async (from: string, to: string): Promise<Entry> => (await request("/api/move", json({ from, to }))).json(),
/** Déplace plusieurs éléments dans dir ; le détail par élément indique les échecs. */
moveMany: async (paths: string[], dir: string): Promise<MoveResult[]> =>
(await request("/api/move-many", json({ paths, dir }))).json(),
copy: async (from: string, to: string): Promise<Entry> => (await request("/api/copy", json({ from, to }))).json(),
/** Met à la poubelle ; dans .poubelle, supprime définitivement (path = .poubelle : la vide). */
remove: async (path: string, recursive: boolean): Promise<void> => {
await request(`/api/entry?path=${q(path)}&recursive=${recursive}`, { method: "DELETE" });
},
/** Remet des éléments de la poubelle à leur emplacement d'origine (to : chemin restauré). */
restoreTrash: async (paths: string[]): Promise<MoveResult[]> =>
(await request("/api/trash/restore", json({ paths }))).json(),
/** Contenu texte d'un fichier (les premiers octets seulement : max). */
readText: async (path: string, max = 512 * 1024): Promise<{ text: string; truncated: boolean }> => {
const res = await request(`/api/file?path=${q(path)}&inline=1`, { headers: { Range: `bytes=0-${max - 1}` } });
const total = Number((res.headers.get("Content-Range") ?? "").split("/")[1]);
return { text: await res.text(), truncated: res.status === 206 && total > max };
},
/** Empreinte SHA-256 (calculée à la demande côté serveur). */
hash: async (path: string): Promise<string> => (await request(`/api/hash?path=${q(path)}`)).json().then((j) => j.sha256),
downloadUrl: (path: string, inline = false) => `/api/file?path=${q(path)}${inline ? "&inline=1" : ""}`,
/** v = date du fichier : l'URL change à chaque nouvelle version (cache navigateur). */
thumbUrl: (path: string, v: string) => `/api/thumb?path=${q(path)}&v=${q(v)}`,
zipUrl: (path: string) => `/api/zip?path=${q(path)}`,
/** Télécharge une sélection en ZIP : formulaire POST, la réponse part en flux vers le navigateur. */
zipSelection: (paths: string[]) => {
const form = document.createElement("form");
form.method = "POST";
form.action = "/api/zip";
form.style.display = "none";
const input = document.createElement("input");
input.name = "paths";
input.value = JSON.stringify(paths);
form.appendChild(input);
document.body.appendChild(form);
form.submit();
form.remove();
},
// --- Historique --------------------------------------------------------------
history: async (path: string): Promise<Version[]> => (await request(`/api/history?path=${q(path)}`)).json(),
versionUrl: (path: string, id: string) => `/api/history/version?path=${q(path)}&id=${q(id)}`,
/** Crée une version du contenu courant (sans attendre un remplacement). */
snapshot: async (path: string): Promise<Version> => (await request("/api/history/snapshot", json({ path }))).json(),
/** Restaure une version ; le contenu remplacé devient lui-même une version. */
restore: async (path: string, id: string): Promise<Entry> => (await request("/api/history/restore", json({ path, id }))).json(),
// --- Partage -----------------------------------------------------------------
/** Liens d'un élément, ou tous les liens si path est omis. */
shares: async (path?: string): Promise<Share[]> => (await request(`/api/shares${path ? `?path=${q(path)}` : ""}`)).json(),
/** days = 0 : lien sans expiration ; password : facultatif. */
createShare: async (path: string, days: number, password: string): Promise<Share> =>
(await request("/api/shares", json({ path, days, password }))).json(),
revokeShare: async (id: string): Promise<void> => {
await request(`/api/shares?id=${q(id)}`, { method: "DELETE" });
},
revokeAllShares: async (): Promise<void> => {
await request("/api/shares/revoke-all", { method: "POST" });
},
shareUrl: (token: string) => `${location.origin}/s/${token}`,
publicInfo: async (token: string, sub = ""): Promise<PublicInfo> =>
(await request(`/api/public/${q(token)}${sub ? `?sub=${q(sub)}` : ""}`)).json(),
publicUnlock: async (token: string, password: string): Promise<void> => {
await request(`/api/public/${q(token)}/unlock`, json({ password }));
},
publicFileUrl: (token: string, sub: string, inline = false) =>
`/api/public/${q(token)}/file?sub=${q(sub)}${inline ? "&inline=1" : ""}`,
publicZipUrl: (token: string, sub: string) => `/api/public/${q(token)}/zip?sub=${q(sub)}`,
publicThumbUrl: (token: string, sub: string) => `/api/public/${q(token)}/thumb?sub=${q(sub)}`,
publicText: async (token: string, sub: string, max = 512 * 1024): Promise<string> =>
(await request(`/api/public/${q(token)}/file?sub=${q(sub)}&inline=1`, { headers: { Range: `bytes=0-${max - 1}` } })).text(),
// --- Jetons d'API ------------------------------------------------------------
tokens: async (): Promise<ApiToken[]> => (await request("/api/tokens")).json(),
/** Le jeton en clair (token) n'est renvoyé qu'à la création. */
createToken: async (name: string): Promise<ApiToken & { token: string }> => (await request("/api/tokens", json({ name }))).json(),
revokeToken: async (id: string): Promise<void> => {
await request(`/api/tokens/${q(id)}`, { method: "DELETE" });
},
// --- Compte ------------------------------------------------------------------
changePassword: async (current: string, next: string): Promise<void> => {
await request("/api/account/password", json({ current, new: next }));
},
patchAccount: async (v: { name?: string; email?: string }): Promise<void> => {
await request("/api/account", json(v, "PATCH"));
},
// --- Administration ----------------------------------------------------------
users: async (): Promise<Account[]> => (await request("/api/admin/users")).json(),
createUser: async (v: { username: string; name: string; email: string; password: string; role: Role }): Promise<Account> =>
(await request("/api/admin/users", json(v))).json(),
patchUser: async (id: string, v: Partial<{ name: string; email: string; role: Role; status: Status; password: string }>): Promise<Account> =>
(await request(`/api/admin/users/${q(id)}`, json(v, "PATCH"))).json(),
deleteUser: async (id: string): Promise<void> => {
await request(`/api/admin/users/${q(id)}`, { method: "DELETE" });
},
settings: async (): Promise<Settings> => (await request("/api/settings")).json(),
setSettings: async (v: Partial<Pick<Settings, "title" | "trashDays" | "registration" | "quotaMB" | "commonReadonly">>): Promise<Settings> =>
(await request("/api/settings", json(v, "PUT"))).json(),
/** Le serveur recadre au centre et ramène le PNG à 64x64. */
uploadLogo: async (png: Blob): Promise<Settings> =>
(await request("/api/logo", { method: "PUT", headers: { "Content-Type": "image/png" }, body: png })).json(),
removeLogo: async (): Promise<Settings> => (await request("/api/logo", { method: "DELETE" })).json(),
logoUrl: (v: string) => `/api/logo?v=${q(v)}`,
};
export type Conflict = "fail" | "overwrite" | "rename";
/**
* Dépose un fichier (PUT en flux) avec progression. mtime : date de modification
* d'origine, conservée par le serveur. Rejette avec ApiError ; abort() annule.
*/
export function uploadFile(
path: string,
file: File,
opts: { conflict: Conflict; onProgress?: (loaded: number) => void },
): { promise: Promise<Entry>; abort: () => void } {
const xhr = new XMLHttpRequest();
const promise = new Promise<Entry>((resolve, reject) => {
xhr.open("PUT", `/api/file?path=${q(path)}&conflict=${opts.conflict}&mtime=${file.lastModified}`);
xhr.upload.onprogress = (e) => opts.onProgress?.(e.loaded);
xhr.onload = () => {
let body: { error?: string; code?: string } & Partial<Entry> = {};
try {
body = JSON.parse(xhr.responseText);
} catch {
/* corps non JSON */
}
const login = xhr.status === 401 ? xhr.getResponseHeader("X-Auth-Login") : null;
if (login) location.assign(`${login}?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`);
if (xhr.status >= 200 && xhr.status < 300) resolve(body as Entry);
else reject(new ApiError(xhr.status, body.error ?? (xhr.statusText || `HTTP ${xhr.status}`), body.code));
};
xhr.onerror = () => reject(new ApiError(0, "connexion interrompue"));
xhr.onabort = () => reject(new ApiError(0, "annulé"));
xhr.send(file);
});
return { promise, abort: () => xhr.abort() };
}
// Helpers de chemins (format "slash", relatifs à la racine).
export const dirname = (p: string) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
export const basename = (p: string) => p.slice(p.lastIndexOf("/") + 1);
export const join = (dir: string, name: string) => (dir ? `${dir}/${name}` : name);
// Dossiers propres à l'utilisateur connecté (voir internal/storage/spaces.go).
export const PERSO = ".perso";
export const FAVORIS = ".favoris";
export const POUBELLE = ".poubelle";
const SPECIAL_LABELS: Record<string, string> = { [PERSO]: "Personnel", [FAVORIS]: "Favoris", [POUBELLE]: "Poubelle" };
/** Libellé d'un composant de chemin (".perso" → "Personnel"). */
export const label = (part: string) => SPECIAL_LABELS[part] ?? part;
/** Chemin affiché : "Personnel/projets" pour ".perso/projets". */
export const displayPath = (p: string) => p.split("/").map(label).join("/");
export const inFavoris = (p: string) => p === FAVORIS || p.startsWith(FAVORIS + "/");
export const inPoubelle = (p: string) => p === POUBELLE || p.startsWith(POUBELLE + "/");
export const inPerso = (p: string) => p === PERSO || p.startsWith(PERSO + "/");
/** Extension (sans le point, minuscules) ; vide si aucune. */
export const extOf = (name: string) => {
const i = name.lastIndexOf(".");
return i > 0 ? name.slice(i + 1).toLowerCase() : "";
};
+81
View File
@@ -0,0 +1,81 @@
// Type d'un fichier d'après son extension : icône, aperçu possible, libellé.
import { extOf } from "./api";
export type Kind = "image" | "video" | "audio" | "pdf" | "text" | "code" | "archive" | "doc" | "sheet" | "slides" | "other";
const sets: Record<Exclude<Kind, "other">, string> = {
image: "png jpg jpeg gif webp avif bmp svg ico heic heif tif tiff raw cr2 nef dng",
video: "mp4 webm mov m4v ogv mkv avi wmv flv mpg mpeg 3gp",
audio: "mp3 ogg oga wav flac aac m4a opus wma aiff mid midi",
pdf: "pdf",
text: "txt md markdown rst log csv tsv json yaml yml toml ini conf cfg env srt tex bib nfo",
code: "html htm css js mjs ts tsx jsx py go rs java c h cpp hpp cs php rb sh bash zsh ps1 sql tf lua xml vue svelte service gitignore",
archive: "zip gz tgz bz2 xz 7z rar tar zst iso dmg jar deb rpm apk",
doc: "doc docx odt rtf pages",
sheet: "xls xlsx ods numbers",
slides: "ppt pptx odp key",
};
const byExt = new Map<string, Kind>();
for (const [kind, list] of Object.entries(sets)) for (const e of list.split(" ")) byExt.set(e, kind as Kind);
const textNames = new Set(["dockerfile", "makefile", "readme", "license", "changelog"]);
export const kindOf = (name: string): Kind => {
const k = byExt.get(extOf(name));
if (k) return k;
return textNames.has(name.toLowerCase()) ? "text" : "other";
};
/** Le serveur sait-il en faire une miniature (JPEG, PNG, GIF) ? */
export const serverThumb = (name: string) => ["jpg", "jpeg", "png", "gif"].includes(extOf(name));
/** Le navigateur affiche-t-il ce format d'image tel quel ? */
export const browserImage = (name: string) => ["png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "svg", "ico"].includes(extOf(name));
const browserVideo = ["mp4", "webm", "mov", "m4v", "ogv"];
const browserAudio = ["mp3", "ogg", "oga", "wav", "flac", "aac", "m4a", "opus"];
/** Aperçu intégré possible ? (texte limité aux premiers Mo, vidéo et audio selon le navigateur). */
export const previewable = (name: string): boolean => {
const k = kindOf(name);
const e = extOf(name);
switch (k) {
case "image":
return browserImage(name);
case "video":
return browserVideo.includes(e);
case "audio":
return browserAudio.includes(e);
case "pdf":
case "text":
case "code":
return true;
default:
return false;
}
};
const labels: Record<Kind, string> = {
image: "Image",
video: "Vidéo",
audio: "Audio",
pdf: "PDF",
text: "Texte",
code: "Code",
archive: "Archive",
doc: "Document",
sheet: "Tableur",
slides: "Présentation",
other: "Fichier",
};
/** « Image PNG », « Archive ZIP », « Fichier »... */
export const typeLabel = (name: string): string => {
const e = extOf(name).toUpperCase();
const k = kindOf(name);
return e ? (k === "other" ? `Fichier ${e}` : `${labels[k]} ${e}`) : labels[k];
};
/** Texte à afficher en monospace (code, journaux, configuration). */
export const monospace = (name: string) => kindOf(name) !== "text" || !["txt", "md", "markdown", "rst", "srt", "nfo"].includes(extOf(name));
+251
View File
@@ -0,0 +1,251 @@
// Icônes proposées pour les dossiers (jeu Tabler, comme icons.tsx). Le nom est
// enregistré côté serveur (.meta.json) : ne pas renommer une clé existante.
import { FolderIcon, icon } from "./icons";
type Icon = ReturnType<typeof icon>;
export const FOLDER_ICONS: { name: string; label: string; Icon: Icon }[] = [
{
name: "briefcase",
label: "Projet",
Icon: icon(
<>
<rect x="3" y="7" width="18" height="13" rx="2" />
<path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M12 12v.01M3 13a20 20 0 0 0 18 0" />
</>,
),
},
{
name: "rocket",
label: "Production",
Icon: icon(
<>
<path d="M4 13a8 8 0 0 1 7 7 6 6 0 0 0 3-5 9 9 0 0 0 6-8 3 3 0 0 0-3-3 9 9 0 0 0-8 6 6 6 0 0 0-5 3" />
<path d="M7 14a6 6 0 0 0-3 6 6 6 0 0 0 6-3" />
<circle cx="15" cy="9" r="1" />
</>,
),
},
{
name: "server",
label: "Serveurs",
Icon: icon(
<>
<rect x="3" y="4" width="18" height="8" rx="3" />
<rect x="3" y="12" width="18" height="8" rx="3" />
<path d="M7 8v.01M7 16v.01" />
</>,
),
},
{
name: "cpu",
label: "Calcul",
Icon: icon(
<>
<rect x="5" y="5" width="14" height="14" rx="1" />
<rect x="9" y="9" width="6" height="6" />
<path d="M3 10h2M3 14h2M10 3v2M14 3v2M21 10h-2M21 14h-2M14 21v-2M10 21v-2" />
</>,
),
},
{
name: "database",
label: "Stockage",
Icon: icon(
<>
<ellipse cx="12" cy="6" rx="8" ry="3" />
<path d="M4 6v6a8 3 0 0 0 16 0V6M4 12v6a8 3 0 0 0 16 0v-6" />
</>,
),
},
{
name: "box",
label: "Conteneurs",
Icon: icon(<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3M12 12l8-4.5M12 12v9M12 12 4 7.5" />),
},
{
name: "cloud",
label: "Cloud",
Icon: icon(
<path d="M6.66 18C4.08 18 2 15.99 2 13.52s2.09-4.49 4.66-4.49c.39-1.76 1.79-3.2 3.67-3.77 1.88-.57 3.96-.19 5.44 1 1.49 1.19 2.16 3.01 1.77 4.77h.99c1.91 0 3.46 1.56 3.46 3.49S20.45 18 18.54 18H6.66" />,
),
},
{
name: "network",
label: "Réseau",
Icon: icon(
<>
<circle cx="12" cy="9" r="6" />
<path d="M12 3c1.33.33 2 2.33 2 6s-.67 5.67-2 6M12 3c-1.33.33-2 2.33-2 6s.67 5.67 2 6M6 9h12M3 20h7M14 20h7M12 15v3" />
<circle cx="12" cy="20" r="2" />
</>,
),
},
{
name: "sitemap",
label: "Topologie",
Icon: icon(
<>
<rect x="3" y="15" width="6" height="6" rx="2" />
<rect x="15" y="15" width="6" height="6" rx="2" />
<rect x="9" y="3" width="6" height="6" rx="2" />
<path d="M6 15v-1a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v1M12 9v3" />
</>,
),
},
{
name: "router",
label: "Routeur",
Icon: icon(
<>
<rect x="3" y="13" width="18" height="8" rx="2" />
<path d="M17 17v.01M13 17v.01M15 13v-2M11.75 8.75a4 4 0 0 1 6.5 0M8.5 6.5a8 8 0 0 1 13 0" />
</>,
),
},
{
name: "world",
label: "Internet",
Icon: icon(
<>
<circle cx="12" cy="12" r="9" />
<path d="M3.6 9h16.8M3.6 15h16.8M11.5 3a17 17 0 0 0 0 18M12.5 3a17 17 0 0 1 0 18" />
</>,
),
},
{
name: "shield",
label: "Sécurité",
Icon: icon(<path d="M12 3a12 12 0 0 0 8.5 3A12 12 0 0 1 12 21 12 12 0 0 1 3.5 6 12 12 0 0 0 12 3" />),
},
{
name: "lock",
label: "Confidentiel",
Icon: icon(
<>
<rect x="5" y="11" width="14" height="10" rx="2" />
<circle cx="12" cy="16" r="1" />
<path d="M8 11V7a4 4 0 1 1 8 0v4" />
</>,
),
},
{
name: "desktop",
label: "Postes",
Icon: icon(
<>
<rect x="3" y="4" width="18" height="12" rx="1" />
<path d="M7 20h10M9 16v4M15 16v4" />
</>,
),
},
{
name: "code",
label: "Code",
Icon: icon(<path d="M7 8l-4 4 4 4M17 8l4 4-4 4M14 4l-4 16" />),
},
{
name: "tool",
label: "Outils",
Icon: icon(<path d="M7 10h3V7L6.5 3.5a6 6 0 0 1 8 8l6 6a2 2 0 0 1-3 3l-6-6a6 6 0 0 1-8-8L7 10" />),
},
{
name: "file-text",
label: "Documents",
Icon: icon(
<>
<path d="M14 3v4a1 1 0 0 0 1 1h4" />
<path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2zM9 9h1M9 13h6M9 17h6" />
</>,
),
},
{
name: "book",
label: "Documentation",
Icon: icon(<path d="M3 19a9 9 0 0 1 9 0 9 9 0 0 1 9 0M3 6a9 9 0 0 1 9 0 9 9 0 0 1 9 0M3 6v13M12 6v13M21 6v13" />),
},
{
name: "presentation",
label: "Présentations",
Icon: icon(<path d="M3 4h18M4 4v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V4M12 16v4M9 20h6M8 12l3-3 2 2 3-3" />),
},
{
name: "chart",
label: "Indicateurs",
Icon: icon(
<>
<rect x="3" y="12" width="6" height="8" rx="1" />
<rect x="9" y="8" width="6" height="12" rx="1" />
<rect x="15" y="4" width="6" height="16" rx="1" />
<path d="M4 20h14" />
</>,
),
},
{
name: "bulb",
label: "Idées",
Icon: icon(
<path d="M3 12h1m8-9v1m8 8h1M5.6 5.6l.7.7m12.1-.7-.7.7M9 16a5 5 0 1 1 6 0 3.5 3.5 0 0 0-1 3 2 2 0 0 1-4 0 3.5 3.5 0 0 0-1-3M9.7 17h4.6" />,
),
},
{
name: "users",
label: "Équipe",
Icon: icon(
<>
<circle cx="9" cy="7" r="4" />
<path d="M3 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2M16 3.13a4 4 0 0 1 0 7.75M21 21v-2a4 4 0 0 0-3-3.85" />
</>,
),
},
{
name: "building",
label: "Client / site",
Icon: icon(
<path d="M3 21h18M9 8h1M9 12h1M9 16h1M14 8h1M14 12h1M14 16h1M5 21V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16" />,
),
},
{
name: "calendar",
label: "Planning",
Icon: icon(
<>
<rect x="4" y="5" width="16" height="16" rx="2" />
<path d="M16 3v4M8 3v4M4 11h16" />
</>,
),
},
{
name: "photo",
label: "Images",
Icon: icon(
<>
<rect x="3" y="3" width="18" height="18" rx="3" />
<path d="M15 8h.01M3 16l5-5c.93-.89 2.07-.89 3 0l5 5M14 14l1-1c.93-.89 2.07-.89 3 0l3 3" />
</>,
),
},
{
name: "flag",
label: "Jalons",
Icon: icon(<path d="M5 5a5 5 0 0 1 7 0 5 5 0 0 0 7 0v9a5 5 0 0 1-7 0 5 5 0 0 0-7 0V5M5 21v-7" />),
},
{
name: "archive",
label: "Archives",
Icon: icon(
<>
<rect x="3" y="4" width="18" height="4" rx="2" />
<path d="M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8M10 12h4" />
</>,
),
},
];
const BY_NAME = new Map(FOLDER_ICONS.map((i) => [i.name, i.Icon]));
/** Icône d'un dossier : celle choisie, ou le dossier classique (nom absent ou inconnu). */
export function FolderGlyph({ name, size }: { name?: string; size?: number }) {
const Icon = (name && BY_NAME.get(name)) || FolderIcon;
return <Icon size={size} />;
}
+43
View File
@@ -0,0 +1,43 @@
// Mise en forme des dates, tailles et auteurs (explorateur, panneau Détails).
export const fmtDate = (iso: string) => new Date(iso).toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" });
export const fmtSize = (n: number) => {
if (n < 1024) return `${n} o`;
const units = ["Ko", "Mo", "Go", "To"];
let v = n / 1024;
let i = 0;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
return `${v >= 100 ? v.toFixed(0) : v.toFixed(1)} ${units[i]}`;
};
export const fmtRate = (bytesPerSecond: number) => `${fmtSize(bytesPerSecond)}/s`;
export const plural = (n: number, word: string) => `${n} ${word}${n > 1 ? "s" : ""}`;
const relative = new Intl.RelativeTimeFormat("fr", { numeric: "auto" });
/** « à l'instant », « il y a 5 minutes », « hier »… puis la date au-delà d'un mois. */
export const fmtRelative = (iso: string) => {
const s = (Date.now() - new Date(iso).getTime()) / 1000;
if (s < 60) return "à l'instant";
if (s < 3600) return relative.format(-Math.round(s / 60), "minute");
if (s < 86400) return relative.format(-Math.round(s / 3600), "hour");
if (s < 30 * 86400) return relative.format(-Math.round(s / 86400), "day");
return new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" });
};
/** Auteur affichable : rien pour l'utilisateur unique sans authentification. */
export const who = (id?: string) => (id && id !== "local" ? id : "");
/** Initiales d'un nom pour l'avatar. */
export const initials = (name: string) =>
name
.split(/[\s._@-]+/)
.filter(Boolean)
.slice(0, 2)
.map((p) => p[0].toUpperCase())
.join("") || "?";
+440
View File
@@ -0,0 +1,440 @@
// Icônes au trait, dans le style d'Excalidraw (jeu Tabler, trait fin, couleur héritée).
import type { ReactNode } from "react";
export const icon = (paths: ReactNode) =>
function Icon({ size = 16, className }: { size?: number; className?: string }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={1.5}
strokeLinecap="round"
strokeLinejoin="round"
className={className}
aria-hidden
>
{paths}
</svg>
);
};
export const SunIcon = icon(
<>
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
</>,
);
export const MoonIcon = icon(<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9z" />);
export const SettingsIcon = icon(
<>
<path d="M10.33 4.32c.43-1.76 2.93-1.76 3.35 0a1.72 1.72 0 0 0 2.57 1.07c1.54-.94 3.31.83 2.37 2.37a1.72 1.72 0 0 0 1.07 2.57c1.76.43 1.76 2.93 0 3.35a1.72 1.72 0 0 0-1.07 2.57c.94 1.54-.83 3.31-2.37 2.37a1.72 1.72 0 0 0-2.57 1.07c-.43 1.76-2.93 1.76-3.35 0a1.72 1.72 0 0 0-2.57-1.07c-1.54.94-3.31-.83-2.37-2.37a1.72 1.72 0 0 0-1.07-2.57c-1.76-.43-1.76-2.93 0-3.35a1.72 1.72 0 0 0 1.07-2.57c-.94-1.54.83-3.31 2.37-2.37 1 .61 2.3.07 2.57-1.07z" />
<circle cx="12" cy="12" r="3" />
</>,
);
export const MenuIcon = icon(<path d="M4 6h16M4 12h16M4 18h16" />);
export const CloseIcon = icon(<path d="M18 6 6 18M6 6l12 12" />);
export const FilePlusIcon = icon(
<>
<path d="M14 3v4a1 1 0 0 0 1 1h4" />
<path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z" />
<path d="M12 11v6M9 14h6" />
</>,
);
export const FolderPlusIcon = icon(
<>
<path d="M12 19H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4l3 3h7a2 2 0 0 1 2 2v3.5" />
<path d="M16 19h6M19 16v6" />
</>,
);
export const UploadIcon = icon(
<>
<path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" />
<path d="M7 9l5-5 5 5M12 4v12" />
</>,
);
export const FolderUploadIcon = icon(
<>
<path d="M12 19H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4l3 3h7a2 2 0 0 1 2 2v3" />
<path d="M19 22v-6M22 19l-3-3-3 3" />
</>,
);
export const FolderIcon = icon(
<path d="M5 4h4l3 3h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2" />,
);
export const UpIcon = icon(<path d="M18 18h-6a3 3 0 0 1-3-3V5M13 10 9 6 5 10" />);
export const SearchIcon = icon(
<>
<circle cx="10" cy="10" r="7" />
<path d="m21 21-6-6" />
</>,
);
export const ListIcon = icon(<path d="M9 6h11M9 12h11M9 18h11M5 6v.01M5 12v.01M5 18v.01" />);
export const GridIcon = icon(
<>
<rect x="4" y="4" width="6" height="6" rx="1" />
<rect x="14" y="4" width="6" height="6" rx="1" />
<rect x="4" y="14" width="6" height="6" rx="1" />
<rect x="14" y="14" width="6" height="6" rx="1" />
</>,
);
export const RefreshIcon = icon(
<>
<path d="M20 11A8.1 8.1 0 0 0 4.5 9M4 5v4h4" />
<path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4" />
</>,
);
export const DotsIcon = icon(
<>
<circle cx="5" cy="12" r="1" />
<circle cx="12" cy="12" r="1" />
<circle cx="19" cy="12" r="1" />
</>,
);
export const TrashIcon = icon(
<path d="M4 7h16M10 11v6M14 11v6M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2l1-12M9 7V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3" />,
);
/** Poubelle qui contient des éléments : une feuille et une boule de papier dépassent du bord. */
export const TrashFullIcon = icon(
<>
<path d="M4 10h16M5 10l1 9a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2l1-9M10 14v3M14 14v3" />
<path d="M7.5 10 9 3.5l4.5 1-1.2 5.5M10.2 6.5l2 .5" />
<circle cx="16" cy="7.8" r="2.2" />
</>,
);
export const RestoreIcon = icon(<path d="M9 14l-4-4 4-4M5 10h11a4 4 0 1 1 0 8h-1" />);
export const FileIcon = icon(
<>
<path d="M14 3v4a1 1 0 0 0 1 1h4" />
<path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z" />
</>,
);
export const SelectAllIcon = icon(
<>
<rect x="4" y="4" width="16" height="16" rx="2" />
<path d="m9 12 2 2 4-4" />
</>,
);
export const DeselectIcon = icon(<rect x="4" y="4" width="16" height="16" rx="2" />);
export const MoveIcon = icon(
<>
<path d="M12 19H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4l3 3h7a2 2 0 0 1 2 2v3" />
<path d="M16 19h6M19 16l3 3-3 3" />
</>,
);
export const SaveIcon = icon(
<>
<path d="M6 4h10l4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2" />
<circle cx="12" cy="14" r="2" />
<path d="M14 4v4H8V4" />
</>,
);
export const UpdateIcon = icon(
<>
<circle cx="12" cy="12" r="9" />
<path d="M12 16V8M8.5 11.5 12 8l3.5 3.5" />
</>,
);
export const CopyIcon = icon(
<>
<rect x="8" y="8" width="12" height="12" rx="2" />
<path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2" />
</>,
);
export const EditIcon = icon(<path d="M4 20h4L18.5 9.5a2.83 2.83 0 0 0-4-4L4 16v4M13.5 6.5l4 4" />);
export const HistoryIcon = icon(
<>
<path d="M12 8v4l2 2" />
<path d="M3.05 11a9 9 0 1 1 .5 4m-.5 5v-5h5" />
</>,
);
export const DownloadIcon = icon(
<>
<path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" />
<path d="M7 11l5 5 5-5M12 4v12" />
</>,
);
export const StarIcon = icon(
<path d="M12 17.75l-6.17 3.24 1.18-6.87-5-4.86 6.9-1 3.09-6.26 3.09 6.26 6.9 1-5 4.86 1.18 6.87z" />,
);
/** Étoile pleine (favori). */
export function StarFilledIcon({ size = 16 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth={1.5} strokeLinejoin="round" aria-hidden>
<path d="M12 17.75l-6.17 3.24 1.18-6.87-5-4.86 6.9-1 3.09-6.26 3.09 6.26 6.9 1-5 4.86 1.18 6.87z" />
</svg>
);
}
export const TagIcon = icon(
<>
<circle cx="8.5" cy="8.5" r="1" />
<path d="M4 7v3.86a2 2 0 0 0 .59 1.41l7.71 7.71a2.4 2.4 0 0 0 3.4 0l4.27-4.27a2.4 2.4 0 0 0 0-3.4L12.26 4.59A2 2 0 0 0 10.85 4H7a3 3 0 0 0-3 3z" />
</>,
);
export const ShareIcon = icon(
<>
<circle cx="6" cy="12" r="3" />
<circle cx="18" cy="6" r="3" />
<circle cx="18" cy="18" r="3" />
<path d="M8.7 10.7l6.6-3.4M8.7 13.3l6.6 3.4" />
</>,
);
export const EyeIcon = icon(
<>
<circle cx="12" cy="12" r="2" />
<path d="M22 12c-2.67 4.67-6 7-10 7s-7.33-2.33-10-7c2.67-4.67 6-7 10-7s7.33 2.33 10 7" />
</>,
);
/** Punaise : panneau épinglé ou flottant (comme le bouton d'ancrage des panneaux d'Excalidraw). */
export const PinIcon = icon(<path d="M15 4.5l-4 4-4 1.5-1.5 1.5 7 7 1.5-1.5 1.5-4 4-4M9 15l-4.5 4.5M14.5 4 20 9.5" />);
/** Espace personnel de l'utilisateur. */
export const UserIcon = icon(
<>
<circle cx="12" cy="8" r="4" />
<path d="M6 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2" />
</>,
);
export const LogoutIcon = icon(
<>
<path d="M14 8V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2-2v-2" />
<path d="M9 12h12l-3-3M18 15l3-3" />
</>,
);
// Vue Galerie et ses métadonnées.
export const GalleryIcon = icon(
<>
<rect x="3" y="4" width="8" height="7" rx="1.5" />
<rect x="13" y="4" width="8" height="7" rx="1.5" />
<path d="M3 15h8M3 19h5M13 15h8M13 19h5" />
</>,
);
export const ClockIcon = icon(
<>
<circle cx="12" cy="12" r="9" />
<path d="M12 7v5l3 3" />
</>,
);
export const ShapesIcon = icon(
<>
<rect x="3" y="3" width="8" height="8" rx="1" />
<circle cx="17" cy="17" r="4" />
<path d="M17 3l4 7h-8z" />
</>,
);
export const TextIcon = icon(<path d="M6 4h12M12 4v16M9 20h6" />);
export const PhotoIcon = icon(
<>
<rect x="3" y="4" width="18" height="16" rx="2" />
<circle cx="9" cy="10" r="1.5" />
<path d="M21 16l-5-5-8 9" />
</>,
);
export const FrameIcon = icon(<path d="M4 7h16M4 17h16M7 4v16M17 4v16" />);
export const ArrowIcon = icon(<path d="M5 19 19 5M10 5h9v9" />);
export const SizeIcon = icon(
<>
<path d="M6 4h10l4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z" />
<path d="M8 4v5h7V4M8 20v-6h8v6" />
</>,
);
export const SortIcon = icon(<path d="M4 6h9M4 12h7M4 18h5M17 4v16M14 17l3 3 3-3" />);
export const InfoIcon = icon(
<>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v.01M11 12h1v4h1" />
</>,
);
export const LinkIcon = icon(
<path d="M9 15l6-6M11 6l.46-.54a5 5 0 0 1 7.07 7.07l-.53.47M13 18l-.4.53a5 5 0 0 1-7.07-7.07L6 11" />,
);
// --- Types de fichiers, aperçu, comptes ---------------------------------------------
const page = <path d="M14 3v4a1 1 0 0 0 1 1h4M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z" />;
export const FileTextIcon = icon(
<>
{page}
<path d="M9 9h1M9 13h6M9 17h6" />
</>,
);
export const FileCodeIcon = icon(
<>
{page}
<path d="M10 13l-2 2 2 2M14 13l2 2-2 2" />
</>,
);
export const FileZipIcon = icon(
<>
{page}
<path d="M11 4h2M11 7h2M11 10h2M11 13h2" />
<rect x="10" y="15" width="4" height="4" rx="1" />
</>,
);
export const FileMusicIcon = icon(
<>
{page}
<circle cx="10" cy="17" r="1.5" />
<path d="M11.5 17v-5l3 1" />
</>,
);
export const FileVideoIcon = icon(
<>
{page}
<path d="M10 12.5v5l4-2.5z" />
</>,
);
export const FilePdfIcon = icon(
<>
{page}
<path d="M8 17v-4h1.5a1.2 1.2 0 0 1 0 2.4H8M12.5 13v4M12.5 13h1a1.5 1.5 0 0 1 1.5 1.5v1a1.5 1.5 0 0 1-1.5 1.5h-1" />
</>,
);
export const FileSheetIcon = icon(
<>
{page}
<path d="M8 12h8M8 15h8M8 18h8M11 12v6" />
</>,
);
export const FileSlidesIcon = icon(
<>
{page}
<path d="M8 18v-3M12 18v-6M16 18v-4" />
</>,
);
export const FileImageIcon = icon(
<>
{page}
<circle cx="10" cy="12" r="1.2" />
<path d="M17 17l-3-3-5 4" />
</>,
);
export const PlayIcon = icon(<path d="M7 4v16l13-8z" />);
export const ChevronLeftIcon = icon(<path d="M15 6l-6 6 6 6" />);
export const ChevronRightIcon = icon(<path d="M9 6l6 6-6 6" />);
export const ChevronDownIcon = icon(<path d="M6 9l6 6 6-6" />);
export const LockIcon = icon(
<>
<rect x="5" y="11" width="14" height="10" rx="2" />
<path d="M8 11V7a4 4 0 0 1 8 0v4M12 15v2" />
</>,
);
export const KeyIcon = icon(
<>
<circle cx="8" cy="15" r="4" />
<path d="M10.85 12.15L19 4M18 5l2 2M15 8l2 2" />
</>,
);
export const UsersIcon = icon(
<>
<circle cx="9" cy="8" r="3.5" />
<path d="M3 20v-1a5 5 0 0 1 5-5h2a5 5 0 0 1 5 5v1M16 4.6a3.5 3.5 0 0 1 0 6.8M21 20v-1a5 5 0 0 0-3.5-4.7" />
</>,
);
export const ShieldIcon = icon(<path d="M12 3l8 3v6c0 4.5-3.2 8-8 9-4.8-1-8-4.5-8-9V6z" />);
export const CheckIcon = icon(<path d="M5 12l5 5L20 7" />);
export const PlusIcon = icon(<path d="M12 5v14M5 12h14" />);
export const HomeIcon = icon(
<>
<path d="M5 12H3l9-9 9 9h-2" />
<path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7M9 21v-6a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v6" />
</>,
);
export const TableIcon = icon(
<>
<rect x="3" y="4" width="18" height="16" rx="2" />
<path d="M3 10h18M3 15h18M10 4v16" />
</>,
);
export const CloudIcon = icon(<path d="M7 18a4.5 4.5 0 0 1-.5-9 6 6 0 0 1 11.4 1.5A3.5 3.5 0 0 1 17.5 18z" />);
export const CloudUpIcon = icon(
<>
<path d="M7 18a4.5 4.5 0 0 1-.5-9 6 6 0 0 1 11.4 1.5A3.5 3.5 0 0 1 17.5 18" />
<path d="M9 14l3-3 3 3M12 11v9" />
</>,
);
export const ExpandIcon = icon(<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />);
export const CopyLinkIcon = icon(
<>
<rect x="9" y="9" width="11" height="11" rx="2" />
<path d="M5 15V6a2 2 0 0 1 2-2h9" />
</>,
);
export const WarningIcon = icon(
<>
<path d="M12 3l10 18H2z" />
<path d="M12 10v5M12 18v.01" />
</>,
);
+91
View File
@@ -0,0 +1,91 @@
// Lecture de fichiers et d'arborescences à envoyer (glisser-déposer ou sélecteur de dossier).
export interface PickedFile {
/** Chemin relatif au point d'envoi, dossiers compris (« Photos/2024/img.jpg »). */
rel: string;
file: File;
}
export interface Collected {
files: PickedFile[];
/** Dossiers à recréer (y compris vides), parents avant enfants. */
dirs: string[];
/** Éléments ignorés : fichiers et dossiers cachés (.DS_Store, .git...). */
ignored: string[];
}
const hidden = (name: string) => name.startsWith(".");
/** Le glisser contient-il des fichiers venant du système ? */
export const hasFiles = (dt: DataTransfer) => dt.types.includes("Files");
const readAll = (reader: FileSystemDirectoryReader) =>
new Promise<FileSystemEntry[]>((resolve, reject) => {
const out: FileSystemEntry[] = [];
// readEntries rend les entrées par lots (100 sous Chrome) : boucler jusqu'au lot vide.
const next = () =>
reader.readEntries((batch) => {
if (batch.length === 0) return resolve(out);
out.push(...batch);
next();
}, reject);
next();
});
const fileOf = (entry: FileSystemFileEntry) => new Promise<File>((resolve, reject) => entry.file(resolve, reject));
async function walk(entry: FileSystemEntry, prefix: string, acc: Collected) {
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
if (hidden(entry.name)) {
acc.ignored.push(rel);
return;
}
if (entry.isDirectory) {
acc.dirs.push(rel);
for (const child of await readAll((entry as FileSystemDirectoryEntry).createReader())) {
await walk(child, rel, acc);
}
} else {
acc.files.push({ rel, file: await fileOf(entry as FileSystemFileEntry) });
}
}
/**
* Lit un dépôt (fichiers et dossiers). Les entrées doivent être capturées pendant
* l'événement drop : le DataTransfer est vidé dès que le gestionnaire rend la main.
*/
export function collectDrop(dt: DataTransfer): Promise<Collected> {
const entries = Array.from(dt.items)
.filter((i) => i.kind === "file")
.map((i) => i.webkitGetAsEntry?.())
.filter((e): e is FileSystemEntry => !!e);
const plain = entries.length ? [] : Array.from(dt.files); // navigateur sans webkitGetAsEntry
return (async () => {
const acc: Collected = { files: [], dirs: [], ignored: [] };
for (const e of entries) await walk(e, "", acc);
collectInto(plain, acc);
return acc;
})();
}
/** Fichiers d'un <input type="file"> (chemins dans webkitRelativePath pour un dossier). */
export function collectFiles(files: FileList | File[]): Collected {
const acc: Collected = { files: [], dirs: [], ignored: [] };
collectInto(Array.from(files), acc);
return acc;
}
function collectInto(files: File[], acc: Collected) {
const dirs = new Set(acc.dirs);
for (const file of files) {
const rel = file.webkitRelativePath || file.name;
const parts = rel.split("/");
if (parts.some(hidden)) {
acc.ignored.push(rel);
continue;
}
for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join("/"));
acc.files.push({ rel, file });
}
acc.dirs = [...dirs].sort((a, b) => a.split("/").length - b.split("/").length);
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";
import App from "./App";
import { ShareView } from "./ShareView";
// /s/<jeton> : lien de partage (sans compte).
const share = location.pathname.match(/^\/s\/([^/]+)\/?$/);
createRoot(document.getElementById("root")!).render(<StrictMode>{share ? <ShareView token={decodeURIComponent(share[1])} /> : <App />}</StrictMode>);
File diff suppressed because it is too large. Load diff
+182
View File
@@ -0,0 +1,182 @@
// File d'envoi : plusieurs fichiers en parallèle, progression par fichier, annulation,
// nouvel essai. L'état est un « store » externe lu par useSyncExternalStore.
import { useSyncExternalStore } from "react";
import { api, ApiError, join, uploadFile, type Conflict } from "./api";
import type { Collected } from "./importer";
export type UploadStatus = "queued" | "uploading" | "done" | "error" | "canceled";
export interface UploadItem {
id: number;
/** Chemin relatif affiché (« Photos/img.jpg »). */
rel: string;
/** Chemin de destination complet. */
path: string;
size: number;
loaded: number;
status: UploadStatus;
error?: string;
/** Chemin final (différent de path si le serveur a renommé). */
result?: string;
}
/** Que faire si un fichier du même nom existe ? */
export type OnExists = Extract<Conflict, "rename" | "overwrite" | "fail">;
const CONCURRENCY = 3;
class UploadStore {
private items: UploadItem[] = [];
private snapshot: readonly UploadItem[] = [];
private files = new Map<number, File>();
private aborts = new Map<number, () => void>();
private listeners = new Set<() => void>();
private next = 1;
private doneListeners = new Set<() => void>();
/** Comportement si le nom existe déjà (mémorisé par navigateur). */
onExists: OnExists = (() => {
try {
const v = localStorage.getItem("uploadOnExists");
return v === "overwrite" || v === "fail" ? v : "rename";
} catch {
return "rename";
}
})();
setOnExists(v: OnExists) {
this.onExists = v;
try {
localStorage.setItem("uploadOnExists", v);
} catch {
/* stockage indisponible */
}
this.emit();
}
subscribe = (fn: () => void) => {
this.listeners.add(fn);
return () => {
this.listeners.delete(fn);
};
};
getSnapshot = () => this.snapshot;
/** Appelé quand des fichiers viennent d'être déposés (rafraîchit l'explorateur). */
onDone(fn: () => void) {
this.doneListeners.add(fn);
return () => {
this.doneListeners.delete(fn);
};
}
private emit() {
this.snapshot = [...this.items];
this.listeners.forEach((l) => l());
}
/** Ajoute des fichiers (et les dossiers vides) à envoyer dans dir. */
add(dir: string, picked: Collected) {
// Dossiers d'abord (y compris vides) ; un dossier existant n'est pas une erreur.
const mk = picked.dirs.map((d) => api.mkdir(join(dir, d)).catch((e) => (e instanceof ApiError && e.status === 409 ? undefined : Promise.reject(e))));
Promise.allSettled(mk).then(() => this.doneListeners.forEach((l) => l()));
for (const { rel, file } of picked.files) {
const id = this.next++;
this.files.set(id, file);
this.items.push({ id, rel, path: join(dir, rel), size: file.size, loaded: 0, status: "queued" });
}
this.emit();
this.pump();
}
private pump() {
let running = this.items.filter((i) => i.status === "uploading").length;
for (const it of this.items) {
if (running >= CONCURRENCY) break;
if (it.status === "queued") {
running++;
this.start(it);
}
}
}
private start(it: UploadItem) {
const file = this.files.get(it.id);
if (!file) return;
it.status = "uploading";
it.loaded = 0;
it.error = undefined;
this.emit();
const { promise, abort } = uploadFile(it.path, file, {
conflict: this.onExists,
onProgress: (loaded) => {
it.loaded = loaded;
this.emit();
},
});
this.aborts.set(it.id, abort);
promise
.then((entry) => {
it.status = "done";
it.loaded = it.size;
it.result = entry.path;
this.files.delete(it.id);
})
.catch((e: unknown) => {
const err = e instanceof ApiError ? e : null;
if (err && err.status === 0 && err.message === "annulé") it.status = "canceled";
else {
it.status = "error";
it.error = err?.status === 409 ? "existe déjà" : err?.status === 507 ? "quota de stockage dépassé" : err?.status === 413 ? "fichier trop volumineux" : err ? err.message : String(e);
}
})
.finally(() => {
this.aborts.delete(it.id);
this.emit();
this.pump();
if (!this.items.some((i) => i.status === "queued" || i.status === "uploading")) this.doneListeners.forEach((l) => l());
});
}
cancel(id: number) {
const it = this.items.find((i) => i.id === id);
if (!it) return;
if (it.status === "uploading") this.aborts.get(id)?.();
else if (it.status === "queued") {
it.status = "canceled";
this.files.delete(id);
this.emit();
}
}
cancelAll() {
for (const it of [...this.items]) this.cancel(it.id);
}
retry(id: number) {
const it = this.items.find((i) => i.id === id);
if (it && (it.status === "error" || it.status === "canceled") && this.files.has(id)) {
it.status = "queued";
this.emit();
this.pump();
}
}
retryFailed() {
this.items.filter((i) => i.status === "error").forEach((i) => this.retry(i.id));
}
/** Retire de la liste les envois terminés ou annulés. */
clearFinished() {
this.items = this.items.filter((i) => i.status === "queued" || i.status === "uploading" || i.status === "error");
this.emit();
}
}
export const uploads = new UploadStore();
export function useUploads(): readonly UploadItem[] {
return useSyncExternalStore(uploads.subscribe, uploads.getSnapshot);
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"isolatedModules": true,
"allowImportingTsExtensions": false,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src"]
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
// Le build est embarqué dans le binaire Go (web/dist).
build: { outDir: "../web/dist", emptyOutDir: true },
// `npm run dev` : l'API Go tourne sur :8080 (les routes /s, /auth et /api passent par le proxy).
server: { proxy: { "/api": "http://localhost:8080", "/auth": "http://localhost:8080", "/s": "http://localhost:8080" } },
});