import PanelToggleIcon from "../shell/PanelToggleIcon"; import "../styles/wave46/rail-select.css"; // ⭐ W50-T09 (owner instruction 10) — the data rail's row metrics. TWO IMPORTERS, deliberately: // `home/HomePage.tsx` side-effect imports this same sheet, because the database glyph rule it // carries paints on the Home route, which never loads the grid chunk. Do not "tidy" either one // away — a stylesheet that nothing on the route imports does nothing at all. import "../styles/wave50/rail.css"; import "../styles/wave61/rails.css"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { RailHeaderIcons, useNarrowRailFold, useRailHeaderSlot } from "../shell/railHeader"; import { useRailSelection } from "../ui/useRailSelection"; import { IconTile } from "../ui/IconTile"; import { ConnectorMark } from "../connectors/brandMarks"; import type { ReactNode } from "react"; import type { KeyboardEvent as ReactKeyboardEvent } from "react"; import { AnchoredOverlay } from "./OverlaySurface"; import FolderNameDialog, { FOLDER_NAME_MAX } from "../home/FolderNameDialog"; import { moduleFolderPath } from "../home/homeModel"; import { EXPORT_FORMATS, EXPORT_LABELS, exportSelectionKey } from "./export"; import type { ExportFormat } from "./export"; import type { DisplayMode, GridFolder, SavedView, Viewer, } from "./types"; import { isModeFrozen, isUndeletableView, mayEditView, mayFileView, mayToggleViewLock, viewDisplayMode, viewDisplayName, viewScopedOutMark, } from "./types"; import { CREATABLE_MODES, DatabaseMark, MODE_LABELS, MODE_TONE, SHARE_SHAPE, } from "./iconShapes"; import { FolderMark, LockMark, MenuLabel, ModeIcon, ToneModeIcon } from "./icons"; /** * ⭐⭐ WAVE 41 · T38 (owner instruction 17) — the stale-workspace signal, from the shared * contract module rather than through a new prop. * * ⚠ `../apiContract` IS NOT `shell/**`. The host-neutral rule this file states and obeys forbids * `customer-grid/**` importing `shell/**`; the event-name/dispatch contract is a sibling of the * grid, and `FormInterface.tsx` and `ImportDialog.tsx` already reach it the same way. */ // ⭐ W47-T11 adds `TOAST_EVENT` on the same channel: a nesting this rail refuses is a sentence // the user has to read, and the frame already listens here for exactly that. import { TOAST_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract"; import { ITEM_DELETED_EVENT, itemDeleted, lendWorkspacePeek, openExistingItem, useItemDeletions } from "../starred/starredApi"; // C6 / R52 shares only the address's folder stratum with chrome; dataPath.ts still owns grid paths. import { readDataAddress } from "../shell/nav"; import type { DeletedItem } from "../starred/starredApi"; import { ROOT_FOLDER_ID } from "./folders"; import { folderPath, CUSTOM_ORIGIN_KEY, dataDatabaseOriginKey, dataDatabaseConnector, dataOriginLabel, groupDataDatabases, levelAt, pathStorageKey, resolveStoredPath, } from "./dataPath"; import type { DataDatabase, DataDatabaseFolder } from "./dataPath"; // ⭐ W32-T23 (owner item 17) — THE BELL, from the shared layer rather than redrawn here. // The alert row wore `cohortAdd` (a LIST with a plus), which names "add to a cohort" on the // one row that creates an ALERT — a borrowed mark is a small lie a menu repeats every time // it opens, and `icons.tsx`'s own `upload` header records the last time this bit. // ⚠ `MenuLabel` takes a NODE for exactly this case: a mark that is not part of the grid's // menu vocabulary. The Inbox module's header wears the SAME component (`ui/icons.BellIcon`), // so the bell that opens the Inbox and the bell that fills it cannot drift apart. import { BellIcon, StarIcon } from "../ui/icons"; /** * ⭐⭐ W50-T27 (contract C4) — THE TRASH PANEL'S ONE MOUNT IN THE PRODUCT. * * W50-T26 shipped `views-trash/TrashPanel.tsx` complete and self-contained and mounted it * NOWHERE: this file belongs to another lane, so the rail entry was a declared handover, and * `platform/verify_shared_views.py` carried a RED-until-wired leg naming exactly this import * plus a ``s inline in the row below, and W40-T20 * lifted that exact geometry into `iconShapes.ts` so the grid header's `aiosShared` canvas sprite * could paint it too. Leaving the copy here would mean the product carried TWO drawings of one * idea, one of which nothing forces to stay in step — the precise failure `iconShapes.ts`'s own * header calls out ("hand-copying every path into a template literal guarantees the header and * the panel eventually disagree"). Same viewBox, same 1.35 stroke as `shapeSource` paints the * canvas twin at, so a shared VIEW in this rail and a shared FIELD in a header are one mark. * * ⛔ NOT `LockMark`. A share is not one of DESIGN.md §4's three locks, and the padlock means a * lock (D-254 is the register row for what happens when one glyph carries both ideas). */ /** * ⭐ W47-T12 — how long the rail shows a folder re-parent the host has not confirmed yet. * * ⛔ DELIBERATELY NOT `ECHO_RECENT_MS` (120s), which is the window `folders.ts` holds a NAME or a * TOMBSTONE for. Those are corrections to a payload that is otherwise right; this is a structural * claim about where a folder lives, and if the host refuses it the rail is lying about the shape * of the tree for the whole window. Two minutes of that is unacceptable and six seconds is a * round trip with room to spare, so a nesting that took hangs on to its place and a nesting that * was refused snaps back while the host's own refusal sentence is still on screen. */ const NEST_HOLD_MS = 6_000; // S85-T25: lend the workspace copy, so `openExistingItem` answers a view or database without a read. lendWorkspacePeek((scope) => peekWorkspace(scope as SurfaceScope)); /** C1 refusal reasons that name a deleted view or member, so the next workspace read drops it. */ const DELETED_TARGET_CODES: readonly string[] = ["target_gone", "view_missing", "view_not_found"]; /** * S85-T33 (D-249, R30): THE ONE SENTENCE A REFUSED FOLDER MOVE CARRIES, or `null` to proceed. * * Every filing door asks here BEFORE it emits, never by reverting after (D-636): a revert-after * still leaves an `item_move` on the wire. The doors are the rail drop, the `...` menu's Move to, * a view created inside a folder, and the grid's `onItemMove` sink. * * ⛔ A READ-ONLY SHARE IS NOT REFUSED. S85-T33 retires W51-T35's R18 refusal: filing writes only * the receiver's own placement (`grid_events::_own_ids` admits every view in their rail) and never * the owner's view, so a person may drag a view out of "Shared with me" and it stays out. * What is left refused is a view that is neither shared with the viewer nor theirs to edit. */ export function viewMoveRefusal(view: SavedView, viewer?: Viewer): string | null { if (mayFileVerdict(view, mayEditView(view, viewer))) return null; return "Only views you can edit or that were shared with you can be moved."; } /** * S85-T33 (D-233): the scoped-out cohort mark, a funnel struck through. The server emptied this * view's filter for this reader, so the mark says why the view shows more rows than its owner's. * ⛔ Not `LockMark`: nothing here is locked, the filter is off. */ export function ScopedOutMark({ size = 13 }: { size?: number }) { return ( ); } function ShareMark({ size = 13 }: { size?: number }) { return ( {SHARE_SHAPE.map((s) => s.fill ? ( ) : ( ) )} ); } /* * ⛔ `DatabaseMark` STOOD HERE AND HAS MOVED TO `iconShapes.ts` (W50-T09, ruling R16). * * R16 puts the outlined database glyph on EVERY listing of a database, which now includes Home. * This file compiles into `CustomerGrid-*.js` (1.5 MB), so a Home import of the component from * here would have pinned the entire grid to the Home route — and `tsc` cannot see that failure * ([[tsc-cannot-see-a-broken-code-split]]). Its geometry (`DATABASE_SHAPE_PATHS`) was already in * the shared `icons-*.js` chunk Home loads anyway, so the component went to the geometry rather * than the geometry to the component. The drawing is unchanged, byte for byte. */ /** What the rail's share mark says, once it has been decided that there is one to show. */ export interface ViewShareMark { title: string; ariaLabel: string; } /** * ⭐⭐ W40-T21 (owner instruction 2, contract C1) — DOES THIS VIEW WEAR THE SHARE MARK, AND WHAT * DOES IT SAY? * * Owner, verbatim: *"A shared View must show the shared/collaborative icon in EVERY account, not * only the recipient's. Normalize it regardless of who shares."* So the GLYPH is one glyph in both * accounts and the WORDS are what differ, which is why this returns copy rather than a boolean. * * ⛔ THE DISCRIMINATOR IS `owner`, AND IT IS AN EXISTING WIRE FIELD, not a new one. * `SavedView.owner` is declared as "whose view this is, WHEN IT IS NOT MINE", and * `grid_events.py::_granted_views` is its only producer — it stamps `shared` / `sharedRole` / * `owner` together on the RECIPIENT's leg of `table_workspace`'s merge and on nothing else. C1 * adds the marker to the caller's OWN leg, where there is no `owner` to stamp because the view is * the caller's. So: * * · `shared` + `owner` → it reached me by grant. Somebody shared it WITH me. * · `shared`, no `owner` → it is mine and I have shared it OUT. * · no `shared` → no mark at all, in either account. * * ⛔ THE RECEIVER'S SENTENCE IS NOT REUSED FOR THE OWNER, and that is the trap this ticket exists * to avoid: `cg-view-shared`'s shipped copy reads "Shared with you by {owner}", so pointing it at * the owner's own leg ships "Shared with you by Farhan" to Farhan. The owner's string is written * fresh and reads as sharing OUT. * * ⛔ NO ROLE SENTENCE ON THE OWNER'S SIDE. `sharedRole` describes a GRANT — what somebody else let * me do with their object — and it is absent and meaningless on a view I own (`SavedView`'s own * note: "on a view that is MINE this is absent and means nothing at all"). Appending "You can edit * it." to my own view would be the product telling me something it does not know. * * ⛔⛔ WAVE 40 QA — THIS FUNCTION SHIPPED READING THE WRONG KEY, AND THAT MADE OWNER * INSTRUCTION 2 A NO-OP. It was written expecting C1 to REDEFINE `shared` to mean "this view * has grants", and its own note here said it was "safe to ship ahead of the server half" because * "nothing stamps `shared` without `owner` today". The server half then landed differently: * AM-5 keeps `shared` meaning "granted TO me" and introduces `hasShares` / `sharedOut` as new * keys. `platform/core/grid_events.py` writes `shared` on exactly two lines, both inside * `_granted_views`, both after `if owner == uname: continue`. So the owner branch below stayed * unreachable, a whole-tree grep for `hasShares` returned ZERO hits in `src/`, and the person * who shared a view saw no mark and no tooltip. Both lanes passed their own ticket. * * ⭐ THREE BRANCHES NOW, AND THE THIRD IS NOT A TIDY-UP. `hasShares` does NOT imply * `sharedRole`: a view living both in the legacy `__shared__` bucket and in the grant registry * reaches its recipient with `hasShares` alone, because the bucket leg outranks the stamped * copy. Lane A wrote that warning down against this very function. Without the neutral branch * that reader would be told "You shared this view", which they did not. * * Pure, exported and total, so the decision can be executed rather than eyeballed: the JSX below * consumes it and holds no second copy of the rule. */ export function viewShareMark( view: Pick< SavedView, "shared" | "owner" | "sharedRole" | "name" | "hasShares" | "sharedOut" > ): ViewShareMark | null { // The MARK is `hasShares`, the viewer-independent fact. `shared` is kept in the test so a // recipient still gets a mark on any leg that stamps the grant without the marker. if (!view.hasShares && !view.shared) return null; if (view.shared && view.owner) { return { title: `Shared with you by ${view.owner}.` + (view.sharedRole === "edit" ? " You can edit it." : " You can view it, not change it."), ariaLabel: `${view.name}, shared with you by ${view.owner}`, }; } if (view.sharedOut) { return { title: "You shared this view. Anyone you gave access to can open it.", ariaLabel: `${view.name}, shared by you`, }; } // `hasShares` with nothing beside it: this view has grants and this payload does not say // whose or on what terms. Say only what is known. Claiming either of the two sentences // above would tell somebody something false about their own access. return { title: "This view is shared.", ariaLabel: `${view.name}, shared`, }; } interface ViewSidebarProps { scope?: SurfaceScope; /** Metadata availability can withhold view writes without changing folder permission. */ readOnly?: boolean; folderReadOnly?: boolean; /** Granted databases live in this secondary navigator, never in the global shell rail. */ databases?: readonly DataDatabase[]; activeDatabaseKey?: string; databaseFolders?: readonly DataDatabaseFolder[]; onSelectDatabase?: (key: string) => void; onDatabaseMove?: (key: string, folderId: string | null) => void; onDatabaseFolderRename?: (folderId: string, name: string) => void; onDatabaseFolderDelete?: (folderId: string) => void; renderDatabaseActions?: (database: DataDatabase) => ReactNode; databaseCreateControl?: ReactNode; /** S72-T63 / C3: a grid mounted at an address. The rail then never reads `location.hash`. */ hosted?: boolean; views: SavedView[]; /** * ⭐⭐ W50-T11 / D-592 — IS THE WORKSPACE STILL IN FLIGHT? * * ⛔ AN EMPTY `views` IS TWO DIFFERENT FACTS AND THE RAIL COULD NOT TELL THEM APART. Before * `/workspace` answers, `payload` is absent and `views` is `[]`; after it answers, `[]` means * a database with no saved views. The rail drew the same nothing for both, so a slow answer * read as "there is nothing here" — and on a cold or degraded connection that window is not * a frame, it is the whole experience. The host already computes the predicate * (`CustomerGrid.tsx::workspaceLoading`); this is that one answer, passed rather than * re-derived [[one-question-two-normalizers]]. */ loading?: boolean; activeViewId: string; saveState?: "saved" | "saving"; onSelect: (id: string) => void; /** The create door persists a personal source; Share view owns every audience and role. */ onCreate: (name: string, mode: DisplayMode) => void; onRename: (id: string, name: string) => void; /** Persist a view's description. "" is a real value — it clears it. */ onNote: (id: string, note: string) => void; onDuplicate: (id: string) => void; onDelete: (id: string) => void; /** Cohorts this user can add to (owner item 6). Empty is fine — the menu then only offers * "New cohort…", which is how the first cohort gets created. */ lists?: { id: string; name: string }[]; /** Add the customers THIS view currently matches to a cohort. `cohortId` empty = create one * called `name`. The view need not be the active one — the caller re-runs the engine for it. */ onAddToList?: (viewId: string, cohortId: string, name: string) => void; /** * ⭐ WAVE 21 item 11 (ruling R10) — open "Select from file…" for the ACTIVE view. * * ⛔ NO ARGUMENTS, and that is the contract rather than an omission. The dialog matches * over the rows the GRID holds, which are the active view's; passing a view id here * would invite a caller to match one view's list against another's rows and report the * difference as missing records. The menu switches views first (see its own note) so * this can stay a verb with one subject. */ onSelectFromFile?: () => void; /** ⭐ WAVE-29 T25 (owner item 6) — open the Import dialog. Supplied only where records may be * added, so a locked database simply has no such row in its menu. */ onImport?: () => void; /** * Item 12 (contract C-LOCK) — lock a view to a cohort, or `null` to unlock. * * ⚠ This menu is the ONLY emitter of `cohortLock` in the client. Optional so the rail still * compiles and renders wherever the host has not accepted the key — the same posture every * other optional action here takes, and the reason a half-deployed wave degrades to "the * action is absent" rather than to "the action silently does nothing". */ onCohortLock?: (viewId: string, cohortId: string | null) => void; /** * The TENANT'S today (wave-2 item 4) — the payload's `today` string VERBATIM, seeding the * default cohort name ` · `. Never the browser clock: a viewer a day * ahead of the tenant would stamp a cohort with a date the host's own data denies * ([[date-window-vocabulary]]). Absent = the name seeds without a date. */ today?: string; /** * Wave-7 item W2 (contract C2) — export THIS view's current matches (filters + sorts, * visible fields in display order), generated client-side. Absent on tables where the * client does not hold the rows (server-windowed), so the entry never lies. */ onExport?: (viewId: string, format: ExportFormat) => void; /** C3 bulk-export path. The caller sends these visible View ids to the server, which evaluates * every tab before the browser gives its result to the one XLSX writer. */ onExportXlsxViews?: (viewIds: string[]) => void; /** * ⭐ W50-T12 / R11 — THE HALF THAT TALKS TO THE SERVER, AND IT RUNS BEFORE THE CLICK. * * `onExportXlsxViews` above is now purely a DOWNLOAD: it hands over an already-built workbook * inside the click gesture and awaits nothing. This is the round trip that used to sit inside * it. The pane calls it when the export panel opens and again whenever the ticked set changes, * so the file is ready by the time anyone presses the button. * * ⛔ SUPPLY BOTH OR NEITHER. With this absent the button below can never become ready and the * pane offers a control that refuses forever. */ onPrepareXlsxViews?: (viewIds: string[]) => void; /** The key of the workbook that is BUILT AND WAITING, as `exportSelectionKey` names it, or "". * The pane compares it with the key of what is currently ticked; equal means the button may be * armed, anything else means the selection has moved on and the build has not caught up. */ xlsxExportReadyKey?: string; /** The server-visible saved Views accepted by C3's export endpoint. Rail-only projections * (for example an unsaved script result) remain out of the chooser. */ exportableViewIds?: readonly string[]; /** * Wave-8 I11c (contract C4) — folders. All of it is OPTIONAL: a caller that * passes no `folders` and no handlers renders exactly the pre-wave-8 flat rail, * which is what keeps the cohort page (and any future rail) from having to opt * into a feature it does not want. */ folders?: GridFolder[]; /** The folder a view belongs to RIGHT NOW — resolved by the caller through * `resolveFolderId`, so a pending drag and a dangling ref are already handled * before the rail sees them. */ folderIdOf?: (viewId: string) => string | null; /** `parent` is the folder the new one goes inside; null means the top level. */ onFolderCreate?: (name: string, parent?: string | null) => void; onFolderRename?: (folderId: string, name: string) => void; onFolderDelete?: (folderId: string) => void; onFolderDuplicate?: (folderId: string) => void; onItemMove?: (viewId: string, folderId: string | null) => boolean | void; /** * WAVE 20 item 19 (C-FOLDER-REORDER) — the folders, in the order the user just dragged * them into. The FULL list every time, never a delta: a partial order cannot say where an * unnamed folder went, and the host has to be able to stamp `order` on all of them. * * Optional like every other folder handler here: a caller that does not pass it gets a * rail with no folder drag at all, rather than a grip that lifts a folder and drops it * back — the posture this whole component takes toward an action nobody can honour. */ onFolderReorder?: (order: string[]) => void; /** * ⭐ WAVE 27 · OWNER ITEM 5 (contract C7) — the rail's new VIEW order, whole. * * ⛔ REQUIRED, AND THE OPTIONAL VERSION OF THIS EXACT PROP IS WHY. `onFolderReorder` above * shipped optional in wave 20: its absence disabled the entire folder drag SILENTLY, every * gate stayed green, and folders simply would not move (the note at its call site in * `CustomerGrid` records it). A required prop fails `tsc` at the unmounted call site, which * is the only version of this rule a person cannot forget. */ onViewReorder: (order: string[]) => void; /** * ⭐ WAVE 27 · OWNER ITEM 21 / RULING R14 — `viewId -> how many records match it RIGHT NOW`, * for the views that carry an alert. A view with no alert is ABSENT from this map, and that * absence is the whole display rule ("alert-on = badge-on"). * * ⛔ REQUIRED, and `{}` is the honest empty. An optional prop would make "no alerts on this * table" and "the caller forgot to compute them" the same state on screen — which is the * shape wave 20's optional `onFolderReorder` shipped in, and it went unnoticed for a wave. * ⚠ ABSENT vs ZERO are DIFFERENT and both are real: absent = no alert, so no badge; `0` = an * alert on a view that currently matches nothing, which is exactly the case a user wants to * see. `!== undefined` rather than a truthiness test, for that reason. */ alertCounts: Record; /** ⭐ WAVE 33 · T14 (D-205) — for a counted view that got NO number, the sentence saying why. * Never both: a row carries a count or a note, and `alertCounts` is checked first. */ countNotes?: Record; /* ⛔ `importantTotal` IS GONE (W35-T27, owner item 9). It carried W33-T16's summed badge at the top of this rail; the owner removed the count from everywhere except the view itself, so the prop has no reader and its memo in `CustomerGrid` went with it rather than being left to compute a value nobody renders [[artifact-with-no-importer]]. */ /** * C4 as AMENDED 2026-07-28 — the folder-level bulk "Add to cohort". The caller * owns the arithmetic (it holds the engine); the rail owns the confirm. * `preview` must return the DEDUPED union plus anything it could not compute, * because the amendment is explicit that a partial union is never silent. */ folderAddPreview?: (folderId: string) => { pids: number[]; counted: number; skipped: { name: string; why: string }[]; }; onFolderAddToList?: (folderId: string, cohortId: string, name: string) => void; /** * Wave-9 contract C3 (I12) — who is looking, so the lock entry appears only for the view's * creator or an admin. Absent = the entry never appears (fail-closed), which is also what * every caller that has not wired `onToggleLock` gets. */ viewer?: Viewer; /** C3 — freeze/unfreeze this view's DISPLAY MODE. The host re-checks the actor. */ onToggleLock?: (viewId: string, locked: boolean) => void; /** * ⭐⭐ WAVE 32 · T24 (owner item 17, ruling R5, contract C4) — mark / unmark a view IMPORTANT. * * ⚠ OPTIONAL, matching every other host callback on this rail: the sidebar is host-neutral and * a host that has not wired it simply does not offer the row (rather than offering one that * throws). The behaviour is not silently degraded — the row is ABSENT, which a reader can see. */ onToggleImportant?: (viewId: string, important: boolean) => void; /** Toolbar gear anchor. It opens this rail's actual ellipsis menu, never a copy of its actions. */ actionAnchor?: HTMLElement | null; onActionAnchorConsumed?: () => void; /* wave17 R1 / C-LOCKV — `cohorts` and `onSelectCohort` are GONE from this component's surface. They carried the transient-lock selection for the retired Cohorts section; a locked view is now an ordinary member of `views` and is selected by `onSelect` like any other, which is the whole point of R1. */ /** ⭐⭐ OWNER, 2026-08-19 — the grid chat's launcher lives in THIS row, beside the minimize * control, exactly as the view agent's does. It was a text pill floating in the gap between * this rail and the grid; the owner called it *"ugly as hell"* and named where it belongs: * *"the same Navigation as the View navigation just beside its minimize icon"*. * ⚠ Optional, and ABSENT rather than disabled when the surface has no database to chat about * (embedded and Query bindings). */ chatOpen?: boolean; /** ⛔ RENDERED AFTER the minimize toggle, never before it. W35-T28 made that control this * row's FIRST child on purpose and `verify_grid_ux.py`'s views-rail scan asserts the ordering, * so adding beside it is the instruction and re-ordering it would undo a shipped owner item to * satisfy a new one — the same rule the view-agent robot follows. * ⚠ IT IS AN ICON, NOT A LABEL. This row is a 26px control strip; the text pill is precisely * what made the old launcher read as bolted on. The sentence it used to show ("Ask about this * data") is now the `aria-label` AND the `title`, so nothing is lost to a screen reader or to * a hover — moving a control must not quietly cost its name. */ onToggleChat?: () => void; } interface DataDatabaseNavigatorProps { databases: readonly DataDatabase[]; activeDatabaseKey: string; folders: readonly DataDatabaseFolder[]; onSelect?: (key: string) => void; onMove?: (key: string, folderId: string | null) => void; onFolderRename?: (folderId: string, name: string) => void; onFolderDelete?: (folderId: string) => void; renderActions?: (database: DataDatabase) => ReactNode; createControl?: ReactNode; /** S72-T63 / C3: a hosted rail keeps its folder in state and never reads `location.hash`. */ hosted?: boolean; /** Draws the rail's one header row (C4). It renders before the data tree, so it stays the rail's first child. */ header?: (path: DataRailPath) => ReactNode; children: (path: { canBack: boolean; back: () => void }) => ReactNode; } /** The data layer's own place, or null when the view layer owns the header (a database is open). */ interface DataRailPlace { name: string; canBack: boolean; back: () => void; canForward: boolean; forward: () => void; } /** What the header reads: the data place, plus the data history Back the view layer falls back to. */ interface DataRailPath { place: DataRailPlace | null; canBack: boolean; back: () => void; } /** One Back control serves both View folders and the enclosing Data path. Keeping its drawing in * one component prevents the two path systems from growing separate buttons again. */ function PathBackButton({ disabled, onClick, }: { disabled: boolean; onClick: () => void; }) { return ( ); } /** ⭐ W46-T08 (owner instruction 26) - THE FORWARD TWIN, drawn beside `PathBackButton` and never * apart from it, so the two halves of one history control cannot grow different shapes. * ⛔ ITS LABEL IS "Forward", NEVER A SECOND "Back": `verify_w45_data_applications.py` counts the * Back control's exact label literal and expects exactly one, so duplicating it is not a * cosmetic slip. Two controls one pixel apart answering to the same name is also, plainly, wrong * for anyone listening rather than looking. * A disabled forward keeps `.cg-path-history-button:disabled`, which dims it rather than merely * refusing the click: nothing ahead has to READ as nothing ahead. */ function PathForwardButton({ disabled, onClick, }: { disabled: boolean; onClick: () => void; }) { return ( ); } type DataNavigatorLevel = | { kind: "root" } | { kind: "origin"; key: string } | { kind: "folder"; id: string } | { kind: "database"; key: string }; function dataNavigatorLevelKey(level: DataNavigatorLevel): string { if (level.kind === "root") return "root"; if (level.kind === "origin") return `origin:${level.key}`; if (level.kind === "folder") return `folder:${level.id}`; return `database:${level.key}`; } /** S78-T02 (C1): the Amazon nav facts `/nav` serves. Optional, so a row without them is unchanged. */ type RailDatabase = DataDatabase & { group?: string; /** `at` null is a read "never synced"; an absent `sync` is unknown and shows nothing. */ sync?: { at: string | null; empty: boolean | null }; }; /** Windows-style Data path rendered with the same segmented-path anatomy as the View path. */ function DataDatabaseNavigator({ databases, activeDatabaseKey, folders, onSelect, onMove, onFolderRename, onFolderDelete, renderActions, createControl, hosted = false, header, children, }: DataDatabaseNavigatorProps) { // S78-T02: declared inside the navigator, because verify_folders runs this function alone in a vm. /** C1's group order under the Amazon level. ⛔ A person reads these: no dash, sentence case. */ const AMAZON_RAIL_GROUPS = ["Sales", "Fees and payouts", "Inventory", "Listings", "Advertising"]; /** A table the mirror reads as 0 rows leaves the rail; Fields and Settings still list it. */ function railListed(database: DataDatabase, activeKey: string): boolean { return (database as RailDatabase).sync?.empty !== true || database.key === activeKey; } /** The muted second line of an Amazon row, in plain words, or null when the fact is unknown. */ function railSyncLine(database: DataDatabase): string | null { const sync = (database as RailDatabase).sync; if (!sync) return null; if (sync.at === null) return "Never synced"; const at = new Date(sync.at); if (Number.isNaN(at.getTime())) return null; return `Synced ${at.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}`; } /** The five groups in order, each with its databases, or null when no database has a group. */ function railGroupSections( listed: readonly DataDatabase[] ): { sections: { label: string; databases: DataDatabase[] }[]; ungrouped: DataDatabase[] } | null { const grouped = new Map(); const ungrouped: DataDatabase[] = []; for (const database of listed) { const group = (database as RailDatabase).group; if (group && AMAZON_RAIL_GROUPS.includes(group)) { grouped.set(group, [...(grouped.get(group) ?? []), database]); } else { ungrouped.push(database); } } if (grouped.size === 0) return null; return { sections: AMAZON_RAIL_GROUPS.filter((label) => grouped.has(label)).map((label) => ({ label, databases: grouped.get(label) ?? [], })), ungrouped, }; } const [draggedDatabase, setDraggedDatabase] = useState(null); const [folderMenu, setFolderMenu] = useState<{ folderId: string; anchor: HTMLElement } | null>( null ); const [renamingFolder, setRenamingFolder] = useState(null); const [folderName, setFolderName] = useState(""); // W46-T04 - the data layer's find box, the twin of the view layer's `viewQuery`. Local and // never persisted, for the same reason: a search is a moment, not a setting. It filters the // rows of the CURRENT level only (source groups and user folders at the root, databases // inside one), so a query never changes where you are standing. const [dataQuery, setDataQuery] = useState(""); const dropDatabase = (event: React.DragEvent, folderId: string | null) => { if (!onMove) return; const key = event.dataTransfer.getData("application/x-aios-database") || draggedDatabase; if (!key) return; event.preventDefault(); event.stopPropagation(); setDraggedDatabase(null); onMove(key, folderId); }; const dropProps = (folderId: string | null) => onMove ? { onDragOver: (event: React.DragEvent) => { if (!event.dataTransfer.types.includes("application/x-aios-database")) return; event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = "move"; }, onDrop: (event: React.DragEvent) => dropDatabase(event, folderId), } : {}; const sourceGroups = useMemo( () => groupDataDatabases(databases.filter((database) => !database.folderId && railListed(database, activeDatabaseKey))), [databases, activeDatabaseKey] ); const parentOfDatabase = (database: DataDatabase): DataNavigatorLevel => database.folderId ? { kind: "folder", id: database.folderId } : { kind: "origin", key: dataDatabaseOriginKey(database) }; const levelsForFolder = (id: string): DataNavigatorLevel[] => moduleFolderPath({ folders }, id).map((folder) => ({ kind: "folder", id: folder.id })); const levelsForDatabase = (database: DataDatabase): DataNavigatorLevel[] => [ { kind: "root" }, ...(database.folderId ? levelsForFolder(database.folderId) : [parentOfDatabase(database)]), { kind: "database", key: database.key }, ]; const levelsForAddress = (): DataNavigatorLevel[] => { const database = databases.find((candidate) => candidate.key === activeDatabaseKey); const folder = hosted ? undefined : readDataAddress().folder; if (folder && folders.some((candidate) => candidate.id === folder)) { return [ { kind: "root" }, ...levelsForFolder(folder), ...(database ? [{ kind: "database" as const, key: database.key }] : []), ]; } return database ? levelsForDatabase(database) : [{ kind: "root" }]; }; const [dataPathState, setDataPathState] = useState<{ levels: DataNavigatorLevel[]; at: number; }>(() => { const levels = levelsForAddress(); return { levels, at: levels.length - 1 }; }); const activePathKey = JSON.stringify(levelsForAddress().map(dataNavigatorLevelKey)); const activeDataKey = useRef(activePathKey); if (activeDataKey.current !== activePathKey) { // The Data navigator remains mounted across database changes. Restore its exact source path // during render so the newly selected database can never commit under the previous source or // folder for one frame; an effect would run after that stale frame had already painted. activeDataKey.current = activePathKey; const levels = levelsForAddress(); setDataPathState({ levels, at: levels.length - 1 }); } const seenAddressFolder = useRef(undefined); useEffect(() => { // C3: a hosted rail has no address to follow, so it never listens to the page's hash. if (hosted) return; const syncAddressFolder = () => { const levels = levelsForAddress(); const addressedFolder = [...levels].reverse().find((level) => level.kind === "folder")?.id; seenAddressFolder.current = addressedFolder; setDataPathState((current) => { const standing = current.levels[current.at]; const standingFolder = standing?.kind === "folder" ? standing.id : standing?.kind === "database" ? current.levels.slice(0, current.at).reverse().find((level) => level.kind === "folder")?.id : undefined; // A view-only hash change must not reset history when the rail is already in this folder. if (addressedFolder === standingFolder) return current; return { levels, at: levels.length - 1 }; }); }; // Folder metadata may arrive after mount. Resolve it once without undoing later rail browsing. const folder = readDataAddress().folder; if (folder && folder !== seenAddressFolder.current && folders.some((candidate) => candidate.id === folder)) syncAddressFolder(); window.addEventListener("hashchange", syncAddressFolder); return () => window.removeEventListener("hashchange", syncAddressFolder); }, [activeDatabaseKey, databases, folders, hosted]); const dataLevel = dataPathState.levels[dataPathState.at] ?? { kind: "root" as const }; const canDataBack = dataPathState.at > 0; /** W46-T08: the levels array was ALREADY an index into history and `pushDataLevel` already * truncates anything ahead, so Forward here is one derived boolean, not a second state * machine beside this one. */ const canDataForward = dataPathState.at < dataPathState.levels.length - 1; const pushDataLevel = (level: DataNavigatorLevel) => { setDataPathState((current) => ({ levels: [...current.levels.slice(0, current.at + 1), level], at: current.at + 1, })); }; const stepDataLevel = (delta: number) => { setDataPathState((current) => { const at = current.at + delta; return at < 0 || at >= current.levels.length ? current : { ...current, at }; }); }; // Wave 44 QA / owner ruling: an address is a sequence of exact destinations. A joined label // wired only to Back looks like a path but cannot do what a Windows path does. const visitDataLevel = (level: DataNavigatorLevel) => { if (dataNavigatorLevelKey(level) === dataNavigatorLevelKey(dataLevel)) return; pushDataLevel(level); }; // C4 (R89): the header names only the current level, never its path; levels remain history. const dataLevelLabel = (level: DataNavigatorLevel): string => { if (level.kind === "root") return "All databases"; if (level.kind === "origin") return dataOriginLabel(level.key); if (level.kind === "folder") return folders.find((folder) => folder.id === level.id)?.name ?? "Folder"; return databases.find((database) => database.key === level.key)?.label ?? "Database"; }; const openDatabase = (database: DataDatabase) => { if (database.externalHref) return; // HOTFIX 2026-09-24: open first, check second. W61-T22's existence read took ~5 s on the // store and the click waited for it; the shell rail already commits before the check (S65-T09). visitDataLevel({ kind: "database", key: database.key }); onSelect?.(database.key); void openExistingItem({ kind: "database", id: database.key }, () => {}); }; const pathDatabaseRow = (database: DataDatabase) => { const active = database.key === activeDatabaseKey; const draggable = !!onMove && !database.protected && database.managedBy !== "loopable"; const syncLine = railSyncLine(database); const content = ( <> {syncLine ? ( // S78-T02 (R11): the true last sync as a quiet second line, the view rows' own pair. {database.label} {syncLine} ) : ( {database.label} )} {database.locked ? ( ) : null} ); return (
{ event.dataTransfer.setData("application/x-aios-database", database.key); event.dataTransfer.effectAllowed = "move"; setDraggedDatabase(database.key); }} onDragEnd={() => setDraggedDatabase(null)} >
{database.externalHref ? ( {content} ) : ( )} {renderActions?.(database)}
); }; // CustomerGrid also renders this sidebar in embedded/query surfaces. Keep those surfaces' // existing View-only navigator when the shell has not supplied a database contract. if (databases.length === 0 || !activeDatabaseKey || !onSelect) { return ( <> {header?.({ place: null, canBack: false, back: () => undefined })} {children({ canBack: false, back: () => undefined })} ); } const dataNeedle = dataQuery.trim().toLowerCase(); const matchesNeedle = (label: string) => !dataNeedle || label.toLowerCase().includes(dataNeedle); const levelMatches = ( dataLevel.kind === "origin" ? sourceGroups.find((group) => group.key === dataLevel.key)?.databases ?? [] : dataLevel.kind === "folder" ? databases.filter((database) => database.folderId === dataLevel.id) : [] ).filter((database) => matchesNeedle(database.label)); const levelSourceGroups = sourceGroups.filter((group) => matchesNeedle(group.label)); const levelFolders = folders.filter((folder) => (dataLevel.kind === "root" || dataLevel.kind === "folder") && (folder.parent ?? null) === (dataLevel.kind === "folder" ? dataLevel.id : null) && matchesNeedle(folder.name)); // S78-T02 (C1): only the Amazon level groups by job. Every other origin stays one flat list. const railSections = dataLevel.kind === "origin" && sourceGroups.find((group) => group.key === dataLevel.key)?.connector === "amazon_sp" ? railGroupSections(levelMatches) : null; // The flat list keeps what no group claims, so a grouped database is drawn exactly once. const levelDatabases = railSections ? railSections.ungrouped : levelMatches; // ⛔ A static heading, never a fold: the Data rail is list-replacing (verify_w44 refuses a // disclosure tree), so a group is the rail's existing quiet section, `.cg-rail-section`. const railGroupRow = (section: { label: string; databases: DataDatabase[] }) => (
{section.label}
{section.databases.map(pathDatabaseRow)}
); const pathFolderRow = (folder: DataDatabaseFolder) => { const members = databases.filter((database) => database.folderId === folder.id); const childFolders = folders.filter((child) => child.parent === folder.id); const connectors = new Set(members.map(dataDatabaseConnector)); const connector = connectors.size === 1 ? [...connectors][0] : null; return (
{onFolderRename || onFolderDelete ? ( ) : null}
); }; // C4: the data layer hands the header its place; at the database level the view layer owns it. const dataPlace: DataRailPlace | null = dataLevel.kind === "database" ? null : { name: dataLevelLabel(dataLevel), canBack: canDataBack, back: () => stepDataLevel(-1), canForward: canDataForward, forward: () => stepDataLevel(1), }; return ( <> {header?.({ place: dataPlace, canBack: canDataBack, back: () => stepDataLevel(-1) })}
{/* ⭐ W46-T04 (owner instruction 12) - THE CREATE DOOR AND THE FIND BOX BELONG TO EVERY DATA LEVEL, not to the root alone. The door used to render under `dataLevel.kind === "root"`, so drilling into a source group or a user folder left the rail with rows and nothing else; the person could see two databases and had no way to make a third without walking back out. ⛔ THE GUARD IS `!== "database"`, NOT "always": at the database level this component hands off to the view layer through `children`, and that layer draws its OWN "+ Create new…" and find box. Rendering here as well would put two of each on one screen. Same classes as the view layer's pair (`cg-data-create` wraps the host's control; `cg-find-view` is the view layer's own box) because the two layers must be indistinguishable in this row, and lookalike classes drift apart. */} {dataLevel.kind !== "database" && createControl ? (
{createControl}
) : null} {dataLevel.kind !== "database" ? (
setDataQuery(event.target.value)} onKeyDown={(event) => { if (event.key === "Escape") setDataQuery(""); }} />
) : null} {dataLevel.kind === "root" ? (
{levelSourceGroups.map((group) => (
))} {levelFolders.map(pathFolderRow)} {dataNeedle && levelSourceGroups.length === 0 && levelFolders.length === 0 ? (
No matches.
) : null}
) : dataLevel.kind === "database" ? (
{children({ canBack: canDataBack, back: () => stepDataLevel(-1) })}
) : (
{levelFolders.map(pathFolderRow)} {levelDatabases.map(pathDatabaseRow)} {railSections?.sections.map(railGroupRow)} {/* The empty line must say WHY it is empty: under a live query "No databases in this folder" is simply false, and a wrong empty state on the control this ticket just un-hid is what QA reopens. */} {levelMatches.length === 0 && levelFolders.length === 0 ? (
{dataNeedle ? "No matches." : "No databases in this folder."}
) : null}
)} {folderMenu ? ( setFolderMenu(null)} placement="right-start" > {renamingFolder === folderMenu.folderId ? (
{ event.preventDefault(); const clean = folderName.trim().replace(/\s+/g, " "); if (clean) onFolderRename?.(folderMenu.folderId, clean); setFolderMenu(null); }} > setFolderName(event.target.value)} />
) : ( <> {onFolderRename ? ( ) : null} {onFolderDelete ? ( ) : null} )}
) : null}
); } /** * A shared folder group is identified by the granting owner and folder name. The visual mark is * fixed by the product, so persisted legacy icon metadata is intentionally not interpreted here. * The wire may carry either the legacy folder name or the newer folder record, so both are read. * * ⛔ BOTH `name` AND `owner` REQUIRED, unchanged from W34-T25: two colleagues can each share a * folder called "Reports", and a group keyed on the name alone merges them under one person's * label. The pair IS the identity, which is why `sharedFolderGroupId` takes both. */ function sharedFolderRecord( view: SavedView ): { name: string; owner: string } | null { const via = (view as { sharedFolder?: unknown }).sharedFolder; // C9's record shape. `null` is an object in JavaScript and an array is one too, so both are // excluded before any key is read off it. const record = via && typeof via === "object" && !Array.isArray(via) ? (via as Record) : null; const rawName = typeof via === "string" ? via : record?.name; const name = typeof rawName === "string" ? rawName.trim() : ""; const owner = typeof view.owner === "string" ? view.owner.trim() : ""; if (!name || !owner) return null; return { name, owner }; } function readRailPath(databaseKey: string): string | null { try { const stored = localStorage.getItem(pathStorageKey(databaseKey)); return typeof stored === "string" && stored !== "" ? stored : null; } catch { return null; } } function writeRailPath(databaseKey: string, folderId: string | null): void { try { const key = pathStorageKey(databaseKey); if (folderId) localStorage.setItem(key, folderId); else localStorage.removeItem(key); } catch { // Storage is optional; losing this convenience must never take down the navigation. } } export default function ViewSidebar({ scope = "customer", readOnly = false, folderReadOnly = readOnly, databases: suppliedDatabases = [], activeDatabaseKey = "", databaseFolders = [], onSelectDatabase, onDatabaseMove, onDatabaseFolderRename, onDatabaseFolderDelete, renderDatabaseActions, databaseCreateControl, hosted = false, chatOpen = false, onToggleChat, views: suppliedViews, loading = false, activeViewId, onSelect: requestSelect, onCreate, onRename, onNote, onDuplicate, onDelete: requestDelete, lists = [], onAddToList, onSelectFromFile, onImport, onCohortLock, today, onExport, onExportXlsxViews, onPrepareXlsxViews, xlsxExportReadyKey, exportableViewIds, folders: suppliedFolders, folderIdOf, onFolderCreate, onFolderRename, onFolderDelete, onFolderDuplicate, onItemMove, onFolderReorder, onViewReorder, alertCounts, countNotes, folderAddPreview, onFolderAddToList, viewer, onToggleLock, onToggleImportant, actionAnchor, onActionAnchorConsumed, }: ViewSidebarProps) { const { isDeleted, restore } = useItemDeletions(); const databases = suppliedDatabases.filter((row) => !isDeleted({ kind: "database", id: row.key })); const views = useMemo(() => suppliedViews.filter((row) => !isDeleted({ kind: "view", id: row.id, database: activeDatabaseKey })), [suppliedViews, isDeleted, activeDatabaseKey]); const onSelect = (id: string) => { /* S85-T25: the view opens in the click's frame and the click reads nothing, so it sends no GET /workspace. The rail learns a deleted view from the next workspace change or from a C1 op refused on a deleted target (the receipt effect below). */ requestSelect(id); }; const activeViewGone = !!activeViewId && isDeleted({ kind: "view", id: activeViewId, database: activeDatabaseKey }); useEffect(() => { if (activeViewGone && views.length) requestSelect(views[0].id); }, [activeViewGone, views, requestSelect]); const requestedDeletes = useRef(new Map()); const onDelete = (id: string) => { requestedDeletes.current.set(id, activeDatabaseKey); requestDelete(id); }; useEffect(() => { // onDelete opens the host's confirmation. Emit only after the host removes the row; // cancelling or a refusal leaves it present and cannot broadcast a deletion. const confirmRemoved = () => { for (const [id, database] of requestedDeletes.current) { if (database !== activeDatabaseKey) { requestedDeletes.current.delete(id); continue; } if (suppliedViews.some((row) => row.id === id)) continue; // The parent's removal is optimistic. Confirm absence through the ordinary reader; // a 403 keeps the server's message and cannot become a deletion event. void openExistingItem({ kind: "view", id, database }, () => {}, { scope }); } }; const confirmed = (event: Event) => { const item = (event as CustomEvent).detail; if (item?.kind === "view" && item.database === activeDatabaseKey) requestedDeletes.current.delete(item.id); }; window.addEventListener(ITEM_DELETED_EVENT, confirmed); window.addEventListener(WORKSPACE_STALE_EVENT, confirmRemoved); confirmRemoved(); return () => { window.removeEventListener(ITEM_DELETED_EVENT, confirmed); window.removeEventListener(WORKSPACE_STALE_EVENT, confirmRemoved); }; }, [suppliedViews, activeDatabaseKey, scope]); useEffect(() => editOutbox.subscribeReceipts((edit, receipt) => { if (edit.scope !== scope || edit.kind !== "event" || receipt.id !== edit.id) return; const event = edit.payload as { type?: string; viewId?: string } | null; // The server's acknowledgement confirms a requested delete, since a workspace copy may lag it. if (receipt.ok && event?.type === "view_delete" && event.viewId && requestedDeletes.current.get(event.viewId) === activeDatabaseKey) { itemDeleted({ kind: "view", id: event.viewId, database: activeDatabaseKey }); return; } // A C1 op refused on a deleted target: the next workspace read drops what is gone. if (!receipt.ok && receipt.confirmedRefusal && event?.type === "view_op" && DELETED_TARGET_CODES.includes(receipt.code ?? "")) signal(WORKSPACE_STALE_EVENT); }), [scope, activeDatabaseKey]); // The old managed View folder put an origin label inside every database. Origin now // belongs one level up in the Data tree, so its views fall back into the database's root group. const folders = useMemo( () => suppliedFolders?.filter( (folder) => (folder as GridFolder & { managedBy?: "loopable" }).managedBy !== "loopable" ), [suppliedFolders] ); /** * I14 — creating a view now always knows WHICH KIND of view is being created, because the * flyout is the only door in. `null` = not creating; a mode = the name step for that mode. */ const [creating, setCreating] = useState(null); /** I14 — the "+ Create new…" flyout's anchor. */ /* ⚠ W50-T11 widened this from `HTMLButtonElement` to `HTMLElement`: the folder "…" menu's own trigger is the SECOND thing that opens this flyout, and `folderMenu.anchor` is already held as an `HTMLElement`. `AnchoredOverlay` takes an `HTMLElement`, so nothing downstream narrows. */ const [createMenu, setCreateMenu] = useState(null); /** * ⭐⭐ W50-T11 (owner instruction 21, ruling R12) — WHICH FOLDER THE CREATE FLYOUT WAS OPENED * FOR, held across its FIRST step. * * ⛔ IT CANNOT BE `folderParent`, and that is the whole reason a second piece of state exists. * `startView(mode, parent)` WRITES `folderParent` and runs at step TWO — after a display mode * has been picked. The folder's "…" menu opens the flyout at step ONE, so between the click on * "New view in folder" and the click on "Grid" there is nothing holding the destination: * writing `folderParent` up front would then be overwritten by `startView`'s own default the * moment the mode row fired. This holds the destination for exactly that gap, and the mode rows * hand it back to `startView`, so the destination still travels through ONE parameter and * `create()` still reads ONE source. * * ⚠ CLEARED BY THE TOP DOOR AND BY `closeCreate`. "+ Create new…" means the level the rail is * standing in (`atId`, in `create()`), never the folder some earlier menu pointed at — the same * staleness `startView`'s own `setFolderParent` note describes, one step earlier. */ const [createInto, setCreateInto] = useState(null); const [name, setName] = useState(""); const [menu, setMenu] = useState<{ viewId: string; anchor: HTMLElement; } | null>(null); const [renamingId, setRenamingId] = useState(null); const [noteFor, setNoteFor] = useState<{ viewId: string; anchor: HTMLElement; } | null>(null); const [noteDraft, setNoteDraft] = useState(""); const [addFor, setAddFor] = useState<{ viewId: string; anchor: HTMLElement; } | null>(null); /** Item 12 (C-LOCK) — which view's cohort lock the picker is open for. */ const [lockFor, setLockFor] = useState<{ viewId: string; anchor: HTMLElement; } | null>(null); const [newListName, setNewListName] = useState(""); /** W2 — the Export format pane, anchored where the "…" menu was. */ const [exportFor, setExportFor] = useState<{ viewId: string; anchor: HTMLElement; } | null>(null); /** C3 begins with the View whose menu opened this pane; later picks are explicit. */ const [exportViewIds, setExportViewIds] = useState([]); const [exportBulk, setExportBulk] = useState(false); // Selection lives in the shared C6 hook below, after the rendered row order is known. // The bar still confirms deletion before anything calls onDelete. const [railDeleteArmed, setRailDeleteArmed] = useState(false); const [railLeftInPlace, setRailLeftInPlace] = useState([]); /** * ⭐ W50-T27 (C4) — THE DATABASE MENU AND THE TRASH PANEL, held as two separate anchors. * * ⛔ NOT ONE PIECE OF STATE WITH A MODE. The menu closes the instant "Trash" is picked and the * panel outlives it, so a single `open: "menu" | "trash"` would have to keep the menu's anchor * alive for the panel and dismiss both together; `AnchoredOverlay` would then re-enter its own * outside-click layer for a menu nobody can see. Two nulls, two overlays, one anchor ELEMENT * shared between them — the panel hangs where the control that opened it stands. * ⚠ THE ANCHOR IS HOISTED OUT OF THE UPDATER at the call site, like every other menu in this * file: React nulls `event.currentTarget` when the handler returns and a functional updater may * be re-invoked after that, which is the white-screen defect recorded at the view row's "…". */ const [databaseMenu, setDatabaseMenu] = useState(null); const [trashAnchor, setTrashAnchor] = useState(null); const [fieldsFor, setFieldsFor] = useState<{ key: string; label: string; opener: HTMLElement } | null>(null); const activeDatabase = databases.find((database) => database.key === activeDatabaseKey); // Connector databases keep their Fields door in their connector's Settings. const canManageFields = viewer?.isAdmin === true && scope === activeDatabaseKey && !!activeDatabase && activeDatabase.key.startsWith("ut_") && dataDatabaseOriginKey(activeDatabase) === CUSTOM_ORIGIN_KEY; const closeFields = useCallback(() => { const opener = fieldsFor?.opener; setFieldsFor(null); window.requestAnimationFrame(() => { if (opener?.isConnected) opener.focus(); }); }, [fieldsFor]); useEffect(() => { if (fieldsFor && (fieldsFor.key !== activeDatabaseKey || !canManageFields)) closeFields(); }, [fieldsFor, activeDatabaseKey, canManageFields, closeFields]); /** * ⭐⭐ W50-T27 / C4 — "comes back whole", WITHOUT A RELOAD, and this is the whole wire. * * `WORKSPACE_STALE_EVENT` is the channel `apiBridge.ts` already binds to * `useCustomerData.reread()`, which re-fetches `/workspace` and hands this component a new * `views` array. So the restored view reappears in the rail on the next render, carrying the * SERVER's copy of itself rather than a row this component guessed at. * ⛔ NO `onSelect(viewId)` HERE. The id has not reached `views` yet at this instant, and asking * the host to activate a view it does not hold is how a rail selects nothing and looks broken. * The view comes back where it was; opening it is the person's next click. * ⚠ `viewId` is READ, not decoration: an empty id means the panel restored nothing, and a * refetch fired on that would be the rail claiming an event that did not happen. */ const onTrashRestored = useCallback((viewId: string) => { if (!viewId) return; restore({ kind: "view", id: viewId, database: activeDatabaseKey }); signal(WORKSPACE_STALE_EVENT); signal(TOAST_EVENT, "That view is back in the rail."); }, [restore, activeDatabaseKey]); /** * ⭐⭐ W50-T27: THE DATABASE-LEVEL "…" CONTROL. C4 (S72-T58) renders it once, in the header's * `span.cg-rail-menu` beside the name, so it stays reachable while a view search is live. * ⛔ ABSENT, NOT DISABLED, WITHOUT A DATABASE. `activeDatabaseKey` is "" on the embedded and * Query surfaces, and it IS the `table_key` every `/api/v1/tables/{key}/…` route resolves * through `user_tables` — the registry spelling (`customer_data`, `ut_*`), never * `gridScopeFor`'s grid scope. A Trash door with no database behind it could only report an * error, and this file's standing posture is to omit an action nobody can honour. */ // `.cg-view-more` ships at opacity 0, and this one instance sits in `span.cg-rail-menu`, never a // hover row, so it carries its own `opacity: 1`. const databaseActions = activeDatabaseKey ? ( ) : null; const xlsxExportViews = useMemo(() => { const allowed = new Set(exportableViewIds ?? []); return views.filter((view) => allowed.has(view.id)); }, [views, exportableViewIds]); const exportView = exportFor ? views.find((view) => view.id === exportFor.viewId) : undefined; /** * ⭐⭐ W50-T12 / R11 — THE IDS THIS PANE WOULD EXPORT RIGHT NOW, and there are TWO doors, which * is the part that is easy to miss. The bulk door exports the ticked set; the single-View door * (rendered when `onExport` is absent, i.e. a server-windowed grid) exports the one View whose * menu opened the pane. Preparing only the first would leave the second permanently unready, * turning "sometimes silent" into "always refuses" on that surface. */ const exportIntendedIds = useMemo(() => { if (!exportView) return [] as string[]; if (exportBulk) return exportViewIds; // ⚠ NOT EVERY OPEN PANE NEEDS A WORKBOOK. When `onExport` is present the single-View Excel // row goes through it instead, and that path builds in the browser inside the click with no // round trip at all. Preparing here anyway would POST on every export-pane open for a file // nobody asks for. if (onExport) return [] as string[]; return exportableViewIds?.includes(exportView.id) ? [exportView.id] : []; }, [exportView, exportBulk, exportViewIds, exportableViewIds, onExport]); const exportIntendedKey = exportSelectionKey(exportIntendedIds); /** True when the workbook waiting in the grid is the workbook this pane would hand over. An * empty selection has a key of its own, so the emptiness is checked separately. */ const exportReady = exportIntendedIds.length > 0 && xlsxExportReadyKey === exportIntendedKey; /** * The preparation trigger. It fires on open and on every tick because `exportIntendedKey` is * the dependency, and the grid's own handler is idempotent per key, so a re-render or a * double-invoked effect costs nothing. ⚠ No debounce: a tick is a deliberate act, the request * is one small POST, and a delay here is exactly the wait the owner would feel at the button. */ useEffect(() => { if (!onPrepareXlsxViews || !exportIntendedIds.length) return; onPrepareXlsxViews([...exportIntendedIds]); }, [onPrepareXlsxViews, exportIntendedKey, exportIntendedIds]); const [moveFor, setMoveFor] = useState<{ viewId: string; anchor: HTMLElement; bulk?: boolean; } | null>(null); const moveView = moveFor ? views.find((view) => view.id === moveFor.viewId) : undefined; const addView = addFor ? views.find((view) => view.id === addFor.viewId) : undefined; const menuView = menu ? views.find((view) => view.id === menu.viewId) : undefined; useEffect(() => { if (!actionAnchor || readOnly) return; const active = views.find((view) => view.id === activeViewId); if (active) setMenu({ viewId: active.id, anchor: actionAnchor }); onActionAnchorConsumed?.(); }, [actionAnchor, activeViewId, onActionAnchorConsumed, views, readOnly]); /** C4 — may this viewer change the menu view's IDENTITY? Courtesy only; the host is the * wall. C3's lock toggle ANDs with this rather than replacing it: the two contracts * compose (C4 says who may edit, C3 says who may freeze the mode). */ const canEditMenuView = !!menuView && mayEditView(menuView, viewer); const canDismissMenuView = !!menuView?.assigned; // I11c local UI state. Collapse is deliberately LOCAL (C4: "minimize state // local") — which folders you have open is a per-person, per-session habit, // not a property of the shared workspace. /** * ⭐⭐ WAVE 41 · T34 (instruction 13) — THE STATE IS "WHICH FOLDERS THE USER OPENED", AND THE * COLLAPSED SET IS DERIVED FROM IT. * * Owner: *"When a user logs in, a folder defaults to CLOSED, not open."* This used to hold the * collapsed ids, so an empty set — the state every mount starts in — meant every folder OPEN, * the exact opposite of the instruction. Inverting the question is what makes the default fall * out of the initial state instead of having to be installed into it. * * ⛔ WHY NOT SEED THE COLLAPSED SET INSTEAD. `useState(() => new Set(folderIds))` captures the * folders present at FIRST RENDER only, and this rail mounts before its workspace lands, so on * the real load order it would seed from an EMPTY list and every folder would still open. Every * folder arriving later — the workspace payload, a newly granted share, a folder T33's nesting * reveals — would be open too. The `useEffect`-collapses-new-arrivals variant fixes the * membership but paints one frame with everything open first, so "on first load every folder is * collapsed" would be false for exactly as long as a user can see it. * * ⛔ NOTHING BUT THE USER'S OWN TOGGLE EVER REMOVES AN ID FROM HERE, which is the whole of * "expanding one and returning later keeps it expanded". A folder that leaves the list and * comes back (a live search, a refreshed payload) keeps its id in this set and returns open. * The set therefore also retains ids of deleted folders; at `MAX_FOLDERS` = 60 and a lifetime * bounded by the component's, that is a rounding error, and pruning it is what would * re-introduce the "opened folder silently re-closes" bug. * * ⚠ SESSION HERE MEANS THE COMPONENT'S LIFETIME, deliberately. There is no localStorage and no * server preference, and adding one would defeat instruction 13's own first clause: a * preference that survives a reload is a folder that is open when the user next logs in. */ // Recovered from 7f6a1c0 (W42-T43): one location replaces the old expand/collapse tree. /** * ⭐⭐ W46-T08 (owner instruction 26) - THE VIEW LAYER'S LOCATION IS NOW AN INDEX INTO HISTORY, * modelled on `dataPathState` one layer down so the two halves of one rail cannot disagree * about what Back and Forward mean. * * ⛔ `at` AND `setAt` STAY, deliberately, as a derived value and a derived setter. `setAt` has * five call sites (the database switch, both create-into-a-folder paths, the Back control and * the folder rows), and w44's gate pins three of those literals. Adding a SECOND history array * beside `at` would leave the folder rows advancing the location without truncating, so Forward * would walk into a folder nobody just left. Routing every existing caller through one * push-and-truncate is the whole point. */ const [viewPath, setViewPath] = useState<{ ids: (string | null)[]; at: number }>(() => { const restored = readRailPath(activeDatabaseKey); return restored ? { ids: [null, restored], at: 1 } : { ids: [null], at: 0 }; }); const at = viewPath.ids[viewPath.at] ?? null; const setAt = (next: string | null) => setViewPath((current) => (current.ids[current.at] ?? null) === next ? current : { ids: [...current.ids.slice(0, current.at + 1), next], at: current.at + 1 } ); const stepViewLevel = (delta: number) => setViewPath((current) => { const index = current.at + delta; return index < 0 || index >= current.ids.length ? current : { ...current, at: index }; }); const canViewBack = viewPath.at > 0; const canViewForward = viewPath.at < viewPath.ids.length - 1; const railDatabaseRef = useRef(activeDatabaseKey); if (railDatabaseRef.current !== activeDatabaseKey) { railDatabaseRef.current = activeDatabaseKey; const restored = readRailPath(activeDatabaseKey); // ⛔ A DATABASE CHANGE RESTORES A LOCATION, IT DOES NOT TRAVEL TO ONE. Pushing here would // carry the previous database's folders into this one's history, and Forward would then point // at a folder that does not exist on the database now on screen. The Data navigator resets // its own `levels` on the same signal for the same reason. setViewPath(restored ? { ids: [null, restored], at: 1 } : { ids: [null], at: 0 }); } const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null); const [renamingFolder, setRenamingFolder] = useState(null); const [creatingFolder, setCreatingFolder] = useState(false); const [folderAnchor, setFolderAnchor] = useState(null); /** * ⭐⭐ WAVE 41 · T33 (instruction 12, R1) — WHICH FOLDER THE DRAFT FOLDER GOES INSIDE. * * ⚠ A SECOND PIECE OF DRAFT STATE RATHER THAN A WIDER `creatingFolder`, because the two * answer different questions and one of them is a boolean the whole pane is gated on. Turning * `creatingFolder` into `string | null | false` would make "no pane" and "a pane at the top * level" the same falsy value, which is W32-T27's absence-holding-two-facts bug in miniature. * Cleared by `startFolder` and by `createFolder`, so a folder made inside one folder cannot * leave its parent behind for the next one. */ const [folderParent, setFolderParent] = useState(null); const [confirmDelete, setConfirmDelete] = useState(null); const [addTarget, setAddTarget] = useState(null); /** The element the bulk-add pane hangs off. Anchoring to document.body * put it at the bottom of the DOCUMENT rather than beside the folder — * painted, and effectively unreachable ([[ui-invisible-to-assertions]]). * Captured from the folder menu before that menu is dismissed. */ const [addAnchor, setAddAnchor] = useState(null); const [addName, setAddName] = useState(""); const [dropTarget, setDropTarget] = useState(null); // Owner item 9 (2026-07-31) — "Find a view". Local and never persisted: a search is a // moment, not a setting. Filtering runs BEFORE grouping so a folder with no matches // simply drops out of the rail while the query is live. const [viewQuery, setViewQuery] = useState(""); // R20 (SDLC 68): remember the desktop fold; narrow expansion lasts only for this visit. const [railShut, setRailShut] = useState(() => { try { return localStorage.getItem("aios-views-rail") === "1"; } catch { return false; } }); const toggleRail = () => setRailShut((v) => { const next = !v; try { localStorage.setItem("aios-views-rail", next ? "1" : "0"); } catch { // storage can be blocked; the fold still works for the session } return next; }); 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 headerSlot = useRailHeaderSlot("data", railEl); const viewNeedle = viewQuery.trim().toLowerCase(); /** * ⭐⭐ WAVE 41 · T37 (owner instruction 14) — THE FIRST LINK IN THE MEMO CHAIN, AND WITHOUT IT * EVERY LINK BELOW IS DEAD. * * The filter allocates a NEW ARRAY on every render while a search is live. Memoizing the * grouping over a freshly-allocated list is a memo that never hits, on inputs that never * changed — green under every gate and worth nothing. So the list the grouping reads is * pinned first, on the only two things that can change it. */ const shownViews = useMemo( () => viewNeedle // ⭐ W40-T28 — searched by what the row SAYS. Filtering on the stored name would leave // the default view unfindable by the only name the user has ever seen it under. ? views.filter((v) => (viewDisplayName(v) || "").toLowerCase().includes(viewNeedle)) : views, [views, viewNeedle] ); // ── WAVE 20 item 19 (C-FOLDER-REORDER) — dragging a FOLDER to reorder the rail ────── // // ⚠ A PRIVATE dataTransfer MIME, and it is not decoration. The VIEW drag two blocks down // carries `text/plain`, and the folder groups already accept that drop ("file this view // into me"). Sharing one channel would make every folder drag look like a view drop to // the handler that fires first — so the two drags are told apart by TYPE, the same // discipline the shell nav's own drag uses, and a drop of this type anywhere // text-editable types nothing. const FOLD_DRAG_TYPE = "application/x-loopable-fold"; /** The folder being dragged, and the group its insertion line is currently drawn above. */ const [foldDrag, setFoldDrag] = useState(null); const [foldOver, setFoldOver] = useState(null); /** * ⭐⭐ W47-T12 (owner instruction 3) — THE FOLDER THE DRAG WOULD GO *INSIDE*, as opposed to * {@link foldOver}, which is the folder it would land ABOVE. * * TWO STATES RATHER THAN ONE WITH A MODE, because they paint two different pictures that must * never both be on: `foldOver` draws the insertion RULE (`.cg-fold.is-drop-above`) and this one * draws the FILL (`.cg-fold.is-drop`). A single "the folder under the pointer" value plus a * separate "and this is what it means" flag would let a render read the two halves out of one * commit and paint a rule and a fill at once, which is precisely the ambiguity this ticket is * about. Every setter below writes both, so exactly one of them is ever non-null. * * ⚠ IT CARRIES `ok`, AND ONLY `ok` PAINTS. `mayNestFolder` is asked during `dragover`, not only * at the drop, so a target that will be refused never lights up — a fill under a drop that is * about to be rejected is worse than no fill. The refused case is still RECORDED rather than * discarded, because `data-fold-drop="refused"` is the difference between "the app has not * noticed my pointer" and "it has, and it will not do this", and releasing there says WHY out * loud on the toast channel. */ const [foldNest, setFoldNest] = useState<{ id: string; ok: boolean } | null>(null); /** * ⭐ W47-T12 — the re-parent this browser just performed, held until the host echoes it. * * The rail renders folders from server state, so between the emit and the echo the dragged * folder would sit exactly where it was and the gesture would read as "nothing happened" — the * NO-BLIP law of `folders.ts`, applied to a parent instead of to a name. `folders.ts`'s stamp * map cannot carry it: `CustomerGrid` writes those stamps and this event does not go through * `CustomerGrid`, so the hold lives beside the gesture that made it. * * ⚠ IT EXPIRES. A refusal (the store is unreachable, the tree validator says the chain is too * deep) never echoes agreement, and a hold with no clock would leave the rail showing a nesting * the server does not have until the page was reloaded. So it clears the moment the incoming * `folders` prop agrees, and unconditionally a few seconds later whether it agreed or not — by * which time the host's own refusal toast has already said why the folder moved back. */ const [nestHold, setNestHold] = useState<{ id: string; parent: string | null; at: number } | null>(null); useEffect(() => editOutbox.subscribeReceipts((edit, receipt) => { if (edit.scope !== scope || edit.kind !== "event" || receipt.id !== edit.id || receipt.ok || receipt.code !== "view_revision_stale") return; const event = edit.payload as { type?: string; surface?: string; itemId?: string } | null; if (event?.type === "item_move" && event.surface === "views") setNestHold((current) => current?.id === event.itemId ? null : current); }), [scope]); const foldsReorderable = !folderReadOnly && !!folders && !!onFolderReorder; /** * ⭐ W47-T12 — nesting needs the folder list and the `item_move` door, and nothing else. It is * deliberately NOT gated on `foldersOn` (which also demands `folderIdOf`, a VIEW-placement * accessor a folder move never consults) so the gesture cannot be switched off by a prop that * has nothing to do with it. * * Folder identities use the same revision sink without arming the view-only watchdog. */ const foldsNestable = !!folders && !!onItemMove; /** * Land `draggedId` before `beforeId` (null = last) and emit the new order. The arithmetic * lives in `folders.ts` so a gate can run it under node — the handler around it is DOM. * * ⚠ The order is computed from the `folders` PROP, never from the rendered groups: a live * "Find a view" query hides folders with no matches, and an order derived from what is on * screen would silently drop the hidden ones out of the sequence. */ const reorderFolders = (draggedId: string, beforeId: string | null) => { const next = reorderFolderIds((folders ?? []).map((f) => f.id), draggedId, beforeId); // `null` is "nothing to say" — an unknown id, or a drop that changed nothing. if (next) onFolderReorder?.(next); }; // ── ⭐ WAVE 27 · OWNER ITEM 5 (contract C7) — dragging a VIEW to reorder the rail ──────── // // The owner asked for both lists to be draggable top-to-bottom; folders already were // (wave 20 item 19) and views could only be FILED INTO a folder, never moved past each // other. This is that drag, built on the same three pieces so the two gestures cannot drift: // a private MIME, the shared `reorderFolderIds` arithmetic, and a whole-order emit. // // ⛔ THE ARITHMETIC IS REUSED, NOT COPIED. `reorderFolderIds` is id-generic — it takes a list // of ids, a dragged id and a "before" id, and every clause in it (dropped-on-itself, the // not-found fallback, the no-op return) is about SEQUENCES rather than about folders. It is // already exercised by `verify_folders.py`, and a second copy here would be a second place // for the dropped-on-itself bug that function's own comment records ([[one-evaluator-per-question]]). const VIEW_DRAG_TYPE = "application/x-loopable-view"; const VIEW_SET_DRAG_TYPE = "application/x-loopable-view-set"; const [viewDrag, setViewDrag] = useState(null); const [viewOver, setViewOver] = useState(null); /** * Land `draggedId` before `beforeId` and emit the FULL order. * * ⚠ Computed from the `views` PROP, never from the rendered rows — a live "Find a view" * query hides non-matching rows, and an order derived from what is on screen would silently * drop every hidden view out of the sequence. (The folder half carries the identical note; * it is the same trap and this rail has both filters on it.) */ const reorderViews = (draggedId: string, beforeId: string | null) => { const next = reorderFolderIds(views.map((v) => v.id), draggedId, beforeId); if (next) onViewReorder(next); // `null` = an unknown id, or a drop that changed nothing }; /** * One pair of handlers per VIEW ROW, listening for the view MIME only. * * ⛔ `stopPropagation` IS LOAD-BEARING. A view row sits inside its folder group, whose own * `onDrop` reads `text/plain` and files the view into that folder. Both types are on this * drag, so without this a reorder inside a folder would ALSO re-file the view — usually into * the folder it is already in, i.e. invisible, until the day it is not. * ⚠ WHAT THIS DELIBERATELY DOES NOT DO: change the view's folder. Dropping a view onto a row * in another folder reorders it and leaves it where it lives; filing stays a drop on the * folder itself. Two gestures, two meanings, rather than one gesture guessing. */ const viewDropHandlers = (viewId: string) => ({ onDragOver: (e: React.DragEvent) => { if (!e.dataTransfer.types.includes(VIEW_DRAG_TYPE)) return; e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = "move"; setViewOver(viewId); }, onDragLeave: () => setViewOver(null), onDrop: (e: React.DragEvent) => { if (!e.dataTransfer.types.includes(VIEW_DRAG_TYPE)) return; const dragged = e.dataTransfer.getData(VIEW_DRAG_TYPE); setViewOver(null); setViewDrag(null); if (!dragged) return; e.preventDefault(); e.stopPropagation(); reorderViews(dragged, viewId); }, }); const viewsReorderable = !readOnly && views.length > 1; const foldersOn = !folderReadOnly && !!folders && !!folderIdOf && !!onItemMove; // Folder structure follows the last workspace, independently of refresh status and edit permission. const foldersShown = !!folders && !!folderIdOf; /** * ⭐⭐ WAVE 41 · T33 (instruction 12, R1, C9) — THE FOLDER LIST, READ AS A TREE. * * ⛔ `nesting.ordered` IS WHAT MAKES NESTING RENDER, and it is the only change the grouping * path needed. `groupByFolder` emits one group per folder IN THE ORDER IT IS HANDED THEM, so a * depth-first list puts every folder immediately after its parent and the rail only has to * indent by `nesting.depth`. The alternative — teaching `groupByFolder` about parents — would * have had to survive its byte-identical `JSON.stringify` assertion, its compiled-artifact * negative controls and the cohort rail's four-argument call, for behaviour a sort supplies. * * ⚠ MEMOIZED WITH THE GROUPING, exactly as this paragraph asked for when it was written: * a memoized grouping fed by a freshly-allocated folder order recomputes on every render * anyway, so the two are pinned together or neither is (W41-T37, owner instruction 14). */ /** * ⭐⭐ W47-T12 — THE FOLDER LIST WITH THIS BROWSER'S PENDING RE-PARENT APPLIED. * * ⛔ APPLIED HERE, ABOVE `folderNesting`, RATHER THAN TO THE GROUPS BELOW IT, because the * parent is not a decoration on a row: it decides `nesting.ordered` (where the folder renders, * and in whose subtree), `nesting.depth` (its indent) and every subsequent `mayNestFolder` * verdict. Patching the picture further down would move the folder on screen while the model * behind the next drag still believed the old tree. * * ⚠ COPIED, NEVER MUTATED. `folders` is the memoized list `CustomerGrid` reconciled; writing * `parent` into that row in place would edit the host's own copy and the hold could then never * expire — the value it is supposed to expire back to would be gone. */ const foldersHeld = useMemo(() => { const list = foldersShown ? (folders as GridFolder[]) : []; if (!nestHold) return list; if (!list.some((f) => f.id === nestHold.id)) return list; return list.map((f) => { if (f.id !== nestHold.id) return f; const next: GridFolder = { ...f }; // ⚠ DELETED, not set to `undefined`. `folderNesting` reads anything that is not a known // string as the top level, so both spellings RENDER the same — but this list is handed on // to `groupByFolder`, whose contract with its own tests is byte-identical output, and a // row carrying an explicit `undefined` key does not serialise like a row without one. if (nestHold.parent) next.parent = nestHold.parent; else delete next.parent; return next; }); }, [folders, foldersShown, nestHold]); const nesting = useMemo(() => folderNesting(foldersHeld), [foldersHeld]); /** * ⭐ W47-T12 — RETIRE THE HOLD. Two exits, and both are needed: * · the incoming list AGREES (the echo landed, or another tab did the same move) — drop it * immediately, so the rail is reading server state again at the first opportunity; * · the clock runs out — drop it whether it agreed or not. A refusal never agrees, and this * is what stops a rejected nesting from sitting on screen as a lie until the next reload. * The wait is measured from the DROP, not from this render, so a rail whose folder list churns * cannot keep restarting the timer and extend the hold indefinitely. */ useEffect(() => { if (!nestHold) return; const row = (folders ?? []).find((f) => f.id === nestHold.id); if (!row || (row.parent ?? null) === nestHold.parent) { setNestHold(null); return; } const timer = window.setTimeout( () => setNestHold(null), Math.max(0, nestHold.at + NEST_HOLD_MS - Date.now()) ); return () => window.clearTimeout(timer); }, [folders, nestHold]); const canFileMenuView = foldersOn && !!menuView && mayFileVerdict(menuView, canEditMenuView); const moveFolders = useMemo( () => nesting.ordered.filter((folder) => !isSyntheticFolderId(folder.id)), [nesting] ); /** * ⭐⭐ WAVE 41 · T37 (owner instruction 14) — THE GROUPING RUNS ONCE PER INPUT CHANGE, NOT * ONCE PER RENDER. * * MEASURED on the real component in a headless browser, 52 views over 8 folders: a drag whose * pointer crosses a new row on every frame commits 60 times a second, and every one of those * commits re-ran this pass — 60 regroupings a second, each of them O(views squared), because * `folderIdOf` resolves a placement by `views.find(...)` per view. Nothing a `dragover` writes * (`dropTarget`, `foldOver`, `viewOver`) is an input to it, so the whole sweep is repeat work. * * ⚠ THE DEPS ARE THE INPUTS AND NOTHING ELSE. `folderIdOf` is the caller's callback and it * carries the placement stamps, so it belongs here; leaving it out would freeze a view in the * folder it was dragged out of until something else changed. */ const groups = useMemo(() => groupByFolder( shownViews, nesting.ordered, (v) => (folderIdOf ? folderIdOf(v.id) : null), /** * ⭐ WAVE 21 item 9 (R12 / contract C1) — THE CONSUMER of `shared`. * * The wire marks each granted view `shared: true` (C1); this is where that mark becomes * a place on screen. Passed unconditionally — NOT gated on `foldersOn` — because the * folder machinery is an opt-in feature of the views rail and "who shared this with me" * is not: a surface with folders switched off must still be able to show you somebody * else's view under a heading that says whose it is. * * ⛔⛔ W40-T21 (contract C1) — `owner` IS PART OF THE TEST NOW, AND WITHOUT IT THIS GROUP * SWALLOWS YOUR OWN VIEWS. C1 widens `shared` from "granted to me" to "this view has * grants", which means the caller's own shared-out views arrive carrying it. This group is * headed **Shared with me**, so the bare flag would file every view I share OUT under a * heading saying somebody shared it with me, and move it out of the folder I put it in. * `owner` is stamped only on the recipient's leg (`_granted_views`), so it is exactly the * half of `shared` that still means "not mine" — the same reading `viewShareMark` above is * built on, so the mark and the grouping cannot disagree about who shared what. */ (v) => v.shared === true && !!v.owner, /** * ⭐⭐ WAVE 34 · T25 (ruling R11) — WHICH shared folder this view arrived through. * * ⚠ READ STRUCTURALLY, and that is a deliberate, temporary compromise rather than sloppiness. * `core/grid_events.py::_granted_views` has stamped `sharedFolder` on every folder-granted * view since `D-37`, its three siblings `shared` / `sharedRole` / `owner` are all declared on * `SavedView`, and this one never was: a census of `web/src` found ZERO occurrences before * this line. `types.ts` is another session's file this wave (`ASK C-1` is out for the * one-line declaration), so rather than block R11 on a type, the field is read through a * narrow local shape and validated here. ⛔ When C-1 lands, delete this cast and take the * declared field: a private spelling of a wire field is exactly how two layers drift. */ /** * ⭐ W41-T35 — THE READ IS `sharedFolderRecord` NOW, and the extraction is the point. * The same function answers the icon map below, so the group a view lands in and the mark * that group wears cannot be derived from two different readings of one wire field. It * still hands `groupByFolder` exactly `{name, owner}` — the extra key is ignored there — * so the grouping is byte-identical to its pre-T35 self. */ (v) => sharedFolderRecord(v), /** * ⭐⭐ WAVE 40 · T28 (owner instruction 30) — THE VIEWS THAT PIN ABOVE EVERY FOLDER. * * Owner: *"when it is not in a folder it must sit at the very top above all folders unless * the user moves it down."* `isUndeletableView` is the set, not a fresh id list, because it * is already THE answer to "which views are facts about this table rather than the user's * own arrangement of it" — the per-database default, Starred, and the IG Overview. A second * spelling here would be a second place to update the day a fourth pinned view exists. * * ⛔ THE YIELD IS INSIDE `groupByFolder`, NOT HERE: it lifts only views with NO stored * placement, so filing one into a folder — or dropping it onto the ungrouped section below, * which stores W32-T27's root sentinel — takes it back out of the pin. Passing the predicate * unconditionally (not gated on `foldersOn`) matches the shared predicate above: the pin is * about the rail's reading order, not about the folder feature being switched on. */ (v) => isUndeletableView(v), (v) => v.assigned === true ), [shownViews, nesting, folderIdOf]); /** * ⭐⭐ WAVE 41 · T34 (instruction 13) — WHICH FOLDERS ARE SHUT RIGHT NOW. * * Read as "every folder head on screen that the user has not opened", so a folder nobody has * touched is closed WHENEVER it appears — at mount, and equally when it arrives afterwards. * That is the same sentence as `opened` above, from the rendering side, and it is why no * effect, no ref of already-seen ids and no second render are needed to hold the default. * * ⛔ DERIVED FROM `groups`, NOT FROM `folders`, AND THE CHEVRON IS WHY. `groupByFolder` emits * one group per stored folder (empty ones included) AND the synthesised groups — "Shared with * me", plus one per shared folder — which own a folder head and a working disclosure chevron * while having no record in `folders` at all. Derived from the stored list, those ids could * never enter this set: their chevron would write to `opened` and nothing would ever read it * back, so the toggle would be DEAD and the group permanently open. Reading the groups also * settles instruction 13 for them the same way it settles it for a stored folder, which is * what the user sees: a folder head is a folder head. Collapse is presentation with no write * behind it, so `isSyntheticFolderId` — the guard that keeps `item_move` / `folder_rename` off * these ids — has nothing to say here. * * ⛔⛔ A LIVE SEARCH YIELDS, and without this clause T34 would silently kill W41-T33. Search * hides folders that matched nothing (below) and T33 taught it to KEEP a parent whose child * matched. With every folder shut by default, `folderHiddenByCollapse` drops those descendants * before they can render and the survivors show as bare heads with no rows: the user types a * view's name and the rail answers with chevrons and nothing else, on the very first search of * every session. So while a needle is live nothing is collapsed. It is presentation only and * it never touches `opened`, so clearing the search returns each folder to exactly the state * the user left it in. */ const standableIds = useMemo( () => groups.flatMap((group) => (group.folder ? [group.folder.id] : [])), [groups] ); const atId = useMemo(() => { if (at === null) return null; if (viewNeedle) return at; return resolveStoredPath(at, standableIds); }, [at, standableIds, viewNeedle]); useEffect(() => { if (activeDatabaseKey && railDatabaseRef.current === activeDatabaseKey) writeRailPath(activeDatabaseKey, at); }, [activeDatabaseKey, at]); const level = useMemo( () => levelAt( atId, foldersShown ? (folders as GridFolder[]) : [], shownViews, (view) => (folderIdOf ? folderIdOf(view.id) : null) ), [atId, foldersShown, folders, shownViews, folderIdOf] ); /** The view layer's levels, database first. C4: the header shows only the LAST one's name. */ const viewPathSegments = useMemo( () => [ { id: null as string | null, name: databases.find((database) => database.key === activeDatabaseKey)?.label ?? "All views", }, ...folderPath(atId, foldersShown ? (folders as GridFolder[]) : []).map((folder) => ({ id: folder.id as string | null, name: folder.name, })), ], [activeDatabaseKey, atId, databases, folders, foldersShown] ); const levelGroups = useMemo(() => { const pin: typeof groups = []; const heads: typeof groups = []; const leaves: typeof groups = []; const childIds = new Set( atId !== null && isSyntheticFolderId(atId) ? [] : level.folders.map((folder) => folder.id) ); for (const group of groups) { const groupId = group.folder?.id ?? null; if (viewNeedle) { if (group.items.length > 0) leaves.push(group); continue; } if (group.pinned === true) { if (atId === null) pin.push(group); continue; } if (groupId === null) { if (atId === null) leaves.push(group); continue; } if (groupId === atId) { leaves.push(group); continue; } if (isSyntheticFolderId(groupId)) { if (atId === null) heads.push(group); continue; } if (childIds.has(groupId)) heads.push(group); } /** * ⭐⭐ W46-T07 (owner instruction 25) - THE DEFAULT VIEW SORTS BELOW FOLDERS. * The pinned group (`pin`) carries the unfiled default view; `heads` are the folder heads and * `leaves` the loose ungrouped views. The pin now falls AFTER every folder head. * * ⛔ THIS REVERSES WAVE 40 · T28, whose comment in `folders.ts` quotes owner instruction 30 * verbatim: "when it is not in a folder it must sit at the very top above all folders unless * the user moves it down". Instruction 25 is the NEWER instruction and it wins. Do not * "restore" the old order on sight - an unexplained swap is exactly what invites that, which * is why this note exists. * * The reorder is done HERE, at the render site, and NOT in `folders.ts::groupByFolder`: * that pure function is shared by more than this rail, and its test * (`_test/folders.test.ts`, run by `verify_folders.py`) asserts `railGroups[0].pinned === true`. * The test asserts what the FUNCTION RETURNS; this line changes only what the RAIL PAINTS, * so the contract and the test both stay true and green. * * `rows` is both what the row loop paints and what `renderedViewIds` flattens for the * shift-click range, so one swap here keeps painted order and selection order identical. */ return { heads, rows: [...heads, ...pin, ...leaves] }; }, [groups, level, atId, viewNeedle]); /** * W46-T02 - DOES THIS GROUP RENDER ITS VIEWS AS ROWS? One arrow, read by the row loop below * AND by the order the shift-range is measured in. Written twice, the two copies drift and the * range stops matching what the person sees, which is the only thing a shift-click means. */ const isLeafGroup = useCallback( (group: { folder?: { id: string } | null }) => !group.folder || (group.folder.id ?? null) === atId || !!viewNeedle, [atId, viewNeedle] ); /** The ids in RENDER order: pinned, then folder heads, then leaves, flattened as drawn. */ const renderedViewIds = useMemo( () => levelGroups.rows.flatMap((group) => isLeafGroup(group) ? group.items.map((view) => view.id) : [] ), [levelGroups, isLeafGroup] ); const { selected: railSelected, anchorId: railAnchorId, onRowClick: selectRailRow, clear: clearSelection, isSelected: isRailSelected, } = useRailSelection(renderedViewIds); /** Editable source Views and recipient-local assignments, never a default/system view. */ const railDeletable = useMemo(() => { const byId = new Map(views.map((view) => [view.id, view])); return railSelected .map((id) => byId.get(id)) .filter((view): view is SavedView => !!view && !isUndeletableView(view) && (view.assigned || mayEditView(view, viewer))); }, [railSelected, views, viewer]); /** The bulk-export path caps a pick at 20 checkboxes; the bar hands it the same 20. */ const railExportIds = useMemo(() => { const allowed = new Set(exportableViewIds ?? []); return railSelected.filter((id) => allowed.has(id)).slice(0, 20); }, [railSelected, exportableViewIds]); const clearRailSel = useCallback(() => { clearSelection(); setRailDeleteArmed(false); setRailLeftInPlace([]); }, [clearSelection]); const railMoveBlocked = railSelected.flatMap((id) => { const view = views.find((candidate) => candidate.id === id); if (!view) return []; const mayEdit = mayEditView(view, viewer); return !mayFileVerdict(view, mayEdit) || viewMoveRefusal(view, viewer) ? [viewDisplayName(view)] : []; }); const railMoveNotice = railLeftInPlace.length > 0 ? `Left in place: ${railLeftInPlace.join(", ")}.` : railMoveBlocked.length > 0 ? `Will stay in place: ${railMoveBlocked.join(", ")}.` : ""; const moveRailViews = (ids: readonly string[], folderId: string | null) => { const leftInPlace: string[] = []; for (const id of ids) { const view = views.find((candidate) => candidate.id === id); if (!view) continue; const mayEdit = mayEditView(view, viewer); if (!mayFileVerdict(view, mayEdit) || viewMoveRefusal(view, viewer)) { leftInPlace.push(viewDisplayName(view)); continue; } // The persist prop accepts a single id; call it once per selected view, in selected order. onItemMove?.(id, folderId ?? ROOT_FOLDER_ID); } clearRailSel(); setRailLeftInPlace(leftInPlace); }; /** * ESCAPE CLEARS THE SELECTION, AND NOTHING ELSE. * * Scoped three ways so it cannot close something the person did not ask to close. It is only * bound while a selection exists; `AnchoredOverlay` already takes Escape on a DOCUMENT CAPTURE * listener and stops propagation, so no open menu, export pane or picker ever reaches this * bubble-phase handler; and a rename box in flight keeps its own Escape. */ useEffect(() => { // The anchor also keeps Escape available when every raw selected row is hidden. if (railSelected.length === 0 && railAnchorId === null && railLeftInPlace.length === 0) return; const onKey = (event: KeyboardEvent) => { if (event.key !== "Escape") return; if (renamingId || renamingFolder) return; const target = event.target as HTMLElement | null; const tag = target?.tagName; if (tag === "INPUT" || tag === "TEXTAREA" || target?.isContentEditable) return; clearRailSel(); }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }, [railSelected.length, railAnchorId, railLeftInPlace.length, renamingId, renamingFolder, clearRailSel]); const folderMenuF = folderMenu ? folders?.find((f) => f.id === folderMenu.id) : undefined; /** * ⭐⭐ WAVE 41 · T33 (instruction 12, R1) — MAY THE OPEN FOLDER TAKE ANOTHER FOLDER INSIDE IT? * * ⛔ WHERE THE 11TH LEVEL IS REFUSED, and it is refused at the DECISION rather than after it: * the menu row that would create the child is the last point at which the user has not yet * typed a name, so that is where DESIGN.md §4 puts the one line stating the cap. Resolved from * the SAME `nesting` the rail renders from, so the verdict and the picture cannot disagree. */ const nestHere = folderMenuF ? mayNestFolder(nesting, folderMenuF.id) : null; /** * ⭐ WAVE 41 · T33 — THE ANCESTORS OF EVERY FOLDER A SEARCH MATCHED INSIDE. * * Item 9's rule ("a folder with no matches is noise") was written when a folder could only * hold views. A parent now holds folders too, so its own `items` being empty says nothing * about whether anything under it matched — and hiding it would orphan the child that did. * * ⚠ BUILT ONLY WHILE A SEARCH IS LIVE. With no needle the set is never walked and the rule it * serves never fires, so the idle rail pays nothing for it. */ const addPreview = addTarget && folderAddPreview ? folderAddPreview(addTarget) : null; /** * ⭐⭐ W47-T12 (owner instruction 3) — PUT `draggedId` INSIDE `parentId`. * * ⛔ `mayNestFolder` IS THE ONLY ORACLE, and it is asked here rather than re-derived: it already * refuses a shared-folder parent, a self-nest, a move into your own descendant and the eleventh * level, and it returns the SENTENCE for each. W47-T11 made the create path speak those same * words on the same channel, so the two halves of the owner's instruction refuse in one voice. * * ⚠ THE SERVER IS A SECOND WALL, NOT A DUPLICATE OF THIS ONE. `mayNestFolder` weighs the * PARENT's level plus one; `core/table_store.py::validate_folder_tree` weighs the whole tree * after the move, so dragging a folder that has three levels under it onto a level-9 parent * passes here and is refused there, by name, with its own sentence on the toast channel. Both * refusals are visible; neither invents a second cap. */ const nestFolder = (draggedId: string, parentId: string) => { if (!foldsNestable || !draggedId) return; const verdict = mayNestFolder(nesting, parentId, draggedId); if (!verdict.ok) { signal(TOAST_EVENT, verdict.reason || "That folder cannot go inside that one."); return; } // Already there: say nothing. An event that changes nothing still bumps every reader's // payload and reconciles to the identical tree — `reorderFolderIds`' own rule, one layer up. if ((nesting.parent[draggedId] ?? null) === parentId) return; setNestHold({ id: draggedId, parent: parentId, at: Date.now() }); // A pending authoritative reload withholds the move and clears its local preview. if (onItemMove?.(draggedId, parentId) === false) setNestHold(null); }; /** * ⭐⭐ W47-T12 — THE FOLDER HEAD IS WHERE THE GESTURE FORKS, and this is the whole affordance. * * ⛔ THE HARD PART OF THIS TICKET IS NOT THE RE-PARENT, IT IS TELLING THE TWO DROPS APART. One * drag now means two things, so without a visible fork every reorder becomes an accidental nest * and the user has to go hunting for the folder they lost. The fork is geometric and the two * pictures already exist in `index.css`, built for exactly these meanings: * * · the top 8px of the head (or a third of it, whichever is less — {@link folderDropIntent}) * -> REORDER. `.cg-fold.is-drop-above`: a 2px inset rule along the folder's top edge, * which is wave 20's own indicator and reads as "it lands here". * · the rest of the head -> NEST. `.cg-fold.is-drop`: the tint plus dashed outline whose own * comment in index.css glosses it as "drop this INTO me". * · everywhere ELSE in the group (the view rows, the space under them) -> REORDER, exactly as * before. That is deliberate: it leaves the big, easy target meaning what it always meant * and asks for deliberate aim only for the new thing. * * ⛔ `stopPropagation` ON THE FOLD TYPE ONLY. This element sits inside the group whose * `dropHandlers` claim the same MIME and would immediately overwrite the fork with a plain * "land above". A VIEW drag (`text/plain`) is deliberately left to bubble, so filing a view by * dropping it on a folder head keeps working byte for byte. * * ⛔ AND THE DROP CLEARS `foldDrag` ITSELF. A successful nest re-parents this folder, React * unmounts the node that started the drag, and the browser never dispatches `dragend` on a * removed node — the scar W34-T21 left on the view path, where `is-viewdrag`'s 45% opacity * stuck permanently. Same shape here, same fix: clear at the drop, not only at `dragend`. */ const foldHeadDropHandlers = (folderId: string) => foldsReorderable ? { onDragOver: (e: React.DragEvent) => { if (!e.dataTransfer.types.includes(FOLD_DRAG_TYPE)) return; e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = "move"; const box = e.currentTarget.getBoundingClientRect(); if (!foldsNestable || folderDropIntent(e.clientY - box.top, box.height) === "before") { setFoldNest(null); setFoldOver(folderId); return; } setFoldOver(null); // ⚠ READ OFF `foldDrag`, NEVER off `dataTransfer`. Every browser puts the payload in // protected mode during `dragover` — `getData` answers "" until the drop — so a // verdict asked of the transfer would be a verdict about an empty id, and the fill // would light up on targets that are about to refuse. setFoldNest({ id: folderId, ok: !!foldDrag && mayNestFolder(nesting, folderId, foldDrag).ok, }); }, onDragLeave: (e: React.DragEvent) => { // The GROUP's `onDragLeave` clears `dropTarget` and `foldOver` and knows nothing // about the fork, so the fill would survive the pointer leaving the head. // // ⛔ BUT ONLY WHEN THE POINTER REALLY LEFT. `dragleave` BUBBLES, and this head holds // a button, a mark and a name span — so crossing between them fires a leave on each // one that arrives here, and an unguarded clear would blink the fill off and on for // the whole time the pointer sits on the very target it is aimed at. `relatedTarget` // is where the pointer went; if that is still inside this head, nothing was left. // (Null means it went outside the document, which IS a leave.) const gone = e.relatedTarget as Node | null; if (gone && e.currentTarget.contains(gone)) return; setFoldNest(null); setFoldOver(null); }, onDrop: (e: React.DragEvent) => { if (!e.dataTransfer.types.includes(FOLD_DRAG_TYPE)) return; e.preventDefault(); e.stopPropagation(); const dragged = e.dataTransfer.getData(FOLD_DRAG_TYPE); const box = e.currentTarget.getBoundingClientRect(); const intent = folderDropIntent(e.clientY - box.top, box.height); setFoldNest(null); setFoldOver(null); setFoldDrag(null); setDropTarget(null); if (!dragged) return; if (!foldsNestable || intent === "before") { reorderFolders(dragged, folderId); return; } nestFolder(dragged, folderId); }, } : {}; /** * ONE pair of drop handlers per group, serving TWO drags — a view being filed into this * folder (`text/plain`) and, since wave 20 item 19, a folder being dropped in front of * this one (`FOLD_DRAG_TYPE`). They must be one pair rather than two spreads: a second * `onDragOver`/`onDrop` on the same element replaces the first, silently, and the drag * that lost would simply stop working. * * The type is read BEFORE anything else, so a folder drag never paints the "file a view * in here" fill and a view drag never draws the insertion rule. */ const dropHandlers = (folderId: string | null) => foldersOn || foldsReorderable ? { onDragOver: (e: React.DragEvent) => { if (e.dataTransfer.types.includes(FOLD_DRAG_TYPE)) { if (!foldsReorderable) return; e.preventDefault(); e.dataTransfer.dropEffect = "move"; setFoldOver(folderId ?? "__root__"); return; } if (!foldersOn) return; e.preventDefault(); setDropTarget(folderId ?? "__root__"); }, onDragLeave: () => { setDropTarget(null); setFoldOver(null); }, onDrop: (e: React.DragEvent) => { if (e.dataTransfer.types.includes(FOLD_DRAG_TYPE)) { const dragged = e.dataTransfer.getData(FOLD_DRAG_TYPE); setFoldOver(null); setFoldDrag(null); if (!foldsReorderable || !dragged) return; e.preventDefault(); e.stopPropagation(); reorderFolders(dragged, folderId); return; } if (!foldersOn) return; e.preventDefault(); setDropTarget(null); // ⭐⭐ WAVE 34 · T21 (ruling R3) — THE ROW STOPS BEING FADED HERE, AND ONLY HERE. // // Owner: moving a View INTO a folder must not leave the view's icon and row blurred // "until i move it around". `viewDrag` is set in the view row's `onDragStart` and was // cleared in exactly two places: that row's own `onDragEnd`, and the SIBLING-REORDER // drop in `viewDropHandlers`. Filing into a folder is NEITHER — it is this handler, // which cleared `dropTarget` and never touched `viewDrag`. // // ⛔ AND `onDragEnd` CANNOT COVER IT, which is why the fade was permanent rather than // one frame long. `onItemMove` below re-parents the row, so React unmounts the node // that started the drag and the browser never dispatches `dragend` on a node removed // mid-gesture. The state stayed set and the FRESH row rendered wearing // `is-viewdrag` (opacity .45) until some later interaction happened to clear it. // // ⚠ Ordered BEFORE `onItemMove`, and that is free rather than delicate: `onItemMove` // is synchronous and React batches both state writes into the same commit, so there // is no frame in which the row is re-parented and still faded. // verify_grid_ux.py's filed-view-stays-faded control pins these three adjacent lines. setViewDrag(null); setViewOver(null); const id = e.dataTransfer.getData("text/plain"); const viewSet = e.dataTransfer.getData(VIEW_SET_DRAG_TYPE); if (viewSet) { let ids: unknown; try { ids = JSON.parse(viewSet); } catch { /* Fall back to the single-view payload. */ } if (Array.isArray(ids) && ids.length > 0 && ids.every((id): id is string => typeof id === "string" && id.length > 0)) { e.stopPropagation(); moveRailViews([...new Set(ids)], folderId); return; } } // ⭐⭐ W32-T27 (owner item 20) — DROPPING ON ROOT SENDS A VALUE, NOT `null`. // // `null` means "no placement", and `groupByFolder` reads a shared view with no // placement as one that arrived by grant — so dragging a shared view to the top // level put it straight back under "Shared with me". `ROOT_FOLDER_ID` is the // receiver saying they filed it here, which is a different fact and now has a // different value. // // ⚠ SENT FOR EVERY ITEM, not only shared ones, and that is deliberate: a rail that // emits one shape for a shared view and another for your own has two move paths to // keep in step, and the bug being fixed here is exactly what happens when two // layers disagree about what absence means. For an unshared view the two are // equivalent — `groupByFolder` maps the sentinel onto the same root bucket. // The refusal is asked BEFORE the emit, so a refused drop snaps back by not moving. // A read-only share is not refused (S85-T33, R30). `dropHandlers` is rebuilt every // render, so `views` and `viewer` are the current ones. const dragged = id ? views.find((view) => view.id === id) : undefined; const refusal = dragged ? viewMoveRefusal(dragged, viewer) : null; if (refusal) { signal(TOAST_EVENT, refusal); return; } if (id) onItemMove?.(id, folderId ?? ROOT_FOLDER_ID); }, } : {}; const noteView = noteFor ? views.find((view) => view.id === noteFor.viewId) : undefined; /* * ⛔⛔ `importantNote` IS DELETED WITH THE BADGE IT LABELLED (W35-T27, owner item 9 / R4). * * It existed because W34-T20's ruling took the WORD off the rail's summed badge and left a * figure with no noun, so the whole sentence moved into that one element's `title` and * `aria-label`. Item 9 removes the badge itself, so there is no element left to label. The * per-view badges keep their own `countNotes` sentence (see the view row below) — that * derivation is separate and is untouched. * * ⚠ D-252's lesson does NOT die here, it moves: "a total that could count nothing must not * paint a manufactured 0" now lives entirely in the per-view badge and in E's * `GET /starred/counts`, whose `notes` map carries the cause for a view whose count is not * free (contract C3). Nothing about it is now stated in two places. */ /** * ⭐⭐ W46-T01 — A VIEW CREATED INSIDE A FOLDER LANDS IN THAT FOLDER. Filed on arrival. * * ⛔ THE PLACEMENT IS NOT PASSED THROUGH `onCreate`, and that is the whole design of this * ticket. `onCreate` is `(name, mode)` and its ONE consumer is the grid's `createView`; * widening it with a third `parent` argument would declare a contract nothing * reads, which is a defect class in this repo rather than a fix. So the destination is applied * from here through `onItemMove` — the SAME channel the drag drop and the Move-to menu already * use, so a view has one way of being filed and not two that can drift apart. * * ⚠ A REF, NOT STATE. It must not cause a render of its own, and it must survive the render * that `onCreate` itself causes. It holds the destination, the ids that existed at the moment * Create was pressed, and the typed name, so the arrival can be identified exactly rather than * guessed at as "whichever view is new". */ const pendingFileRef = useRef< { into: string; before: Set; name: string } | null >(null); useEffect(() => { const pending = pendingFileRef.current; if (!pending) return; const arrivals = views.filter((view) => !pending.before.has(view.id)); if (arrivals.length === 0) return; // Normally exactly one view arrives. If two land in the same window (a concurrent tab, a // refetch), the typed name is the discriminator; with no match this files nothing at all, // because moving the wrong view is worse than leaving the new one at the top level. const arrived = arrivals.length === 1 ? arrivals[0] : arrivals.find((view) => viewDisplayName(view) === pending.name); /* * ⛔ CLEARED WHETHER OR NOT IT FILES, and before the guard below can return. A destination * that outlived its own attempt would fire again on the next unrelated change to `views` and * move a view nobody asked to move. */ pendingFileRef.current = null; if (!arrived) return; // The same verdict every other filing door asks, so a view that cannot be filed by dragging // cannot be filed by being born here either. /** * ⭐⭐ W50-T11 / D-249 — AND IT SAYS SO. This return was silent, and a silent refusal on a * door the user just used reads as the app losing the click: they pick "New view in folder", * the view appears at the top level, and nothing anywhere explains why. DESIGN §4 asks a * refusal to be a plain sentence naming its subject, so this one gives the reason rather than * reporting that something failed. * * This door asks `viewMoveRefusal`, the helper every filing door asks (S85-T33). The arrival * is a view this user just created, so it is their own and the helper returns null. */ const refusal = viewMoveRefusal(arrived, viewer); if (refusal) { signal(TOAST_EVENT, refusal); return; } onItemMove?.(arrived.id, pending.into); }, [views, viewer, onItemMove]); const create = () => { /* * ⛔ CLEARED FIRST, on every attempt. If an earlier create never produced a view (the host * refused it, or the pane was abandoned mid-flight), its destination must not survive to * catch some unrelated view that arrives later. */ pendingFileRef.current = null; const value = name.trim(); if (!value || !creating) return; /* * The destination is re-checked HERE, at the commit, exactly as `createFolder` re-checks its * own parent below: the pane outlives the click that opened it, and the folder it was pointed * at can be deleted or arrive a level deeper from another tab while the name is being typed. * A refused destination leaves the view at the top level, which is where a view can always go. * * ⚠ TWO SOURCES, IN THIS ORDER. `folderParent` is the explicit destination a door set when it * opened the pane; `atId` is the folder the rail is currently standing in, which is what the * ordinary "+ Create new" door means by "here". Root is `null` from both, and then the effect * above is inert and the view is created at the root as before. */ const wanted = folderParent ?? atId; const into = wanted && mayNestFolder(nesting, wanted).ok ? wanted : null; if (into) pendingFileRef.current = { into, before: new Set(views.map((view) => view.id)), name: value, }; // Views start as a personal source. The Share view dialog is the single place where people // choose the audience and role, so creation never embeds a second access model. onCreate(value, creating); // Filing into a folder the rail is not standing in has to OPEN it, or the view is created // invisibly — the same regression T34 recorded for folders, one surface over. if (into && into !== atId) setAt(into); setName(""); setCreating(null); // WAVE 20 item 20 — the two steps share ONE panel, so the anchor outlives step 1 and // has to be released here. Left set, the flyout would spring back to the type chooser // the instant the view was created. setCreateMenu(null); }; /** Item 20 — abandon the whole flyout, from either step. Escape, an outside click and * Cancel all mean the same thing ("I am not creating anything"), so they call one * function rather than three combinations of setters — and abandoning drops the DRAFT * too, or the next "+ Create new…" would hand back a half-filled form from a decision * the user already walked away from. */ const closeCreate = () => { setCreating(null); setCreateMenu(null); // W50-T11 — abandoning the flyout drops its DESTINATION too, for the same reason it already // drops the draft name: the next opening must not inherit a decision the user walked away from. setCreateInto(null); setName(""); }; /** * ⭐⭐ W47-T11 (owner instruction 3) — WHERE A NEW FOLDER ACTUALLY GOES, answered ONCE for both * the pane's label and the Create click, so the form cannot name one destination and the * commit quietly choose another. * * ⛔ `folderParent ?? atId` IS THE FIX, and the missing half was the whole of what the owner * reported as *"Creating a folder inside a folder needs to work, it doesn't for now. Only view * works."* `create` (views, above) has always read BOTH sources; this door read only the * explicit one, so "+ Create new" then "Folder" while the rail was standing three levels down * built a folder at the TOP LEVEL. Both doors now mean the same thing by "here", which is why * one worked and the other did not. * * ⚠ THE PARENT IS RESOLVED AT THE COMMIT, not trusted from when the pane opened (W41-T33's * reason, unchanged): the pane outlives the click that pointed it somewhere, and that folder * can be deleted or arrive a level deeper from another tab while the name is being typed. * * ⚠ A PARENT THE TREE CANNOT RESOLVE STILL FALLS TO THE ROOT IN SILENCE, exactly as it did * before, and only the verdicts a person can actually cause are spoken. `atId` is returned raw * while a search needle is live, so an unresolvable id is a stale path rather than a placement * anyone chose; refusing it by name would replace the old lie with a new one. */ const folderDestOf = ( wanted: string | null ): { into: string | null; refusal: string | null } => { if (!wanted) return { into: null, refusal: null }; if (!isSyntheticFolderId(wanted) && !nesting.depth[wanted]) return { into: null, refusal: null }; const verdict = mayNestFolder(nesting, wanted); if (verdict.ok) return { into: wanted, refusal: null }; /* * The CAUSE comes from `mayNestFolder`, which is the one place that decides it; the OUTCOME * and the next step are added here, because a sentence that explains the cap and stops * leaves the user hunting for a folder that was never made. Same shape as the refusals * `core/grid_events.py` already sends from the other wall. */ return { into: null, refusal: `${verdict.reason ?? "That folder cannot hold another folder."} ` + "Nothing was created, so pick a different place for it and try again.", }; }; const folderDest = folderDestOf(folderParent ?? atId); const createFolder = (name: string) => { const value = name.trim(); if (!value) return; /* * ⭐⭐ W47-T11 — A REFUSED NESTING IS SAID OUT LOUD AND NOTHING IS WRITTEN. * * ⛔ THIS LINE USED TO READ `mayNestFolder(...).ok ? folderParent : null`, which put the * folder at the top level with no word said. From outside that is indistinguishable from * "creating a folder inside a folder does not work": the user aimed at a folder, pressed * Create, and found the result somewhere else. The pane is deliberately LEFT OPEN with the * typed name in it, so the choice between cancelling and aiming somewhere else is still * theirs to make. */ if (folderDest.refusal) { signal(TOAST_EVENT, folderDest.refusal); return; } const into = folderDest.into; /** * ⭐⭐ WAVE 41 · T34 — FILING A FOLDER INTO ONE OPENS IT, or the new folder is created * INVISIBLY. * * ⛔ THIS IS T34's OWN REGRESSION ON T33, and it only exists once folders default to shut. * A collapsed folder KEEPS ITS HEAD (`folderHiddenByCollapse` reads ancestors only), so its * "…" menu — and T33's "New folder inside" row on it — stays reachable while it is closed. * Create a folder in there and `folderHiddenByCollapse` finds the shut parent above the new * child and renders it as null: the user names a folder, presses Create, and the rail does * not move. Before T34 the parent was open by default and the path could not be walked. * * ⚠ THE PARENT ALONE IS ENOUGH, no ancestor walk. The head that carries this menu renders * only when NO ancestor of it is collapsed, so reaching this line already proves every * folder above `into` is open. * * ⚠ IT CAN ONLY ADD. Nothing here removes an id, so this cannot close a folder the user * opened, and the same-set short-circuit keeps a repeat create from re-rendering the rail. */ if (into) setAt(into); onFolderCreate?.(value, into); setCreatingFolder(false); setFolderAnchor(null); setFolderParent(null); }; /** * WAVE 20 item 20 — the view door keeps the anchor, because the name step * now renders in the SAME anchored box the type chooser used. The old comment ("close * the flyout first, or the menu sits on top of the input") described the bug the owner * reported from the other side: the two steps of one action were drawn in two different * places, one beside the rail and one inside it, so step 2 read as an unrelated form. * One panel, two contents, one geometry. * * The folder door closes the menu and opens the shared naming popup at that same trigger. */ /** * ⭐ W46-T01 — IT TAKES A PARENT, exactly as its sibling `startFolder` already does, and the * default is the same `null`. * * ⚠ THE `setFolderParent` IS LOAD-BEARING EVEN THOUGH EVERY CALLER TAKES THE DEFAULT. * `startFolder(folderMenuF.id)` sets `folderParent` and nothing clears it when that pane is * abandoned, so opening the create menu afterwards would find a stale folder id sitting there * and `create` would file the new view into a folder the user walked away from. Setting it here * makes "+ Create new" mean the level the rail is actually standing in, every time. */ const startView = (mode: DisplayMode, parent: string | null = null) => { setCreatingFolder(false); setFolderParent(parent); setCreating(mode); }; /** * ⭐⭐ W41-T33 — ONE DOOR, TWO DESTINATIONS. "+ Create new" opens the pane at the top level; * a folder's own "..." menu opens the SAME pane pointed at that folder. DESIGN.md §4: a * nested folder is made by the control that already makes folders, not by a second form. */ const startFolder = (parent: string | null = null) => { setFolderAnchor(createMenu ?? folderMenu?.anchor ?? null); setCreateMenu(null); setCreating(null); setFolderParent(parent); setCreatingFolder(true); }; /** * WAVE 20 items 18/23/26 (R10, C-SHARE) — open the access editor for a view or a * folder. * * ⚠ A WINDOW EVENT, NOT A PROP, and not for convenience. The dialog is the SHELL's * (one editor for views, folders and databases — R10 asks for one vocabulary), and * this tree is host-neutral: `customer-grid/**` must not import a shell. The frame * already listens on this channel for toasts and staleness; this is one more note on * it. The literal is spelled once here and once in `shell/shareModel.ts`, which is * where it becomes a shared constant when S3 publishes it in `apiContract.ts` * (amendment A-S4-4). * * ⛔ It degrades to NOTHING when no shell is listening (the Streamlit-era bare grid): * a dispatched event nobody hears opens no dialog and throws no error — which is the * right failure for a frame-level surface reached from a rail. */ const openShare = (kind: "view" | "folder", id: string, label: string) => { window.dispatchEvent( new CustomEvent("aios:share-open", { detail: { kind, id, label } }) ); }; const onMenuKeyDown = (event: ReactKeyboardEvent) => { if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return; const items = [ ...event.currentTarget.querySelectorAll('[role="menuitem"]'), ]; if (!items.length) return; event.preventDefault(); const current = items.indexOf(document.activeElement as HTMLButtonElement); const next = event.key === "Home" ? 0 : event.key === "End" ? items.length - 1 : event.key === "ArrowDown" ? (current + 1) % items.length : (current - 1 + items.length) % items.length; items[next]?.focus(); }; /** * ⭐⭐ S72-T58 / C4 (owner instruction 39, R89): THE RAIL'S ONE HEADER ROW. Back, Forward, the * current place's name, the database "…" menu, then Minimize views and Ask about this data. * The name is the last level only, never a path. `DataDatabaseNavigator` renders this first, * so `.cg-views-top` stays the rail's first child and the data history stays inside it. */ const railPlace = ({ place, canBack: canDataBack, back: stepDataBack }: DataRailPath) => { const name = place?.name ?? viewPathSegments[viewPathSegments.length - 1]?.name ?? "All views"; return ( <> { // History first. The parent walk is unreachable (`ids[0]` is null) and stays so Back never pushes. if (canViewBack) stepViewLevel(-1); else if (atId !== null) setAt(level.parent); else stepDataBack(); }} /> stepViewLevel(1)} /> {name} {!place && databaseActions ? {databaseActions} : null} ); }; const railHeader = (path: DataRailPath) => ( <> {/* Owner item 11 — the rail's own minimize control: the same three-bars glyph as the shell nav's, because the two rails are one idea ("a navigation bar folds"). */}
{!folded && railPlace(path)} {/* R20 (SDLC 68) reverses W40-T22's folded-state hide: Ask moves to the C9 header slot when folded. Keep the W37 C6 chat-toggle class literal unchanged. */} {onToggleChat && !folded && ( )} {/* ⛔⛔ THE DATABASE'S OWN TOTAL IS DELETED FROM THIS ROW (W35-T27, owner item 9 / R4). Owner, verbatim: *"remove [the important count] anywhere else but the View itself."* W33-T16 put a summed badge here and W34-T20 stripped its label; item 9 removes the badge outright. **The PER-VIEW badge on each view row is untouched** — that is what "the View itself" means, and it is the half that survives. ⚠ C4 (S72-T58) puts Back, Forward and the place name before the toggle in this row. ⛔ `verify_grid_ux.py`'s `[VIEWS RAIL]` scan is INVERTED, not deleted: it asserts the badge's ABSENCE from this row and its PRESENCE on the view rows, so re-adding one reds it. */} {/* I13 — the "Views / All changes saved" header block is GONE and everything moved up. */}
); return ( <>