import "./notebooks.css"; import { useState } from "react"; import type { NotebookSummary } from "@shellbook/core"; import type { Api } from "./api"; import { newNotebook } from "./authoring"; import { Dialog, Menu } from "./ui"; type Node = { folders: Map; files: NotebookSummary[] }; function tree(list: NotebookSummary[]): Node { const root: Node = { folders: new Map(), files: [] }; for (const file of list) { let node = root; for (const part of file.path.split("/").slice(0, -1)) { if (!node.folders.has(part)) node.folders.set(part, { folders: new Map(), files: [] }); node = node.folders.get(part)!; } node.files.push(file); } return root; } export function NotebookList({ api, list, path, version, onSelect, onChanged, canLeave, }: { api: Api; list: NotebookSummary[]; path: string; version?: string; onSelect(path: string): void; onChanged(path?: string): Promise; canLeave(): boolean; }) { const [search, setSearch] = useState(""); const [action, setAction] = useState< "new" | "rename" | "duplicate" | "delete" >(); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const choose = (op: "rename" | "duplicate" | "delete") => { setAction(op); setError(""); }; const render = (node: Node) => ( <> {[...node.folders] .sort(([a], [b]) => a.localeCompare(b)) .map(([name, child]) => (
{name} {render(child)}
))} {node.files.map((item) => (
{item.path === path && ( {(close) => (["rename", "duplicate", "delete"] as const).map((op) => ( )) } )}
))} ); const shown = list.filter((n) => `${n.path} ${n.title}`.toLowerCase().includes(search.toLowerCase()), ); return ( <>
setSearch(e.target.value)} />
{action && ( { if (!busy) setAction(undefined); }} >
{ e.preventDefault(); if (busy) return; const data = new FormData(e.currentTarget); if (!canLeave()) return; setBusy(true); setError(""); try { let next: string | undefined; if (action === "new") { const folder = String(data.get("folder")).trim(); let name = String(data.get("name")).trim(); if (!name.endsWith(".md")) name += ".md"; const result = await api.create( (folder ? folder + "/" : "") + name, newNotebook(String(data.get("title"))), ); next = result.path; } else { if (!version) throw new Error("Reload the notebook before changing it"); if (action === "delete") await api.deleteNotebook(path, version); else next = ( await api.move( path, String(data.get("path")).trim(), version, action === "duplicate", ) ).path; } await onChanged(next); setAction(undefined); } catch (err) { setError( `${String(err)}. Refresh the list and retry if the notebook changed.`, ); } finally { setBusy(false); } }} > {action === "delete" ? (

Delete {path}? This cannot be undone.

) : ( action !== "new" && (

From {path}

) )} {action === "new" ? ( <> ) : ( action !== "delete" && ( ) )} {error && (

{error}

)}
)} ); }