Download web/src/settings/ManageDatabase.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 34.3 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/settings/ManageDatabase.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/settings/ManageDatabase.tsx
-
curl -L -o ManageDatabase.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/settings/ManageDatabase.tsx
34.3 kB
| // R31 puts field controls on one database in Connectors or Data, never in Settings. | |
| import { useCallback, useEffect, useMemo, useRef, useState } from "react"; | |
| import { API_V1, CREDENTIALS, WORKSPACE_STALE_EVENT, signal } from "../apiContract"; | |
| import { useEscapeClose } from "../ui/useEscapeClose"; | |
| import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface"; | |
| // `.set-perm-back` — the way out of a full-pane takeover, already shipped for | |
| // the Manage User one. Wearing it rather than redrawing it is half of why this | |
| // pane and that one can be shot side by side and match (W46-T39). | |
| import "./perms.css"; | |
| // ⛔ C6 — the lane sheet is imported HERE, from the component, not added to | |
| // `index.css`. `index.css` `@import`s the older sheets at its top, so a sheet | |
| // arriving that way loses every equal-specificity fight with the thousands of | |
| // rules below it; a sheet imported from a component lands after `index.css` in | |
| // the bundle and wins. `AssistantPage.tsx:17` is the shipped precedent. | |
| import "../styles/wave46/manage-database.css"; | |
| import "../styles/sdlc74/settings.css"; | |
| import "../styles/sdlc77/fields-disclosure.css"; | |
| import type { ConnectorDatabase, ConnectorIntrospection } from "../connectors/ConnectorModal"; | |
| /** R21 behind the Fields click: a connector database's raw source fields and what its catalogue left out. */ | |
| export interface FieldDisclosure { | |
| database: ConnectorDatabase; | |
| introspection: ConnectorIntrospection; | |
| /** A failed deferred field read; empty while it loads. */ | |
| readError: string; | |
| onRetry: () => void; | |
| } | |
| // ── the wire (contract C1) ────────────────────────────────────────────────── | |
| // | |
| // Store key `ut_schema_overlay`, one document per tenant, shaped | |
| // { "<database_key>": { "<field_key>": {hidden, label, order} } } | |
| // with an absent key meaning "inherit the canonical contract". | |
| // | |
| // `GET /api/v1/admin/schema-overlay` returns the MERGED view (contract plus | |
| // overlay) as `{fields:[{key,label,type,source,hidden,order,locked}]}`; `PATCH` | |
| // takes a partial of the document above and returns the merged view again. | |
| /** | |
| * ⭐⭐ `database` IS REQUIRED HERE, AND THE PATCH SHAPE IS WHY. C1 declares the | |
| * GET's rows without spelling the database key out, but the document a PATCH | |
| * carries is keyed by `database_key` FIRST. A row that cannot name its database | |
| * therefore cannot be written back at all — the key is load-bearing for the | |
| * write path, not a grouping nicety for the list. | |
| * | |
| * ⛔ SO IT IS NEVER GUESSED. `source` is a FIELD property (where the column comes | |
| * from) and reusing it as the database key would be the "a grep for a NAME is not | |
| * a wire key" defect exactly: plausible groups the server never meant, and a | |
| * PATCH addressed to a database that does not exist. A row missing the key is | |
| * dropped by the parser and counted, and the pane says how many it dropped. | |
| */ | |
| export interface OverlayField { | |
| /** The `database_key` a PATCH is addressed to. */ | |
| database: string; | |
| /** What to call that database on screen. Absent ⇒ the key, which is honest if ugly. */ | |
| databaseLabel?: string; | |
| field: string; | |
| label: string; | |
| type: string; | |
| source: string; | |
| hidden: boolean; | |
| order: number | null; | |
| /** | |
| * A join key or the record id. ⛔ The overlay MAY NOT HIDE IT (C1), and that is | |
| * the whole of what this flag means. It is NOT the "locked database" lock and | |
| * NOT the "pre-set field" lock (DESIGN.md §4) — neither vocabulary is borrowed | |
| * for it, because a shared word would have an admin read a guarantee about | |
| * records or about editing that nothing here makes. | |
| */ | |
| locked: boolean; | |
| } | |
| interface ParsedOverlay { | |
| fields: OverlayField[]; | |
| /** Rows the server sent that carry no database key, so nothing may be written for them. */ | |
| dropped: number; | |
| } | |
| function str(v: unknown, fallback = ""): string { | |
| return typeof v === "string" && v ? v : fallback; | |
| } | |
| /** | |
| * The parse lives at the BOUNDARY, in one testable function, rather than being | |
| * spread through the render — the same arrangement `permsModel.parsePermsPayload` | |
| * uses for the permissions wire and for the same reason: a shape check half in a | |
| * fetch wrapper and half in JSX is a shape check nobody can read. | |
| */ | |
| export function parseOverlay(body: unknown): ParsedOverlay { | |
| const raw = (body as { fields?: unknown } | null)?.fields; | |
| if (!Array.isArray(raw)) return { fields: [], dropped: 0 }; | |
| const fields: OverlayField[] = []; | |
| let dropped = 0; | |
| for (const item of raw) { | |
| const r = item as Record<string, unknown> | null; | |
| if (!r || typeof r !== "object") { | |
| dropped += 1; | |
| continue; | |
| } | |
| // ⚠ TWO SPELLINGS, NOT THREE, AND BOTH ARE EVIDENCED. `database` is the | |
| // camelCase dialect this client's wires already speak (`accessSummary`, | |
| // `canBusiness`, `tenantWideTypes`); `database_key` is the name the data | |
| // layer itself uses (`platform/core/schema_overlay.py`, `locked_keys` and | |
| // `merge`). Anything else would be a guess wearing a defensive costume — and | |
| // a wrong-but-accepted spelling is worse than none, because it silently | |
| // defeats the honest degrade below. | |
| const database = str(r.database) || str(r.database_key); | |
| const field = str(r.key); | |
| if (!database || !field) { | |
| dropped += 1; | |
| continue; | |
| } | |
| fields.push({ | |
| database, | |
| databaseLabel: str(r.databaseLabel) || undefined, | |
| field, | |
| label: str(r.label, field), | |
| // An unknown or absent type reads as text, the house fallback the field | |
| // vocabulary already uses; it is never blank, because a blank cell in a | |
| // schema list reads as "this field has no type" rather than "not stated". | |
| type: str(r.type, "text"), | |
| source: str(r.source, "unknown"), | |
| hidden: r.hidden === true, | |
| order: typeof r.order === "number" ? r.order : null, | |
| locked: r.locked === true, | |
| }); | |
| } | |
| return { fields, dropped }; | |
| } | |
| // ── the SEMANTIC wire (owner instruction 8) ───────────────────────────────── | |
| // | |
| // ⛔⛔ A SECOND DESCRIPTION STORE IS THE ONE THING THIS MUST NOT BUILD, and it is | |
| // the obvious way to write it. The schema overlay above owns `label`, `hidden` | |
| // and `order` and nothing else. The description and the governance state are the | |
| // SEMANTIC REGISTRY's `purpose` and `state`, which already exist, are already | |
| // admin-gated and are already persisted: | |
| // | |
| // GET /api/v1/query/semantics/{database} -> {database, fields:[...], router} | |
| // PATCH /api/v1/query/semantics/{database}/{field} <- {purpose} | |
| // | |
| // Both halves shipped in an earlier wave and NOBODY EVER CONNECTED THEM to this | |
| // pane, which is the whole of instruction 8 ("I don't see the semantic .md file | |
| // or description per field under manage database"). So this reads and writes | |
| // THOSE routes, and adds no key to the overlay document and none to `patch_field`. | |
| // | |
| // ⚠ THE MARKDOWN IS A GENERATED PROJECTION (`semantic_registry.generated_markdown`) | |
| // and is never hand-edited, so no markdown editor is offered here. What an admin | |
| // edits is `purpose`; the .md the instruction names is that value, rendered. | |
| // | |
| // ⚠ TWO STORES, TWO PERMISSION WALLS, AND THEY ARE NOT THE SAME WALL. The overlay | |
| // sits behind the admin gate; the semantic routes sit behind Query's own source | |
| // boundary plus `is_admin` inside the registry. A database with no semantic | |
| // contract answers 404 by design. Neither refusal may be dressed as an empty | |
| // list, so both are STATED and the description control still renders. | |
| /** One field's governed meaning. `purpose` IS the description an admin edits. */ | |
| export interface SemanticField { | |
| field: string; | |
| purpose: string; | |
| /** `draft` | `approved` | `disabled` — the registry's closed set. */ | |
| state: string; | |
| role: string; | |
| sensitivity: string; | |
| } | |
| /** The same boundary parse the overlay gets, for the same reason. */ | |
| export function parseSemantics(body: unknown): Record<string, SemanticField> { | |
| const raw = (body as { fields?: unknown } | null)?.fields; | |
| const out: Record<string, SemanticField> = {}; | |
| if (!Array.isArray(raw)) return out; | |
| for (const item of raw) { | |
| const r = item as Record<string, unknown> | null; | |
| if (!r || typeof r !== "object") continue; | |
| const field = str(r.field); | |
| if (!field) continue; | |
| out[field] = { | |
| field, | |
| purpose: str(r.purpose), | |
| state: str(r.state, "draft"), | |
| role: str(r.role), | |
| sensitivity: str(r.sensitivity), | |
| }; | |
| } | |
| return out; | |
| } | |
| /** The chip word for a governance state. Sentence case: DESIGN.md §2 forbids | |
| * ALL-CAPS app chrome, and the registry's own values are lower case. */ | |
| function stateWord(state: string | undefined): string { | |
| if (state === "approved") return "Approved"; | |
| if (state === "disabled") return "Disabled"; | |
| if (state === "draft") return "Draft"; | |
| return "No semantic record"; | |
| } | |
| /** The explanation, in the tooltip rather than on the row (DESIGN.md §2). */ | |
| function stateHint(state: string | undefined): string { | |
| if (state === "approved") return "This field is approved for retrieval by the assistant."; | |
| if (state === "disabled") return "This field is withheld from retrieval."; | |
| if (state === "draft") | |
| return "This field is not approved for retrieval yet, so the assistant will not use it."; | |
| return "This database publishes no governed meaning for this field."; | |
| } | |
| /** The chip tone. Blue is the interactive or affirmed state and red is the | |
| * withheld one, per DESIGN.md §3; draft earns no colour, the way Member does not. */ | |
| function stateChipClass(state: string | undefined): string { | |
| if (state === "approved") return "set-chip set-chip--admin"; | |
| if (state === "disabled") return "set-chip set-chip--off"; | |
| return "set-chip"; | |
| } | |
| /** One database's PATCH body: `{ "<field_key>": {hidden, label, order} }`. */ | |
| type FieldPatch = { hidden?: boolean; label?: string | null; order?: number | null }; | |
| type Result<T> = { ok: true; data: T } | { ok: false; message: string }; | |
| const READ_LIMIT_MS = 2000; | |
| const DETAIL_READ_LIMIT_MS = 10000; | |
| function LoadingDatabases() { | |
| return <div className="set-skeleton" role="status" aria-label="Loading databases"> | |
| {[0, 1, 2, 3].map((key) => <span key={key} className="set-skeleton-line" />)} | |
| </div>; | |
| } | |
| /** | |
| * The fetch idiom is `settingsApi.call`'s, deliberately not an import of it: | |
| * that module's helper is private to it, and C1's routes are this pane's, so a | |
| * widening of a shared file for one caller would be a fence this ticket does not | |
| * own. Same credentials word, same "never surface a 5xx verbatim" rule. | |
| */ | |
| async function callOverlay<T>( | |
| init?: RequestInit & { body?: string }, | |
| path = "", | |
| readLimitMs = READ_LIMIT_MS, | |
| ): Promise<Result<T>> { | |
| const controller = new AbortController(); | |
| const abort = () => controller.abort(); | |
| init?.signal?.addEventListener("abort", abort, { once: true }); | |
| if (init?.signal?.aborted) abort(); | |
| const timer = !init?.method || init.method === "GET" | |
| ? window.setTimeout(abort, readLimitMs) : undefined; | |
| try { | |
| const res = await fetch(`${API_V1}/admin/schema-overlay${path}`, { | |
| credentials: CREDENTIALS, | |
| headers: init?.body ? { "Content-Type": "application/json" } : undefined, | |
| ...init, | |
| signal: controller.signal, | |
| }); | |
| let body: unknown = null; | |
| try { | |
| body = await res.json(); | |
| } catch { | |
| /* an empty body is not fatal; the status below decides */ | |
| } | |
| if (controller.signal.aborted) throw new Error("Read aborted"); | |
| if (!res.ok) { | |
| const err = (body as { error?: { message?: string } } | null)?.error; | |
| const message = | |
| res.status === 404 | |
| ? "The database could not be found." | |
| : res.status >= 500 | |
| ? "The databases could not be loaded." | |
| : err?.message || | |
| (res.status === 403 | |
| ? "Administrators only." | |
| : "That change could not be saved."); | |
| return { ok: false, message }; | |
| } | |
| return { ok: true, data: body as T }; | |
| } catch { | |
| return { ok: false, message: controller.signal.aborted | |
| ? "The database request took too long." : "The server could not be reached." }; | |
| } finally { | |
| window.clearTimeout(timer); | |
| init?.signal?.removeEventListener("abort", abort); | |
| } | |
| } | |
| /** | |
| * The semantic half's fetch, deliberately a sibling of `callOverlay` rather than | |
| * a generalisation of it: the two speak different routes with different refusals, | |
| * and one helper taking a path would make the 404 sentence below impossible to | |
| * write honestly. Same credentials word, same "never surface a 5xx verbatim" rule. | |
| */ | |
| async function callSemantics<T>( | |
| path: string, | |
| init?: RequestInit & { body?: string }, | |
| ): Promise<Result<T>> { | |
| try { | |
| const res = await fetch(`${API_V1}/query/semantics/${path}`, { | |
| credentials: CREDENTIALS, | |
| headers: init?.body ? { "Content-Type": "application/json" } : undefined, | |
| ...init, | |
| }); | |
| let body: unknown = null; | |
| try { | |
| body = await res.json(); | |
| } catch { | |
| /* an empty body is not fatal; the status below decides */ | |
| } | |
| if (!res.ok) { | |
| const err = (body as { error?: { message?: string } } | null)?.error; | |
| const message = | |
| // ⛔ 404 IS A REAL ANSWER HERE, NOT AN OUTAGE. Only a database with a | |
| // declared topic contract has governed meanings, so a plain user table | |
| // answers 404 and that is correct. Reporting it as a broken service | |
| // would send an admin looking for a fault that is not there. | |
| res.status === 404 | |
| ? "This database publishes no semantic contract, so it carries no field descriptions." | |
| : res.status >= 500 | |
| ? "Something went wrong on our side. Try again in a moment." | |
| : err?.message || | |
| (res.status === 403 | |
| ? "Administrators only." | |
| : "That description could not be saved."); | |
| return { ok: false, message }; | |
| } | |
| return { ok: true, data: body as T }; | |
| } catch { | |
| return { ok: false, message: "The server could not be reached." }; | |
| } | |
| } | |
| // ── the pane ──────────────────────────────────────────────────────────────── | |
| /** Sort by the overlay's order where it has one, then by label, so a database | |
| * with no stored order still lists in a stable, readable sequence rather than | |
| * in whatever order the server happened to serialise. */ | |
| function inOrder(rows: OverlayField[]): OverlayField[] { | |
| return [...rows].sort((a, b) => { | |
| const ao = a.order ?? Number.MAX_SAFE_INTEGER; | |
| const bo = b.order ?? Number.MAX_SAFE_INTEGER; | |
| if (ao !== bo) return ao - bo; | |
| return a.label.localeCompare(b.label); | |
| }); | |
| } | |
| /** Data's drawer keeps the shared editor, focus trap and saving guard together. */ | |
| export function DatabaseFieldsDrawer({ databaseKey, databaseLabel, onBack }: { | |
| databaseKey: string; | |
| databaseLabel: string; | |
| onBack: () => void; | |
| }) { | |
| const panelRef = useRef<HTMLElement>(null); | |
| const [busy, setBusy] = useState(false); | |
| useOverlayLayer({ panelRef, onDismiss: () => { if (!busy) onBack(); }, | |
| dismissOnOutside: false, trapFocus: true, restoreFocus: false }); | |
| return <BodyPortal> | |
| <div className="w46-db-drawer-backdrop"> | |
| <section className="w46-db-drawer" ref={panelRef} role="dialog" aria-modal="true" | |
| aria-label={`${databaseLabel} fields`} tabIndex={-1} data-overlay-kind="database-fields"> | |
| <DatabaseFieldsEditor databaseKey={databaseKey} databaseLabel={databaseLabel} | |
| onBack={onBack} backLabel="Back to database" onBusyChange={setBusy} /> | |
| </section> | |
| </div> | |
| </BodyPortal>; | |
| } | |
| /** Each database uses the same overlay and semantic stores from Connectors or Data. */ | |
| export function DatabaseFieldsEditor({ databaseKey, databaseLabel, onBack, onBusyChange, | |
| backLabel = "Back to databases", disclosure }: { | |
| databaseKey: string; | |
| databaseLabel: string; | |
| onBack: () => void; | |
| onBusyChange?: (busy: boolean) => void; | |
| backLabel?: string; | |
| disclosure?: FieldDisclosure; | |
| }) { | |
| const [parsed, setParsed] = useState<ParsedOverlay | null>(null); | |
| const [detailReload, setDetailReload] = useState(0); | |
| const [addingField, setAddingField] = useState(false); | |
| const [fieldName, setFieldName] = useState(""); | |
| const [error, setError] = useState(""); | |
| const [notice, setNotice] = useState(""); | |
| const [saving, setSaving] = useState(false); | |
| useEscapeClose(true, () => { if (!saving) onBack(); }); | |
| useEffect(() => { | |
| onBusyChange?.(saving); | |
| return () => onBusyChange?.(false); | |
| }, [onBusyChange, saving]); | |
| /** The unsaved relabel and reorder for the open database, keyed by field. */ | |
| const [draft, setDraft] = useState<Record<string, FieldPatch>>({}); | |
| /** | |
| * The open database's governed meanings, keyed by field. `null` is "not asked | |
| * yet"; an empty object is "asked, and there are none", which is a different | |
| * thing and the row renders differently for it. | |
| */ | |
| const [semantics, setSemantics] = useState<Record<string, SemanticField> | null>(null); | |
| /** Why there are no descriptions, when there are none. Empty means there are. */ | |
| const [semNote, setSemNote] = useState(""); | |
| /** The unsaved description edits for the open database, keyed by field. */ | |
| const [semDraft, setSemDraft] = useState<Record<string, string>>({}); | |
| /** | |
| * The governed meanings are fetched PER DATABASE, when one is opened, because | |
| * the route is per database and the list page shows no field rows to hang them | |
| * on. Closing the takeover drops them, so re-opening a database cannot paint a | |
| * previous one's descriptions for a moment. | |
| */ | |
| useEffect(() => { | |
| let live = true; | |
| const controller = new AbortController(); | |
| setParsed(null); | |
| setError(""); | |
| setSemantics(null); | |
| setSemNote(""); | |
| setSemDraft({}); | |
| setDraft({}); | |
| setNotice(""); | |
| setAddingField(false); | |
| setFieldName(""); | |
| void callOverlay<{ semantics?: unknown; semanticNote?: string }>( | |
| { signal: controller.signal }, `/databases/${encodeURIComponent(databaseKey)}`, | |
| DETAIL_READ_LIMIT_MS, | |
| ).then((r) => { | |
| if (!live) return; | |
| if (r.ok) { | |
| const fields = parseOverlay(r.data); | |
| if (!Array.isArray((r.data as { fields?: unknown } | null)?.fields) || fields.dropped | |
| || fields.fields.some((field) => field.database !== databaseKey)) { | |
| setError("The database fields could not be loaded."); | |
| return; | |
| } | |
| setParsed(fields); | |
| setSemantics(parseSemantics(r.data.semantics)); | |
| setSemNote(r.data.semanticNote || ""); | |
| } else { | |
| // ⛔ NOT an error page, and NOT an empty list dressed as success. The | |
| // rows still render their description control; what changes is that the | |
| // pane SAYS why every one of them is empty. A refusal that removes the | |
| // control would read as "this feature is missing" rather than as "this | |
| // database has no governed meanings", which is the exact confusion | |
| // instruction 8 reports about the previous wave. | |
| setSemantics({}); | |
| setError(r.message); | |
| } | |
| }); | |
| return () => { | |
| live = false; | |
| controller.abort(); | |
| }; | |
| }, [databaseKey, detailReload]); | |
| /** | |
| * ONE ACTION, TWO STORES, AND THE CODE SAYS SO. The overlay owns label, hidden | |
| * and order; the semantic registry owns the description. An admin edits both in | |
| * one row and saves once, but neither write is allowed to pretend to be the | |
| * other, and a refusal on one must not silently discard the other's edits. | |
| */ | |
| const save = useCallback( | |
| (database: string) => { | |
| const patch = draft; | |
| const notes = semDraft; | |
| const noteFields = Object.keys(notes); | |
| if (Object.keys(patch).length === 0 && noteFields.length === 0) return; | |
| setSaving(true); | |
| void (async () => { | |
| let failure = ""; | |
| // 1. the overlay half. | |
| if (Object.keys(patch).length) { | |
| const r = await callOverlay<unknown>({ | |
| method: "PATCH", | |
| body: JSON.stringify({ [database]: patch }), | |
| }, `?database_key=${encodeURIComponent(database)}`); | |
| if (r.ok) { | |
| setParsed(parseOverlay(r.data)); | |
| setDraft({}); | |
| signal(WORKSPACE_STALE_EVENT); | |
| } else { | |
| failure = r.message; | |
| } | |
| } | |
| // 2. the semantic half, ONE FIELD AT A TIME because the route is per | |
| // field. Only the fields the server actually accepted are cleared | |
| // from the draft; a field it refused keeps the admin's text on screen | |
| // rather than throwing away typing the row still appears to hold. | |
| const stillDraft: Record<string, string> = {}; | |
| for (const field of noteFields) { | |
| const one = await callSemantics<{ field?: unknown }>( | |
| `${encodeURIComponent(database)}/${encodeURIComponent(field)}`, | |
| { method: "PATCH", body: JSON.stringify({ purpose: notes[field] }) }, | |
| ); | |
| if (one.ok) { | |
| const written = parseSemantics({ | |
| fields: [(one.data as { field?: unknown } | null)?.field], | |
| })[field]; | |
| if (written) setSemantics((s) => ({ ...(s ?? {}), [field]: written })); | |
| } else { | |
| stillDraft[field] = notes[field]; | |
| if (!failure) failure = one.message; | |
| } | |
| } | |
| setSemDraft(stillDraft); | |
| setSaving(false); | |
| setError(failure); | |
| setNotice(failure ? "" : "Saved."); | |
| })(); | |
| }, | |
| [draft, semDraft], | |
| ); | |
| const db = useMemo(() => ({ key: databaseKey, label: databaseLabel, | |
| rows: parsed?.fields ?? [] }), [databaseKey, databaseLabel, parsed]); | |
| const rows = inOrder(db.rows).map((f) => ({ ...f, ...pick(draft[f.field]) })); | |
| // The draft's own order wins over the server's, so a move shows immediately. | |
| rows.sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER)); | |
| /** Reorder writes an order for EVERY row, not only the two that swapped: a | |
| * sparse order over a list that was previously unordered would leave the | |
| * rest to the tiebreak and read as a random shuffle. */ | |
| const move = (index: number, delta: number) => { | |
| const next = [...rows]; | |
| const to = index + delta; | |
| if (to < 0 || to >= next.length) return; | |
| const [row] = next.splice(index, 1); | |
| next.splice(to, 0, row); | |
| setDraft((d) => { | |
| const out = { ...d }; | |
| next.forEach((r, i) => { | |
| out[r.field] = { ...out[r.field], order: i }; | |
| }); | |
| return out; | |
| }); | |
| setNotice(""); | |
| }; | |
| // Both stores count. A description edited on its own must arm Save and | |
| // Discard exactly as a relabel does, or the row holds typing the page says | |
| // there is nothing to save. | |
| const dirty = Object.keys(draft).length > 0 || Object.keys(semDraft).length > 0; | |
| return ( | |
| <div className="set-pane set-manage-database" data-database-fields={db.key}> | |
| <button type="button" className="set-perm-back" onClick={onBack} disabled={saving} autoFocus> | |
| {/* The chevron the accounts takeover already draws, at the same | |
| geometry: the house vocabulary extended rather than a second icon | |
| language imported (DESIGN.md §4). */} | |
| <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden focusable="false"> | |
| <path | |
| d="M9.5 4 5.5 8l4 4" | |
| stroke="currentColor" | |
| strokeWidth={1.3} | |
| strokeLinecap="round" | |
| strokeLinejoin="round" | |
| /> | |
| </svg> | |
| {backLabel} | |
| </button> | |
| <div className="set-perm-ident"> | |
| <h3 className="set-h">{db.label}</h3> | |
| <span className="set-username">{db.key}</span> | |
| </div> | |
| {error ? <div className="set-error" role="alert"> | |
| <span>{error}</span> | |
| {parsed === null ? <button type="button" className="set-secondary" | |
| onClick={() => setDetailReload((value) => value + 1)}>Retry</button> : null} | |
| </div> : null} | |
| {notice ? <p className="set-notice" role="status">{notice}</p> : null} | |
| {parsed === null && !error ? <LoadingDatabases /> : null} | |
| {parsed !== null && db.key.startsWith("ut_") ? <div className="set-actions"> | |
| <button type="button" className="set-secondary" disabled={saving || dirty} | |
| onClick={() => setAddingField((value) => !value)}> | |
| Add field | |
| </button> | |
| {addingField ? <form className="set-db-add-field" onSubmit={(event) => { | |
| event.preventDefault(); | |
| if (!fieldName.trim() || saving) return; | |
| setSaving(true); | |
| void fetch(`${API_V1}/tables/${encodeURIComponent(db.key)}/fields`, { | |
| method: "POST", credentials: CREDENTIALS, | |
| headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ label: fieldName.trim(), type: "text" }), | |
| }).then((response) => { | |
| if (!response.ok) { setError("The field could not be added."); return; } | |
| setAddingField(false); setFieldName(""); | |
| setDetailReload((value) => value + 1); | |
| }).catch(() => setError("The server could not be reached.")) | |
| .finally(() => setSaving(false)); | |
| }}> | |
| <label className="set-field"><span className="set-label">Field name</span> | |
| <input className="set-input" value={fieldName} required maxLength={100} | |
| onChange={(event) => setFieldName(event.currentTarget.value)} /> | |
| </label> | |
| <button type="submit" className="set-secondary" disabled={saving || !fieldName.trim()}>Add text field</button> | |
| </form> : null} | |
| </div> : null} | |
| {/* ⭐ STANDING RULE 1's SECOND SENTENCE, which is the half that gets | |
| dropped: a limit that cannot be removed is REPORTED with its cause, | |
| never silently enforced. Here the limit is that only a database with | |
| a declared topic contract has governed meanings at all. Saying so is | |
| what stops an empty Description column reading as a broken feature. */} | |
| {semNote ? <p className="set-help">{semNote}</p> : null} | |
| <ul className="w46-db-fields"> | |
| {rows.map((f, i) => ( | |
| <li className="w46-db-field" key={f.field}> | |
| <div className="w46-db-idline"> | |
| <span className="w46-db-key">{f.field}</span> | |
| <span className="w46-db-meta"> | |
| {f.type} in {f.source} | |
| </span> | |
| {f.locked ? ( | |
| <span | |
| className="set-chip" | |
| title="This field is a join key or the record id, so it cannot be hidden." | |
| > | |
| Always shown | |
| </span> | |
| ) : null} | |
| {/* The GOVERNANCE state, in the chip vocabulary this row already | |
| speaks. The explanation rides the tooltip rather than the row | |
| (DESIGN.md §2: explanations go in a hover, not on screen). */} | |
| <span | |
| className={stateChipClass(semantics?.[f.field]?.state)} | |
| title={stateHint(semantics?.[f.field]?.state)} | |
| > | |
| {stateWord(semantics?.[f.field]?.state)} | |
| </span> | |
| </div> | |
| {/* ⛔⛔ ONE GRID CHILD, NOT TWO, AND THAT IS STRUCTURAL RATHER THAN | |
| TIDY. `.w46-db-field` is a THREE column grid declared in | |
| `styles/wave46/manage-database.css`, and that sheet is in NO | |
| lane's fence this wave — so a fourth child here would wrap into | |
| an implicit fourth row and break every row on the page, with no | |
| way to correct it from this file. The description therefore | |
| sits INSIDE the relabel block, which stays the second column. | |
| ⚠ `.set-field`'s 13px bottom margin is what separates the two | |
| boxes; the second label deliberately carries no class, so the | |
| block has no trailing margin to fight `align-items: end`. */} | |
| <div className="w46-db-relabel"> | |
| <label className="set-field"> | |
| <span className="set-label">Label</span> | |
| <input | |
| className="set-input" | |
| type="text" | |
| disabled={saving} | |
| value={f.label} | |
| onChange={(e) => { | |
| const value = e.currentTarget.value; | |
| setDraft((d) => ({ ...d, [f.field]: { ...d[f.field], label: value } })); | |
| setNotice(""); | |
| }} | |
| /> | |
| </label> | |
| {/* ⭐ INSTRUCTION 8. Always rendered, including for a field with | |
| no governed meaning and for a database with no contract at | |
| all: the done-when is that an absent description "reads as | |
| empty rather than as missing UI". The 500 character cap is | |
| the registry's own (`semantic_registry._text(..., 500)`), so | |
| the box refuses what the server would have truncated. */} | |
| <label> | |
| <span className="set-label">Description</span> | |
| <input | |
| className="set-input" | |
| type="text" | |
| maxLength={500} | |
| disabled={saving} | |
| placeholder="No description yet" | |
| value={semDraft[f.field] ?? semantics?.[f.field]?.purpose ?? ""} | |
| onChange={(e) => { | |
| const value = e.currentTarget.value; | |
| setSemDraft((d) => ({ ...d, [f.field]: value })); | |
| setNotice(""); | |
| }} | |
| /> | |
| </label> | |
| </div> | |
| <div className="w46-db-acts"> | |
| <label className="set-check"> | |
| <input | |
| type="checkbox" | |
| checked={f.hidden} | |
| disabled={f.locked || saving} | |
| onChange={(e) => { | |
| const value = e.currentTarget.checked; | |
| setDraft((d) => ({ ...d, [f.field]: { ...d[f.field], hidden: value } })); | |
| setNotice(""); | |
| }} | |
| /> | |
| Hidden | |
| </label> | |
| <button | |
| type="button" | |
| className="w46-db-move" | |
| onClick={() => move(i, -1)} | |
| disabled={saving || i === 0} | |
| aria-label={`Move ${f.label} up`} | |
| > | |
| Up | |
| </button> | |
| <button | |
| type="button" | |
| className="w46-db-move" | |
| onClick={() => move(i, 1)} | |
| disabled={saving || i === rows.length - 1} | |
| aria-label={`Move ${f.label} down`} | |
| > | |
| Down | |
| </button> | |
| </div> | |
| </li> | |
| ))} | |
| </ul> | |
| {disclosure ? ( | |
| <details className="set-db-source"> | |
| <summary>Source fields</summary> | |
| {disclosure.database.fieldsDeferred ? ( | |
| disclosure.readError ? ( | |
| <div className="set-error" role="alert"> | |
| <span>{disclosure.readError}</span> | |
| <button type="button" className="set-secondary" onClick={disclosure.onRetry}>Retry</button> | |
| </div> | |
| ) : <p className="set-help" role="status" aria-live="polite">Reading the source fields.</p> | |
| ) : ( | |
| <> | |
| {disclosure.database.fields.length ? ( | |
| <ul className="set-db-source-list"> | |
| {disclosure.database.fields.map((field) => ( | |
| <li key={field.key}> | |
| <span className="w46-db-key">{field.sourceField || field.key}</span> | |
| <span className="w46-db-meta">{field.type}, shown as {field.label}</span> | |
| </li> | |
| ))} | |
| </ul> | |
| ) : <p className="set-help">The source reported no fields for this database.</p>} | |
| <h4 className="set-label">Excluded</h4> | |
| {disclosure.database.excluded.length ? ( | |
| <ul className="set-db-source-list"> | |
| {disclosure.database.excluded.map((item) => ( | |
| <li key={item.sourceField}> | |
| <span className="w46-db-key">{item.sourceField}</span> | |
| <span className="w46-db-meta">{item.reason}</span> | |
| </li> | |
| ))} | |
| </ul> | |
| ) : <p className="set-help">The field catalogue held nothing back from this database.</p>} | |
| {/* The server's own sentence: an empty diff is not a claim about policy. */} | |
| <p className="set-help">{disclosure.introspection.excludedBasis || "No exclusion basis was recorded."}</p> | |
| </> | |
| )} | |
| </details> | |
| ) : null} | |
| <div className="set-actions"> | |
| <button | |
| type="button" | |
| className="set-primary" | |
| disabled={!dirty || saving || parsed === null} | |
| onClick={() => save(db.key)} | |
| > | |
| {saving ? "Saving" : "Save changes"} | |
| </button> | |
| <button | |
| type="button" | |
| className="set-secondary" | |
| disabled={!dirty || saving} | |
| onClick={() => { | |
| setDraft({}); | |
| setSemDraft({}); | |
| setNotice(""); | |
| }} | |
| > | |
| Discard | |
| </button> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| /** The draft merged over a server row, so the list shows unsaved edits without | |
| * the draft having to carry the parts nobody touched. */ | |
| function pick(patch: FieldPatch | undefined): Partial<OverlayField> { | |
| if (!patch) return {}; | |
| const out: Partial<OverlayField> = {}; | |
| if (typeof patch.label === "string") out.label = patch.label; | |
| if (typeof patch.hidden === "boolean") out.hidden = patch.hidden; | |
| if (patch.order !== undefined) out.order = patch.order; | |
| return out; | |
| } | |