Explorateur : vignettes, sélection et déplacement multiples

- vue vignettes/liste, miniatures générées à la sauvegarde et à la demande
- multi-sélection (cases, Ctrl/Maj+clic, Ctrl+A, Échap, Suppr)
- glisser-déposer de la sélection, dialogue « Déplacer vers… » tactile

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CZ78TqR7fgtRx3rvpNUbAL
This commit is contained in:
claude BotandClaude Opus 5.5 committed 2026-10-07 12:46:37 +02:00
1 parent 66eb1c08de
commit d04350df7a
6 files changed
+548 -3

No files matched your search

+3
View File
@@ -16,6 +16,7 @@ import type {
import type { OrderedExcalidrawElement } from "@excalidraw/excalidraw/element/types";
import { api, ApiError, basename, stripExt } from "./api";
import { Explorer } from "./Explorer";
import { storeThumb } from "./thumbs";
type Theme = "light" | "dark";
type SaveState = "saved" | "dirty" | "saving" | "error";
@@ -91,6 +92,8 @@ export default function App() {
try {
etagRef.current = await api.write(path, body, force ? "" : etagRef.current);
savedVersion.current = version;
// Miniature pour l'explorateur ; un échec n'affecte pas la sauvegarde.
await storeThumb(path, elements, appState, files).catch((e) => console.warn("miniature", e));
// D'autres modifications ont pu arriver pendant l'envoi.
const now = sceneVersion(ex.getSceneElements(), ex.getAppState(), ex.getFiles());
setSaveState(now === version ? "saved" : "dirty");
+96
View File
@@ -0,0 +1,96 @@
import { useEffect, useState } from "react";
import { api, basename, dirname, join, type Entry } from "./api";
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);
useEffect(() => {
let live = true;
setError(null);
api
.list(dir)
.then((es) => live && setFolders(es.filter((e) => e.isDir)))
.catch((e) => live && setError(e.message));
return () => {
live = false;
};
}, [dir]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onCancel();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onCancel]);
// 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 () => {
const name = prompt("Nom du dossier :");
if (!name?.trim()) return;
try {
const e = await api.mkdir(join(dir, name.trim()));
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)}>{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 aria-hidden>📁</span> {f.name}
</button>
</li>
))}
{folders.length === 0 && <li className="muted empty">Aucun sous-dossier</li>}
</ul>
<div className="modal-actions">
<button onClick={newFolder}>+ Dossier</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>
</div>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { useEffect, useRef, useState } from "react";
import { api } from "./api";
import { ensureThumb, knownThumb } from "./thumbs";
type State = "idle" | "server" | "generating" | "retry" | "empty" | "error";
/**
* Miniature d'un schéma, chargée quand elle devient visible. Si le serveur
* n'en a pas (ou qu'elle est périmée), elle est générée dans le navigateur
* puis envoyée au serveur pour les visites suivantes.
*/
export function Thumb({ path, version }: { path: string; version: string }) {
const ref = useRef<HTMLSpanElement>(null);
const [visible, setVisible] = useState(false);
const [state, setState] = useState<State>("idle");
useEffect(() => {
const k = knownThumb(path, version);
setState(k === "empty" || k === "error" ? k : "idle");
}, [path, version]);
useEffect(() => {
const el = ref.current;
if (!el || visible) return;
const io = new IntersectionObserver(
(es) => {
if (es.some((e) => e.isIntersecting)) {
setVisible(true);
io.disconnect();
}
},
{ rootMargin: "200px" },
);
io.observe(el);
return () => io.disconnect();
}, [visible]);
useEffect(() => {
if (visible && state === "idle") setState("server");
}, [visible, state]);
const onError = () => {
if (state !== "server") return setState("error");
setState("generating");
ensureThumb(path, version).then((r) => setState(r === "ok" ? "retry" : r));
};
const src =
state === "server"
? api.thumbUrl(path, version)
: state === "retry"
? `${api.thumbUrl(path, version)}&r=1` // la réponse 404 précédente n'est pas réutilisée
: null;
return (
<span ref={ref} className={`thumb ${state}`} aria-hidden>
{src ? (
<img src={src} alt="" loading="lazy" decoding="async" draggable={false} onError={onError} />
) : (
<span className="ph">{state === "empty" ? "∅" : state === "error" ? "📄" : ""}</span>
)}
</span>
);
}
+21
View File
@@ -8,6 +8,12 @@ export interface Entry {
modTime: string;
}
export interface MoveResult {
from: string;
to?: string;
error?: string;
}
export class ApiError extends Error {
constructor(public status: number, message: string) {
super(message);
@@ -61,6 +67,10 @@ export const api = {
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(),
@@ -79,6 +89,17 @@ export const api = {
},
downloadUrl: (path: string) => `/api/file?path=${q(path)}`,
/** v = date du schéma : l'URL change à chaque nouvelle version (cache navigateur). */
thumbUrl: (path: string, v: string) => `/api/thumb?path=${q(path)}&v=${q(v)}`,
writeThumb: async (path: string, png: Blob): Promise<void> => {
await request(`/api/thumb?path=${q(path)}`, {
method: "PUT",
headers: { "Content-Type": "image/png" },
body: png,
});
},
};
// Helpers de chemins (format "slash", relatifs à la racine).
+261 -3
View File
@@ -10,7 +10,7 @@
--ok: #2b8a3e;
--warn: #e67700;
--topbar-h: 44px;
--drawer-w: 300px;
--drawer-w: 330px;
color-scheme: light;
}
@@ -45,6 +45,7 @@ body,
button,
.actions a {
-webkit-tap-highlight-color: transparent;
font: inherit;
color: inherit;
background: var(--panel);
@@ -179,8 +180,14 @@ button:disabled {
flex-wrap: wrap;
gap: 4px;
}
.searchbar {
display: flex;
align-items: center;
gap: 2px;
}
.search {
width: 100%;
flex: 1;
min-width: 0;
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 6px;
@@ -222,7 +229,7 @@ button:disabled {
li.active > .row {
background: var(--accent-soft);
}
.row.drop,
.item.drop > .row,
.crumbs button.drop {
border-color: var(--accent);
background: var(--accent-soft);
@@ -296,3 +303,254 @@ li.active > .row {
padding: 10px 6px; /* cibles tactiles plus grandes */
}
}
/* --- Explorateur : sélection, vignettes, déplacement ----------------------- */
:root {
--thumb-bg: #ffffff;
}
:root[data-theme="dark"] {
--thumb-bg: #121212;
}
.spacer {
flex: 1;
}
button.primary {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
:root[data-theme="dark"] button.primary {
color: #121212;
}
.selbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
padding: 4px 6px;
border-radius: 6px;
background: var(--accent-soft);
font-size: 13px;
}
.selbar .count {
flex: 1;
font-weight: 600;
white-space: nowrap;
}
.selbar button:not(.icon-btn) {
padding: 4px 8px;
}
.selbar .icon-btn {
padding: 4px 6px;
}
/* Case à cocher : au survol (souris), toujours visible pendant une sélection
et sur écran tactile. */
.item .check {
width: 16px;
height: 16px;
margin: 0 0 0 4px;
flex: none;
accent-color: var(--accent);
cursor: pointer;
opacity: 0;
}
.item:hover .check,
.item .check:focus-visible,
.selecting .item .check {
opacity: 1;
}
@media (hover: none) {
.item .check {
opacity: 1;
}
}
.item.selected > .row {
background: var(--accent-soft);
outline: 1px solid var(--accent);
}
.entries .item.up .row {
padding-left: 20px;
}
/* Miniatures */
.thumb {
flex: none;
display: grid;
place-items: center;
width: 44px;
height: 33px;
border-radius: 4px;
border: 1px solid var(--border);
background: var(--thumb-bg);
overflow: hidden;
}
.thumb img {
width: 100%;
height: 100%;
object-fit: contain;
}
:root[data-theme="dark"] .thumb img {
filter: invert(93%) hue-rotate(180deg); /* même rendu que le mode sombre d'Excalidraw */
}
.thumb .ph {
color: var(--muted);
font-size: 14px;
}
.thumb.server,
.thumb.generating {
background: linear-gradient(90deg, var(--thumb-bg), var(--panel), var(--thumb-bg));
background-size: 200% 100%;
animation: shimmer 1.2s linear infinite;
}
@keyframes shimmer {
to {
background-position: -200% 0;
}
}
/* Vue grille */
.entries.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
grid-auto-flow: row dense;
gap: 6px;
align-content: start;
}
.entries.grid > .empty,
.entries.grid > .menu-row {
grid-column: 1 / -1;
}
.entries.grid .row {
position: relative;
flex-direction: column;
align-items: stretch;
gap: 0;
height: 100%;
border: 1px solid var(--border);
background: var(--bg);
}
.entries.grid .row .name {
flex-direction: column;
align-items: stretch;
gap: 4px;
padding: 4px;
}
.entries.grid .thumb,
.entries.grid .icon {
width: 100%;
height: auto;
aspect-ratio: 4 / 3;
}
.entries.grid .icon {
display: grid;
place-items: center;
font-size: 42px;
}
.entries.grid .label {
text-align: center;
font-size: 12.5px;
}
.entries.grid .where {
display: block;
}
.entries.grid .check {
position: absolute;
top: 8px;
left: 6px;
z-index: 1;
}
.entries.grid .more {
position: absolute;
top: 4px;
right: 4px;
z-index: 1;
background: color-mix(in srgb, var(--bg) 80%, transparent);
border-radius: 6px;
opacity: 0;
}
.entries.grid .item:hover .more,
.entries.grid .more:focus-visible {
opacity: 1;
}
@media (hover: none) {
.entries.grid .more {
opacity: 1;
}
}
.entries.grid .actions {
padding: 4px 2px 8px;
}
.drag-ghost {
position: fixed;
top: -100px;
left: -100px;
padding: 4px 10px;
border-radius: 12px;
background: var(--accent);
color: #fff;
font: 600 13px system-ui, sans-serif;
}
/* Dialogue « Déplacer vers… » */
.modal-backdrop {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
padding: 16px;
background: rgb(0 0 0 / 0.4);
}
.modal {
width: min(420px, 100%);
max-height: min(560px, 90dvh);
display: flex;
flex-direction: column;
gap: 8px;
padding: 14px;
border-radius: 10px;
background: var(--panel);
border: 1px solid var(--border);
box-shadow: 0 8px 32px rgb(0 0 0 / 0.3);
}
.modal h3 {
margin: 0;
font-size: 15px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.modal .folders {
list-style: none;
margin: 0;
padding: 0;
flex: 1;
min-height: 120px;
overflow-y: auto;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg);
}
.modal .folders button {
width: 100%;
text-align: left;
border: none;
border-radius: 0;
background: transparent;
padding: 9px 10px;
}
.modal .folders button:hover:not(:disabled) {
background: var(--accent-soft);
}
.modal .folders .empty {
padding: 10px;
}
.modal-actions {
display: flex;
gap: 6px;
align-items: center;
}
+103
View File
@@ -0,0 +1,103 @@
// Miniatures PNG des schémas : rendues dans le navigateur par Excalidraw
// (exportToBlob), stockées côté serveur dans .thumbs/ (voir storage/thumbs.go).
import { exportToBlob, restoreElements } from "@excalidraw/excalidraw";
import type { AppState, BinaryFiles } from "@excalidraw/excalidraw/types";
import type { ExcalidrawElement } from "@excalidraw/excalidraw/element/types";
import { api } from "./api";
const THUMB_PX = 320;
/** Rend la miniature d'une scène ; null si la scène est vide. */
export async function renderThumb(
elements: readonly ExcalidrawElement[],
appState: Partial<AppState>,
files: BinaryFiles,
): Promise<Blob | null> {
const live = elements.filter((e) => !e.isDeleted);
if (live.length === 0) return null;
return exportToBlob({
elements: live,
appState: {
viewBackgroundColor: appState.viewBackgroundColor ?? "#ffffff",
exportBackground: true,
exportWithDarkMode: false, // le thème sombre est appliqué en CSS
exportEmbedScene: false,
},
files,
maxWidthOrHeight: THUMB_PX,
exportPadding: 16,
mimeType: "image/png",
});
}
/** Rend puis envoie la miniature ; renvoie false si la scène est vide. */
export async function storeThumb(
path: string,
elements: readonly ExcalidrawElement[],
appState: Partial<AppState>,
files: BinaryFiles,
): Promise<boolean> {
const png = await renderThumb(elements, appState, files);
if (png) await api.writeThumb(path, png);
return png !== null;
}
// --- Génération à la demande (schémas importés, anciens, modifiés ailleurs) ---
export type ThumbResult = "ok" | "empty" | "error";
const MAX_PARALLEL = 2;
const results = new Map<string, ThumbResult>(); // "chemin@date" -> résultat
const pending = new Map<string, Promise<ThumbResult>>();
const queue: (() => void)[] = [];
let running = 0;
const next = () => {
while (running < MAX_PARALLEL && queue.length) {
running++;
queue.shift()!();
}
};
async function generate(path: string): Promise<ThumbResult> {
try {
const { text } = await api.read(path);
const data = JSON.parse(text);
const elements = restoreElements(data.elements ?? [], null);
return (await storeThumb(path, elements, data.appState ?? {}, data.files ?? {})) ? "ok" : "empty";
} catch (e) {
console.warn("miniature", path, e);
return "error";
}
}
/** Résultat déjà connu pour cette version du schéma (évite de régénérer en boucle). */
export const knownThumb = (path: string, version: string) => results.get(`${path}@${version}`);
/** Génère la miniature manquante d'un schéma (file d'attente, 2 en parallèle). */
export function ensureThumb(path: string, version: string): Promise<ThumbResult> {
const key = `${path}@${version}`;
const known = results.get(key);
if (known) return Promise.resolve(known);
let p = pending.get(key);
if (!p) {
p = new Promise<ThumbResult>((resolve) => {
queue.push(() =>
generate(path)
.then((r) => {
results.set(key, r);
resolve(r);
})
.finally(() => {
pending.delete(key);
running--;
next();
}),
);
next();
});
pending.set(key, p);
}
return p;
}