// --------------------------------------------------------------------------- // sheet/SheetRail.tsx — the Sheet module's view rail (wave 50 · W50-T17, owner instruction 20). // // ⭐⭐ THE OWNER'S WORDS ARE "THE SHEET RAIL MUST BE EXACTLY THE DATA RAIL", AND PARITY HERE IS // BY CLASSES AND BEHAVIOUR, NOT BY IMPORT. `customer-grid/ViewSidebar.tsx` is not a portable // props component and its own header says why: it reads `localStorage` directly, dispatches on // the shared `apiContract` event bus, pulls six sibling `customer-grid` modules, and mounting // it needs a `SavedView[]`, an `onViewReorder`, an `alertCounts` map and eight more required // callbacks. So this file reproduces the rail's CSS VOCABULARY instead — `cg-views`, // `cg-view-row`, `cg-view-main`, `cg-view-more`, `cg-fold`, `cg-fold-head`, `cg-fold-toggle`, // `cg-data-create`, `cg-create-new`, `cg-find-view`, `cg-segmented-path` — every one of which is // declared at TOP LEVEL and UNSCOPED in `index.css`, so they paint identically here with no // extra rule. Nothing below re-declares a measure, a colour or a font that those rules already // own; `styles/wave50/sheet.css` carries only what the shared vocabulary has no class for. // // ⛔⛔ WAVE-49 R2's SECOND HALF IS THE RULE THAT SHAPED WHAT IS *NOT* HERE: "any control the Data // rail shows that the Sheet cannot honour must be ABSENT, not present-and-inert. A dead button is // a fake affordance." Two of the Data rail's controls are therefore deliberately missing: // // · ROW REORDER (`is-drop-above`, the insertion rule). The Data rail persists an arrangement // through `save_view_order`; the workbook index has no order stratum, so a drag that promised // to reorder would spring back on every reload. The drag that IS honoured is FILING, which // the index does store, so `is-viewdrag` and `is-drop` are here and `is-drop-above` is not. // · THE VIEW-KIND PICKER inside "+ Create new…". R2 gives the Sheet EXACTLY ONE view kind, so // a picker would offer a choice with one item. The create menu offers Workbook and Folder, // which are the two things this rail can actually make. // // ⛔ WAVE-49 R7: ONE RAIL ENTRY IS A WORKBOOK WITH TABS. Tabs live inside a workbook and are NOT // rail rows, so nothing below ever renders a tab. // // ⚠ THE FOLDER INTERACTION IS THE DATA LAYER'S, NOT THE VIEW LAYER'S: walking into a folder // REPLACES the list and the breadcrumb says where you are (`Sheet / `), exactly as // `ViewSidebar`'s `cg-data-path-level` does. That is why no `.cg-view-row` is ever rendered // INSIDE a `.cg-fold` here — `index.css:5946` (`.cg-fold .cg-view-row { margin-left: 12px }`) // indents a NESTED row, and a path-replacing level has no nested rows to indent. // --------------------------------------------------------------------------- import { useEffect, useMemo, useRef, useState } from "react"; import type { DragEvent as ReactDragEvent } from "react"; import "../styles/wave46/rail-select.css"; import "../styles/wave52/parity.css"; // W53-T04 (instr 15). Loaded AFTER wave52's parity patch and at a higher specificity, so the // path row's seating is decided by weight rather than by emission order. See the file's header // for the two measured row heights that make the extra pixel necessary. import "../styles/wave53/sheet-rail.css"; import "../styles/wave59/templates.css"; import "../styles/wave61/rails.css"; import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; import FolderNameDialog, { FOLDER_NAME_MAX } from "../home/FolderNameDialog"; import { FolderMark, MenuLabel } from "../customer-grid/icons"; import { SHARE_SHAPE, SHEET_SHAPE } from "../customer-grid/iconShapes"; import { StarIcon } from "../ui/icons"; import { openExistingItem, useItemDeletions, useStarred } from "../starred/starredApi"; import { ConfirmDialog } from "../ui/ConfirmDialog"; import { useRailSelection } from "../ui/useRailSelection"; import { NAV_MINIMIZE_EVENT, signal } from "../apiContract"; import { NAV_PANEL_EVENT, RailHeaderIcons, useNarrowRailFold, useRailHeaderSlot } from "../shell/railHeader"; import type { NavPanelDetail } from "../shell/railHeader"; import PanelToggleIcon from "../shell/PanelToggleIcon"; import ImportDialog from "./ImportDialog"; import TemplateGallery from "./templates/TemplateGallery"; import { ROOT_FOLDER_ID } from "./types"; import type { SheetFolder, WorkbookRow } from "./types"; /** The three strata the rail owns. Sent wholesale, because a placement needs its folder. */ export interface RailStrata { folders: SheetFolder[]; itemFolders: Record; starred: string[]; } export interface SheetRailProps { /** C3: each embedded page supplies its own storage and event namespace. */ storagePrefix?: string; /** * W53-T09: a monotonic counter the page bumps when the RIBBON's Import button is pressed. Any * change opens the import dialog this rail already owns. Optional, so every existing mount and * every test that renders this rail without the page compiles unchanged. */ importRequest?: number; loading: boolean; /** Has GET /sheets/index answered? A strata write before it has is a wholesale PUT of an * empty folder tree over the stored one. Optional and defaults to true for existing callers. */ indexKnown?: boolean; rows: readonly WorkbookRow[]; /** * W51-T10 (contract C5) — the workbooks OTHER people have shared with this account. * * ⛔ OPTIONAL, AND ABSENT IS THE ORDINARY CASE TODAY. `GET /sheets/index` grows this list in * W51-T25; until it does the server sends nothing, and a section with a heading and no rows * would tell a person that sharing exists and has given them nothing. So the whole section is * rendered only when the list has something in it. */ sharedWithMe?: readonly WorkbookRow[]; folders: readonly SheetFolder[]; itemFolders: Record; starred: readonly string[]; activeId: string; revealFolder?: string; onOpen: (id: string) => void; onCreateWorkbook: () => void; onRenameWorkbook: (id: string, name: string) => void; onDuplicateWorkbook: (id: string) => void; onDeleteWorkbook: (id: string) => void; /** Folder and placement changes preserve the legacy index star stratum through this door. */ onStrataChange: (next: RailStrata) => void; /** * W51-T09 (owner instruction 2, ruling R12) — whether the page's assistant dock is open, and * the one door that flips it. * * ⛔ THE PAGE OWNS THE STATE, NOT THIS RAIL, exactly as `CustomerGrid` owns it for the Data * rail. The launcher and the panel are two halves of one thing; a rail holding its own copy * would let the button say "close" over a dock that was never open. */ chatOpen: boolean; onToggleChat: () => void; } /** * ⭐⭐ THE FOLD KEY IS THE DATA RAIL'S OWN, AND THAT IS THE TICKET RATHER THAN A COINCIDENCE. * `ViewSidebar.tsx:1463` reads and writes this same string, the name is after neither module, and * that file's own comment says the two rails "are one idea (a navigation bar folds)". The * done-when asks for "the same shut state Data uses", so ONE stored state serves both rails and a * person who folds the navigation in Data finds it folded here. */ const RAIL_FOLD_KEY = "aios-views-rail"; /** W63-T07: reopening after a cell-driven fold holds only for this browser session. */ const SHEET_WORKBOOK_RAIL_HOLD_KEY = "aios-sheet-workbook-rail-held-open"; function readWorkbookRailHold(prefix = ""): boolean { try { return sessionStorage.getItem(prefix + SHEET_WORKBOOK_RAIL_HOLD_KEY) === "1"; } catch { return false; } } function writeWorkbookRailHold(prefix = ""): void { try { sessionStorage.setItem(prefix + SHEET_WORKBOOK_RAIL_HOLD_KEY, "1"); } catch { /* in-memory state remains */ } } /** W56-T05: one last folder id, separate from the rail-fold and workbook stores. */ const LAST_FOLDER_KEY = "aios-sheet-last-folder"; function readLastFolder(prefix = ""): string | null { try { return localStorage.getItem(prefix + LAST_FOLDER_KEY) || null; } catch { return null; } } function writeLastFolder(folderId: string | null, prefix = ""): void { try { if (folderId) localStorage.setItem(prefix + LAST_FOLDER_KEY, folderId); else localStorage.removeItem(prefix + LAST_FOLDER_KEY); } catch { /* session only */ } } /** How many rows the rail draws while it is loading. Matches `Shell.tsx::RAIL_SKELETON_ROWS`. */ const SKELETON_ROWS = 6; const STAR_PATH = "M8 2.9l1.63 3.3 3.64.53-2.63 2.57.62 3.63L8 11.24 4.74 12.93l.62-3.63L2.73 6.73l3.64-.53z"; /** * The rail's loading state (DESIGN.md 5: skeletons over spinners for a RAIL). * * ⛔ THE CLASSES ARE `shell/navExtras.css`'s AND THEY ARE USED BY NAME, NOT BY IMPORT. That sheet * is imported by `shell/NavExtras.tsx`, which `shell/Shell.tsx` imports statically, which * `App.tsx` renders unconditionally, so the rules are in the bundle whenever the app is. Adding * a second import here would put the same rules in a second chunk, and editing `shell/**` is * outside this ticket's fence anyway. The skeleton is `aria-hidden` per row with ONE `role= * "status"` on the container, so a screen reader hears "loading" once rather than six times. */ function RailSkeleton() { return (
{Array.from({ length: SKELETON_ROWS }, (_, i) => ( ))}
); } /** * The mark one workbook row wears: a page ruled into cells. 16x16, painted by * `.sheet-view-icon` (wave49/sheet.css), which sets the fill, the stroke and the muted tone on the * element itself, so the paths carry no attributes of their own. * * ⭐ W51-T10 — THE GEOMETRY IS `SHEET_SHAPE`'s NOW, not a third hand-drawn sheet. The rail's row * mark, the create menu's Workbook mark and the shell's nav mark were three drawings of one idea * with three sets of coordinates; two of them now read the same constant and the third is the one * it was traced from. */ function SheetViewIcon() { return ( ); } /** * ⛔⛔ THESE TWO ARE LOCAL BECAUSE THE COMPONENTS THEY MIRROR CANNOT BE IMPORTED, AND THAT IS A * FENCE RATHER THAN A PREFERENCE. `ViewSidebar.tsx::ShareMark` and `Shell.tsx::SheetIcon` are both * private to files this lane may not edit this wave, so exporting either one is off the table. * What travels instead is the GEOMETRY: `SHARE_SHAPE` and `SHEET_SHAPE` in `iconShapes.ts`, the * vocabulary's own home, drawn here at the menu's stroke conventions. This is exactly the * precedent `ViewSidebar::ShareMark` set for the same shape, and it keeps the icon LANGUAGE single * while touching no other lane's file. * * ⚠ NOT PAINTED BY A CLASS. A menu row's mark takes its colour from `.cg-view-menu button:hover * .cg-mi-ic` and from `.is-danger`; an svg carrying its own `color` rule would out-rank that * inheritance and the row's hover state would leave one glyph behind. */ function ShareMark({ size = 16 }: { size?: number }) { return ( ); } function SheetMark({ size = 16 }: { size?: number }) { return ( ); } function StarMark() { return ( ); } function FindIcon() { return ( ); } function PathArrow({ back }: { back: boolean }) { return ( ); } type Menu = | { kind: "workbook"; id: string; anchor: HTMLElement } | { kind: "folder"; id: string; anchor: HTMLElement }; type Dragged = | { kind: "workbook"; id: string; ids?: readonly string[] } | { kind: "folder"; id: string }; // The index projects the server's role onto each row. Filing and deletion belong to owners. const mayManageWorkbook = (row: WorkbookRow | undefined) => !!row && "role" in row && row.role === "owner"; const newFolderId = () => "f" + Date.now().toString(36) + Math.floor(Math.random() * 46656).toString(36); /** * ⚠ A NAME IS COLLAPSED, NOT MERELY TRIMMED. `core/sheets.py` collapses runs of whitespace on * the way in, so a client that only trimmed would show one name and store another. */ const cleanName = (raw: string) => raw.trim().replace(/\s+/g, " ").slice(0, FOLDER_NAME_MAX); export default function SheetRail({ storagePrefix = "", importRequest, loading, indexKnown = true, rows: suppliedRows, sharedWithMe: suppliedSharedWithMe = [], folders, itemFolders, starred, activeId, revealFolder, onOpen: requestOpen, onCreateWorkbook, onRenameWorkbook, onDuplicateWorkbook, onDeleteWorkbook, onStrataChange, chatOpen, onToggleChat, }: SheetRailProps) { const embedded = storagePrefix.startsWith("embed:"); const minimizeEvent = embedded ? `${NAV_MINIMIZE_EVENT}:${storagePrefix}` : NAV_MINIMIZE_EVENT; const panelEvent = embedded ? `${NAV_PANEL_EVENT}:${storagePrefix}` : NAV_PANEL_EVENT; const { isDeleted } = useItemDeletions(); const rows = suppliedRows.filter((row) => !isDeleted({ kind: "workbook", id: row.id })); const sharedWithMe = suppliedSharedWithMe.filter((row) => !isDeleted({ kind: "workbook", id: row.id })); const onOpen = (id: string) => { requestOpen(id); // The embedded page fetches the workbook and renders refusals without the helper's hash reads. if (!embedded) void openExistingItem({ kind: "workbook", id }, () => {}); }; const indexPendingReason = indexKnown ? undefined : "Folders are still loading."; // Menu and picker rules override native disabled styling, so the wait must stay visible. const indexPendingStyle = indexKnown ? undefined : { opacity: 0.45, cursor: "not-allowed" }; const { load: starLoad, starred: userStarred, busy: starBusy, toggle } = useStarred(); /** * W51-T09 — IS THE RAIL FOLDED. Read from storage on the first render only, exactly as * `ViewSidebar.tsx:1463` does, so the fold survives a reload and a walk between the two modules. * * ⛔ THE `try` IS NOT DECORATION. `localStorage` THROWS on a browser with storage blocked, and an * unguarded read here would take the whole rail down with it. Blocked storage must still fold * for the session, which is what a `false` start plus an ignored write gives. */ const [railShut, setRailShut] = useState(() => { try { return localStorage.getItem(storagePrefix + RAIL_FOLD_KEY) === "1"; } catch { return false; } }); const narrow = useNarrowRailFold(); const [narrowOpen, setNarrowOpen] = useState(false); useEffect(() => { if (!narrow) setNarrowOpen(false); }, [narrow]); const folded = narrow ? !narrowOpen : railShut; const [railEl, setRailEl] = useState(null); const sharedHeaderSlot = useRailHeaderSlot("sheet", railEl); const headerSlot = embedded ? null : sharedHeaderSlot; const [railHeldOpen, setRailHeldOpen] = useState(() => readWorkbookRailHold(storagePrefix)); const [railAutoFolded, setRailAutoFolded] = useState(false); const railShutRef = useRef(railShut); const narrowOpenRef = useRef(narrowOpen); railShutRef.current = railShut; narrowOpenRef.current = narrowOpen; const panelSavedRef = useRef<{ railShut: boolean; narrowOpen: boolean } | null>(null); const toggleRail = () => { panelSavedRef.current = null; setRailShut((v) => { const next = !v; if (v) { setRailHeldOpen(true); writeWorkbookRailHold(storagePrefix); } try { localStorage.setItem(storagePrefix + RAIL_FOLD_KEY, next ? "1" : "0"); } catch { /* session only */ } return next; }); }; useEffect(() => { if (railHeldOpen || railAutoFolded) return; const onCellKey = (event: KeyboardEvent) => { if (event.repeat || (event.key !== "Enter" && event.key !== "F2")) return; const target = event.target as Element | null; // Glide focuses this scroller for cell-key handling. Formula inputs, ribbon controls, // dialogs, headers and both rails are outside this descendant selector. if (!target?.closest(".sheet-grid-canvas .dvn-scroller")) return; // An embedded cell belongs only to the rail in its own page. const page = target.closest(".sheet-page"); if (embedded ? page !== railEl?.closest(".sheet-page") : page?.getAttribute("data-embedded") === "true") return; signal(minimizeEvent); }; const onNavMinimize = () => { // Automatic collapse is deliberately not persisted: a fresh Sheet/session starts eligible. setRailShut(true); setRailAutoFolded(true); }; document.addEventListener("keydown", onCellKey); window.addEventListener(minimizeEvent, onNavMinimize); return () => { document.removeEventListener("keydown", onCellKey); window.removeEventListener(minimizeEvent, onNavMinimize); }; }, [embedded, minimizeEvent, railEl, railHeldOpen, railAutoFolded]); // R21 (SDLC 68): Edit and View data always fold; closing restores how the user had the rail. // A manual toggle clears the saved state so the user's newest choice wins. useEffect(() => { const onNavPanel = (event: Event) => { const { open } = (event as CustomEvent).detail; if (open) { if (panelSavedRef.current === null) { panelSavedRef.current = { railShut: railShutRef.current, narrowOpen: narrowOpenRef.current, }; } setRailShut(true); setNarrowOpen(false); } else if (panelSavedRef.current) { const saved = panelSavedRef.current; setRailShut(saved.railShut); setNarrowOpen(saved.narrowOpen); panelSavedRef.current = null; } }; window.addEventListener(panelEvent, onNavPanel); return () => window.removeEventListener(panelEvent, onNavPanel); }, [panelEvent]); /** The folder whose contents are on screen, or null for the top level. */ const openedFolder = (): string | null => { const folder = revealFolder ?? itemFolders[activeId] ?? (activeId ? null : readLastFolder(storagePrefix)); return folder === ROOT_FOLDER_ID ? null : folder; }; const [at, setAt] = useState(() => openedFolder()); const lastReveal = useRef<{ activeId: string; revealFolder?: string } | null>(null); /** Restored folders start after root, so Back reaches root and Forward returns here. */ const [history, setHistory] = useState<(string | null)[]>( () => at === null ? [null] : [null, at], ); const [step, setStep] = useState(() => at === null ? 0 : 1); const [query, setQuery] = useState(""); const [menu, setMenu] = useState(null); const [renaming, setRenaming] = useState(""); const [createAt, setCreateAt] = useState(null); const [namingFolder, setNamingFolder] = useState(false); const [folderName, setFolderName] = useState(""); const [dragged, setDragged] = useState(null); const [dropOn, setDropOn] = useState(null); /** * W51-T10 / R13 — "Move to folder", the picker the menu item opens. * * ⛔ THE MENU CLOSES AND A SECOND OVERLAY OPENS ON THE SAME ANCHOR. That is the Data rail's own * shape (`ViewSidebar.tsx`'s `moveFor`), and it is the shape because a picker nested INSIDE the * menu overlay would be an outside click as far as the menu's own dismiss handler is concerned: * choosing a folder would close the thing being clicked. One overlay at a time, anchored to the * `…` button both times, so the picker opens where the menu was. */ const [moveFor, setMoveFor] = useState<{ id: string; anchor: HTMLElement; ids?: readonly string[]; } | null>(null); const [railLeftInPlace, setRailLeftInPlace] = useState([]); /** * W51-T10 / R6 — the pending destructive act, or null. ONE ConfirmDialog for the workbook and * the folder both, because R6 is about there being one shape for the promise, not one per noun. */ const [confirmDelete, setConfirmDelete] = useState< | { kind: "workbook" | "folder"; id: string; name: string } | { kind: "workbooks"; ids: readonly string[]; name: string } | null >(null); /** * W51-T13 (owner instruction 7, contract C4) — is the import dialog on screen. * * ⛔ THE DIALOG IS MOUNTED CONDITIONALLY, AND THAT IS THE RESET. It holds the chosen file, the * poll's run token, the job and its report; a component kept mounted behind an `open={false}` * would hand the next import the previous one's progress bar, and the previous poll would still * be ticking behind it. Unmounting is one of the poll's five terminal conditions. */ const [importing, setImporting] = useState(false); // Keep the server's summary after the import dialog unmounts to open the workbook. const [importSummary, setImportSummary] = useState(""); const [pickingTemplate, setPickingTemplate] = useState(false); /** * ⭐⭐ W53-T09 (owner instruction 20) — THE RIBBON'S IMPORT BUTTON IS THE SECOND DOOR ONTO THIS * SAME DIALOG, AND UNTIL NOW IT OPENED NOTHING. The owner reported "the import button doesn't do * anything" and the ribbon looked correctly wired, which is why it survived a code read: the * chain `Ribbon.tsx case "import"` -> `onOpenImport?.()` -> `SheetGrid.tsx` -> `SheetPage.tsx` * is intact end to end, and the LAST link was a function whose entire body was `return;`, * carrying the comment *"W51-T13 mounts the import dialog on this handler. Deliberately inert * until then."* W51-T13 never landed, so a deliberate placeholder shipped as a dead button. * ⛔ THE DIALOG IS NOT MOVED, and that is the point: one dialog, two doors. `importing` above * stays this rail's own state because the rail's "Import .xlsx" menu item is the other door, * and the counter below only ever REQUESTS an open, so the two cannot fight over who owns it. * ⚠ A COUNTER, NOT A BOOLEAN. A boolean prop would latch: the page would have to be told when * the dialog closed in order to reset it, which is exactly the two-way coupling this shape * avoids. Every increment is one fresh request to open. */ useEffect(() => { if (importRequest) { setImportSummary(""); setImporting(true); } }, [importRequest]); const byId = useMemo(() => { const map: Record = {}; folders.forEach((f) => { map[f.id] = f; }); return map; }, [folders]); /** A folder deleted here or belonging to another tenant silently restores the top level. */ useEffect(() => { if (loading || !indexKnown || at === null || byId[at]) return; setAt(null); setHistory([null]); setStep(0); writeLastFolder(null, storagePrefix); }, [at, byId, loading, indexKnown]); // Wait for placement metadata, then reveal each address choice once. Rail browsing stays put. useEffect(() => { if (loading || !indexKnown) return; if (lastReveal.current?.activeId === activeId && lastReveal.current?.revealFolder === revealFolder) return; lastReveal.current = { activeId, revealFolder }; const folder = openedFolder(); const next = folder && byId[folder] ? folder : null; setAt(next); setHistory(next === null ? [null] : [null, next]); setStep(next === null ? 0 : 1); setQuery(""); writeLastFolder(next, storagePrefix); }, [activeId, revealFolder, itemFolders, byId, loading, indexKnown]); const strata = (): RailStrata => ({ folders: folders.map((f) => ({ ...f })), itemFolders: { ...itemFolders }, starred: [...starred], }); /** Where a workbook is filed. An absent placement and the root sentinel mean the same thing. */ const placedIn = (id: string): string | null => { const fid = itemFolders[id]; return !fid || fid === ROOT_FOLDER_ID ? null : fid; }; const goTo = (next: string | null) => { writeLastFolder(next, storagePrefix); setAt(next); setQuery(""); setHistory((prev) => [...prev.slice(0, step + 1), next]); setStep((prev) => prev + 1); }; const walk = (delta: number) => { const target = step + delta; if (target < 0 || target >= history.length) return; writeLastFolder(history[target], storagePrefix); setStep(target); setAt(history[target]); setQuery(""); }; // ⚠ THE CRUMBS ARE WALKED FROM THE CURRENT FOLDER UPWARD AND THEN REVERSED, with a visited set // guarding the walk. The server refuses a cycle, so one should be unreachable; a rail that // hangs the browser rather than painting is not a defect worth risking on "should". const crumbs = useMemo(() => { const chain: SheetFolder[] = []; const seen = new Set(); let cursor = at; while (cursor && byId[cursor] && !seen.has(cursor)) { seen.add(cursor); chain.push(byId[cursor]); cursor = byId[cursor].parent ?? null; } chain.reverse(); return [{ key: "__sheet__", label: "Sheet", target: null as string | null }, ...chain.map((f) => ({ key: f.id, label: f.name, target: f.id as string | null }))]; }, [at, byId]); const needle = query.trim().toLowerCase(); const matches = (label: string) => !needle || label.toLowerCase().includes(needle); const levelFolders = folders.filter((f) => (f.parent ?? null) === at && matches(f.name)); const levelRows = rows.filter((r) => placedIn(r.id) === at && matches(r.name)); const levelRowIds = levelRows.map((row) => row.id); const { selected: railSelected, anchorId: railAnchorId, onRowClick: selectRailRow, clear: clearRailSelection, isSelected: isRailSelected, } = useRailSelection(levelRowIds); const workbookById = new Map(rows.map((row) => [row.id, row])); const blockedWorkbooks = (ids: readonly string[]) => ids.flatMap((id) => { const row = workbookById.get(id); return row && !mayManageWorkbook(row) ? [row.name] : []; }); const railManageable = railSelected.filter((id) => mayManageWorkbook(workbookById.get(id))); const railBlocked = blockedWorkbooks(railSelected); const railNotice = railLeftInPlace.length > 0 ? `Left in place: ${railLeftInPlace.join(", ")}.` : railBlocked.length > 0 ? `Will stay in place: ${railBlocked.join(", ")}.` : ""; useEffect(() => { if (railSelected.length === 0 && railAnchorId === null && railLeftInPlace.length === 0) return; const onKey = (event: KeyboardEvent) => { if (event.key !== "Escape" || event.defaultPrevented) return; if (menu || createAt || moveFor || confirmDelete || renaming) return; const target = event.target as HTMLElement | null; if (target?.tagName === "INPUT" || target?.tagName === "TEXTAREA" || target?.isContentEditable) return; clearRailSelection(); setRailLeftInPlace([]); }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }, [railSelected.length, railAnchorId, railLeftInPlace.length, menu, createAt, moveFor, confirmDelete, renaming, clearRailSelection]); /** The shared list obeys the find box like every other row, so one search covers the rail. */ const sharedRows = sharedWithMe.filter((r) => matches(r.name)); const isStarred = (id: string) => starLoad.phase === "ready" && userStarred.sheets.includes(id); const moveWorkbooks = (ids: readonly string[], target: string | null) => { if (!indexKnown) return; // The index PUT replaces all strata, so every placement must share this one snapshot. const next = strata(); let moved = false; for (const id of ids) { if (!mayManageWorkbook(workbookById.get(id))) continue; next.itemFolders[id] = target ?? ROOT_FOLDER_ID; moved = true; } if (moved) onStrataChange(next); clearRailSelection(); setRailLeftInPlace(blockedWorkbooks(ids)); }; const fileInto = (drag: Dragged, target: string | null) => { if (!indexKnown) return; if (drag.kind === "workbook") { moveWorkbooks(drag.ids ?? [drag.id], target); return; } if (drag.id === target) return; const next = strata(); next.folders = next.folders.map((f) => (f.id === drag.id ? { ...f, parent: target } : f)); // ⛔ SENT EVEN WHEN IT MAKES A CYCLE. The wall is `core/sheets.py::validate_folder_tree`, and // a client-side pre-check would either duplicate it (two rules, one drifting) or hide the // refusal sentence the owner is supposed to read. The rail asks; the server answers by name. onStrataChange(next); }; /** * ⛔⛔ EVERY LEG STOPS PROPAGATION, AND `onDragOver` IS THE ONE THAT MATTERS. A folder row sits * INSIDE the level container and both are drop targets, so React bubbles the same dragover from * the row to the box around it: the row sets `dropOn` to its own id and the container overwrites * it a microsecond later with the level's. The drop still LANDED in the right folder, because * `onDrop` already stopped there, so the bug was invisible to every functional check and showed * only as the wrong thing lighting up: drag a workbook onto "Plans" and the whole list glows * while "Plans" stays flat. A drop mark on the wrong target is worse than none, because it says * the drop is going somewhere it is not. */ const dropProps = (target: string | null, key: string) => ({ onDragOver: (event: ReactDragEvent) => { if (!indexKnown) { event.stopPropagation(); event.dataTransfer.dropEffect = "none"; setDropOn(null); return; } if (!dragged) return; if (dragged.kind === "folder" && dragged.id === target) return; event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = "move"; setDropOn(key); }, onDragLeave: (event: ReactDragEvent) => { event.stopPropagation(); setDropOn((prev) => (prev === key ? null : prev)); }, onDrop: (event: ReactDragEvent) => { event.preventDefault(); event.stopPropagation(); setDropOn(null); if (!indexKnown) { setDragged(null); return; } if (dragged) fileInto(dragged, target); setDragged(null); }, }); const closeMenu = () => { setMenu(null); setRenaming(""); }; const renameFolder = (id: string, name: string) => { if (!indexKnown) return; const clean = cleanName(name); if (!clean) return; const next = strata(); next.folders = next.folders.map((f) => (f.id === id ? { ...f, name: clean } : f)); onStrataChange(next); }; const deleteFolder = (id: string) => { if (!indexKnown) return; // ⚠ THE CHILDREN ARE LEFT DANGLING ON PURPOSE, and the server REPAIRS them to the top level // and says so. Reparenting them here would be a second implementation of the rule that // `validate_folder_tree` already owns, and the two would drift. const next = strata(); next.folders = next.folders.filter((f) => f.id !== id); onStrataChange(next); if (at === id) goTo(null); }; const toggleStar = (id: string) => { if (starLoad.phase !== "ready" || starBusy) return; toggle("sheet", id, !isStarred(id)); }; /** * W51-T10 / R13 — file one workbook into a folder, or back to the top level. * * ⚠ THE SAME DOOR THE DRAG USES, and deliberately so: `fileInto` already knows that an absent * placement and the root sentinel mean the same thing, and that the PUT carries all three strata * because a placement is only legal while its folder exists (D-639). A second write path here * would be a second chance to send half an index. */ const moveWorkbook = (id: string, target: string | null) => { if (!indexKnown) return; fileInto({ kind: "workbook", id, ids: moveFor?.ids }, target); setMoveFor(null); }; /** * W51-T10 / R16 — Share. The dispatch is the one channel the other three share controls use, * spelled here as the literal exactly as `ColumnMenu.tsx`, `MapView.tsx` and `ViewSidebar.tsx` * spell it: the emitter and the dialog live in trees that must not import each other. * * ⛔ IT ONLY OPENS ANYTHING BECAUSE `"workbook"` IS IN `SHARE_KINDS`. `parseShareRequest` * fail-closes on a kind that tuple does not carry and returns null, so before this ticket a * workbook dispatch was DROPPED IN SILENCE: no dialog, no error, nothing in the console. */ const shareWorkbook = (id: string, name: string) => { window.dispatchEvent( new CustomEvent("aios:share-open", { detail: { kind: "workbook", id, label: name } }), ); }; const nameOfWorkbook = (id: string) => rows.find((r) => r.id === id)?.name ?? ""; const runDelete = () => { const pending = confirmDelete; setConfirmDelete(null); if (!pending) return; if (pending.kind === "folder") deleteFolder(pending.id); else { const ids = pending.kind === "workbooks" ? pending.ids : [pending.id]; for (const id of ids) { if (mayManageWorkbook(workbookById.get(id))) onDeleteWorkbook(id); } clearRailSelection(); setRailLeftInPlace(blockedWorkbooks(ids)); } }; const createFolder = (name: string) => { if (!indexKnown) return; const clean = cleanName(name); if (!clean) return; const next = strata(); next.folders = [...next.folders, { id: newFolderId(), name: clean, parent: at }]; onStrataChange(next); setNamingFolder(false); setCreateAt(null); }; return ( ); }