loopable / web /src /customer-grid /ViewSidebar.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
85f794d verified
Raw History Blame
261 kB
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 `<TrashPanel` element. Both halves are below. * * β›” THE BRIEFED ANCHOR DID NOT EXIST. The handover names "the database `...` menu" as though * one were already here; it is not. This file has exactly three ellipsis controls β€” the DATA * navigator's folder menu, the VIEW folder menu and the per-view menu β€” and the only control on * a database ROW (`.shell-dots`) is rendered by `shell/Shell.tsx` through `renderDatabaseActions`, * which is not this fence. So the database-level menu is CREATED here, on the view path row, * which is the one row that is about the open database rather than about a view or a folder. * * β›” A STATIC IMPORT, DELIBERATELY. `TrashPanel` imports only `./trashApi` and `./trash.css`, and * this file already compiles into the grid chunk that the panel would be lazily fetched from the * moment the rail is on screen β€” a `lazy()` here would buy a Suspense boundary and no split worth * having. The measured cost is in the ticket's handoff, because `tsc` cannot see chunk shape * ([[tsc-cannot-see-a-broken-code-split]]). */ import { TrashPanel } from "../views-trash/TrashPanel"; import { DatabaseFieldsDrawer } from "../settings/ManageDatabase"; /** Folder nesting shares the stamped parent sink and skips its view-only watchdog. */ import { editOutbox, peekWorkspace } from "./apiBridge"; import type { SurfaceScope } from "./apiBridge"; // ⚠ `SHARED_FOLDER_ID` is no longer imported: W34-T25 replaced both of its call sites with // `isSyntheticFolderId`, and `noUnusedLocals` turns a leftover import into a build error rather // than into dead weight. The constant itself is still exported and still used by `folders.ts`. import { folderDropIntent, folderNesting, groupByFolder, isSyntheticFolderId, // S85-T33: the verdict-level twin, for doors that already hold `mayEdit`. The drag site asks // `types.ts::mayFileView`; both must give one answer (verify_folders.py runs the parity). mayFileView as mayFileVerdict, mayNestFolder, reorderFolderIds, // ⭐ W41-T35 β€” the SAME key function `groupByFolder` synthesises a shared group with, so the // icon map below cannot key one way while the grouping keys another. } from "./folders"; /* ───────────────────────────────────────────────────────────────────────────────────────── Share-view ownership note for the create door. View creation now stays private and delegates audience/edit choices to the single Share view dialog. Keep this note aligned with that ownership boundary if the sharing surface changes. β›” WHY THE PATHS LIVE HERE AND NOT IN `icons.tsx`, stated so a later wave does not "tidy" it back: `icons.tsx` renders `MODE_SHAPES` from `iconShapes.ts`, which the glide CANVAS also paints β€” geometry with two painters belongs there. These three have exactly ONE call site, thirty lines below, and no canvas draws them. `LockMark` and `EyeOffIcon` already carry the same argument at their definitions ("paths are inline… no header ever draws this one"). ⚠ The wave-27 ownership map puts `iconShapes.ts` in session D's fence and leaves `icons.tsx` in NOBODY's; a one-call-site component in a file this session owns has zero collision risk, and the ask to settle `icons.tsx`'s owner is in the mailbox (C-3). The tone follows the STRENGTH of the grant β€” neutral for the private default, blue for the open one, green for the deliberate pick β€” and the paint comes from the shared pastel table, never a literal, so these can never be the one place in the product with its own colours. Outline-only, the register the owner set in 2026-07-29: "it doesn't have a full color, only the linings". */ /** head + shoulders, at `x`. One drawing, three uses β€” a second hand-drawn person is how two * marks in one panel end up different heights. */ /* WAVE 20 item 18 (C-SHARE) β€” the system folder every view shared WITH you lands in until you file it somewhere of your own. It is the only folder id this component recognises by name, and as of wave 21 (item 9) it is DECLARED IN `folders.ts` beside the synthesis that produces it β€” a component-local copy of a contract id is a copy that can drift from the rule, and the rule is the half a gate can run. */ /** * ⭐ W40-T21 β€” THE SHARE GLYPH, drawn from `SHARE_SHAPE` rather than from a second copy of the * same paths. * * This component used to be three hand-written `<path>`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 ( <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden> <path d="M2.6 3.4h10.8L9.2 8.3v4.1l-2.4 1.2V8.3z" fill="none" stroke="currentColor" strokeWidth={1.35} strokeLinejoin="round" /> <path d="M2.8 13.2 13.2 2.8" fill="none" stroke="currentColor" strokeWidth={1.35} strokeLinecap="round" /> </svg> ); } function ShareMark({ size = 13 }: { size?: number }) { return ( <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden> {SHARE_SHAPE.map((s) => s.fill ? ( <path key={s.d} d={s.d} fill="currentColor" /> ) : ( <path key={s.d} d={s.d} fill="none" stroke="currentColor" strokeWidth={1.35} strokeLinecap="round" strokeLinejoin="round" /> ) )} </svg> ); } /* * β›” `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 `<view name> Β· <YYYY-MM-DD>`. 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<string, number>; /** ⭐ 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<string, string>; /* β›” `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 ( <button type="button" className="cg-path-history-button" aria-label="Back" title="Back" disabled={disabled} onClick={onClick} > <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"> <path d="M9.8 3.6 5.4 8l4.4 4.4" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" strokeLinejoin="round" /> </svg> </button> ); } /** ⭐ 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 ( <button type="button" className="cg-path-history-button" aria-label="Forward" title="Forward" disabled={disabled} onClick={onClick} > <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"> <path d="M6.2 3.6 10.6 8l-4.4 4.4" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" strokeLinejoin="round" /> </svg> </button> ); } 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<string, DataDatabase[]>(); 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<string | null>(null); const [folderMenu, setFolderMenu] = useState<{ folderId: string; anchor: HTMLElement } | null>( null ); const [renamingFolder, setRenamingFolder] = useState<string | null>(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<HTMLElement>, 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<HTMLElement>) => { if (!event.dataTransfer.types.includes("application/x-aios-database")) return; event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = "move"; }, onDrop: (event: React.DragEvent<HTMLElement>) => 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<string | undefined>(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 = ( <> <span className="cg-db-mark"> <IconTile icon={database.icon} surface="rail"><DatabaseMark size={16} /></IconTile> </span> <ConnectorMark connector={dataDatabaseConnector(database)} size={16} className="lp-source-mark" /> {syncLine ? ( // S78-T02 (R11): the true last sync as a quiet second line, the view rows' own pair. <span className="cg-view-text"> <span className="cg-fold-name">{database.label}</span> <span className="cg-view-desc" data-rail-sync>{syncLine}</span> </span> ) : ( <span className="cg-fold-name">{database.label}</span> )} {database.locked ? ( <span className="cg-data-database-lock" role="img" aria-label={`${database.label}, locked database`} title="Locked database. Records are managed by its source; fields remain editable." > <LockMark size={12} /> </span> ) : null} </> ); return ( <div key={database.key} className={ "cg-fold cg-data-database" + (active ? " is-active" : "") + (draggedDatabase === database.key ? " is-dragging" : "") } draggable={draggable} onDragStart={(event) => { event.dataTransfer.setData("application/x-aios-database", database.key); event.dataTransfer.effectAllowed = "move"; setDraggedDatabase(database.key); }} onDragEnd={() => setDraggedDatabase(null)} > <div className="cg-fold-head"> {database.externalHref ? ( <a className="cg-fold-toggle" href={database.externalHref} target="_blank" rel="noreferrer" aria-label={`Open ${database.label}`} > {content} </a> ) : ( <button type="button" className="cg-fold-toggle" aria-current={active ? "page" : undefined} aria-label={`Open database ${database.label}`} onClick={() => openDatabase(database)} > {content} </button> )} {renderActions?.(database)} </div> </div> ); }; // 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[] }) => ( <div key={section.label} className="cg-rail-section cg-data-group" role="group" aria-label={`${section.label}, ${section.databases.length} databases`} data-rail-group={section.label}> <div className="cg-fold-head"> <span className="cg-view-desc">{section.label}</span> </div> {section.databases.map(pathDatabaseRow)} </div> ); 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 ( <div key={folder.id} className="cg-fold cg-data-user-folder" {...dropProps(folder.id)}> <div className="cg-fold-head"> <button type="button" className="cg-fold-toggle" aria-label={`Open folder ${folder.name}`} onClick={() => pushDataLevel({ kind: "folder", id: folder.id })}> <IconTile surface="rail"> {connector && connector !== "loopable" ? <ConnectorMark connector={connector} size={16} className="lp-source-mark" /> : <FolderMark size={16} />} </IconTile> <span className="cg-fold-name">{folder.name}</span> <span className="cg-fold-count">{members.length + childFolders.length}</span> </button> {onFolderRename || onFolderDelete ? ( <button type="button" className="cg-view-more" aria-label={`Actions for ${folder.name}`} aria-haspopup="menu" onClick={(event) => { setFolderMenu({ folderId: folder.id, anchor: event.currentTarget }); setRenamingFolder(null); setFolderName(folder.name); }}>Β·Β·Β·</button> ) : null} </div> </div> ); }; // 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) })} <div className="cg-data-tree" data-data-path-tree data-data-path-history> {/* ⭐ 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 ? ( <div className="cg-data-create">{createControl}</div> ) : null} {dataLevel.kind !== "database" ? ( <div className="cg-find-view"> <svg className="cg-find-view-icon" width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true" > <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" /> <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" /> </svg> <input type="text" value={dataQuery} placeholder="Find…" aria-label="Find a database" onChange={(event) => setDataQuery(event.target.value)} onKeyDown={(event) => { if (event.key === "Escape") setDataQuery(""); }} /> </div> ) : null} {dataLevel.kind === "root" ? ( <div className="cg-data-path-level" data-data-level="root"> {levelSourceGroups.map((group) => ( <div key={group.key} className="cg-fold cg-data-origin" {...dropProps(null)}> <div className="cg-fold-head"> <button type="button" className="cg-fold-toggle" aria-label={`Open folder ${group.label}`} onClick={() => pushDataLevel({ kind: "origin", key: group.key })} > <IconTile surface="rail"> {group.connector && group.connector !== "loopable" ? <ConnectorMark connector={group.connector} size={16} className="lp-source-mark" /> : <FolderMark size={16} />} </IconTile> {/* ⭐ W54-T48 (R4 / C4) β€” THE FULL NAME ON HOVER, BECAUSE THIS NAME IS NOW THE USER'S. This row used to read the literal "Odoo" for every connected database and could not truncate; it now reads the CONNECTION's keychain label once a tenant has two connections to tell apart, and a label may run to 80 characters against a rail measured to the pixel. `.cg-fold-name` (index.css:5929) is `overflow:hidden; text-overflow:ellipsis; white-space:nowrap`, so "Royal Production (Jakarta warehouse)" reads as "Royal Production (Jakart…" with nothing to open it. ⚠ ON THE SPAN, NOT ON THE BUTTON, and that is the accessibility half. The button's accessible name is its `aria-label` ("Open folder <name>"), which already carries the whole label to a screen reader; a `title` on the button would be a second name competing with it. On the text span it is a POINTER affordance only and adds nothing to the accessibility tree. ⚠ The same treatment the header's `.cg-rail-name` gives a truncatable name (`title={name}`, this file) and the shape `.cg-fold-name` already takes in the view layer below. No CSS: a title needs none. */} <span className="cg-fold-name" title={group.label}> {group.label} </span> <span className="cg-fold-count">{group.databases.length}</span> </button> </div> </div> ))} {levelFolders.map(pathFolderRow)} {dataNeedle && levelSourceGroups.length === 0 && levelFolders.length === 0 ? ( <div className="cg-fold-empty">No matches.</div> ) : null} </div> ) : dataLevel.kind === "database" ? ( <div className="cg-data-database-views" data-data-level="database"> {children({ canBack: canDataBack, back: () => stepDataLevel(-1) })} </div> ) : ( <div className="cg-data-path-level" data-data-level={dataLevel.kind} {...dropProps(dataLevel.kind === "folder" ? dataLevel.id : null)}> {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 ? ( <div className="cg-fold-empty"> {dataNeedle ? "No matches." : "No databases in this folder."} </div> ) : null} </div> )} {folderMenu ? ( <AnchoredOverlay anchor={folderMenu.anchor} className="cg-view-menu" role="menu" ariaLabel="Database folder actions" onDismiss={() => setFolderMenu(null)} placement="right-start" > {renamingFolder === folderMenu.folderId ? ( <form className="cg-data-folder-rename" onSubmit={(event) => { event.preventDefault(); const clean = folderName.trim().replace(/\s+/g, " "); if (clean) onFolderRename?.(folderMenu.folderId, clean); setFolderMenu(null); }} > <input className="cg-input" autoFocus value={folderName} maxLength={FOLDER_NAME_MAX} aria-label="Database folder name" onChange={(event) => setFolderName(event.target.value)} /> <button type="submit" className="cg-btn cg-btn--primary" disabled={!folderName.trim()}> Save </button> </form> ) : ( <> {onFolderRename ? ( <button type="button" role="menuitem" onClick={() => setRenamingFolder(folderMenu.folderId)} > Rename </button> ) : null} {onFolderDelete ? ( <button type="button" role="menuitem" className="is-danger" onClick={() => { onFolderDelete(folderMenu.folderId); setFolderMenu(null); }} > Delete folder </button> ) : null} </> )} </AnchoredOverlay> ) : null} </div> </> ); } /** * 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<string, unknown>) : 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<string, string>()); 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<DeletedItem>).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<DisplayMode | null>(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<HTMLElement | null>(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<string | null>(null); const [name, setName] = useState(""); const [menu, setMenu] = useState<{ viewId: string; anchor: HTMLElement; } | null>(null); const [renamingId, setRenamingId] = useState<string | null>(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<string[]>([]); 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<readonly string[]>([]); /** * ⭐ 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<HTMLElement | null>(null); const [trashAnchor, setTrashAnchor] = useState<HTMLElement | null>(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 ? ( <button type="button" className="cg-view-more" style={{ opacity: 1 }} aria-label="Database actions" aria-haspopup="menu" aria-expanded={!!databaseMenu} onClick={(event) => { // β›” THE ANCHOR IS HOISTED OUT OF THE UPDATER, like every other menu in this file: React // nulls `event.currentTarget` when the handler returns and may re-invoke a functional // updater afterwards, which is the white-screen defect recorded at the view row's "…". const anchor = event.currentTarget; // The panel is dismissed on every press of this control, so the menu can never stack on // top of a panel that came out of the same button. setTrashAnchor(null); setDatabaseMenu((current) => (current ? null : anchor)); }} > Β·Β·Β· </button> ) : 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<string | null>(null); const [creatingFolder, setCreatingFolder] = useState(false); const [folderAnchor, setFolderAnchor] = useState<HTMLElement | null>(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<string | null>(null); const [confirmDelete, setConfirmDelete] = useState<string | null>(null); const [addTarget, setAddTarget] = useState<string | null>(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<HTMLElement | null>(null); const [addName, setAddName] = useState(""); const [dropTarget, setDropTarget] = useState<string | null>(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<boolean>(() => { 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<HTMLElement | null>(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<string | null>(null); const [foldOver, setFoldOver] = useState<string | null>(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<string | null>(null); const [viewOver, setViewOver] = useState<string | null>(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<string>(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<string>; 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<HTMLElement>) => { if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return; const items = [ ...event.currentTarget.querySelectorAll<HTMLButtonElement>('[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 ( <> <PathBackButton disabled={place ? !place.canBack : !canViewBack && atId === null && !canDataBack} onClick={place ? place.back : () => { // 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(); }} /> <PathForwardButton disabled={place ? !place.canForward : !canViewForward} onClick={place ? place.forward : () => stepViewLevel(1)} /> <span className="cg-rail-name" aria-current="page" title={name}>{name}</span> {!place && databaseActions ? <span className="cg-rail-menu">{databaseActions}</span> : 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"). */} <div className="cg-views-top"> {!folded && railPlace(path)} <button type="button" className="cg-rail-toggle" aria-label={folded ? "Expand views" : "Minimize views"} aria-expanded={!folded} title={folded ? "Expand views" : "Minimize views"} onClick={narrow ? () => setNarrowOpen((open) => !open) : toggleRail} > <PanelToggleIcon open={!folded} /> </button> {/* 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 && ( <button type="button" className={"cg-chat-toggle" + (chatOpen ? " is-on" : "")} aria-label={chatOpen ? "Close the chat about this data" : "Ask about this data"} aria-expanded={chatOpen} title={chatOpen ? "Close the chat about this data" : "Ask about this data"} onClick={onToggleChat} > <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"> <path d="M13.4 9.2c0 1.5-1.3 2.7-2.9 2.7H6.9l-3 2.1v-2.3a2.8 2.8 0 0 1-1.3-2.3V5.1c0-1.5 1.3-2.7 2.9-2.7h5c1.6 0 2.9 1.2 2.9 2.7z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" /> <path d="M5.9 7.2h4.2" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" /> </svg> </button> )} {/* β›”β›” 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. */} </div> </> ); return ( <> <aside ref={setRailEl} className={"cg-views" + (folded ? " is-collapsed" : "") + (folded && headerSlot ? " is-header-folded" : "") + (narrow && narrowOpen ? " is-narrow-open" : "")} aria-label={databases.length ? "Record and View navigation" : "Views"} > <DataDatabaseNavigator databases={databases} activeDatabaseKey={activeDatabaseKey} folders={databaseFolders} onSelect={onSelectDatabase} onMove={onDatabaseMove} onFolderRename={onDatabaseFolderRename} onFolderDelete={onDatabaseFolderDelete} renderActions={renderDatabaseActions} createControl={databaseCreateControl} hosted={hosted} header={railHeader} > {() => ( <> {/* A live view search states its scope. The header keeps the place name and the "…" menu. */} {viewNeedle ? ( <div className="cg-fold-empty" data-view-folder-path> Showing matches in every folder </div> ) : null} {/* I14 β€” "+ Create new…", left-aligned, opening a flyout to the RIGHT of the rail that lists every creatable view type AND "Folder". Wave-10 item 12: the second door β€” a separate "+ New folder" link that used to sit directly under this one β€” is DELETED. It was a duplicate of the flyout's own Folder row, so the rail offered two controls that did the same thing. `startFolder()` still has exactly one caller (the flyout row); only the redundant entry point is gone. ⚠ wave17 R1 β€” the reason `.cg-fold-new` was kept has EXPIRED. It survived wave 10 because `CohortSidebar.tsx` rendered its own "+ New folder" under that class and had no create-flyout to fold it into; that file is deleted this wave, so the class now has no consumer in this tree. Left in index.css rather than swept blind: a CSS rule with no consumer is inert, and hunting one down mid-wave is how a rule something else still reads gets removed. Named here so the sweep is a decision, not a discovery. ⭐⭐ WAVE 47 T10 (owner instruction 1) β€” `cg-link-btn cg-create-btn` AND THE TWO SPANS BELOW ARE NOW READ BY A SECOND CALL SITE. The owner walked from a database into a folder path and saw one job in two treatments, and named THIS one as the keeper. So `shell/NavExtras.tsx::CreateNewRow` β€” the door the data layer mounts through `createControl`, one level up in this same rail β€” renders exactly this markup instead of its old `.shell-newfolder` register. β›” CONSEQUENCE FOR ANY LATER EDIT HERE: these class names are a shared contract now, not private to this button. Changing the treatment means changing both call sites, and moving it to a local class re-opens the drift the owner reported. */} {!folderReadOnly && <div className="cg-create-new"> <button type="button" className="cg-link-btn cg-create-btn" disabled={readOnly} aria-haspopup="menu" aria-expanded={!!createMenu} onClick={(event) => { // β›” THE ANCHOR IS HOISTED OUT OF THE UPDATER β€” the same line that took the whole // app white from the view row's "…" (see the long note at that button). React // nulls `event.currentTarget` when the handler returns and may re-invoke a // functional updater afterwards, so `setCreateMenu(cur => … event.currentTarget)` // can store null. Item 20 made this panel outlive a single click β€” it now carries // the name step too β€” so a randomly-nulled anchor would close a form mid-typing // rather than merely mis-place a menu. const anchor = event.currentTarget; if (createMenu) { closeCreate(); return; } // Every open starts at the type chooser: `creating` left set by an abandoned // flyout would re-enter at step 2 for a kind nobody just picked. setCreating(null); // W50-T11 β€” and at NO destination. This door means "here", which `create()` reads // off `atId`; a folder left over from the "…" menu would file the view somewhere // the user is not standing. setCreateInto(null); setCreateMenu(anchor); }} > <span className="cg-create-icon" aria-hidden="true">+</span> <span className="cg-create-label">Create new…</span> </button> </div>} {/* Owner item 9 β€” "Find a view". Borderless on the white rail (no box until it is being used); focus paints the brand-purple outline. Clearing the query restores the full rail β€” filtering never persists. */} <div className="cg-find-view"> <svg className="cg-find-view-icon" width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true" > <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" /> <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" /> </svg> {/* W46-T04 - the PLACEHOLDER reads "Find…" so this box and the data layer's twin are the same control to the eye; the ACCESSIBLE NAME stays "Find a view", because a screen reader gets no layer context from three dots and because `verify_w45_data_applications.py` indexes on that exact literal. */} <input type="text" value={viewQuery} placeholder="Find…" aria-label="Find a view" onChange={(event) => setViewQuery(event.target.value)} onKeyDown={(event) => { if (event.key === "Escape") setViewQuery(""); }} /> </div> {/* β›” WAVE 20 item 20 β€” THE CREATE FORM NO LONGER RENDERS HERE. It is the flyout's second step, inside the same `AnchoredOverlay` (below, next to the type list it follows). This comment stands in for the moved markup because the move IS the item: two steps of one action that used to appear in two different places. */} {foldersOn && onFolderCreate && creatingFolder && ( <FolderNameDialog anchor={folderAnchor} title={folderDest.into && folders?.find((folder) => folder.id === folderDest.into) ? `New folder in ${folders.find((folder) => folder.id === folderDest.into)!.name}` : "New folder"} siblingNames={(folders ?? []).filter((folder) => (nesting.parent[folder.id] ?? null) === folderDest.into).map((folder) => folder.name)} onSubmit={createFolder} onDismiss={() => { setCreatingFolder(false); setFolderAnchor(null); setFolderParent(null); }} /> )} {/* I14 β€” the flyout. To the RIGHT (placement right-start), every creatable view type with its own pastel mark, and Folder LAST behind a separator: it is not a view, and the owner put it at the bottom of the list rather than among them. */} {createMenu && ( <AnchoredOverlay anchor={createMenu} className="cg-view-menu cg-create-flyout" placement="right-start" // WAVE 20 item 20 β€” ONE panel, two contents. A menu of choices and a form are // different KINDS of thing to a screen reader even when they are one box to the // eye, so the role and the label follow the step rather than being frozen at the // panel's first purpose. role={creating ? "dialog" : "menu"} ariaLabel={ creating ? `New ${MODE_LABELS[creating].toLowerCase()} view` : "Create new" } onDismiss={closeCreate} // β›” THE ARROW-KEY HANDLER IS STEP 1's ONLY. `onMenuKeyDown` swallows // ArrowUp/ArrowDown to walk `[role=menuitem]`; over a text input that is the // cursor keys refusing to move through what you just typed. {...(creating ? {} : { onKeyDown: onMenuKeyDown })} dataKind={creating ? "create-new-name" : "create-new"} > {creating ? ( <div className="cg-view-create cg-create-form"> <label htmlFor="cg-new-view"> {/* The prompt NAMES the kind picked one step ago β€” the panel replaced its own contents, so without this the box gives no sign that "Calendar" was ever chosen. */} New {MODE_LABELS[creating].toLowerCase()} view </label> <input id="cg-new-view" className="cg-input" autoFocus // The overlay's own initial-focus effect fires on MOUNT, and this panel does // not re-mount between the two steps β€” so the input carries `autoFocus` (React // focuses it when it mounts) and the marker the other in-panel forms use. data-overlay-autofocus value={name} placeholder="e.g. Florida at risk" onChange={(event) => setName(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") create(); // Escape is handled by the overlay layer too; both mean "abandon", and // calling the same closer twice is idempotent. if (event.key === "Escape") closeCreate(); }} /> <p className="cg-create-share-note"> This view starts private. After you create it, use Share view to choose who can view or edit it. </p> <div className="cg-form-actions"> <button type="button" className="cg-btn cg-btn--primary" onClick={create} disabled={!name.trim()} > Create </button> <button type="button" className="cg-btn" onClick={closeCreate}> Cancel </button> </div> </div> ) : ( <> {/** * ⭐⭐ WAVE 41 Β· T39 (instruction 5) β€” FOLDER IS THE FIRST ROW, ABOVE GRID VIEW. * * Owner: *"In '+ Create new', Folder goes to the top, above Grid view."* Grid view * is `CREATABLE_MODES[0]`, so "above Grid view" is above the WHOLE map, not a * position inside it. * * β›” THE ROSTER IS NOT REORDERED, and that is the point of moving the JSX instead. * `CREATABLE_MODES` is the one list `verify_icons.py` pins by exact join, the mode * dropdown reads for its column order, and `icons.test.ts` compares against * `aios_grid.py::DISPLAY_MODES`. Folder is not a display mode at all β€” it has no * entry there to move β€” so the reading order of this ONE flyout is a fact about * this flyout, and it belongs here. * * ⚠ THE SEPARATOR TRAVELS WITH THE ROW, inside the same gate, and it now sits * BELOW Folder rather than above it. Left where it was it would have been the * flyout's first child, drawing a rule against the top edge whenever folders are * off; kept inside the fragment it cannot orphan, because the only thing that can * render it is the row it divides. */} {foldersOn && onFolderCreate && ( <> <button type="button" role="menuitem" className="cg-create-row" onClick={() => startFolder()} > <FolderMark size={16} /> <span>Folder</span> </button> <div className="cg-menu-sep" role="separator" aria-hidden /> </> )} {CREATABLE_MODES.map((mode) => ( <button key={mode} type="button" role="menuitem" className="cg-create-row" /* ⭐ W50-T11 β€” the destination the flyout was OPENED with. `null` from the rail's own "+ Create new…" door (it clears `createInto`), so this call is byte-equivalent to the shipped `startView(mode)` on that path; the folder "…" menu's "New view in folder" is the caller that supplies a folder id. */ onClick={() => startView(mode, createInto)} > {/* size 16 β€” item 13's "bigger icons", and the SAME 16 the view rows use, so a Calendar is one mark at one size on this whole surface. */} <ToneModeIcon mode={mode} tone={MODE_TONE[mode]} size={16} /> <span>{MODE_LABELS[mode]}</span> </button> ))} </> )} </AnchoredOverlay> )} <div className="cg-view-list cg-views-scroll"> {/** * ⭐⭐ W50-T11 / D-592 β€” WHILE `/workspace` IS IN FLIGHT THE RAIL DRAWS A SKELETON, NOT * AN EMPTY LIST. * * β›” THE EMPTY LIST IS A CLAIM, AND IT WAS BEING MADE BEFORE THE ANSWER ARRIVED. * `views` is `[]` both before `/workspace` answers and when a database genuinely has no * saved views, and the rail rendered the same nothing for both. On a cold container or a * degraded database that window has been measured in MINUTES, so "this database has no * views" was the whole experience rather than one frame of it. * * β›” AND ONLY WHILE THERE IS NOTHING TO SHOW (`views.length === 0`). A re-read triggered * by a write must not blank a populated rail β€” `useCustomerData.ts::reread` holds exactly * that line for the payload ("absent stays absent β€” never blank a live panel"), and a * skeleton painted over rows the user is reading would break it from the other side. * * ⚠ IT BORROWS THE SHELL'S OWN SKELETON CLASSES, deliberately, and this rail adds no * stylesheet of its own for it. `shell/navExtras.css` declares `.shell-rail-skeleton*` * UNSCOPED (only the `.shell-nav.is-rail-loading > *` hider is scoped to the nav), so the * marks paint here unchanged β€” and a second, near-identical `cg-` skeleton beside it is * how the two navigation rails start looking like two products. */} {loading && views.length === 0 ? ( <div className="shell-rail-skeleton" role="status" aria-label="Loading views"> {[0, 1, 2, 3, 4].map((row) => ( <div className="shell-rail-skeleton-row" key={row} aria-hidden="true"> <span className="shell-rail-skeleton-mark" /> <span className="shell-rail-skeleton-bar" /> </div> ))} </div> ) : null} {levelGroups.rows.map((group) => { const gid = group.folder?.id ?? null; /** * ⭐⭐ WAVE 41 Β· T33 (instruction 12, R1) β€” HOW DEEP THIS FOLDER SITS, AND WHETHER IT * SHOWS AT ALL. * * ⚠ A SYNTHETIC GROUP HAS NO ENTRY IN `nesting` and must not acquire one: `__shared__` * and every `__sharedfld__:` group are a reading of the view list, not records, so they * fall to level 1 and to "not hidden" β€” which is exactly where they rendered before this * ticket. The same is true of both `folder: null` groups. */ const asLeaves = isLeafGroup(group); /** * ⭐⭐ WAVE 40 Β· T28 (owner instruction 30) β€” THE PIN GROUP: the unfiled default views, * rendered above every folder. * * β›” IT IS A SECOND `folder: null` GROUP, so every expression below that reads * `gid ?? "__root__"` now has TWO groups answering to it and each one has to be told * which it is. That is not cosmetic: `dropTarget`, `foldOver` and `viewDrag` all * compare against that same fallback string, so leaving them alone would paint the * drop fill and the folder insertion rule on THIS section every time the user hovered * the real ungrouped section below it β€” one hover, two highlights, and only one of them * is where the item would land. * * ⚠ SO `isRoot` EXCLUDES IT, and that is the load-bearing line. `isRoot` is what grants * the drag-time drop AREA (`is-viewdrop`), and there must be exactly ONE of those: it is * the surface a user drops the default view onto to move it down, and a second one that * files it right back where it started would make the gesture unreachable. */ const isPinnedGroup = group.pinned === true; const isRoot = gid === null && !isPinnedGroup; /** * ⭐ WAVE 21 item 9 (R12/C1) β€” "Shared with me" IS NOT A STORED FOLDER, and every * folder affordance below has to know it. * * The group is synthesised from `shared: true` views (`folders.ts`), so there is no * record behind it: a drop would emit `item_move(viewId, "__shared__")` and persist * a folderId naming a folder that does not exist, and a folder-drag would send an * order containing an id `reorderFolderIds` was never given. Both write nonsense the * server would store. The row menu was already suppressed for this id in wave 20; * the DRAG surfaces were not, because nothing ever constructed the group. */ // ⭐ W34-T25 (R11): `isSyntheticFolderId`, NOT `=== SHARED_FOLDER_ID`. There is more than // one synthesised group now (one per shared FOLDER), and a rail that suppressed writes on // "Shared with me" while offering them on a colleague's folder would emit `item_move` / // `folder_rename` / `folder_delete` against an id that exists in nobody's store. const isSynthetic = isSyntheticFolderId(gid); // C1 injects this system-owned folder into the ordinary folder list. It remains // readable and expandable, but no generic rename, move, delete, or menu control is // offered for it. Keep the additive wire fact local until its broader type owner lands. const isManaged = (group.folder as (GridFolder & { managedBy?: "loopable" }) | undefined)?.managedBy === "loopable"; const isLevelFolder = asLeaves && gid !== null && !isSynthetic && !viewNeedle; return ( <div /* ⭐ W40-T28 β€” a key of its own. Both this group and the ungrouped section have a null folder, so the old `gid ?? "__root__"` would give React two children with the same key and it would reconcile one over the other. */ key={isPinnedGroup ? "__pinned__" : gid ?? "__root__"} /** * ⭐⭐ W47-T12 β€” WHICH OF THE TWO THINGS THIS DROP WOULD DO, in a word, on the element. * * β›” AN ATTRIBUTE RATHER THAN A THIRD CLASS, and the reason is a fence rather than a * preference: this ticket may not add a CSS rule, so a class nothing styles would be * invisible and a class something styles would need that rule. The two PICTURES are * `.is-drop` (nest) and `.is-drop-above` (reorder), which already exist; this says the * same thing in a form a person driving the gesture, or a headless check, can read * without measuring pixels β€” including the one state that paints NOTHING on purpose, * `refused`, which is otherwise indistinguishable from the app not noticing the pointer. * * ⚠ ABSENT unless a folder drag is actually in flight, so the idle rail's DOM is * byte-identical to the pre-T12 one. */ data-fold-drop={ foldDrag === null ? undefined : foldNest && foldNest.id === gid ? (foldNest.ok ? "nest" : "refused") : !isPinnedGroup && foldOver === (gid ?? "__root__") && foldDrag !== gid ? "before" : undefined } /** * ⭐⭐ WAVE 41 Β· T33 (instruction 12) β€” A NESTED FOLDER IS THIS ROW, INDENTED. * * DESIGN.md Β§4: new nav joins the existing rhythm and never introduces a control * shape. 12px is not a new number either β€” it is the step `.cg-fold .cg-view-row` * already uses to set a view in from its folder head, so a folder inside a folder * lands exactly where a view inside a folder lands, one level on. * * ⚠ INLINE BECAUSE THE DEPTH IS DATA, not because the rail is short of a class. A * stylesheet would need one rule per level to a cap the model owns, and the two * numbers would then have to be kept equal by hand. */ className={ /* ⭐ W40-T28 β€” `gid === null`, not `isRoot`: the pin group wears the SAME class as the ungrouped section (no head, the rail's measured root indent) because it is the same shape of thing rendered in a different place. DESIGN.md Β§4 β€” this is an existing element joining the existing rhythm, not a new control shape. */ (asLeaves ? "cg-fold-root" : "cg-fold") + // ⭐⭐ W47-T12 β€” THE SECOND READER OF THIS FILL, and it is the same sentence. // `.is-drop` has meant "drop this INTO me" since wave 8 (index.css says so in as many // words); a folder about to be nested is that sentence with a folder in it, so the // rail gains a meaning without gaining a vocabulary. `foldNest.ok` gates it: a target // `mayNestFolder` will refuse never lights up, it only records `data-fold-drop`. (!isPinnedGroup && (dropTarget === (gid ?? "__root__") || (!!foldNest && foldNest.ok && foldNest.id === gid)) ? " is-drop" : "") + // Item 19 β€” the insertion rule reads "the folder you are dragging lands HERE": // above this folder, or above the ungrouped section, which is after them all. (!isPinnedGroup && foldOver === (gid ?? "__root__") && foldDrag && foldDrag !== gid ? " is-drop-above" : "") + // β›” `foldDrag !== null` FIRST. `gid` is null for the UNGROUPED section and // `foldDrag` idles at null, so a bare `foldDrag === gid` is `null === null` β€” TRUE // from first paint, with no drag anywhere. The ungrouped section (which is where // most people's views live) rendered at `opacity: .45` permanently, and the symptom // is not "a folder looks dragged" but "my view NAMES are faded, as if hidden" β€” // which is why it read as a colour bug rather than a drag-state bug. // // The `is-drop-above` line above got this right (`&& foldDrag &&`), which is the // tell: two conditions written minutes apart, one guarded and one not. (!isPinnedGroup && foldDrag !== null && foldDrag === gid ? " is-folddrag" : "") + // ⭐⭐ WAVE 34 Β· T22 (ruling R4) β€” THE ROOT SECTION IS A DROP TARGET WITH NO PIXELS. // // β›” THIS IS THE HALF `D-249` DOES NOT NAME, and on its own it reproduces the owner's // whole report. `groupByFolder` ALWAYS pushes the root group, so a user who has filed // every view into folders gets `<div class="cg-fold-root">` with no head, no rows and // no min-height: a ZERO-PIXEL drop zone. The drag starts fine (that is B1's fix) and // there is physically nowhere to release it. Even a POPULATED root is barely better β€” // this element has no padding, so its box is exactly the union of its rows, and each // row's own `onDragOver` calls `stopPropagation` to claim the reorder gesture. The // only surface that ever meant "file at the top level" was the sliver between rows. // // So while a VIEW drag is in flight the root section is given real height and a real // strip below its last row (index.css `.cg-fold-root.is-viewdrop`). The hover paint is // the existing `.is-drop` rule: this ticket supplies the AREA, not a second vocabulary. // // ⚠ `viewDrag !== null` explicitly, never a bare truthiness test on a value that idles // at `null` beside a `gid` that is `null` for this very section β€” that is the // `foldDrag === gid` trap two lines up, which faded the whole ungrouped section // permanently once already. `isRoot` is a separate boolean, so the two cannot collide. (isRoot && viewDrag !== null ? " is-viewdrop" : "") + (isLevelFolder && viewDrag !== null ? " is-viewdrop" : "") } {/* No drop handlers on the synthetic group β€” see `isSynthetic`. Spreading `{}` rather than branching the element keeps ONE render path for every group. ⭐ W40-T28 β€” nor on the pin group, for a different reason: it is a READING of the view list ("these have no placement"), so a drop on it would emit `item_move(id, ROOT_FOLDER_ID)` β€” a stored placement, which is the very thing that takes a view OUT of this group. The drop would file the view and then move it somewhere else on screen. The ungrouped section below is the one root target. */ ...(isSynthetic || isManaged || isPinnedGroup ? {} : dropHandlers(gid))} > {group.folder && !asLeaves && ( <div className="cg-fold-head" // ── Item 19 β€” the folder itself is the drag handle ───────────────────── // Draggable only while it is renameable-idle: a `draggable` ancestor eats // the text selection inside an input, so dragging would win over editing // the name you just opened. draggable={ foldsReorderable && !isSynthetic && !isManaged && renamingFolder !== group.folder.id } onDragStart={(e) => { e.dataTransfer.setData(FOLD_DRAG_TYPE, group.folder!.id); e.dataTransfer.effectAllowed = "move"; setFoldDrag(group.folder!.id); }} onDragEnd={() => { setFoldDrag(null); setFoldOver(null); // ⭐ W47-T12 β€” the fork's own state joins the two it was modelled on. A drag // abandoned over a folder head would otherwise leave the "will nest" fill lit // with nothing being dragged. setFoldNest(null); }} /* ⭐⭐ W47-T12 β€” THE TWO-BAND FORK, on the head and only on the head. Spread LAST so it is unmistakable that these add `onDragOver` / `onDragLeave` / `onDrop` and replace none of the three handlers above: this element had no drop handlers at all before this ticket, which is why the group underneath could claim every folder drop as "land above me". β›” AND NOT ON A SYNTHESISED OR MANAGED HEAD, matching the group's own spread two dozen lines up. "Shared with me" and a colleague's shared folder are a READING of the view list with no record behind them, so a nest would emit `item_move` naming a parent that exists in nobody's store and a reorder would send an order carrying an id `reorderFolderIds` was never given. `mayNestFolder` refuses the first in words; the second has no such wall, so the gesture simply is not offered here. */ {...(isSynthetic || isManaged ? {} : foldHeadDropHandlers(group.folder.id))} > {/* β›” NO DRAG GRIP, and that is a decision rather than an omission. A grip in flow shifts the folder's name to the right, and this rail's indent is MEASURED to the pixel (index.css: "root view name 41.00px / folder header 48.36px" β€” the whole point of the wave-10 item-2 fix); the gutter it would otherwise hide in is already occupied by the disclosure chevron, whose open/shut state is the only one this row has. The view rows above have been draggable with no handle since wave 8, so a folder that drags the same way is the vocabulary this list already teaches, not a hidden feature. */} <button type="button" className="cg-fold-toggle" /** * ⚠ W41-T34 β€” THE CLICK IS READ OFF `shut`, THE STATE THE CHEVRON IS DRAWING, * not off membership of `opened`. * * With no search live the two are the same sentence and this behaves exactly as * the old symmetric toggle did. They come apart during a SEARCH, which shows * every folder open whatever `opened` holds: keyed on membership, clicking the * chevron of a folder the user had never opened would ADD it β€” the row would not * move, because the search is still forcing it open, and the folder would then be * open once the search cleared. The user pressed "close" and got "open", one * gesture later. Reading the drawn state makes the click mean what it looks like. */ aria-label={`Open folder ${group.folder.name}`} onClick={() => setAt(group.folder!.id)} > {/* size 16 β€” one mark box across the whole rail (view rows, flyout rows and now folder headers), which is what lets item 2's text alignment be exact rather than approximately right. */} <FolderMark size={16} /> {renamingFolder === group.folder.id ? ( <input className="cg-input cg-fold-rename" autoFocus defaultValue={group.folder.name} onClick={(e) => e.stopPropagation()} onBlur={(e) => { const v = e.target.value.trim(); if (v && v !== group.folder!.name) onFolderRename?.(group.folder!.id, v); setRenamingFolder(null); }} onKeyDown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); if (e.key === "Escape") setRenamingFolder(null); }} /> ) : ( <span className="cg-fold-name" /* ⭐ W34-T25 (R11) β€” WHOSE folder this is, on the folder itself. A synthesised shared-folder group looks exactly like one of the reader's own folders otherwise, and two people can share folders with the SAME NAME. The owner rides on every projected view (`_granted_views` stamps `owner`), so the group can answer it without a second wire field. Left as a `title` rather than painted into the name: the rail's indent is measured to the pixel and a second line here would push every view row. */ title={ isSynthetic && group.items[0]?.owner ? `Shared with you by ${group.items[0].owner}` : undefined } > {group.folder.name} </span> )} {/* β›” WAVE 20 item 21 β€” THE VIEW COUNT IS DELETED, and the item is not really about the number. `.cg-view-more` (the "…" beside this button) ships `opacity: 0` and is revealed by `.cg-view-row:hover`; a folder head is not a view row, so NO rule ever revealed it β€” the folder's actions button was painted at zero opacity in every state but keyboard focus. The badge is what the owner saw sitting where the control should have been. Deleting it and making the "…" unconditionally visible (one rule in this wave's S4 region) are the two halves of one fix. ⚠ `.cg-fold-count` in index.css now has no consumer in this tree. Left in place rather than swept blind β€” same posture as `.cg-fold-new` above β€” and booked in the S4 mailbox so the sweep is a decision, not a discovery. The NAV rail's own count stays: that rail reveals its "…" on hover already, so it never had this defect and item 21 never named it. */} </button> {/* β›” THE SYSTEM FOLDER HAS NO ACTIONS (item 18 / C-SHARE). "Shared with me" is not the reader's folder: it cannot be renamed into something else, duplicated into a second copy of other people's work, or deleted β€” the contract calls it undeletable, and a menu whose every row the server would refuse is three fake affordances rather than one. Views MOVE OUT of it normally (that is per-receiver placement), which is the only thing anyone needs to do to it. */} {/* ⭐ W34-T25 (R11) β€” widened from `=== SHARED_FOLDER_ID` to EVERY synthesised group, for the reason the block above gives: a colleague's shared folder is no more the reader's to rename, duplicate or delete than "Shared with me" is, and every row of that menu would be refused by a server that has no such folder. */} {folderReadOnly || isSynthetic || isManaged ? null : ( <button type="button" className="cg-view-more" aria-label={`Actions for folder ${group.folder.name}`} aria-haspopup="menu" onClick={(e) => { // β›” HOISTED OUT OF THE UPDATER β€” see the view menu's twin below. React // nulls `currentTarget` when the handler returns, and a functional // updater can be re-invoked AFTER that. const anchor = e.currentTarget; setFolderMenu((cur) => cur?.id === group.folder!.id ? null : { id: group.folder!.id, anchor } ); }} > Β·Β·Β· </button> )} </div> )} {asLeaves && group.items.map((view) => { const active = view.id === activeViewId; const renaming = renamingId === view.id; const mode = viewDisplayMode(view); // W40-T21 β€” resolved ONCE, here rather than inside the row's JSX. The badge slice below // is a bounded scan subject in `verify_grid_ux.py`, and a rule inlined there would grow // it for no benefit; the decision itself lives in `viewShareMark`. const shareMark = viewShareMark(view); // S85-T33 (D-233): the server emptied this view's filter for this reader. const scopedOut = viewScopedOutMark(view); return ( <div // Item 12 (C-LOCK) β€” `cg-view-lockset` marks a view locked to a cohort. The // rail is where someone chooses which table to open, and a locked view shows a // different row set than its siblings for a reason no filter states; the mark // is what makes that visible before the click rather than after it. className={ "cg-view-row" + (active ? " is-active" : "") + // W46-T02 - in the shift-selected range. Distinct from `is-active`, which says // "this is the table you are looking at" and can be true at the same time. (isRailSelected(view.id) ? " is-railsel" : "") + (viewDrag && isRailSelected(viewDrag) && railSelected.length > 1 && isRailSelected(view.id) ? " is-rail-multidrag" : "") + (view.config?.cohortLock ? " cg-view-lockset" : "") + (view.assigned ? " cg-view-lockset" : "") + // ⭐ ITEM 5 (C7) β€” the same two marks the folder drag uses: the row being // carried fades, and the row it would land ABOVE draws an insertion rule. (viewDrag === view.id ? " is-viewdrag" : "") + (viewOver === view.id && viewDrag && viewDrag !== view.id ? " is-drop-above" : "") } key={view.id} // S85-T33 (D-249, R30): `types.ts::mayFileView`, NOT `mayEditView`, and this is // its only call site. A read-only share must be able to begin a drag, because // filing writes only this viewer's placement. draggable={(foldersOn || viewsReorderable) && !renaming && mayFileView(view, viewer)} onDragStart={(e) => { // β›” TWO TYPES ON ONE DRAG, and that is the discrimination C7 asks for. // `text/plain` is the FILE-INTO-A-FOLDER channel the folder groups already // listen on and must keep working; `VIEW_DRAG_TYPE` is what a view ROW listens // for. Sharing one channel would make a reorder look like a file-into to // whichever handler fired first β€” the same collision `FOLD_DRAG_TYPE` exists to // prevent one level up. e.dataTransfer.setData("text/plain", view.id); e.dataTransfer.setData(VIEW_DRAG_TYPE, view.id); if (isRailSelected(view.id) && railSelected.length > 1) { e.dataTransfer.setData(VIEW_SET_DRAG_TYPE, JSON.stringify(railSelected)); } e.dataTransfer.effectAllowed = "move"; setViewDrag(view.id); }} // ⚠ A DRAG THAT ENDS ANYWHERE clears the marks. Without this, releasing over a // non-drop target leaves the row faded and an insertion rule painted, and the // rail looks stuck mid-gesture until the next render happens to clear it. onDragEnd={() => { setViewDrag(null); setViewOver(null); }} {...viewDropHandlers(view.id)} > {renaming ? ( <input className="cg-view-rename cg-input" autoFocus /* ⭐⭐ W40-T28 β€” THE BOX OPENS ON WHAT THE ROW SAYS, AND THE NO-OP TEST READS THE SAME STRING. Seeding this from `view.name` while the row reads "Default view" would show the user a name they have never seen; worse, the guard below would then compare their untouched "Default view" against the stored "All customers", call it a change, and PERSIST it β€” after which the name is no longer the host's mint and `viewDisplayName` stops resolving it. Opening rename and pressing Enter would permanently defeat the display rule. */ defaultValue={viewDisplayName(view)} onBlur={(event) => { const next = event.target.value.trim(); if (next && next !== viewDisplayName(view)) onRename(view.id, next); setRenamingId(null); }} onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); if (event.key === "Escape") setRenamingId(null); }} /> ) : ( <button type="button" className="cg-view-main" // Selection gestures stay in the rail; only a plain click opens the view. onClick={(event) => { selectRailRow(view.id, { shiftKey: event.shiftKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, }); setRailDeleteArmed(false); setRailLeftInPlace([]); if (!event.shiftKey && !event.ctrlKey && !event.metaKey) onSelect(view.id); }} // Item 9 kept this tooltip rather than dropping it as redundant: BOTH lines // ellipsis at 188px, so the hover is now the only way to read either one in // full. It used to show the note INSTEAD of the name, which meant a // described view could not have its own truncated name revealed at all. title={view.note ? `${viewDisplayName(view)}: ${view.note}` : viewDisplayName(view)} > {/* I12 β€” the row wears the view's CURRENT display mode, not a kind dot. Same geometry the mode switcher and the create flyout use, so "what Calendar looks like" is one drawing everywhere on this surface. Wave-10 item 3 β€” and now the same PAINT, not just the same geometry. The flyout has always drawn these marks in pastel (`ToneModeIcon`); the list drew the bare `ModeIcon` and index.css forced `--lp-muted` over it, so a view created as a blue Grid or a yellow Calendar landed in the rail GREY. There is no per-view "creation colour" to restore β€” `MODE_TONE` is a static modeβ†’tone map, never a persisted field (amendment A-1) β€” so painting the current mode's tone here reproduces what the flyout showed, by construction. */} <ToneModeIcon mode={mode} tone={MODE_TONE[mode]} size={16} /> {/* Wave-10 item 9 β€” name, then the description as a quiet second line. Wrapped in one column so the icon and the lock stay on the ROW axis while the text stacks; without the wrapper the note would become a third flex sibling and sit beside the name. Both lines ellipsis rather than wrap: a rail this narrow turns a wrapped sentence into a four-line row and the list stops being scannable. */} <span className="cg-view-text"> <span className="cg-view-name">{viewDisplayName(view)}</span> {view.assigned ? <span className="cg-view-desc">Assigned filter locked</span> : null} {view.note && ( <span className="cg-view-desc">{view.note}</span> )} </span> {/* ⭐ WAVE 27 Β· OWNER ITEM 21 / RULING R14 β€” ALERT ON = BADGE ON. The LIVE number of records matching this view's filter, in the red accent, shown for exactly the views that carry an alert. Deleting the alert removes it, because the badge is not stored anywhere β€” it is a rendering of `alertCounts`, which is keyed by the alerts the server lists. β›” OUTSIDE `.cg-view-text`, deliberately. That element is the ellipsising COLUMN holding the name over its description; a badge inside it becomes part of the run that gets cut off, so the one number the user asked to always see is the first thing to disappear on a long name. On the row axis it takes its width first and the NAME ellipsises around it β€” which is the correct priority and what the 188px budget is for. */} {alertCounts[view.id] !== undefined && ( <span className="cg-view-count" // ⭐ WAVE 32 Β· T24 (R5) β€” ONE badge, TWO reasons it can be here, and the // hover has to say WHICH. A view marked important shows the identical red // pill as an alerted one (deliberately β€” R5 asks for the same number in the // same place), so a single sentence about alerting would tell a reader who // marked a view that they had created an alert they did not create. The // number is the same fact; the promise attached to it is not. // ⭐ W35-T26 (R4): the word on screen is STAR. The stored key is still // `config.important` β€” R4 makes them ONE flag, so renaming the key would // create the second store the ruling forbids. title={ view.config?.important ? `${alertCounts[view.id].toLocaleString()} records match this view. ` + `You starred it.` : `${alertCounts[view.id].toLocaleString()} records match this ` + `view. You are alerted when a new one arrives.` } > {alertCounts[view.id].toLocaleString()} </span> )} {/* ⭐⭐ WAVE 33 Β· T14 (D-205) β€” THE ROW SAYS WHY THERE IS NO NUMBER. β›” The badge above is switched off on a server-windowed grid and on a view whose measure the server has not answered β€” both correct (the browser holds ONE window; a count from it would be a page's size wearing a scope's name), and both previously SILENT. An absent badge and "nothing matches" read the same, on exactly the big Odoo grids the owner has been chasing. ⭐ R6's second sentence is the rule: a limit that cannot be removed must be REPORTED with its cause. So the mark stays visible and carries the sentence instead of a number β€” never an invented count. ⚠ Mutually exclusive with the badge by construction (`alertCounts` is checked first), so a row can never wear both a count and an excuse. */} {alertCounts[view.id] === undefined && countNotes?.[view.id] && ( <span className="cg-view-count is-unknown" title={countNotes[view.id]} aria-label={countNotes[view.id]} > {/* ⚠ W34-T26 (R6): an ASCII hyphen, not the EN DASH this shipped with. The en dash is exactly the character the standing rule bans from copy that reaches a screen, and `web_prose` CANNOT SEE IT: its JSX pass requires the text run to contain no newline, and this span has enough attributes that Prettier puts the closing `>` on its own line. Reported to A in mailbox C-3 as a structural hole rather than worked around silently. ⭐ It is also what makes T20's header badge and this one ONE mark rather than two that merely claim to match. */} - </span> )} {/* ⭐ wave17 R1 / C-LOCKV β€” ONE mark, TWO meanings, and they are genuinely different things that both read as "locked": Β· `kind === "locked"` β€” the view's ROWS are a hand-curated set. This is what the retired Cohorts section used to say, and it is the more consequential of the two: it explains why this view shows fewer records than its siblings, which no filter chip accounts for. Β· `isModeFrozen` β€” the view's DISPLAY MODE is frozen (the legacy `locked` flag). It says nothing about which rows are here. A locked view does NOT get the legacy flag set (the host's projection says so explicitly), so most rows have exactly one reason. When a row has both, the row-set meaning leads and the title carries the other β€” never two padlocks side by side, which would read as a bug. */} {/* ⭐ WAVE 20 item 23 (C-SHARE) β€” THE SECOND MARK, beside the padlock and never instead of it. They answer different questions: the lock says what this view may become, this says how it got to you. A view someone shared with you is one you can be looking at without having made it β€” the single most useful thing the rail can tell you before the click. ⚠ WAVE 21 (item 9, R12/C1): the narrowed cast this used to need is gone β€” `shared`, `sharedRole` and `owner` are declared on `SavedView` and the server now projects them. The mark also says WHICH GRANT: a read-only share and an editable one look identical in the rail otherwise, and the reader's first question on finding a menu with no Rename in it is why. ⭐⭐ W40-T21 (owner instruction 2 / C1) β€” AND IT IS THE SAME MARK IN BOTH ACCOUNTS NOW. Owner: *"A shared View must show the shared/collaborative icon in EVERY account, not only the recipient's."* One glyph, two sentences: the recipient's still names who shared it, the owner's reads as sharing OUT. Which one, and whether there is a mark at all, is `viewShareMark` β€” a pure exported function, so the rule can be executed rather than read off JSX. The geometry is `SHARE_SHAPE`, the ONE share drawing the grid header's canvas sprite paints too; this row used to hold a second copy of it. */} {shareMark ? ( <span className="cg-view-shared" role="img" aria-label={shareMark.ariaLabel} title={shareMark.title} > <ShareMark /> </span> ) : null} {(view.kind === "locked" || isModeFrozen(view)) && ( <span className="cg-view-lock" // Not aria-hidden: "this view is frozen" is information, and the row's // accessible name is the only place a non-sighted user can receive it. role="img" aria-label={ view.kind === "locked" ? `${viewDisplayName(view)}, a locked view` : `${MODE_LABELS[mode]} view, locked` } title={ view.kind === "locked" ? "Locked: this view shows only the records locked into it. " + "Filters, sorts and columns still narrow within them." + (isModeFrozen(view) ? ` It also stays a ${MODE_LABELS[mode].toLowerCase()}.` : "") : `Locked: this view stays a ${MODE_LABELS[ mode ].toLowerCase()}. Filters, sorts and columns are still editable.` } > <LockMark /> </span> )} {/* S85-T33 (D-233): the scoped-out cohort mark, last in the row. Inline style because index.css is outside this ticket; it copies `.cg-view-lock`, and a preceding mark already took the auto margin. */} {scopedOut ? ( <span className="cg-view-scopedout" role="img" aria-label={scopedOut.ariaLabel} title={scopedOut.title} style={{ flex: "0 0 auto", display: "inline-flex", alignItems: "center", marginLeft: shareMark || view.kind === "locked" || isModeFrozen(view) ? 0 : "auto", paddingLeft: 4, color: "var(--lp-muted)", }} > <ScopedOutMark /> </span> ) : null} </button> )} {!readOnly && <button type="button" className="cg-view-more" aria-label={`Actions for ${viewDisplayName(view)}`} aria-haspopup="menu" aria-expanded={menu?.viewId === view.id} onClick={(event) => { /** * β›” THE ANCHOR IS READ HERE, NOT INSIDE THE UPDATER β€” and that one line * is the difference between this rail working and the whole app going * white. Found by _qa_live_rail.py on 2026-08-04, reproduced on the * shipped build. * * React sets `event.currentTarget = null` the moment this handler * returns (`executeDispatch`'s finally). A FUNCTIONAL updater is not * guaranteed to run inside the handler: the eager-state path evaluates * it once, synchronously, while `currentTarget` is still the button β€” * but React re-invokes it when it processes the queue for real, and by * then it is null. The menu therefore opened correctly and only died * later, on a re-render triggered by something else entirely β€” which is * why a white screen appeared one interaction AFTER the click that * caused it. `AnchoredOverlay` then did `"getBoundingClientRect" in * null` and took the tree down with it. */ const anchor = event.currentTarget; /** * ⭐⭐ WAVE 41 Β· T38 (owner instruction 17) β€” ASK FOR A FRESHER ANSWER BEFORE * WITHHOLDING THE MENU'S EDIT ROWS. * * β›” THIS IS WHERE THE OWNER MEETS THE DEFECT. Rename, Description and Delete * are all gated on `canEditMenuView`, so a stale permission copy does not * refuse a rename, it removes the entry that starts one β€” *"will not let a * view be renamed until a refresh"*, exactly. `viewer` and every view's * `sharedRole` ride the payload, which is re-read only on a stale signal, and * nothing raises one on a timer. * * ⚠ ONLY ON THE NEGATIVE, which keeps this cheap and keeps it honest: a view * this reader can already edit needs no second opinion, so the extra * `/workspace` read happens on the minority of rows and only where the menu is * about to show less than it might. The menu stays open while the read lands, * so the rows appear under the user's cursor without a reload. */ if (!mayEditView(view, viewer)) signal(WORKSPACE_STALE_EVENT); setMenu((current) => current?.viewId === view.id ? null : { viewId: view.id, anchor } ); }} > Β·Β·Β· </button>} {/* Wave-10 item 9 inverted this: the description now renders HERE, on the row, and the across-the-table banner in CustomerGrid is gone. Still one place, not two β€” and now it is the place that names the view, and EVERY view shows its own, not just the active one. */} </div> ); })} {group.folder && asLeaves && group.items.length === 0 && levelGroups.heads.length === 0 && ( <div className="cg-fold-empty">Empty. Drag a view here.</div> )} </div> ); })} {/* ⭐ wave17 R1 / C-LOCKV β€” THE "COHORTS" SECTION IS GONE, and nothing replaced it here. Wave 15 projected each cohort as a transient row under its own heading, which made a locked view a second-class object: it could not be renamed, filed into a folder, reordered, sorted or shared, because it was not a view. R1: it IS a view. The host projects each one into the SAME list above (`locked_view_projection` β€” id preserved, `config.cohortLock` naming its own id), so every one of those capabilities arrives for free and this section has nothing left to render. The lock MARK moved onto the ordinary view row, where `kind === "locked"` drives it. */} </div> </> )} </DataDatabaseNavigator> {/* W46-T02 - The selection bar names the rendered selection and its bulk actions. β›” DELETE ASKS ONCE, AND THE ASK IS NOT DECORATION: there is no store history behind a deleted view, so the confirm is the only thing standing between a mis-shift and work that cannot be brought back. `onDelete` is called from the armed branch alone. */} {!readOnly && (railSelected.length > 0 || railLeftInPlace.length > 0) && ( <div className="cg-railsel" role="group" aria-label="Selected views"> {railSelected.length === 0 ? ( <button type="button" onClick={clearRailSel}>Dismiss</button> ) : railDeleteArmed ? ( <> <span className="cg-railsel-ask"> {railDeletable.length === 1 ? "Delete 1 view? This cannot be undone." : `Delete ${railDeletable.length} views? This cannot be undone.`} {railSelected.length > railDeletable.length && ` ${railSelected.length - railDeletable.length} of them cannot be deleted ` + `and will stay.`} </span> <button type="button" className="is-danger" onClick={() => { for (const view of railDeletable) onDelete(view.id); clearRailSel(); }} > Delete </button> <button type="button" onClick={() => setRailDeleteArmed(false)}> Keep them </button> </> ) : ( <> <span className="cg-railsel-count"> {railSelected.length === 1 ? "1 view selected" : `${railSelected.length} views selected`} </span> {onExportXlsxViews && ( <button type="button" disabled={railExportIds.length === 0} onClick={(event) => { // β›” HOISTED BEFORE THE setState, the scar the folder menu records above: // React nulls `currentTarget` once the handler returns. const anchor = event.currentTarget; // ONE export panel, not two: this opens the existing bulk pane with the // selection already ticked, so the formats, the 20-view cap and the tab // rule all stay where they were written. setExportViewIds([...railExportIds]); setExportBulk(true); setExportFor({ viewId: railExportIds[0], anchor }); }} > Export </button> )} {foldersOn && ( <button type="button" className="cg-railsel-move" onClick={(event) => { const anchor = event.currentTarget; setMoveFor({ viewId: railSelected[0], anchor, bulk: true }); }} > Move to folder </button> )} <button type="button" className="is-danger" disabled={railDeletable.length === 0} onClick={() => setRailDeleteArmed(true)} > Delete </button> </> )} {railMoveNotice && ( <span className="cg-railsel-left" role="status" title={railMoveNotice}> {railMoveNotice} </span> )} </div> )} {/* I11c β€” the folder "…" menu. Rename Β· Add to cohort Β· Duplicate Β· Delete. WAVE 20 item 22 β€” every row now carries the SAME icon vocabulary the view row's menu uses (`MenuLabel` over `MENU_ICONS`), and Delete is red AT REST rather than only once armed. Two menus that do the same kind of thing to two kinds of object were drawn in two registers: one with icons and a red delete, one with neither. ⚠ NO NEW CSS FOR THE COLOUR: this overlay already wears `cg-view-menu`, so adding `is-danger` to the button reuses `.cg-view-menu button.is-danger` β€” the exact rule that paints the view row's Delete, which is what "matching" has to mean. The `cg-menu-item--danger` class stays for its armed background. */} {folderMenu && folderMenuF && ( <AnchoredOverlay anchor={folderMenu.anchor} className="cg-view-menu" placement="bottom-end" role="menu" ariaLabel={`Actions for folder ${folderMenuF.name}`} onDismiss={() => { setFolderMenu(null); setConfirmDelete(null); }} dataKind="folder-menu" > {/* ⭐⭐ WAVE 41 Β· T33 (owner instruction 12, ruling R1) β€” A FOLDER INSIDE THIS FOLDER. β›” AND THE PLACE THE 11TH LEVEL IS REFUSED. DESIGN.md Β§4 asks for one short line stating the cap, put where the decision is made rather than on a landing pane β€” so the row states it IN ITS OWN LABEL and goes inert, which is the idiom the Delete row three items down already uses to say a whole sentence at the moment of the click. An enabled row that opened a form only to reject the name at the end would spend the user's typing to tell them something knowable before they started. */} {/* ⚠ `foldersOn` as well as the callback, matching the create PANE's own gate three hundred lines up. Without it a rail with the folder machinery switched off would offer a row whose pane never renders, and `nesting` (built from an empty list in that case) would answer every verdict with "that folder is no longer here". */} {/* ⭐⭐ W50-T11 (owner instruction 21, ruling R12) β€” NEW VIEW IN FOLDER. Owner, R12: *"The new-view door that leaves the view closed: the folder's `...` menu, New view in folder."* Before this row the folder menu could make a FOLDER inside a folder and nothing else, so the only way to put a view in a folder was to create it at the top level and then drag it β€” the gesture R13 reports as broken. β›” IT REUSES THE ONE CREATE FLYOUT rather than growing a second form. DESIGN Β§4, and the same sentence T33 wrote for "New folder inside": a view is made by the control that already makes views, pointed at a destination. So this row opens the SAME two-step panel the rail's own door opens β€” anchored on the folder's own "…" button, so the pane sits beside the folder it will file into β€” and hands the mode rows the destination through `createInto`. ⚠ NO `foldersOn` GATE OF ITS OWN and none is missing: this whole menu only renders for a stored folder, which cannot exist with the folder machinery off. */} <button type="button" role="menuitem" className="cg-menu-item" onClick={() => { // Step one, every time: a `creating` left set by an abandoned flyout would // re-enter at the name form for a kind nobody just picked. setCreating(null); setCreatingFolder(false); setCreateInto(folderMenuF.id); setCreateMenu(folderMenu.anchor); setFolderMenu(null); }} > <MenuLabel icon="addEnd" text="New view in folder" /> </button> {foldersOn && onFolderCreate && nestHere && ( <button type="button" role="menuitem" className="cg-menu-item" disabled={!nestHere.ok} title={nestHere.reason} onClick={() => { startFolder(folderMenuF.id); setFolderMenu(null); }} > <MenuLabel icon="addEnd" text={nestHere.ok ? "New folder inside" : nestHere.reason!} /> </button> )} <button type="button" role="menuitem" className="cg-menu-item" onClick={() => { setRenamingFolder(folderMenuF.id); setFolderMenu(null); }} > <MenuLabel icon="rename" text="Rename" /> </button> {/* ⭐⭐ WAVE 41 Β· T35 (owner instruction 11) β€” CHANGE ICON, BETWEEN RENAME AND DUPLICATE. The ticket asks for it there and "Add to cohort" already sat inside that span (C4 as amended 2026-07-28), so it goes DIRECTLY BELOW RENAME rather than displacing a shipped row: renaming a folder and remarking it are the same kind of edit to the same object, and the pair now reads as one block above the actions that COPY, SHARE or DELETE it. The ticket's ordering holds either way; this reading also groups. ⚠ THE ROW WEARS THE FOLDER'S OWN CURRENT MARK, passed as a NODE the way "Share folder" passes `ShareMark`. `MENU_ICONS` has no glyph for this and `icons.tsx` is not this ticket's to extend β€” but more to the point, the honest picture of "change this icon" IS this icon, and it makes the row say which mark is about to change. */} {folderAddPreview && onFolderAddToList && ( <button type="button" role="menuitem" className="cg-menu-item" onClick={() => { setAddTarget(folderMenuF.id); setAddAnchor(folderMenu.anchor); setAddName(today ? `${folderMenuF.name} Β· ${today}` : folderMenuF.name); setFolderMenu(null); }} > <MenuLabel icon="cohortAdd" text="Add to cohort" /> </button> )} {onFolderDuplicate && ( <button type="button" role="menuitem" className="cg-menu-item" onClick={() => { onFolderDuplicate(folderMenuF.id); setFolderMenu(null); }} > <MenuLabel icon="duplicate" text="Duplicate folder and its views" /> </button> )} {/* WAVE 20 item 18 (R10) β€” a folder shares, and its views ride along (the server's rule, stated in C-SHARE; this row only opens the editor). ⭐ W40-T21 (D-254) β€” THE PADLOCK IS GONE FROM THIS ROW. Sharing is not one of DESIGN.md Β§4's three locks, and Β§4 is explicit that "a surface painting one lock where another applies tells the user something false" β€” so the mark was false, not merely ambiguous. A `title` reading "this is access, not a lock" would have existed only to correct its own icon, which Β§4's "never over-explain" forbids: fix the mark and the sentence is unnecessary. Now it wears `SHARE_SHAPE`, the same drawing as the rail's share mark and the grid header's `aiosShared` sprite. Passed as a NODE, the way the Star and alert rows pass theirs, so a glyph no other menu row needs costs the shared `MENU_ICONS` vocabulary nothing. */} <button type="button" role="menuitem" className="cg-menu-item" onClick={() => { openShare("folder", folderMenuF.id, folderMenuF.name); setFolderMenu(null); }} > <MenuLabel icon={<ShareMark size={16} />} text="Share folder" /> </button> {onFolderDelete && ( <button type="button" role="menuitem" className={ "cg-menu-item cg-menu-item--danger is-danger" + (confirmDelete === folderMenuF.id ? " is-armed" : "") } onClick={() => { if (confirmDelete !== folderMenuF.id) { setConfirmDelete(folderMenuF.id); return; } onFolderDelete(folderMenuF.id); setConfirmDelete(null); setFolderMenu(null); }} > {/* The ARMED label is a whole sentence and the menu row is `nowrap` with a 260px ceiling, so it used to run out of the panel. It wraps while armed (one rule in the S4 region) rather than being ellipsised: a confirmation the reader cannot finish reading is not a confirmation. */} <MenuLabel icon="trash" text={ confirmDelete === folderMenuF.id ? "Delete folder? Its views move to the top level." : "Delete folder" } /> </button> )} </AnchoredOverlay> )} {moveFor && moveView && (() => { const currentId = moveFor.bulk ? undefined : folderIdOf ? folderIdOf(moveFor.viewId) : null; const fileInto = (folderId: string | null) => { if (moveFor.bulk) { moveRailViews(railSelected, folderId); setMoveFor(null); return; } // The `...` menu's Move to asks the same helper the drag does, BEFORE the emit, so // there is no placement to take back. A read-only share files here too (S85-T33). const refusal = viewMoveRefusal(moveView, viewer); if (refusal) { signal(TOAST_EVENT, refusal); setMoveFor(null); return; } onItemMove?.(moveFor.viewId, folderId ?? ROOT_FOLDER_ID); setMoveFor(null); }; return ( <AnchoredOverlay anchor={moveFor.anchor} className="cg-pop" placement="bottom-end" role="dialog" ariaLabel={moveFor.bulk ? "Move selected views to a folder" : `Move ${viewDisplayName(moveView)} to a folder`} onDismiss={() => setMoveFor(null)} dataKind="view-move-to" > <div className="cg-pop-title">Move to</div> <div className="cg-pop-list" data-full-folder-path-picker> <button type="button" className={ "cg-pick-row" + (currentId === null || currentId === ROOT_FOLDER_ID ? " is-on" : "") } onClick={() => fileInto(null)} > <FolderMark size={16} /> {databases.find((database) => database.key === activeDatabaseKey)?.label ?? "Database"} </button> {moveFolders.map((folder) => ( <button type="button" key={folder.id} className={"cg-pick-row" + (folder.id === currentId ? " is-on" : "")} style={{ paddingLeft: 6 + (nesting.depth[folder.id] ?? 0) * 12 }} title={folderPath(folder.id, moveFolders).map((part) => part.name).join(" / ")} onClick={() => fileInto(folder.id)} > <FolderMark size={16} /> {folder.name} </button> ))} {moveFolders.length === 0 ? ( <div className="cg-pop-note">There are no folders in this database yet.</div> ) : null} </div> </AnchoredOverlay> ); })()} {/* Item 12 (C-LOCK) β€” the lock picker. Lists the cohorts this reader can see, marks the current one, and offers Unlock when there is one: a lock removable only from somewhere other than where it was applied is a trap, and the owner asked for a feature, not a one-way door. */} {lockFor && onCohortLock && (() => { const target = views.find((v) => v.id === lockFor.viewId); const current = target?.config?.cohortLock; return ( <AnchoredOverlay anchor={lockFor.anchor} className="cg-pop cg-lock-pop" placement="bottom-start" role="dialog" ariaLabel="Lock this view to a locked view" onDismiss={() => setLockFor(null)} dataKind="view-cohort-lock" > <div className="cg-pop-title">Lock to a locked view</div> <div className="cg-pop-note"> This view can then only ever show the records locked into the view you pick. Filters still narrow within it, and the lock cannot be removed as a condition. </div> {(lists ?? []).map((l) => ( <button type="button" key={l.id} className={"cg-pick-row" + (l.id === current ? " is-on" : "")} onClick={() => { onCohortLock(lockFor.viewId, l.id); setLockFor(null); }} > {l.name} </button> ))} {current && ( <button type="button" className="cg-pick-row cg-lock-clear" onClick={() => { onCohortLock(lockFor.viewId, null); setLockFor(null); }} > Unlock and show the whole table again </button> )} </AnchoredOverlay> ); })()} {/* C4 as amended β€” the folder-level bulk add. The confirm pane states the DEDUPED union and names every view it could not compute, because a partial union that looks complete is the failure this pane exists to prevent ([[no-unverifiable-aggregates]]). */} {addTarget && addAnchor && addPreview && onFolderAddToList && ( <AnchoredOverlay anchor={addAnchor ?? undefined} className="cg-pop cg-fold-addpop" placement="bottom-start" role="dialog" ariaLabel="Add this folder's customers to a locked view" onDismiss={() => setAddTarget(null)} dataKind="folder-add-to-list" > <div className="cg-pop-title">Add to cohort</div> <div className="cg-pop-note"> {addPreview.pids.length.toLocaleString()} customer {addPreview.pids.length === 1 ? "" : "s"} from {addPreview.counted.toLocaleString()}{" "} view{addPreview.counted === 1 ? "" : "s"} in this folder, counted once each. </div> {addPreview.skipped.length > 0 && ( <div className="cg-pop-note cg-fold-skipped"> Not included: {addPreview.skipped.map((sk) => ( <span key={sk.name} className="cg-fold-skip"> {sk.name}: {sk.why} </span> ))} </div> )} {(lists ?? []).map((l) => ( <button type="button" key={l.id} className="cg-pick-row" onClick={() => { onFolderAddToList(addTarget, l.id, l.name); setAddTarget(null); }} > {l.name} </button> ))} <div className="cg-view-create"> <label htmlFor="cg-fold-new-list">Lock records into a new view</label> <input id="cg-fold-new-list" className="cg-input" data-overlay-autofocus value={addName} onChange={(e) => setAddName(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && addName.trim()) { onFolderAddToList(addTarget, "", addName.trim()); setAddTarget(null); } }} /> <button type="button" className="cg-btn cg-btn--primary" disabled={!addName.trim() || addPreview.pids.length === 0} onClick={() => { onFolderAddToList(addTarget, "", addName.trim()); setAddTarget(null); }} > Create and add </button> </div> </AnchoredOverlay> )} {menu && menuView && ( <AnchoredOverlay anchor={menu.anchor} className="cg-view-menu" placement="bottom-end" role="menu" ariaLabel={`Actions for ${viewDisplayName(menuView)}`} onDismiss={() => setMenu(null)} onKeyDown={onMenuKeyDown} dataKind="saved-view-menu" > {/* W2 (C2): Export sits ABOVE the rename/delete group, thin divider between. */} {(onExport || onExportXlsxViews || onImport) && ( <> {/* ⭐ WAVE-29 T32 (owner item 16 / R10) β€” the DATA group's header. The owner's complaint was that Export "looks like an orphan": it is already the FIRST row of this menu and the divider under it is the only one, but every row is styled identically, so the divider reads as a stray line rather than as the end of a group. A header names the group instead. β›” NOT A TOOLBAR BUTTON (R10) β€” a standalone Export was deliberately removed on 2026-08-03 so this menu is the ONE door; item 6's Import joins it here. ⚠ INLINE STYLE, and it is a fence decision rather than a preference: this menu has no group-header class anywhere in the stylesheet, and `index.css` belongs to another session this wave. Tokens only, so it cannot invent a colour. */} <div role="presentation" style={{ padding: "6px 10px 2px", fontSize: "10px", fontWeight: 600, letterSpacing: "0.02em", color: "var(--lp-muted)", }} > Data </div> {(onExport || onExportXlsxViews) && ( <button type="button" role="menuitem" onClick={() => { setExportFor({ viewId: menuView.id, anchor: menu.anchor }); setExportBulk(false); setExportViewIds([]); setMenu(null); }} > <MenuLabel icon="download" text="Export" /> </button> )} {/* ⭐ WAVE-29 T25 (owner item 6) β€” IMPORT, beside Export, because they are the same question in two directions and this menu is the ONE door for both (a standalone Export button was deliberately removed on 2026-08-03; a second Import entry anywhere else would re-open that). ⚠ Supplied only on an EDITABLE database β€” the host passes `undefined` when records are not mutable, which is what keeps the row off a locked one rather than a check repeated here. ⚠ `cohortAdd` is the nearest glyph the registry has; there is no upload mark and `icons.tsx` is not this session's to extend. */} {onImport && ( <button type="button" role="menuitem" onClick={() => { onImport(); setMenu(null); }} > <MenuLabel icon="upload" text="Import" /> </button> )} <div className="cg-menu-sep" role="separator" aria-hidden /> {/* …and the VIEW group's own header, so the divider now sits BETWEEN two named groups rather than under one lonely row. R10 asks for both names. */} <div role="presentation" style={{ padding: "2px 10px 2px", fontSize: "10px", fontWeight: 600, letterSpacing: "0.02em", color: "var(--lp-muted)", }} > View </div> </> )} {/* I17 (C4) β€” the view's IDENTITY (name, description, deletion) is what the view permission governs. Duplicate is deliberately NOT gated: making your own copy changes nothing about this view, and it is how someone without edit rights gets a version they can work in. β›” W34-T22 REMOVED "folder" FROM THAT LIST, and the removal is the point rather than a tidy-up. Filing a view writes a PLACEMENT into the reader's own workspace stratum and never touches the owner's object, so it is navigation rather than an identity edit; the drag site asks `mayFileView` now (`types.ts`) while every row below still asks `mayEditView`. Left as a correction rather than deleted, because a sentence three hundred lines from the code it describes is exactly the shape that went stale unnoticed here. */} {canEditMenuView && ( <button type="button" role="menuitem" onClick={() => { setRenamingId(menuView.id); setMenu(null); }} > <MenuLabel icon="rename" text="Rename" /> </button> )} {canEditMenuView && ( <button type="button" role="menuitem" onClick={() => { setNoteDraft(menuView.note ?? ""); setNoteFor({ viewId: menuView.id, anchor: menu.anchor }); setMenu(null); }} > <MenuLabel icon="description" text={menuView.note ? "Edit description" : "Add description"} /> </button> )} <button type="button" role="menuitem" onClick={() => { onDuplicate(menuView.id); setMenu(null); }} > <MenuLabel icon="duplicate" text="Duplicate" /> </button> {canFileMenuView && ( <button type="button" role="menuitem" onClick={() => { setMoveFor({ viewId: menuView.id, anchor: menu.anchor }); setMenu(null); }} > <MenuLabel icon={<FolderMark size={16} />} text="Move to" /> </button> )} {/* WAVE 20 items 23/26 (R10) β€” "who else can reach this view", the same editor a folder and a database open. Deliberately NOT gated on `canEditMenuView`: the server decides who may administer (owner or admin) and says so in the dialog, and hiding the row from everyone else would hide the ANSWER too β€” "who has this?" is a fair question for anyone the view was shared with. ⭐ W40-T21 (D-254) β€” THE PADLOCK IS GONE FROM THIS ROW TOO, for the reason spelled out on the Share folder row: sharing is none of DESIGN.md Β§4's three locks, so the padlock was a false mark rather than an ambiguous one, and correcting it in a `title` would have been Β§4's "never over-explain" instead of a fix. ⚠ `verify_wiring.py` (W39-T29) used to IDENTIFY this row by the whole `MenuLabel` literal, `icon=` included, while checking that this row is offered outside the edit-only predicate. That pinned the GLYPH as part of a row identity rather than as the claim; it is retargeted at the row's label alone in the same change [[a-gate-that-pins-a-spelling-not-a-claim]]. The label below must therefore keep its exact spelling, which `verify_icons`'s T23 leg pins as well. β›” AND IT IS NOT SPELLED OUT IN THIS COMMENT ON PURPOSE. Both gates read the row through `code_only`, which strips comments precisely so prose cannot answer a question asked about code; a note repeating the row's own identity verbatim is the string that would satisfy the scan if that stripping were ever weakened. */} {!menuView.assigned && ( <button type="button" role="menuitem" onClick={() => { openShare("view", menuView.id, viewDisplayName(menuView)); setMenu(null); }} > <MenuLabel icon={<ShareMark size={16} />} text="Share view" /> </button> )} {/* WAVE 20 item 25 (C-ALERT) β€” the door that MAKES an alert, on the view it watches. It belongs here and nowhere else: an alert IS "tell me when a record enters THIS view", so the only place the question has an obvious subject is the view's own menu. ⚠ The frame answers, because this rail does not know its own topic (it holds views; the scope key belongs to the route) β€” and because the server refuses a view with no active filter, which is a message the frame is already in the business of showing. */} {/* ⭐⭐ WAVE 32 Β· T24 (owner item 17, ruling R5, contract C4) β€” the one mark. β›” ABOVE the alert row, which is the done-when's own word and not a nicety: the two rows produce THE SAME red pill in the rail, and the cheap, private, instantly reversible one has to be reachable before the one that creates a stored server-side alert. Offered first, a user who only wanted to keep an eye on a number never has to make an alert to get one. β›” ONE MARK. W32-R5 is explicit: no second severity, no colour variants β€” `verify_icons` asserts the absence of a second one so it cannot arrive by copy-paste from this very row. The label FLIPS rather than the state being implied, because a "star this" label on an already-starred view reads as a label for the view. ⭐⭐ W35-T26 (owner item 9 / R4) β€” THE LABEL IS "STAR" NOW, AND ONLY THE LABEL. Owner: star and mark-important are ONE idea and ONE flag, and the word on screen is **Star**. So this pair reads Star / Unstar, the glyph was ALREADY a star (W33-T15), and the STORED key stays `config.important` β€” renaming the key would create exactly the second store R4 forbids, and would 400 every view already marked. ⚠ `verify_icons.py`'s T24 leg PINS these two strings and is A's file, so it reds on this rename until A retargets it at the CLAIM (one mark, above the alert row) rather than the spelling [[a-gate-that-pins-a-spelling-not-a-claim]]. Raised as `ASK C-10`. */} {onToggleImportant && ( <button type="button" role="menuitem" onClick={() => { onToggleImportant(menuView.id, !menuView.config?.important); setMenu(null); }} > {/* ⭐ WAVE 33 Β· T15 (D-206) β€” A STAR, NOT A PADLOCK. β›” This row shipped wearing MenuIcon `permissions` / `unlock` β€” a padlock that three other rows in these same menus ALSO wore, untitled. Marking a view important is none of the three locks (DESIGN.md Β§4): it freezes no record, no column and no row set. So the answer is to drop the lock, not to title it β€” a title naming a lock that does not exist would be believed. ⭐ W40-T21 (D-254) finished the job this row started: the two SHARE rows took the same treatment (sharing is not a lock either, so they wear the share glyph now), and "Lock to a locked view" β€” the one row of the four that really is a lock β€” keeps the padlock and names WHICH lock in its title. So the count in the sentence above is history, not a description of these menus today. ⚠ Passed as a NODE, exactly the way the alert row below passes `<BellIcon/>`: `MenuLabel` takes `MenuIconName | ReactNode`, so a glyph no other menu row needs costs the shared `MENU_ICONS` vocabulary nothing. ⚠ `filled` is what says the view IS marked, so the pair still reads mark/unmark. ⚠ `verify_icons`'s T24 leg pins this row's position above the alert row, which does not move here; W35-T26 changes only the two LABEL strings. */} <MenuLabel icon={<StarIcon size={16} filled={!!menuView.config?.important} />} text={menuView.config?.important ? "Unstar" : "Star"} /> </button> )} <button type="button" role="menuitem" onClick={() => { window.dispatchEvent( new CustomEvent("aios:alert-create", { detail: { viewId: menuView.id, label: viewDisplayName(menuView) }, }) ); setMenu(null); }} > <MenuLabel icon={<BellIcon size={16} />} text="Alert me about new records" /> </button> {/* ⭐ WAVE 21 item 11 (ruling R10) β€” "paste a list of names and tick those records". It belongs in the VIEW's menu because the view is what decides which records are on the table to be found, and the result says so. ⚠ IT SELECTS THE VIEW FIRST when this is not the active one. The dialog matches over the rows the grid currently holds, so offering it on a view nobody is looking at would tick records in a DIFFERENT view's row set and report misses against the wrong table. Switching first makes the menu's subject and the dialog's subject the same object β€” and it is what clicking the row would have done anyway. */} {onSelectFromFile && ( <button type="button" role="menuitem" onClick={() => { if (menuView.id !== activeViewId) onSelect(menuView.id); onSelectFromFile(); setMenu(null); }} > <MenuLabel icon="cohortAdd" text="Select from file" /> </button> )} {onAddToList && ( <button type="button" role="menuitem" onClick={() => { // Item 4: `<view name> Β· <today>`, today from the PAYLOAD verbatim. No date // when the host sent none β€” never the browser clock. setNewListName(today ? `${viewDisplayName(menuView)} Β· ${today}` : viewDisplayName(menuView)); setAddFor({ viewId: menuView.id, anchor: menu.anchor }); setMenu(null); }} > <MenuLabel icon="cohortAdd" text="Add to locked view" /> </button> )} {/* Item 12 (C-LOCK) β€” LOCK the view to a cohort. This menu is the ONLY emitter of `cohortLock`, which is why it lands after RECORD's engine: an emitter for an engine that cannot yet read the key writes a config that silently does nothing. Deliberately NOT beside "Add to locked view" in meaning, though it sits beside it in the menu: that one COPIES today's matches into a set; this one makes the set the view's permanent boundary. The submenu lists the sets and offers Unlock when one is already set, because a lock that cannot be removed from the same place it was applied is a trap. β›” wave17 R1 β€” HIDDEN ON A LOCKED VIEW ITSELF, and this is not tidiness. A projected locked view's lock IS its identity: `aios_grid.views_from_defs` re-stamps `config.cohortLock = view.id` on EVERY READ, unconditionally, so a lock chosen here would be accepted by the UI, sent, and then silently overwritten by the host on the next payload. The rail would show no change and nothing would go red β€” the present-and-silently-inert affordance this file's own posture forbids. An action the server will not honour must be ABSENT, not merely ineffective. ⭐ W40-T21 (D-254) β€” THE ONE ROW OF THE THREE THAT REALLY IS A LOCK, so it KEEPS the padlock and gains the title Β§4 asks of anything wearing the shared mark: it names WHICH of the three locks it means. The locked-view kind, the row set, and not the other two β€” a locked database forbids adding, deleting and editing RECORDS, a pre-set field freezes one COLUMN, and painting either meaning here would tell the user something false. */} {onCohortLock && lists.length > 0 && canEditMenuView && menuView.kind !== "locked" && ( <button type="button" role="menuitem" title="Locked view: the records in it become a fixed set. Fields and other views are untouched." onClick={() => { setLockFor({ viewId: menuView.id, anchor: menu.anchor }); setMenu(null); }} > <MenuLabel icon="permissions" text={menuView.config?.cohortLock ? "Change the lock" : "Lock to a locked view"} /> </button> )} {/* I12 (C3) β€” freeze the DISPLAY MODE. Offered only to the creator or an admin, and only a courtesy: the host enforces the same rule, because a hidden control is still a reachable event. */} {onToggleLock && menuView.kind !== "system" && canEditMenuView && mayToggleViewLock(menuView, viewer) && ( <button type="button" role="menuitem" onClick={() => { onToggleLock(menuView.id, !isModeFrozen(menuView)); setMenu(null); }} > {/* The FROZEN action wears the mode's own mark rather than a second padlock: "Lock as Kanban" beside the kanban glyph says what gets frozen, which a padlock cannot. Unlocking is the undo, so it takes the open shackle. */} <MenuLabel icon={ isModeFrozen(menuView) ? "unlock" : <ModeIcon mode={viewDisplayMode(menuView)} size={16} /> } text={ isModeFrozen(menuView) ? "Unlock view" : `Lock as ${MODE_LABELS[viewDisplayMode(menuView)]}` } /> </button> )} {/* ⚠ Delete is gated on the HOST's actual rule, NOT on `locked`. C3 widens `locked` to every view and defines it as mode-frozen only; leaving Delete on it would hide the entry for a user-frozen Kanban that the host would happily delete. */} {!isUndeletableView(menuView) && (canEditMenuView || canDismissMenuView) && ( <button type="button" role="menuitem" className="is-danger" onClick={() => { onDelete(menuView.id); setMenu(null); }} > <MenuLabel icon="trash" text={canDismissMenuView ? "Dismiss" : "Delete"} /> </button> )} </AnchoredOverlay> )} {/* W2 (C2) β€” the format pane: CSV Β· Excel Β· PDF Β· JSON, keyboard-navigable like the menu it came from. Rows/columns are the view's CURRENT matches and visible fields; generation is client-side (the grid already holds the answer). */} {exportFor && exportView && (onExport || onExportXlsxViews) && ( <AnchoredOverlay anchor={exportFor.anchor} className="cg-view-menu" placement="bottom-end" role="dialog" ariaLabel={`Export ${viewDisplayName(exportView)}`} onDismiss={() => { setExportFor(null); setExportBulk(false); setExportViewIds([]); }} onKeyDown={onMenuKeyDown} dataKind="view-export" > <div className="cg-pop-title cg-export-title">Export {viewDisplayName(exportView)}</div> {onExportXlsxViews && !exportBulk && ( <button type="button" role="menuitem" onClick={() => { setExportBulk(true); setExportViewIds( exportableViewIds?.includes(exportView.id) ? [exportView.id] : [] ); }} > Bulk select </button> )} {onExportXlsxViews && exportBulk && ( <div className="cg-pop-body"> <div className="cg-pop-note">Each selected View becomes its own Excel tab.</div> {xlsxExportViews.map((view) => { const selected = exportViewIds.includes(view.id); return ( /* W46-T03: its OWN class, not `cg-radio-row`. These are checkboxes, and the radio class carries no font-size at all, so the rows were inheriting the 17px root while `.cg-pop-title` and `.cg-pop-note` beside them sit at `--lp-fs-2xs`. `rail-select.css` puts the whole panel on one step. */ <label key={view.id} className="cg-export-view-row"> <input type="checkbox" checked={selected} disabled={(selected && exportViewIds.length === 1) || (!selected && exportViewIds.length >= 20)} onChange={() => setExportViewIds((current) => selected ? current.filter((id) => id !== view.id) : [...current, view.id]) } /> <span>{viewDisplayName(view)}</span> </label> ); })} </div> )} {EXPORT_FORMATS.map((format) => { /* ⭐ W50-T12 / R11 β€” BOTH Excel doors are gated on READINESS, and both hand over a workbook that is already built. The click does no network work at all: that is what makes the download reachable from inside the gesture, which is the whole of the fix. While the build is in flight the button says so rather than pretending to be idle, because a control that looks live and does nothing is the defect. */ if (format === "xlsx" && exportBulk && onExportXlsxViews) { return ( <button key={format} type="button" role="menuitem" disabled={!exportReady} onClick={() => { onExportXlsxViews(exportIntendedIds); setExportFor(null); }} > {exportReady || !exportViewIds.length ? "Export Excel" : "Preparing your workbook"} </button> ); } if (format === "xlsx" && !exportBulk && !onExport && onExportXlsxViews) { return ( <button key={format} type="button" role="menuitem" disabled={!exportReady} onClick={() => { onExportXlsxViews(exportIntendedIds); setExportFor(null); }} > {exportReady ? "Export Excel" : "Preparing your workbook"} </button> ); } if (!onExport || (exportBulk && format !== "xlsx")) return null; return ( <button key={format} type="button" role="menuitem" onClick={() => { onExport(exportView.id, format); setExportFor(null); }} > {EXPORT_LABELS[format]} </button> ); })} </AnchoredOverlay> )} {/* Add to cohort β€” the view's CURRENT matches become fixed members of a cohort. Worded as a one-time copy ("Add ... to") rather than a link, because that is what it is: the cohort does not track the view afterwards, which is the entire difference between a cohort and a saved view. */} {addFor && addView && onAddToList && ( <AnchoredOverlay anchor={addFor.anchor} className="cg-pop cg-add-list-pop" placement="bottom-end" role="dialog" ariaLabel={`Add ${viewDisplayName(addView)} to a locked view`} onDismiss={() => setAddFor(null)} dataKind="add-to-list" > <div className="cg-pop-title">Add to cohort</div> <div className="cg-pop-note"> Adds the customers <strong>{viewDisplayName(addView)}</strong> matches right now. The cohort stays fixed as the data changes. </div> {lists.map((l) => ( <button type="button" key={l.id} className="cg-pick-row" onClick={() => { onAddToList(addView.id, l.id, l.name); setAddFor(null); }} > {l.name} </button> ))} <div className="cg-view-create"> <label htmlFor="cg-new-list">Lock records into a new view</label> <input id="cg-new-list" className="cg-input" data-overlay-autofocus value={newListName} placeholder="e.g. Q3 call plan" onChange={(event) => setNewListName(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter" && newListName.trim()) { onAddToList(addView.id, "", newListName.trim()); setAddFor(null); } }} /> <div className="cg-form-actions"> <button type="button" className="cg-btn cg-btn--primary" disabled={!newListName.trim()} onClick={() => { onAddToList(addView.id, "", newListName.trim()); setAddFor(null); }} > Create and add </button> </div> </div> </AnchoredOverlay> )} {/* Description editor β€” mirrors the column menu's field-note interaction so the two "explain this thing" affordances behave identically. */} {noteFor && noteView && ( <AnchoredOverlay anchor={noteFor.anchor} className="cg-pop cg-view-note-pop" placement="bottom-end" role="dialog" ariaLabel={`Description for ${viewDisplayName(noteView)}`} onDismiss={() => setNoteFor(null)} dataKind="saved-view-note" > <div className="cg-pop-title">Description</div> <label className="cg-column-note"> {/* Wave-10 item 9 moved the description off the grid and onto the view's row, so this sentence had to move with it β€” it described a banner that no longer exists. */} {/* ⚠ W34-T26 β€” "the view name", not "this view's name", and the apostrophe is the whole reason. `web_prose`'s TypeScript walk has no parser: an apostrophe in JSX TEXT opens a single-quoted string it never closes, so the walk ran from here to the end of this region, swallowing ~37 lines (this span's tail, the <textarea> and its attributes, two <button>s and a `//` comment). It then reported the em dash inside that swallowed COMMENT as a finding on this line: mislocated, and a false positive by the gate's own contract, since comments are exempt. β›” THE POINT OF THIS EDIT IS NOT THE GREEN. A walker that believes it is inside a string also SKIPS every real string after it, so those 37 lines were unscanned; removing the apostrophe restores the gate's sight over them. The underlying defect is `verify_prose.py`'s and is reported to A (post C-3; lane B raised the same thing as B-3, measuring 248 lines lost in one file). Do NOT rewrite the COMMENTS it reports to silence it, which is the version of this that destroys reasoning. */} <span>Shown under the view name in the list.</span> <textarea data-overlay-autofocus value={noteDraft} maxLength={2000} placeholder="What is this list for?…" onChange={(event) => setNoteDraft(event.target.value)} /> </label> <div className="cg-form-actions"> <button type="button" className="cg-btn cg-btn--primary" // Enabled whenever the text CHANGED β€” including changing it to empty, // which is how a description is removed. Never compared against the // template seed, only against what is currently stored. disabled={noteDraft === (noteView.note ?? "")} onClick={() => { onNote(noteView.id, noteDraft); setNoteFor(null); }} > Save description </button> <button type="button" className="cg-btn" onClick={() => setNoteFor(null)} > Cancel </button> </div> </AnchoredOverlay> )} {/* Database actions share the existing menu row and focus styles. */} {databaseMenu ? ( <AnchoredOverlay anchor={databaseMenu} className="cg-view-menu" role="menu" ariaLabel="Database actions" onDismiss={() => setDatabaseMenu(null)} placement="bottom-end" > {!readOnly && canManageFields && activeDatabase ? <button type="button" role="menuitem" onClick={() => { setFieldsFor({ key: activeDatabase.key, label: activeDatabase.label, opener: databaseMenu }); setDatabaseMenu(null); }}> Fields </button> : null} <button type="button" role="menuitem" onClick={() => { // The panel takes the SAME anchor: it belongs to the control that was pressed, // not to a menu row that is about to stop existing. setTrashAnchor(databaseMenu); setDatabaseMenu(null); }} > Trash </button> </AnchoredOverlay> ) : null} {fieldsFor && canManageFields && fieldsFor.key === activeDatabaseKey ? ( <DatabaseFieldsDrawer key={fieldsFor.key} databaseKey={fieldsFor.key} databaseLabel={fieldsFor.label} onBack={closeFields} /> ) : null} {/* ⭐⭐ W50-T27 (C4) β€” THE PANEL ITSELF. β›” AN EMPTY `className`, AND IT IS A DECISION RATHER THAN AN OMISSION β€” `AnchoredOverlay` declares the prop REQUIRED, so "" is written out where every other overlay in this file names a surface. `AnchoredOverlay` stamps `cg-overlay` unconditionally, and that class sets a z-index and nothing else; `.vt-panel` already carries this panel's whole surface (background, hairline border, radius, overflow) from `views-trash/trash.css`. Adding `cg-view-menu` here would drag in `index.css`'s `.cg-view-menu button { width: 100% }` β€” a DESCENDANT selector β€” and stretch the panel's two tabs and every Restore button across the box, and `cg-pop` would frame an already-framed panel inside a second border. The child IS the surface, which is the only version of [[a-portal-overlay-carries-its-own-surface]] that does not need new CSS, and new CSS is outside this ticket's two files. ⚠ `role="dialog"`, not `menu`: this is a working surface with tabs, a list and its own controls, and calling it a menu would tell a screen reader to expect menu items. */} {trashAnchor && activeDatabaseKey ? ( <AnchoredOverlay anchor={trashAnchor} className="" role="dialog" ariaLabel="Trash" onDismiss={() => setTrashAnchor(null)} placement="bottom-end" dataKind="view-trash" > <TrashPanel tableKey={activeDatabaseKey} onRestored={onTrashRestored} /> </AnchoredOverlay> ) : null} </aside> {folded && <RailHeaderIcons owner="data" anchor={railEl} onExpand={narrow ? () => setNarrowOpen(true) : toggleRail} chatOpen={chatOpen} onToggleChat={onToggleChat} />} </> ); }
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 `<TrashPanel` element. Both halves are below.
*
* β›” THE BRIEFED ANCHOR DID NOT EXIST. The handover names "the database `...` menu" as though
* one were already here; it is not. This file has exactly three ellipsis controls β€” the DATA
* navigator's folder menu, the VIEW folder menu and the per-view menu β€” and the only control on
* a database ROW (`.shell-dots`) is rendered by `shell/Shell.tsx` through `renderDatabaseActions`,
* which is not this fence. So the database-level menu is CREATED here, on the view path row,
* which is the one row that is about the open database rather than about a view or a folder.
*
* β›” A STATIC IMPORT, DELIBERATELY. `TrashPanel` imports only `./trashApi` and `./trash.css`, and
* this file already compiles into the grid chunk that the panel would be lazily fetched from the
* moment the rail is on screen β€” a `lazy()` here would buy a Suspense boundary and no split worth
* having. The measured cost is in the ticket's handoff, because `tsc` cannot see chunk shape
* ([[tsc-cannot-see-a-broken-code-split]]).