loopable / web /src /query /queryParts.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
071ce2b verified
Raw History Blame Contribute Delete
25.7 kB
import { useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { useEscapeClose } from "../ui/useEscapeClose";
import { TOAST_EVENT } from "../apiContract";
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
import { FolderMark } from "../customer-grid/icons";
import { DbIcon } from "../shell/dbFrame";
import { ASSISTANT_ROUTE } from "../shell/nav";
import type { NavEntry } from "../shell/nav";
/**
* ⭐⭐ W35-T47 (R4, contract C2) — ONE STAR, AND THE BEHAVIOUR IS BORROWED WHOLE.
*
* `useStarred` is B's: the read, the optimistic flip, the reconcile, the toast on refusal, the
* generation guard against two writes racing. R4 makes star and "mark important" ONE idea, so a
* second client for it here would be the drift that ruling exists to prevent.
*
* ⛔ THE BUTTON'S MARKUP IS INLINE AND THAT IS NOT LAZINESS — IMPORTING `StarButton` BREAKS A's
* GATE. `StarredPage.tsx` imports `shell/Brand`, which reads `import.meta.env.BASE_URL`, and
* `verify_wiring.py` COMPILES AND RUNS `query/_test/queryRender.test.tsx` under node as CommonJS:
* `import.meta` is ESM-only syntax, node flips the emitted module to ESM, and the run dies with
* `ReferenceError: exports is not defined in ES module scope`. Reproduced here first, which is the
* only reason it is not a red `web_wiring` in somebody else's lane.
* ⚠ SO WHAT IS COPIED IS EIGHT LINES OF MARKUP, using B's own `.st-star` classes and the shared
* `StarIcon`, and `query.css` restyles nothing except placement. Posted to B as `NOTE C-16`: if
* `StarButton` moves into `starredApi`, this becomes an import.
*/
import { StarIcon } from "../ui/icons";
import { useStarred } from "../starred/starredApi";
import { duplicateQuery, exportQueryHref, renameQuery, revertQuery, saveQueryToDatabase } from "./queryApi";
import type { SavedQuery } from "./queryApi";
/**
* ⭐⭐ W35-T22 (owner item 3) — THE STYLESHEET BELONGS TO THE MODULE THAT RENDERS THE CLASSES, AND
* THAT IS THE WHOLE FIX. Owner, verbatim: *"When I click 'Query' toggle, before it loads, it shows
* a really ugly outdated format, fix it."*
*
* â›” MEASURED, not guessed, on a production build. `query.css` was imported ONLY by `QueryPage`,
* which the Assistant loads with `lazy()`. Vite splits an async chunk's CSS into its own file, so
* all 44 `.qy-rail*` rules landed in `QueryPage-*.css` and the boot stylesheet carried ZERO of
* them. But this module — which renders every one of those classes — is imported STATICALLY by
* `AssistantPage`, and the rail it exports sits OUTSIDE the `<Suspense>` boundary the workspace is
* behind. So flipping the toggle committed the rail in the same frame while its stylesheet was
* still one network round trip away: browser-default buttons, default `<p>` margins, a blue
* underlined link. That is the "outdated format".
*
* âš  It is NOT the Suspense fallback (a bare spinner) and NOT the empty state, the two candidates
* the wave listed. Capture of both states: `AutoWiki/waves/wave35/proto/T22-query-flash/`.
*
* âš  KEEP THE TWIN IMPORT IN `QueryPage.tsx`. Vite emits one stylesheet either way, and the
* standalone `#/query` host reaches the page without passing through here.
*/
import "./query.css";
/** Which label of which row is being typed into. One at a time, by construction. */
function useRefusalToast() {
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
const sequence = useRef(0);
const delivered = useRef(0);
useEffect(() => {
if (!messages.length) return;
const through = messages[messages.length - 1].id;
for (const message of messages) {
if (message.id <= delivered.current) continue;
delivered.current = message.id;
const text = message.text;
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
}
setMessages((current) => current.filter((message) => message.id > through));
}, [messages]);
return (text: string) => {
if (!text) return;
const message = { id: ++sequence.current, text };
setMessages((current) => [...current, message]);
};
}
interface Editing { id: string; field: "name" | "description"; value: string; }
function QueryActionMenu({ anchor, onClose, children }: {
anchor: { top: number; right: number } | null;
onClose: () => void;
children: ReactNode;
}) {
const panelRef = useRef<HTMLDivElement>(null);
useOverlayLayer({ panelRef, onDismiss: onClose });
return <div className="qy-rail-menu" role="menu" ref={panelRef}
style={anchor ? { top: anchor.top, right: anchor.right } : undefined}>{children}</div>;
}
/**
* â›” THE MENU IS `position: fixed`, AND THAT IS NOT A STYLE PREFERENCE. Its natural home,
* `.qy-rail-scroll`, is `overflow-y: auto`, which clips BOTH axes: an absolutely positioned menu
* on a row near the bottom of the list renders cut off or not at all, so the reader clicks and
* nothing appears. It fails worst on the rows most likely to be used, the ones you scrolled to.
* Fixed positioning takes it out of the scroll box entirely, which costs one measurement.
*
* âš  `MENU_H` is an estimate used ONLY to decide whether to flip upward near the viewport floor. It
* does not size anything, so being a little wrong shifts the menu rather than breaking it.
*/
const MENU_H = 190;
function menuAnchor(button: HTMLElement): { top: number; right: number } {
const rect = button.getBoundingClientRect();
const below = rect.bottom + 4;
return {
top: below + MENU_H > window.innerHeight ? Math.max(8, rect.top - MENU_H - 4) : below,
right: Math.max(8, window.innerWidth - rect.right),
};
}
/** Query has no top-right view dropdown: the rail below IS the navigation (owner item 3). */
export function QueryEmpty({ loaded, unnamed = 0 }: { loaded: boolean; unnamed?: number }) {
return (
<div className="qy-empty">
{!loaded ? <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" /> : unnamed > 0 ? (
<>
<h1 className="qy-empty-h">Your views could not be opened</h1>
<p className="qy-empty-p">The source database is no longer in your current permission scope. Nothing was changed.</p>
</>
) : (
<>
<h1 className="qy-empty-h">No Query views yet</h1>
<p className="qy-empty-p">Ask the assistant for a table or chart. It creates the Query view immediately.</p>
<a className="qy-empty-go" href={`#/${ASSISTANT_ROUTE}`}>Open the AI assistant</a>
</>
)}
</div>
);
}
/** The kind glyph a Query row wears — the same vocabulary the grid's own view rail uses. */
const KIND_MARK: Record<string, string> = {
grid: "Table", list: "List", chart: "Chart", kanban: "Board",
calendar: "Calendar", map: "Map",
};
export interface QueryGroup {
database: string;
label: string;
icon?: NavEntry["icon"];
views: SavedQuery[];
}
/**
* âš  GROUPED IN THE ORDER THE DATABASES ARE GRANTED, not by artefact age. The rail is a list of
* DATABASES first (owner: "each View correspond to the relevant database"), so a new answer about
* Customers must not move the Customers heading — it appears under it. Within a database the
* newest is first, which is the order the server already sends.
*
* ⭐ R14 GAVE THIS LIST A SECOND HOST, which is why the loop is a function and lives HERE rather
* than inside `QueryPage`. The merged Assistant surface renders the same rail in its own left
* panel; two hosts computing "which views belong to which database" from two copies of one loop
* is one question with two normalizers, and the copy that drifts is the one nobody is looking at.
* It sits beside `QueryGroup`, the type it builds, and in a module that does NOT import the grid
* — a static import from `QueryPage.tsx` would pull `CustomerGrid` into the chat bundle and undo
* the lazy boundary the Assistant keeps around it.
*
* A view whose source database is not in `entries` is dropped: the caller's grant is the wall.
*/
export function queryGroups(views: SavedQuery[], entries: NavEntry[]): QueryGroup[] {
const byDatabase = new Map<string, SavedQuery[]>();
for (const view of views) {
const list = byDatabase.get(view.source.database);
if (list) list.push(view);
else byDatabase.set(view.source.database, [view]);
}
const out: QueryGroup[] = [];
for (const entry of entries) {
const list = byDatabase.get(entry.key);
if (!list || entry.kind === "group") continue;
out.push({
database: entry.key,
label: list[0].source.label || entry.label,
...(entry.icon ? { icon: entry.icon } : {}),
views: list,
});
}
return out;
}
/**
* ⭐⭐ OWNER ITEM 3 (2026-08-15) — GROUPED BY SOURCE DATABASE, WHICH IS THE WHOLE INSTRUCTION.
* Verbatim: *"these AI generated query should live under the query module. And that each View
* correspond to the relevant database. So we need to remove that dumb dropdown that suddenly
* appears at the top right of the Database when the AI does query. That's not how we should do
* the navigation."*
*
* ⛔ THE DROPDOWN WAS NOT THE DEFECT — THE ABSENCE OF NAVIGATION WAS. Deleting it (which the
* previous pass did) left Query with no way to move between artefacts at all: the page picked
* `known[0]` and every other view the assistant had ever built was unreachable. A surface with
* one implicit selection is not "no dropdown", it is no navigation, and the owner asked for the
* navigation to be done differently rather than removed.
*
* âš  AND THIS IS WHERE A DATABASE PUTS ITS VIEWS. `dbFrame.tsx` carries the owner's earlier
* sentence — *"the query module should exactly BE looking like the database module, COMPLETELY,
* with all the views etc."* — so the rail sits in the slot `CustomerGrid`'s own `ViewSidebar`
* occupies on every other database, at the same `--lp-rail-w`. It is a separate component only
* because THIS list spans several databases and the grid's rail, by construction, cannot: the
* grid is mounted at one scope.
*/
export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: {
groups: QueryGroup[];
activeId: string;
onSelect: (id: string) => void;
onDelete: (id: string) => void;
/**
* ⭐ The rail OWNS the rename/duplicate calls and hands the host the resulting artefact to
* upsert. Two hosts render this list (the standalone page and the merged Assistant surface), so
* putting the calls in the hosts would be one question with two implementations, and the copy
* that drifts is the one nobody is looking at.
*/
onChanged?: (view: SavedQuery) => void;
}) {
// Two-click delete, in the row. A modal for "remove one of my own saved answers" is heavier
// than the act; a single click with no confirm loses work to a mis-click on a hover control.
const [confirming, setConfirming] = useState("");
const [menuFor, setMenuFor] = useState("");
const [anchor, setAnchor] = useState<{ top: number; right: number } | null>(null);
const [editing, setEditing] = useState<Editing | null>(null);
const menuOpenerRef = useRef<HTMLButtonElement | null>(null);
const editingFinishedRef = useRef(false);
const editingSequence = useRef(0);
useEscapeClose(editing !== null, () => {
editingSequence.current += 1;
editingFinishedRef.current = true;
setEditing(null);
menuOpenerRef.current?.focus();
});
const beginEditing = (next: Editing) => {
editingSequence.current += 1;
editingFinishedRef.current = false;
setMenuFor("");
setEditing(next);
};
// âš  TWO STATES, NOT ONE. A refusal and a confirmation read differently and are coloured
// differently; sharing one slot painted "Saved as ..." in the refusal red.
const [notice, setNotice] = useState("");
const refuse = useRefusalToast();
/**
* ⭐ C2's star list, read AFTER PAINT and never blocking the rail (E-2: `GET /starred` scans
* every visible database's view bucket and was MEASURED at 7,331 ms on a cold container). The
* hook fires in an effect and reports `phase`, so the control simply is not drawn until the
* answer arrives — a star toggled from a list nobody has read would be a guess at its own
* current value.
*/
const stars = useStarred();
const starred = new Set(stars.starred.queries);
const said = (message: string) => setNotice(message);
const failed = (text: string) => {
setNotice("");
refuse(text);
};
const commit = async () => {
if (!editing || editingFinishedRef.current) return;
editingFinishedRef.current = true;
const current = editing;
const sequence = editingSequence.current;
setEditing(null);
const result = await renameQuery(current.id, current.field === "name"
? { name: current.value } : { description: current.value });
if (!result.ok) {
if (sequence === editingSequence.current) {
editingFinishedRef.current = false;
setEditing((next) => next ?? current);
}
failed(result.message);
return;
}
said("");
onChanged?.(result.value);
};
/**
* âš  THE REPLY IS SHOWN WHETHER OR NOT ANYTHING WAS DROPPED, and the dropped half is the useful
* one: a database view carries no aggregation, so "sum of deal value" lands as the rows and not
* the sum. Saying so beats a view that looks complete and answers a different question.
*/
const saveToDatabase = async (view: SavedQuery) => {
const result = await saveQueryToDatabase(view.id);
if (!result.ok) { failed(result.message); return; }
said(result.value.dropped.length
? `Saved as "${result.value.name}". Not carried over: ${result.value.dropped.join(", ")}.`
: `Saved as "${result.value.name}" in this database's own views.`);
};
/**
* ⭐⭐ W35-T25 · CONTRACT C4 (R3) — "Revert to AI original", and the sentence comes FIRST.
*
* ⛔ THE CONFIRM SAYS WHAT REVERT DOES **NOT** DO, BEFORE IT ACTS, AND R3 REQUIRES THAT WORDING
* RATHER THAN SUGGESTING IT. A Query view is live since R2, so a cell somebody changed through
* it is a real write to a real record in the source database. Putting the filters back cannot
* walk that back, and a reader who assumed otherwise has been told the opposite of the truth at
* the one moment they could still have chosen differently.
*
* ⚠ `window.confirm`, deliberately, and this is the one place in this module that uses it. Every
* other destructive door here is a two-click in the row, which works because those are cheap and
* reversible (a rename, a delete of one saved answer). This one is neither: it discards work with
* no undo, and a two-click cannot carry a sentence.
*/
const revert = async (view: SavedQuery) => {
setMenuFor("");
const ok = window.confirm(
`Revert "${view.name}" to the version the assistant built?\n\n`
+ "This restores the filters, sorting, grouping, visible columns and column widths.\n\n"
+ "It does NOT undo any record you changed in the source database. Those edits stay.");
if (!ok) return;
const result = await revertQuery(view.id);
if (!result.ok) { failed(result.message); return; }
said(`"${result.value.name}" is back to the assistant's version.`);
onChanged?.(result.value);
};
const duplicate = async (id: string) => {
const result = await duplicateQuery(id);
// âš  The refusal is the useful half: MAX_ARTIFACTS names its cause and the remedy, and a copy
// that silently did not happen is the failure mode this whole module is written against.
if (!result.ok) { failed(result.message); return; }
said("");
onChanged?.(result.value);
onSelect(result.value.id);
};
return (
<aside className="qy-rail" aria-label="Query views">
<p className="qy-rail-head">Views</p>
{menuFor ? (
<button type="button" className="qy-rail-scrim" aria-label="Close menu"
onClick={() => setMenuFor("")} />
) : null}
{notice ? <p className="qy-rail-notice" role="status">{notice}</p> : null}
<div className="qy-rail-scroll">
{groups.map((group) => (
<section className="qy-rail-group" key={group.database}>
<p className="qy-rail-db">
<span className="qy-rail-db-mark" aria-hidden="true">
{group.icon ? <FolderMark icon={group.icon} size={14} /> : <DbIcon />}
</span>
<span className="qy-rail-db-name">{group.label}</span>
</p>
{group.views.map((view) => (
<div className={"qy-rail-row" + (view.id === activeId ? " is-active" : "")} key={view.id}>
{editing && editing.id === view.id ? (
/* Inline, like the database sidebar's own rename. A window.prompt would block
every other event on the page and cannot carry a placeholder or a cancel. */
<form className="qy-rail-edit" onSubmit={(event) => { event.preventDefault(); void commit(); }}>
<input className="qy-rail-input" autoFocus value={editing.value}
aria-label={editing.field === "name" ? "View name" : "View description"}
placeholder={editing.field === "name" ? "Name" : "Description"}
onChange={(event) => setEditing({ ...editing, value: event.currentTarget.value })}
// The arbiter blurs before cancelling; let its close disarm this save.
onBlur={() => queueMicrotask(() => { void commit(); })} />
</form>
) : (
<button
type="button"
className="qy-rail-view"
aria-current={view.id === activeId ? "true" : undefined}
onClick={() => { setConfirming(""); onSelect(view.id); }}
title={view.description || view.question}
>
<span className="qy-rail-name">{view.name}</span>
<span className="qy-rail-kind">
{KIND_MARK[view.kind] ?? view.kind}
{/* ⭐⭐ W35-T25 (R3) — THE EDITED MARK, ON THE ROW THAT NAMES THE VIEW.
R3 says "its header"; since owner item 3 replaced the top-right dropdown
with this rail, this row IS a Query view's header, and owner item 4 has
just deleted the only strip above the grid. Putting the badge back up
there would re-grow the row the same wave removed.
⚠ Absent, not false, for an artefact with no `original_spec`: `edited` is
derived server-side by comparing against it, so a pre-wave artefact
reports `false` and shows neither this nor the Revert row (C4). */}
{view.edited ? (
<span className="qy-rail-edited"
title="You changed this view. Revert to AI original is in its menu.">
Edited
</span>
) : null}
</span>
</button>
)}
{/* ⭐ W35-T47 — the star, on the row, in BOTH hosts (this rail is the only place a
Query view is listed, and the standalone page and the Assistant's Query mode
both render it). Not drawn until `/starred` has answered: see `stars` above. */}
{stars.load.phase === "ready" ? (
<button
type="button"
className={"st-star" + (starred.has(view.id) ? " is-on" : "")}
aria-pressed={starred.has(view.id)}
aria-label={(starred.has(view.id) ? "Unstar " : "Star ") + view.name}
title={(starred.has(view.id) ? "Unstar " : "Star ") + view.name}
disabled={stars.busy}
onClick={() => stars.toggle("query", view.id, !starred.has(view.id))}
>
<StarIcon size={15} filled={starred.has(view.id)} />
</button>
) : null}
{confirming === view.id ? (
<button type="button" className="qy-rail-confirm"
onClick={() => { setConfirming(""); onDelete(view.id); }}>
Delete
</button>
) : (
<button type="button" className="qy-rail-more" aria-haspopup="menu"
aria-expanded={menuFor === view.id}
aria-label={`Actions for ${view.name}`}
onClick={(event) => {
if (menuFor === view.id) { setMenuFor(""); return; }
menuOpenerRef.current = event.currentTarget;
setAnchor(menuAnchor(event.currentTarget));
setMenuFor(view.id);
}}>
<svg viewBox="0 0 16 16" aria-hidden="true" width="13" height="13">
<circle cx="3.2" cy="8" r="1.1" /><circle cx="8" cy="8" r="1.1" />
<circle cx="12.8" cy="8" r="1.1" />
</svg>
</button>
)}
{menuFor === view.id ? (
/* R20: the same vocabulary a database view offers, minus the ones that mean
nothing here. Import writes rows; Share and Mark important belong to a view a
team navigates; the lock family describes a cohort. What is left is what a
person actually does with an answer they kept. */
<QueryActionMenu anchor={anchor} onClose={() => setMenuFor("")}>
{/* "Export", the database sidebar's own word. Theirs then opens a format
submenu; a submenu holding one row would be chrome for its own sake, so
this downloads the CSV the server names. */}
<a className="qy-rail-item" role="menuitem" href={exportQueryHref(view.id)}
download onClick={() => setMenuFor("")}>Export</a>
<button type="button" className="qy-rail-item" role="menuitem"
onClick={() => beginEditing({ id: view.id, field: "name", value: view.name })}>
Rename
</button>
<button type="button" className="qy-rail-item" role="menuitem"
onClick={() => beginEditing({ id: view.id, field: "description", value: view.description })}>
{view.description ? "Edit description" : "Add description"}
</button>
<button type="button" className="qy-rail-item" role="menuitem"
onClick={() => { setMenuFor(""); void duplicate(view.id); }}>Duplicate</button>
{/* ⭐ R3: armed only when there IS an original AND the view has moved from it.
A Revert that reverts to nothing is worse than an absent one (C4), and a
Revert on an unedited view is a control that does nothing. */}
{view.edited && view.original_spec ? (
<button type="button" className="qy-rail-item" role="menuitem"
onClick={() => { void revert(view); }}>
Revert to AI original
</button>
) : null}
{/* R20's one difference from a database view's menu: this one can BECOME one. */}
<button type="button" className="qy-rail-item" role="menuitem"
onClick={() => { setMenuFor(""); void saveToDatabase(view); }}>
Save into the database
</button>
<button type="button" className="qy-rail-item is-danger" role="menuitem"
onClick={() => { setMenuFor(""); setConfirming(view.id); }}>Delete</button>
</QueryActionMenu>
) : null}
{view.description && !(editing && editing.id === view.id) ? (
<p className="qy-rail-note">{view.description}</p>
) : null}
</div>
))}
</section>
))}
</div>
<a className="qy-rail-ask" href={`#/${ASSISTANT_ROUTE}`}>Ask the assistant</a>
</aside>
);
}
/*
* ⛔⛔ `QueryProvenance` IS DELETED (W35-T21, owner item 4 / R2), AND WHAT WENT WITH IT MATTERS.
* Owner, verbatim: *"there is a 'Source' button under Query as well. The end user doesn't need to
* see this so delete it."* R2 retires the snapshot framing with it, because the two were one
* control: the button read "Sources" and the row beside it read the snapshot version.
*
* âš  THE CITATIONS DID NOT GO. They still reach the grid through `bindingFor(active, citations)`
* in `QueryPage`, and they are still RENDERED for a reader in the surface that owns the claim —
* the chat, where `AssistantPage::CitationLine` prints one clickable line per citation under the
* answer that used it. What R2 removed is a second provenance surface above a grid, not the
* auditability R9 asked for. `verify_grid_ux.py::query_preview_shape` asserts exactly that pair:
* no provenance chrome on this page, citations still bound.
*/