import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Check, Plus, Search, X } from "lucide-react"; import { api } from "../lib/api"; import { NODE_CATALOG, synthesizePluginSpec, type NodeKind, type NodeSpec, type PluginNodeSpec, } from "../lib/nodeCatalog"; import { useApp } from "../lib/store"; import { bumpPluginsRev, getUserId } from "../lib/userId"; import { useDismissOn } from "../lib/useDismissOn"; /** * "+ Add block" — THE block chooser (marker: block-chooser). * * The palette's PERMANENT chrome cost is exactly the one trigger * button this component renders in canvas-toolbar row 1; the whole * catalog — search, five stage sections, plugin management — lives in * a popover that exists only while open. That is the design principle * that killed the pipeline shelf (an always-visible ~300px strip that * grew with the catalog at the canvas's expense): chrome cost stays * constant, growth lands in on-demand surfaces. * * The popover still TEACHES the grammar the shelf used to spell out: * five stage sections in pipeline order — Source → Backend → * Algorithm → Metric → Sink, each a 10px uppercase header plus the * shelf's one-line tagline — the same canonical chain auto-connect * enforces. Plugins appear inside their declared family's section. * * Interactions: * - click a row → queue the kind through the pendingBlockKinds * store bridge (FlowCanvas creates the node + auto-connects). * The popover STAYS OPEN so multiple blocks can be added by * clicking; the clicked row flashes "added ✓". * - drag a row onto the canvas — identical "application/reactflow" * dataTransfer payload as the old shelf tiles, so FlowCanvas's * onDrop and splice-on-edge targeting work unchanged. The popover * closes on dragstart (deferred one tick: synchronously removing * the drag source cancels the HTML5 drag in Chromium). * - search filters rows live across all sections. * - tap-to-add IS the touch path (the shelf's PointerEvent * touch-drag bridge died with the shelf). * - rows disable while a run is in progress — same authoring lock * as the preset picker and param editors. */ const STAGE_META: { key: NodeSpec["family"]; label: string; tagline: string; }[] = [ { key: "source", label: "Source", tagline: "where the circuit comes from" }, { key: "backend", label: "Backend", tagline: "the noisy machine" }, { key: "algorithm", label: "Algorithm", tagline: "transforms the circuit" }, { key: "metric", label: "Metric", tagline: "measures the result" }, { key: "sink", label: "Sink", tagline: "collects the evidence" }, ]; export function BlockPicker() { const [open, setOpen] = useState(false); const [search, setSearch] = useState(""); const rootRef = useRef(null); const searchRef = useRef(null); const addBlocksToCanvas = useApp((s) => s.addBlocksToCanvas); const running = useApp((s) => s.running); useDismissOn(open, rootRef, useCallback(() => setOpen(false), [])); // Fresh search + focus it on every open. useEffect(() => { if (open) { setSearch(""); searchRef.current?.focus(); } }, [open]); // Kinds currently on the canvas — a MULTISET (one entry per node) // published by FlowCanvas through the store bridge — drives the // per-row "n on canvas" count dot. const canvasKindsArr = useApp((s) => s.canvasKinds); const canvasCounts = useMemo(() => { const m = new Map(); for (const k of canvasKindsArr) m.set(k, (m.get(k) ?? 0) + 1); return m; }, [canvasKindsArr]); // "added ✓" flash on the row just clicked. A single kind + timer is // enough: rapid multi-adds move the flash to the latest row, which // reads correctly. const [flashKind, setFlashKind] = useState(null); const flashTimer = useRef(null); useEffect( () => () => { if (flashTimer.current != null) window.clearTimeout(flashTimer.current); }, [], ); const addOne = (kind: NodeKind) => { addBlocksToCanvas([kind]); setFlashKind(kind); if (flashTimer.current != null) window.clearTimeout(flashTimer.current); flashTimer.current = window.setTimeout(() => setFlashKind(null), 900); }; // Deferred close on row dragstart — see the component doc comment. const closeForDrag = () => { window.setTimeout(() => setOpen(false), 0); }; // Merge built-ins with this browser's uploaded plugin manifests so // plugins list under their declared family alongside the built-ins. const plugins = useApp((s) => s.plugins); const setPlugins = useApp((s) => s.setPlugins); const combined: (NodeSpec | PluginNodeSpec)[] = useMemo( () => [...NODE_CATALOG, ...plugins.map(synthesizePluginSpec)], [plugins], ); const filtered = useMemo(() => { if (!search.trim()) return combined; const q = search.toLowerCase(); return combined.filter( (n) => n.label.toLowerCase().includes(q) || n.tagline.toLowerCase().includes(q) || n.family.toLowerCase().includes(q) || n.kind.toLowerCase().includes(q), ); }, [search, combined]); const handleDeletePlugin = async (kind: string) => { try { await api.deletePlugin(getUserId(), kind); const fresh = await api.listPlugins(getUserId()); setPlugins(fresh); bumpPluginsRev(); } catch (err) { // Destructive actions failing silently look like the click // didn't register — surface via the global toast channel // (danger = sticky). window.confirm stays as the guard BEFORE // the delete. const msg = err instanceof Error ? err.message : String(err); useApp.getState().setGlobalNotice({ text: `Could not delete plugin "${kind}": ${msg}`, tone: "danger", }); } }; return (
{open && (
's overflow-x-hidden — // pin it under the toolbar instead. ≥sm: anchored under the // trigger, the normal popover idiom. className="fixed left-3 top-24 sm:absolute sm:left-0 sm:top-full sm:mt-1 z-30 w-[min(480px,calc(100vw-1.5rem))] sm:w-[min(480px,90vw)] max-h-[min(380px,70vh)] rounded-lg border border-edge bg-surface shadow-xl flex flex-col" > {/* Search — filters rows live across all five sections */}
setSearch(e.target.value)} placeholder="Search blocks..." className="w-full text-[11px] bg-surfaceAlt border border-edge rounded-md pl-6 pr-6 py-1.5 text-ink placeholder:text-mute/60 focus:outline-none focus:border-accent/60" /> {search && ( )}
{/* Five stage sections in pipeline order */}
{STAGE_META.map((st) => { const items = filtered.filter((n) => n.family === st.key); if (items.length === 0) return null; return (
{st.label}
{st.tagline}
{items.map((n) => ( handleDeletePlugin(n.kind) : undefined } /> ))}
); })} {filtered.length === 0 && (
No blocks match "{search.trim()}"
)}
{/* One-line affordance hint */}
Click to add (stays open for more) · or drag a row onto the canvas
)}
); } /** One compact catalog row: icon, name, plugin badge, on-canvas count * dot; the full description rides the title tooltip. Click adds via * the store bridge; HTML5 drag carries the same payload the shelf * tiles did. */ function ChooserRow({ spec, canvasCount, flashed, running, onAdd, onDragToCanvas, onDelete, }: { spec: NodeSpec | PluginNodeSpec; /** Copies of this kind already on the canvas (0 = none). */ canvasCount: number; /** True for ~1s after this row was clicked — renders "added ✓". */ flashed: boolean; running: boolean; onAdd: (kind: NodeKind) => void; onDragToCanvas: () => void; /** Set for user-uploaded plugins — renders the small delete ×. */ onDelete?: () => void; }) { const isPlugin = "isPlugin" in spec && spec.isPlugin; const Icon = spec.icon; return ( )} ); }