Download web/src/sheet/SheetRail.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 64.4 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/sheet/SheetRail.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/sheet/SheetRail.tsx
-
curl -L -o SheetRail.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/sheet/SheetRail.tsx
64.4 kB
// ---------------------------------------------------------------------------
// 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 / <folder>`), 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<string, string>;
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<string, string>;
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 (
<div className="shell-rail-skeleton" role="status" aria-label="Loading workbooks">
{Array.from({ length: SKELETON_ROWS }, (_, i) => (
<div className="shell-rail-skeleton-row" key={i} aria-hidden="true">
<span className="shell-rail-skeleton-mark" />
<span className="shell-rail-skeleton-bar" />
</div>
))}
</div>
);
}
/**
* 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 (
<svg className="sheet-view-icon" viewBox="0 0 16 16" aria-hidden="true">
{SHEET_SHAPE.map((s) => (
<path key={s.d} d={s.d} />
))}
</svg>
);
}
/**
* ββ 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 (
<svg width={size} height={size} viewBox="0 0 16 16" aria-hidden="true">
{SHARE_SHAPE.map((s) => (
<path
key={s.d}
d={s.d}
fill={s.fill ? "currentColor" : "none"}
stroke={s.fill ? "none" : "currentColor"}
strokeWidth={1.35}
strokeLinecap="round"
strokeLinejoin="round"
/>
))}
</svg>
);
}
function SheetMark({ size = 16 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 16 16" aria-hidden="true">
{SHEET_SHAPE.map((s) => (
<path
key={s.d}
d={s.d}
fill="none"
stroke="currentColor"
strokeWidth={1.35}
strokeLinecap="round"
strokeLinejoin="round"
/>
))}
</svg>
);
}
function StarMark() {
return (
<svg className="sheet-view-star" viewBox="0 0 16 16" aria-hidden="true">
<path d={STAR_PATH} />
</svg>
);
}
function FindIcon() {
return (
<svg className="cg-find-view-icon" width="14" height="14" viewBox="0 0 16 16" fill="none"
aria-hidden="true">
<circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
<path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" />
</svg>
);
}
function PathArrow({ back }: { back: boolean }) {
return (
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path
d={back ? "M9.8 3.6 5.4 8l4.4 4.4" : "M6.2 3.6 10.6 8l-4.4 4.4"}
stroke="currentColor"
strokeWidth="1.35"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}
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<boolean>(() => {
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<HTMLElement | null>(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<NavPanelDetail>).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<string | null>(() => 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<Menu | null>(null);
const [renaming, setRenaming] = useState("");
const [createAt, setCreateAt] = useState<HTMLElement | null>(null);
const [namingFolder, setNamingFolder] = useState(false);
const [folderName, setFolderName] = useState("");
const [dragged, setDragged] = useState<Dragged | null>(null);
const [dropOn, setDropOn] = useState<string | null>(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<string[]>([]);
/**
* 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<string, SheetFolder> = {};
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<string>();
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 (
<nav
ref={setRailEl}
className={"cg-views" + (folded ? " is-collapsed" : "") + (folded && headerSlot ? " is-header-folded" : "") + (narrow && narrowOpen ? " is-narrow-open" : "")}
aria-label="Sheet workbooks"
>
<div className="cg-views-top">
{/* The first child stays visible when folded. C4 gives the expanded rail one header row. */}
{!folded && (
<>
<button
type="button"
className="cg-path-history-button"
aria-label="Back"
title="Back"
disabled={step <= 0}
onClick={() => walk(-1)}
>
<PathArrow back />
</button>
<button
type="button"
className="cg-path-history-button"
aria-label="Forward"
title="Forward"
disabled={step >= history.length - 1}
onClick={() => walk(1)}
>
<PathArrow back={false} />
</button>
<span className="cg-rail-name" aria-current="page">
{crumbs[crumbs.length - 1].label}
</span>
</>
)}
<button
type="button"
className="cg-rail-toggle"
aria-label={folded ? "Expand views" : "Minimize views"}
aria-expanded={!folded}
title={folded ? "Expand views" : "Minimize views"}
onClick={narrow ? () => { panelSavedRef.current = null; setNarrowOpen((open) => !open); } : toggleRail}
>
<PanelToggleIcon open={!folded} />
</button>
{/* R20 (SDLC 68) moves Ask to the C9 header slot when folded.
Keep the in-rail launcher behind a render guard. */}
{!folded && (
<button
type="button"
className={"cg-chat-toggle" + (chatOpen ? " is-on" : "")}
aria-label="Ask about this data"
aria-expanded={chatOpen}
title={chatOpen ? "Close the chat about this data" : "Ask about this data"}
onClick={onToggleChat}
>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path d="M13.4 9.2c0 1.5-1.3 2.7-2.9 2.7H6.9l-3 2.1v-2.3a2.8 2.8 0 0 1-1.3-2.3V5.1c0-1.5 1.3-2.7 2.9-2.7h5c1.6 0 2.9 1.2 2.9 2.7z"
stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" />
<path d="M5.9 7.2h4.2" stroke="currentColor" strokeWidth="1.3"
strokeLinecap="round" />
</svg>
</button>
)}
</div>
{loading ? (
<RailSkeleton />
) : (
<>
{/* β `cg-data-create` WRAPS `cg-create-new`, which is the nesting the Data rail uses:
the outer class is the host's slot and the inner one is the control.
β W51-T09 CORRECTS WHAT THIS COMMENT USED TO CLAIM. It said flattening the pair
"loses the 8px the outer wrapper contributes"; measured, the 8px is `.cg-create-new`'s
OWN `margin-top` (index.css:504) and the wrapper contributes nothing on this page at
all. What the wrapper does contribute is a BOX TYPE, and that was the real difference:
in the Data rail `.cg-create-new` is a flex item of `.cg-data-database-views` and
computed `min-height: auto`, while here it was a block child and computed `0px`. The
slot is a flex column in `styles/wave50/sheet.css` for exactly that reason. */}
<div className="cg-data-create">
<div className="cg-create-new">
<button
type="button"
className="cg-link-btn cg-create-btn"
aria-haspopup="menu"
aria-expanded={Boolean(createAt)}
onClick={(event) => {
setMenu(null);
setNamingFolder(false);
setCreateAt(createAt ? null : event.currentTarget);
}}
>
<span className="cg-create-icon" aria-hidden="true">+</span>
<span className="cg-create-label">Create newβ¦</span>
</button>
</div>
</div>
<div className="cg-find-view">
<FindIcon />
<input
type="text"
value={query}
placeholder="Findβ¦"
aria-label="Find a workbook"
onChange={(event) => setQuery(event.currentTarget.value)}
/>
</div>
{/* THE LEVEL. `cg-fold-root` is the Data rail's own drop target for "file it here",
and dropping on it moves the dragged row into the folder currently open.
ββ W51-T09 β IT IS A BLOCK NOW, AND THAT IS A MEASURED FIX RATHER THAN A TIDY-UP.
`.sheet-rail-level` made this a flex COLUMN with a 2px gap. `min-height: auto`
resolves to the keyword `auto` for a flex ITEM and to `0px` for anything else, so
every `.cg-view-row` in here computed `auto` while the Data rail's computed `0px` β
the owner's "not exactly the same format". The Data rail's rows sit in a plain block
`.cg-fold-root` inside a flex `.cg-view-list`, so the row rhythm there comes from the
LIST between fold groups and rows inside one group are flush. Matching that is what
makes the two computed styles identical, and the gap went with the class. */}
<div
className={
"cg-views-scroll cg-fold-root"
+ (indexKnown && dropOn === "__level__" ? " is-drop" : "")
}
{...dropProps(at, "__level__")}
>
{levelFolders.map((folder) => (
<div
key={folder.id}
className={
"cg-fold"
+ (indexKnown && dragged?.kind === "folder" && dragged.id === folder.id ? " is-folddrag" : "")
+ (indexKnown && dropOn === folder.id ? " is-drop" : "")
}
draggable={indexKnown}
title={indexPendingReason}
onDragStart={(event) => {
if (!indexKnown) { event.preventDefault(); return; }
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", folder.id);
setDragged({ kind: "folder", id: folder.id });
}}
onDragEnd={() => { setDragged(null); setDropOn(null); }}
{...dropProps(folder.id, folder.id)}
>
<div className="cg-fold-head">
<button
type="button"
className="cg-fold-toggle"
aria-label={`Open folder ${folder.name}`}
onClick={() => goTo(folder.id)}
>
<FolderMark size={16} />
<span className="cg-fold-name">{folder.name}</span>
</button>
<button
type="button"
className="cg-view-more"
aria-haspopup="menu"
aria-label={`Actions for folder ${folder.name}`}
onClick={(event) => {
setCreateAt(null);
setRenaming("");
setMenu({ kind: "folder", id: folder.id, anchor: event.currentTarget });
}}
>
β¦
</button>
</div>
</div>
))}
{levelRows.map((row) => (
<div
key={row.id}
className={
"cg-view-row"
+ (row.id === activeId ? " is-active" : "")
+ (isRailSelected(row.id) ? " is-railsel" : "")
+ (indexKnown && dragged?.kind === "workbook" && dragged.id === row.id ? " is-viewdrag" : "")
+ (indexKnown && dragged?.kind === "workbook" && (dragged.ids?.length ?? 0) > 1
&& dragged.ids?.includes(row.id) ? " is-rail-multidrag" : "")
}
draggable={indexKnown}
title={indexPendingReason}
onDragStart={(event) => {
if (!indexKnown) { event.preventDefault(); return; }
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", row.id);
const ids = isRailSelected(row.id) && railSelected.length > 1
? railSelected : [row.id];
setDragged({ kind: "workbook", id: row.id, ids });
}}
onDragEnd={() => { setDragged(null); setDropOn(null); }}
>
<button
type="button"
className="cg-view-main"
aria-current={row.id === activeId ? "true" : undefined}
aria-pressed={isRailSelected(row.id)}
onClick={(event) => {
selectRailRow(row.id, event);
setRailLeftInPlace([]);
if (event.shiftKey || event.ctrlKey || event.metaKey) return;
onOpen(row.id);
}}
>
<SheetViewIcon />
<span className="cg-view-text">
<span className="cg-view-name">{row.name}</span>
</span>
{isStarred(row.id) ? <StarMark /> : null}
</button>
<button
type="button"
className="cg-view-more"
aria-haspopup="menu"
aria-label={`Actions for ${row.name}`}
onClick={(event) => {
setCreateAt(null);
setRenaming("");
setMenu({ kind: "workbook", id: row.id, anchor: event.currentTarget });
}}
>
β¦
</button>
</div>
))}
{levelFolders.length === 0 && levelRows.length === 0 ? (
<p className="cg-fold-empty">
{needle ? "No workbook here matches what you typed." : "Nothing filed here yet."}
</p>
) : null}
{/* ββ W51-T10 / CONTRACT C5 β "SHARED TO ME", AND IT IS ABSENT UNTIL SOMEBODY SHARES.
The list arrives on `GET /sheets/index` once W51-T25 serves it; today it is empty,
and an empty heading would announce a feature that has given this account nothing.
So the guard is on the ROWS, not on the flag.
β NO `β¦` MENU ON THESE ROWS. Rename, Duplicate, Star, Move and Delete are all acts
on a workbook you own; a shared one is somebody else's, and the strata that would
record a star or a placement are the OWNER's index, not this reader's. Wave-49 R2
again: a control that cannot be honoured is absent.
β TOP LEVEL ONLY. These workbooks are not filed into this account's folders, so
repeating them inside every folder would say they were. */}
{at === null && sharedRows.length > 0 ? (
<div className="sheet-shared">
<p className="sheet-shared-head">Shared to me</p>
{sharedRows.map((row) => (
<div
key={row.id}
className={"cg-view-row" + (row.id === activeId ? " is-active" : "")}
>
<button
type="button"
className="cg-view-main"
aria-current={row.id === activeId ? "true" : undefined}
onClick={() => onOpen(row.id)}
>
<SheetViewIcon />
<span className="cg-view-text">
<span className="cg-view-name">{row.name}</span>
</span>
</button>
</div>
))}
</div>
) : null}
</div>
</>
)}
{!railShut && railSelected.length > 0 ? (
<div className="cg-railsel" role="group" aria-label="Selected workbooks">
<span className="cg-railsel-count">
{railSelected.length === 1 ? "1 workbook selected" : `${railSelected.length} workbooks selected`}
</span>
<button
type="button"
className="cg-railsel-move"
disabled={!indexKnown || railManageable.length === 0}
title={indexPendingReason}
style={indexPendingStyle}
onClick={(event) => {
const anchor = event.currentTarget;
closeMenu();
setCreateAt(null);
setMoveFor({ id: railSelected[0], ids: [...railSelected], anchor });
}}
>
Move to folder
</button>
<button
type="button"
className="is-danger"
disabled={railManageable.length === 0}
onClick={() => setConfirmDelete({
kind: "workbooks", ids: [...railSelected],
name: `${railManageable.length} ${railManageable.length === 1 ? "workbook" : "workbooks"}`,
})}
>
Delete
</button>
{railNotice ? (
<span className="cg-railsel-left" role="status" title={railNotice}>{railNotice}</span>
) : null}
</div>
) : null}
{!railShut && railSelected.length === 0 && railNotice ? (
<p className="cg-railsel-left" role="status" title={railNotice}>{railNotice}</p>
) : null}
{!folded && importSummary ? (
<p className="cg-railsel-left" role="status" style={{ whiteSpace: "normal" }}>
{importSummary}
</p>
) : null}
{createAt && namingFolder ? (
<FolderNameDialog
anchor={createAt}
title="New folder"
siblingNames={folders.filter((folder) => (folder.parent ?? null) === at).map((folder) => folder.name)}
disabled={!indexKnown}
disabledReason={indexPendingReason}
onSubmit={createFolder}
onDismiss={() => { setCreateAt(null); setNamingFolder(false); }}
/>
) : createAt ? (
<AnchoredOverlay
anchor={createAt}
className="cg-view-menu"
role="menu"
ariaLabel="Create new"
placement="right-start"
onDismiss={() => { setCreateAt(null); setNamingFolder(false); }}
>
{/* β A WORKBOOK IS MADE AND OPENED IN ONE ACT, with no name step. The page shows
the new workbook the moment the server answers, which is the done-when clause,
and renaming it is one item down in its own `β¦` menu. */}
{/* β W51-T10 β EACH ROW WEARS A MARK, THROUGH `MenuLabel`, so the icon slot and the
label sit in the `cg-mi-ic` / `cg-mi-text` anatomy `index.css` already paints for
the Data rail's menus. A Workbook wears the Sheet module's own glyph and a Folder
wears `FolderMark`: the two things this rail can make, each named by the mark it
will wear once it exists. */}
<button
type="button"
role="menuitem"
onClick={() => { setCreateAt(null); onCreateWorkbook(); }}
>
<MenuLabel icon={<SheetMark size={16} />} text="Workbook" />
</button>
<button
type="button"
role="menuitem"
disabled={!indexKnown}
title={indexPendingReason}
style={indexPendingStyle}
onClick={() => { setNamingFolder(true); }}
>
<MenuLabel icon={<FolderMark size={16} />} text="Folder" />
</button>
{/* ββ W51-T13 (owner instruction 7, ruling R1) β THE THIRD THING THIS RAIL CAN
MAKE: a workbook that already exists somewhere else. It sits with Workbook and
Folder because those two and this one answer the same question ("where does a new
workbook come from"), and it wears `upload` from `MENU_ICONS`, which is the
vocabulary's own word for bytes arriving from outside. Nothing new was drawn. */}
<button
type="button"
role="menuitem"
onClick={() => { setCreateAt(null); setImportSummary(""); setImporting(true); }}
>
<MenuLabel icon="upload" text="Import .xlsx" />
</button>
<button
type="button"
role="menuitem"
onClick={() => { setCreateAt(null); setPickingTemplate(true); }}
>
<MenuLabel icon={<SheetMark size={16} />} text="From a template" />
</button>
</AnchoredOverlay>
) : null}
{menu ? (
<AnchoredOverlay
anchor={menu.anchor}
className="cg-view-menu"
role={renaming ? "dialog" : "menu"}
ariaLabel={menu.kind === "folder" ? "Folder actions" : "Workbook actions"}
placement="right-start"
onDismiss={closeMenu}
>
{renaming === menu.id ? (
<form
className="cg-data-folder-rename"
onSubmit={(event) => {
event.preventDefault();
const clean = cleanName(folderName);
if (!clean && menu.kind === "folder") return;
if (menu.kind === "folder") renameFolder(menu.id, clean);
else onRenameWorkbook(menu.id, clean);
closeMenu();
}}
>
<input
className="cg-input"
autoFocus
value={folderName}
maxLength={FOLDER_NAME_MAX}
aria-label={menu.kind === "folder" ? "Folder name" : "Workbook name"}
disabled={menu.kind === "folder" && !indexKnown}
title={menu.kind === "folder" ? indexPendingReason : undefined}
style={menu.kind === "folder" ? indexPendingStyle : undefined}
onChange={(event) => setFolderName(event.currentTarget.value)}
/>
<button type="submit" className="cg-btn cg-btn--primary"
disabled={menu.kind === "folder" && (!indexKnown || !folderName.trim())}
title={menu.kind === "folder" ? indexPendingReason : undefined}>
Save
</button>
</form>
) : (
<>
{/* ββ W51-T10 / R13 β THE WORKBOOK MENU IS THE VIEW MENU'S, WITH SHARE. Rename,
Duplicate, Star or Unstar, Move to folder, Share, Delete, IN THAT ORDER, each
through `MenuLabel` with the view menu's own icon component. The order is the
ruling's; before this ticket Duplicate came first and only four of the six
existed.
β A FOLDER KEEPS THE REDUCED SET (Rename and Delete). Wave-49 R2: a control the
rail cannot honour is ABSENT, not present and inert. There is no duplicate-folder
door, no folder star stratum and no folder share kind, and a folder already moves
by drag, so offering four dead rows would be four fake affordances. */}
<button
type="button"
role="menuitem"
disabled={menu.kind === "folder" && !indexKnown}
title={menu.kind === "folder" ? indexPendingReason : undefined}
style={menu.kind === "folder" ? indexPendingStyle : undefined}
onClick={() => {
const current = menu.kind === "folder"
? byId[menu.id]?.name ?? ""
: nameOfWorkbook(menu.id);
setFolderName(current);
setRenaming(menu.id);
}}
>
<MenuLabel icon="rename" text="Rename" />
</button>
{/* β DUPLICATE IS COMPOSED FROM DOORS THAT ALREADY EXIST (read, create, write) and
needs no route of its own. It is here rather than absent because the Sheet CAN
honour it, which is the test R2 sets. */}
{menu.kind === "workbook" ? (
<button
type="button"
role="menuitem"
onClick={() => { const id = menu.id; closeMenu(); onDuplicateWorkbook(id); }}
>
<MenuLabel icon="duplicate" text="Duplicate" />
</button>
) : null}
{menu.kind === "workbook" ? (
<button
type="button"
role="menuitem"
onClick={() => { const id = menu.id; closeMenu(); toggleStar(id); }}
>
<MenuLabel
icon={<StarIcon size={16} filled={isStarred(menu.id)} />}
text={isStarred(menu.id) ? "Unstar" : "Star"}
/>
</button>
) : null}
{menu.kind === "workbook" ? (
<button
type="button"
role="menuitem"
disabled={!indexKnown}
title={indexPendingReason}
style={indexPendingStyle}
onClick={() => {
const target = { id: menu.id, anchor: menu.anchor };
closeMenu();
setMoveFor(target);
}}
>
<MenuLabel icon={<FolderMark size={16} />} text="Move to folder" />
</button>
) : null}
{menu.kind === "workbook" ? (
<button
type="button"
role="menuitem"
onClick={() => {
const id = menu.id;
const name = nameOfWorkbook(id);
closeMenu();
shareWorkbook(id, name);
}}
>
<MenuLabel icon={<ShareMark size={16} />} text="Share" />
</button>
) : null}
{/* ββ R6 β THE DELETE ASKS FIRST, AND UNTIL THIS TICKET IT DID NOT. One click on
this row removed a workbook and everything in it with no confirmation anywhere in
`src/sheet/`: no dialog, no armed second click, not even a native confirm. The
row now only ARMS the one `ConfirmDialog` the whole app shares. */}
<button
type="button"
role="menuitem"
className="is-danger"
disabled={menu.kind === "folder" && !indexKnown}
title={menu.kind === "folder" ? indexPendingReason : undefined}
style={menu.kind === "folder" ? indexPendingStyle : undefined}
onClick={() => {
const target = menu;
const name = target.kind === "folder"
? byId[target.id]?.name ?? ""
: nameOfWorkbook(target.id);
closeMenu();
setConfirmDelete({ kind: target.kind, id: target.id, name });
}}
>
<MenuLabel icon="trash" text="Delete" />
</button>
</>
)}
</AnchoredOverlay>
) : null}
{/* β W51-T10 / R13 β THE FOLDER PICKER, ANCHORED WHERE THE MENU WAS. Same anatomy as the
Data rail's own move picker (`cg-pop`, `cg-pop-title`, `cg-pop-list`, `cg-pick-row`), so
the two rails ask the same question the same way. Every folder in the workbook index is
offered, flat: this rail navigates folders by walking INTO them rather than by unfolding
a tree, so a path is the honest label and an indent would draw a shape the rail does not
otherwise have. The folder a workbook is already in is marked, and Top level is a row
rather than a "remove from folder" verb, because moving to the top is a move. */}
{moveFor ? (
<AnchoredOverlay
anchor={moveFor.anchor}
className="cg-pop"
role="dialog"
ariaLabel={moveFor.ids ? "Move selected workbooks to a folder" : `Move ${nameOfWorkbook(moveFor.id)} to a folder`}
placement="right-start"
onDismiss={() => setMoveFor(null)}
>
<div className="cg-pop-title">Move to folder</div>
<div className="cg-pop-list">
<button
type="button"
className={"cg-pick-row" + (!moveFor.ids && placedIn(moveFor.id) === null ? " is-on" : "")}
disabled={!indexKnown}
title={indexPendingReason}
style={indexPendingStyle}
onClick={() => moveWorkbook(moveFor.id, null)}
>
<FolderMark size={16} />
My workbooks
</button>
{folders.map((folder) => (
<button
key={folder.id}
type="button"
className={
"cg-pick-row" + (!moveFor.ids && placedIn(moveFor.id) === folder.id ? " is-on" : "")
}
disabled={!indexKnown}
title={indexPendingReason}
style={indexPendingStyle}
onClick={() => moveWorkbook(moveFor.id, folder.id)}
>
<FolderMark size={16} />
{folder.name}
</button>
))}
{folders.length === 0 ? (
<div className="cg-pop-note">
There are no folders yet. Create one from Create new.
</div>
) : null}
</div>
</AnchoredOverlay>
) : null}
{/* ββ R6 / CONTRACT C8 β THE ONE CONFIRM DIALOG, NOT A SECOND ONE SHAPED LIKE IT. It brings
the centered panel, the quiet Cancel first, initial focus on Cancel, the focus trap,
Escape, the backdrop and the return of focus to the opener. Re-implementing any of that
here would be the second shape DESIGN.md Β§4 refuses.
β THE TITLE IS A QUESTION on purpose, and it is the done-when's own wording: a title that
names the workbook is what stops a person confirming the wrong one from muscle memory. */}
<ConfirmDialog
open={Boolean(confirmDelete)}
title={`Delete ${confirmDelete?.name ?? ""}?`}
body={
confirmDelete?.kind === "folder"
? indexPendingReason ?? "The workbooks inside it are not deleted. They move back to the top level."
: confirmDelete?.kind === "workbooks"
? "This deletes the selected workbooks and every sheet in them. It cannot be undone."
+ (blockedWorkbooks(confirmDelete.ids).length > 0
? ` Left in place: ${blockedWorkbooks(confirmDelete.ids).join(", ")}.` : "")
: "This deletes the workbook and every sheet in it. It cannot be undone."
}
confirmLabel="Delete"
busy={confirmDelete?.kind === "folder" && !indexKnown}
tone="destructive"
onConfirm={runDelete}
onCancel={() => setConfirmDelete(null)}
/>
{/* β W51-T13 / CONTRACT C4 β THE IMPORT DIALOG, MOUNTED WHERE ITS DOOR IS. The create menu
is this rail's, so the dialog it opens is this rail's too, and mounting it here needs no
edit to `SheetPage.tsx` at all.
β `onOpened` IS THE RAIL'S OWN `onOpen`, which is the page's `openWorkbook`. An import
that finished and left the person looking at the dialog would have done the work and
hidden the result. */}
{importing ? (
<ImportDialog
open
onCancel={() => setImporting(false)}
onSummary={(summary) => {
setImportSummary(summary);
if (summary) {
setRailShut(false);
if (narrow) setNarrowOpen(true);
}
}}
onOpened={(workbookId) => { setImporting(false); onOpen(workbookId); }}
/>
) : null}
{pickingTemplate ? (
<TemplateGallery
open
onCancel={() => setPickingTemplate(false)}
onOpened={(workbookId) => { setPickingTemplate(false); onOpen(workbookId); }}
/>
) : null}
{folded && !embedded && <RailHeaderIcons owner="sheet" anchor={railEl}
onExpand={narrow ? () => { panelSavedRef.current = null; setNarrowOpen(true); } : toggleRail}
chatOpen={chatOpen} onToggleChat={onToggleChat}
/>}
</nav>
);
}
// ---------------------------------------------------------------------------
// 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 / <folder>`), 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<string, string>;
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<string, string>;
starred: readonly string[];
activeId: string;
revealFolder?: string;
onOpen: (id: string) => void;