@surfaces-ui/components 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,85 @@
1
+ import { type JsonObject } from "@bufbuild/protobuf";
2
+ import { type DataSource, type Operations } from "@surfaces-ui/data";
3
+ import { type MouseEvent } from "react";
4
+ import type { OnContext } from "../controls/context.js";
5
+ import { type RecordOperation, type RecordRow } from "./record.js";
6
+ /**
7
+ * How the last save stands, as whoever ran the operation reports it. It is the shape of an app shell's run state
8
+ * (`/@run/<id>`), so a renderer passes that straight in.
9
+ */
10
+ export interface RecordSaveState {
11
+ status: "running" | "approving" | "done" | "partial" | "invalid" | "refused" | "stale" | "failed";
12
+ /** The server's sentence for the person. */
13
+ message?: string;
14
+ /** For `invalid`: what the server would not take, by argument. */
15
+ errors?: Record<string, string>;
16
+ /** When this was reported: a new answer is a new time. */
17
+ at: string;
18
+ }
19
+ export interface RecordFormProps {
20
+ /** What the record is, for assistive technology: "Ticket". */
21
+ label: string;
22
+ /**
23
+ * The operation that saves, as the backend defines it: its `args` are the fields (label, type, required, options,
24
+ * limits, what waits on what). `null` when the backend has no such operation. Left out, it is asked for from
25
+ * `operations`, and while there is neither the form waits.
26
+ */
27
+ definition?: RecordOperation | null;
28
+ /** The operation's id, to ask `operations` for its definition when `definition` is not given. */
29
+ operationId?: string;
30
+ /** Where to ask for the definition. The form never runs an operation itself: saving calls `onSave`. */
31
+ operations?: Pick<Operations, "getOperation">;
32
+ /** Where the record is read from. With no `recordKey` the form is for a new record and reads nothing. */
33
+ sourceId?: string;
34
+ /** One read-only SELECT. The key is added as a filter, bound as a parameter. */
35
+ sql?: string;
36
+ /** The column that tells records apart, and the key of the one to show. No value (yet) is "not found". */
37
+ recordKey?: {
38
+ column: string;
39
+ value: string | number | boolean | null | undefined;
40
+ };
41
+ /** A record the host already read, shown at once (a server render); it is read again when `notBefore` changes. */
42
+ record?: RecordRow;
43
+ /** Which fields to show, in order: arguments of the operation to edit, other columns of the record to read. Left out: every argument. */
44
+ fields?: readonly string[];
45
+ /** The column that changes whenever the record does. Sent with a save, so the server can refuse a stale one. */
46
+ version?: string;
47
+ /** `read` shows the record with an Edit button; `edit` (the default) opens on the fields. */
48
+ mode?: "read" | "edit";
49
+ /** What the person changed and has not saved, by field: only the fields that differ from the record. Leave out to let the form keep its own. */
50
+ draft?: JsonObject;
51
+ onDraftChange?(draft: JsonObject): void;
52
+ /** Saves: run the operation with these arguments, and report how it went through `save`. */
53
+ onSave(args: JsonObject): void;
54
+ /** How the last save stands. */
55
+ save?: RecordSaveState;
56
+ /** For a save that ended `stale`: have views of the same source read again, and clear the state. The form reads its own record again. */
57
+ onReread?(): void;
58
+ /** Told the record each time it is read, and `undefined` when there is none. */
59
+ onRecord?(record: RecordRow | undefined): void;
60
+ /** ISO 8601 time of the last change to the source: the record is read again when it changes. */
61
+ notBefore?: string;
62
+ /** Where "not found" links back to. */
63
+ back?: {
64
+ href: string;
65
+ label?: string;
66
+ onClick?(event: MouseEvent<HTMLAnchorElement>): void;
67
+ };
68
+ saveLabel?: string;
69
+ /** In place of the engine's text when the record cannot be read. */
70
+ errorMessage?: string;
71
+ /** Something above says each finished save in a live region of its own, so the form does not say "Saved" twice. */
72
+ announced?: boolean;
73
+ /** Told what the person did: which fields a save changed, never their values. */
74
+ onContext?: OnContext;
75
+ dataSource?: DataSource;
76
+ className?: string;
77
+ }
78
+ /**
79
+ * One record, shown and changed. The fields come from the operation that saves it, so a field is described once
80
+ * and what the form checks is what the server checks. The record is read once through the `DataSource`; what a
81
+ * person changes is a draft holding only the changed fields; saving hands the arguments to `onSave`, which runs the
82
+ * operation (an app shell's `run`, with its approvals and receipts), and the answer comes back through `save`: a
83
+ * refused value is shown beside its field, a stale save keeps the draft and offers to read again.
84
+ */
85
+ export declare function RecordForm(props: RecordFormProps): import("react").JSX.Element;
@@ -0,0 +1,221 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { create } from "@bufbuild/protobuf";
3
+ import { fieldAsked, queryErrorInfo } from "@surfaces-ui/data";
4
+ import { FieldType, FormDefinitionSchema } from "@surfaces-ui/proto";
5
+ import { useEffect, useId, useMemo, useRef, useState } from "react";
6
+ import { useOptionalDataSource } from "../data/DataSourceProvider.js";
7
+ import { FieldInput } from "../form/Form.js";
8
+ import { label as text } from "../locale/locale.js";
9
+ import { draftWith, fieldSpec, recordPlan, recordReader, recordSave } from "./record.js";
10
+ const shownValue = (value, type) => (value === null || value === undefined || value === "" ? "–" : type === FieldType.BOOLEAN || typeof value === "boolean" ? text(value === true ? "record.yes" : "record.no") : String(value));
11
+ /**
12
+ * One record, shown and changed. The fields come from the operation that saves it, so a field is described once
13
+ * and what the form checks is what the server checks. The record is read once through the `DataSource`; what a
14
+ * person changes is a draft holding only the changed fields; saving hands the arguments to `onSave`, which runs the
15
+ * operation (an app shell's `run`, with its approvals and receipts), and the answer comes back through `save`: a
16
+ * refused value is shown beside its field, a stale save keeps the draft and offers to read again.
17
+ */
18
+ export function RecordForm(props) {
19
+ const { label, fields, version, recordKey, sourceId, sql, save, notBefore } = props;
20
+ const formId = useId();
21
+ const source = useOptionalDataSource(props.dataSource);
22
+ const isNew = recordKey === undefined;
23
+ // The operation's definition: given, or asked for once.
24
+ const [asked, setAsked] = useState();
25
+ const { operations, operationId } = props;
26
+ useEffect(() => {
27
+ if (props.definition !== undefined || !operations || !operationId)
28
+ return;
29
+ let alive = true;
30
+ operations.getOperation({ id: operationId }).then((reply) => alive && setAsked({ id: operationId, definition: reply.operation ?? null }), () => alive && setAsked({ id: operationId, definition: null }));
31
+ return () => {
32
+ alive = false;
33
+ };
34
+ }, [props.definition, operations, operationId]);
35
+ const definition = props.definition !== undefined ? props.definition : asked && asked.id === operationId ? asked.definition : undefined;
36
+ // The record: read once, and again when the source changed or the person asks.
37
+ const [reloads, setReloads] = useState(0);
38
+ const keyValue = recordKey?.value;
39
+ const wanted = JSON.stringify([sourceId, sql, recordKey?.column, keyValue]);
40
+ const [read, setRead] = useState(() => ({ wanted, reading: isNew ? { status: "new" } : props.record ? { status: "ready" } : { status: "loading" }, row: props.record }));
41
+ const first = useRef(props.record !== undefined);
42
+ useEffect(() => {
43
+ if (isNew)
44
+ return setRead({ wanted, reading: { status: "new" } });
45
+ // A record the host handed over is what is shown until something says it changed.
46
+ if (first.current) {
47
+ first.current = false;
48
+ return;
49
+ }
50
+ if (keyValue === null || keyValue === undefined || keyValue === "")
51
+ return setRead({ wanted, reading: { status: "missing" } });
52
+ if (!source || !sourceId || !sql)
53
+ return setRead({ wanted, reading: { status: "failed", error: "No DataSource, source or SQL to read the record with." } });
54
+ const controller = new AbortController();
55
+ // Reading the same record again keeps what is shown until the new row arrives.
56
+ setRead((current) => (current.wanted === wanted && current.row ? current : { wanted, reading: { status: "loading" } }));
57
+ recordReader(source)({ sourceId, sql, key: { column: recordKey.column, value: keyValue }, notBefore, signal: controller.signal }).then((rows) => {
58
+ if (controller.signal.aborted)
59
+ return;
60
+ setRead(rows.length === 1 ? { wanted, reading: { status: "ready" }, row: rows[0] } : { wanted, reading: { status: rows.length === 0 ? "missing" : "many" } });
61
+ }, (error) => {
62
+ if (!controller.signal.aborted)
63
+ setRead({ wanted, reading: { status: "failed", error: queryErrorInfo(error).message } });
64
+ });
65
+ return () => controller.abort();
66
+ }, [source, wanted, notBefore, reloads]); // eslint-disable-line react-hooks/exhaustive-deps
67
+ const reading = read.wanted === wanted ? read.reading : isNew ? { status: "new" } : { status: "loading" };
68
+ const record = read.wanted === wanted && !isNew ? read.row : undefined;
69
+ const onRecord = useRef(props.onRecord);
70
+ onRecord.current = props.onRecord;
71
+ useEffect(() => onRecord.current?.(record), [record]);
72
+ // The draft: only what differs from the record.
73
+ const [own, setOwn] = useState({});
74
+ const draft = props.draft ?? own;
75
+ const setDraft = (next) => {
76
+ if (props.draft === undefined)
77
+ setOwn(next);
78
+ props.onDraftChange?.(next);
79
+ };
80
+ const changes = Object.keys(draft).length;
81
+ const [mode, setMode] = useState(props.mode ?? "edit");
82
+ const [errors, setErrors] = useState({ at: 0, by: {} });
83
+ const [note, setNote] = useState();
84
+ const [compare, setCompare] = useState(false);
85
+ const box = useRef(null);
86
+ const summary = useRef(null);
87
+ const editButton = useRef(null);
88
+ const moveTo = useRef(undefined);
89
+ const plan = useMemo(() => (definition ? recordPlan(definition, { fields, key: recordKey?.column, version, record }) : undefined), [definition, fields, recordKey?.column, version, record]);
90
+ const form = useMemo(() => create(FormDefinitionSchema, { fields: definition?.args ?? [] }), [definition]);
91
+ const current = { ...Object.fromEntries(Object.entries(record ?? {}).filter(([name]) => plan?.editable.some((field) => field.name === name))), ...draft };
92
+ const visible = (plan?.shown ?? []).filter((entry) => entry.kind === "column" || fieldAsked(form, entry.field, current));
93
+ const fieldNames = new Set(visible.flatMap((entry) => (entry.kind === "field" ? [entry.field.name] : [])));
94
+ const labelOf = (name) => definition?.args.find((field) => field.name === name)?.label || name;
95
+ const inputOf = (name) => [...(box.current?.querySelectorAll("[data-field]") ?? [])].find((element) => element.dataset.field === name)?.querySelector("input, select, textarea");
96
+ // One thing wrong: focus goes to it. Several: to the list of them, which links to each.
97
+ useEffect(() => {
98
+ if (errors.at === 0)
99
+ return;
100
+ const names = Object.keys(errors.by);
101
+ if (names.length === 1 && fieldNames.has(names[0]))
102
+ inputOf(names[0])?.focus();
103
+ else
104
+ summary.current?.focus();
105
+ }, [errors.at]); // eslint-disable-line react-hooks/exhaustive-deps
106
+ useEffect(() => {
107
+ const to = moveTo.current;
108
+ moveTo.current = undefined;
109
+ if (to === "edit")
110
+ editButton.current?.focus();
111
+ else if (to === "first")
112
+ box.current?.querySelector("[data-field] input, [data-field] select, [data-field] textarea")?.focus();
113
+ }, [mode]);
114
+ // The answer to a save, once: what the server refused, or that it is done.
115
+ const answered = useRef(undefined);
116
+ const sent = useRef([]);
117
+ useEffect(() => {
118
+ if (!save || save.at === answered.current || save.status === "running" || save.status === "approving")
119
+ return;
120
+ answered.current = save.at;
121
+ if (save.status === "invalid") {
122
+ const by = save.errors ?? {};
123
+ const count = Object.keys(by).length;
124
+ setErrors({ at: Date.now(), by });
125
+ setNote({ kind: "attention", text: count === 1 ? text("record.notSavedOne") : text("record.notSaved", { count }) });
126
+ }
127
+ else if (save.status === "done" || save.status === "partial") {
128
+ setErrors({ at: 0, by: {} });
129
+ setDraft({});
130
+ setCompare(false);
131
+ setNote({ kind: "saved", text: save.message || text("record.saved") });
132
+ setReloads((count) => count + 1);
133
+ props.onContext?.({ kind: isNew ? "record.created" : "record.saved", summary: isNew ? `Created a ${label} record.` : `Saved changes to ${label}: ${sent.current.map(labelOf).join(", ") || "no fields"}.`, subject: { record: label, fields: sent.current } });
134
+ if (props.mode === "read") {
135
+ moveTo.current = "edit";
136
+ setMode("read");
137
+ }
138
+ }
139
+ else {
140
+ // Refused, stale or failed: said beside the button, and whatever an earlier answer said about a field no longer stands.
141
+ setErrors({ at: 0, by: {} });
142
+ setNote(undefined);
143
+ }
144
+ }, [save?.at, save?.status]); // eslint-disable-line react-hooks/exhaustive-deps
145
+ const busy = save?.status === "running" || save?.status === "approving";
146
+ const change = (name, value) => {
147
+ const field = definition?.args.find((candidate) => candidate.name === name);
148
+ if (!field)
149
+ return;
150
+ setDraft(draftWith(draft, record, field, value));
151
+ if (errors.by[name])
152
+ setErrors(({ at, by: { [name]: _gone, ...rest } }) => ({ at: Object.keys(rest).length ? at : 0, by: rest }));
153
+ };
154
+ const submit = (event) => {
155
+ event.preventDefault();
156
+ if (busy || !definition)
157
+ return;
158
+ if (!isNew && changes === 0)
159
+ return setNote({ kind: "unchanged", text: text("record.unchanged") });
160
+ const plan = recordSave(definition, { record, draft, key: recordKey && keyValue !== null && keyValue !== undefined ? { column: recordKey.column, value: keyValue } : undefined, version });
161
+ const count = Object.keys(plan.errors).length;
162
+ if (!plan.args) {
163
+ setErrors({ at: Date.now(), by: plan.errors });
164
+ setNote({ kind: "attention", text: count === 1 ? text("record.notSavedOne") : text("record.notSaved", { count }) });
165
+ return;
166
+ }
167
+ setErrors({ at: 0, by: {} });
168
+ setNote(undefined);
169
+ sent.current = plan.changed;
170
+ props.onSave(plan.args);
171
+ };
172
+ const reread = () => {
173
+ setCompare(true);
174
+ setReloads((count) => count + 1);
175
+ props.onReread?.();
176
+ };
177
+ const className = ["sf-form", "sf-record", props.className].filter(Boolean).join(" ");
178
+ if (reading.status === "missing" || reading.status === "many" || reading.status === "failed") {
179
+ return (_jsx("div", { className: className, "data-record": reading.status, children: _jsxs("div", { className: "sf-record-missing", role: "alert", "data-error": reading.status === "failed" ? reading.error : undefined, children: [_jsx("p", { children: reading.status === "missing" ? text("record.notFound", { label }) : reading.status === "many" ? text("record.many") : (props.errorMessage ?? text("record.unread")) }), props.back && (_jsx("p", { children: _jsx("a", { className: "sf-a2-link", href: props.back.href, onClick: props.back.onClick, children: props.back.label ?? text("record.back") }) }))] }) }));
180
+ }
181
+ if (definition === null) {
182
+ return (_jsx("div", { className: className, "data-record": "undefined", children: _jsx("p", { className: "sf-record-missing", role: "alert", children: text("record.noOperation") }) }));
183
+ }
184
+ if (!definition || (reading.status === "loading" && !record)) {
185
+ return (_jsx("div", { className: className, "data-record": "loading", "aria-busy": "true", children: _jsx("p", { className: "sf-form-status", role: "status", children: text("record.reading") }) }));
186
+ }
187
+ const alert = save && save.at === answered.current && (save.status === "refused" || save.status === "stale" || save.status === "failed") ? save : undefined;
188
+ const alertBox = alert && (_jsxs("div", { className: "sf-run-alert", role: "alert", "data-status": alert.status, children: [_jsx("p", { children: alert.message }), alert.status === "stale" && (_jsx("button", { type: "button", className: "sf-button", onClick: reread, children: text("run.reread") }))] }));
189
+ if (mode === "read") {
190
+ return (_jsxs("div", { className: className, "data-record": "read", role: "group", "aria-label": label, children: [_jsx("dl", { className: "sf-record-facts", children: visible.map((entry) => {
191
+ const name = entry.kind === "field" ? entry.field.name : entry.name;
192
+ return (_jsxs("div", { children: [_jsx("dt", { children: entry.kind === "field" ? entry.field.label || name : entry.label }), _jsx("dd", { children: shownValue(record?.[name], entry.kind === "field" ? entry.field.type : undefined) })] }, name));
193
+ }) }), _jsxs("div", { className: "sf-form-actions", children: [_jsx("button", { ref: editButton, type: "button", className: "sf-button", onClick: () => {
194
+ moveTo.current = "first";
195
+ setMode("edit");
196
+ }, children: text("record.edit") }), _jsx("p", { className: "sf-form-status", role: "status", "aria-live": "polite", children: note?.kind === "saved" && !props.announced ? note.text : "" }), note?.kind === "saved" && props.announced && _jsx("p", { className: "sf-form-status", children: note.text })] })] }));
197
+ }
198
+ const problems = Object.entries(errors.by);
199
+ const listed = problems.length > 1 || problems.some(([name]) => !fieldNames.has(name));
200
+ const quiet = note?.kind === "saved" && props.announced;
201
+ return (_jsxs("form", { ref: box, className: className, "data-record": "edit", onSubmit: submit, noValidate: true, "aria-label": label, children: [listed && (_jsxs("div", { ref: summary, className: "sf-record-summary", role: "group", "aria-labelledby": `${formId}-problems`, tabIndex: -1, children: [_jsx("p", { id: `${formId}-problems`, className: "sf-record-summary-title", children: problems.length === 1 ? text("record.problemsOne") : text("record.problems", { count: problems.length }) }), _jsx("ul", { children: problems.map(([name, message]) => (_jsx("li", { children: fieldNames.has(name) ? (_jsx("a", { href: `#${formId}-${name}`, onClick: (event) => {
202
+ event.preventDefault();
203
+ inputOf(name)?.focus();
204
+ }, children: `${labelOf(name)}: ${message}` })) : (`${labelOf(name)}: ${message}`) }, name))) })] })), visible.map((entry) => {
205
+ if (entry.kind === "column") {
206
+ return (_jsx("dl", { className: "sf-record-facts", children: _jsxs("div", { children: [_jsx("dt", { children: entry.label }), _jsx("dd", { children: shownValue(record?.[entry.name]) })] }) }, entry.name));
207
+ }
208
+ const spec = fieldSpec(entry.field);
209
+ const name = spec.name;
210
+ // After a stale save was read again, a changed field says what is saved now, so the person can compare.
211
+ const was = compare && record && Object.hasOwn(draft, name) ? text("record.savedValue", { value: shownValue(record[name], entry.field.type) }) : "";
212
+ return (_jsx("div", { id: `${formId}-${name}`, className: "sf-record-field", "data-field": name, "data-changed": Object.hasOwn(draft, name) || undefined, children: _jsx(FieldInput, { field: { ...spec, help: [spec.help, was].filter(Boolean).join(" ") || undefined }, value: current[name], error: errors.by[name], onChange: (value) => change(name, value) }) }, name));
213
+ }), alertBox, _jsxs("div", { className: "sf-form-actions", children: [_jsx("button", { type: "submit", className: "sf-button", "data-variant": "primary", "aria-disabled": busy || undefined, children: busy ? text("record.saving") : (props.saveLabel ?? text("record.save")) }), props.mode === "read" && (_jsx("button", { type: "button", className: "sf-button", onClick: () => {
214
+ setDraft({});
215
+ setErrors({ at: 0, by: {} });
216
+ setNote(undefined);
217
+ moveTo.current = "edit";
218
+ setMode("read");
219
+ }, children: text("record.cancel") })), _jsx("p", { className: note?.kind === "attention" ? "sf-form-error" : "sf-form-status", role: "status", "aria-live": "polite", children: note && !quiet ? note.text : "" }), quiet && _jsx("p", { className: "sf-form-status", children: note.text })] })] }));
220
+ }
221
+ //# sourceMappingURL=RecordForm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RecordForm.js","sourceRoot":"","sources":["../../src/record/RecordForm.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,MAAM,EAAmC,MAAM,oBAAoB,CAAC;AAC7E,OAAO,EAAoC,UAAU,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACjG,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAmD,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAErH,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,KAAK,IAAI,IAAI,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAwC,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAu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C,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,aAAa,CAAC,CAAC,GACjE,EACR,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,CACxB,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,WAAW,EACrB,OAAO,EAAE,GAAG,EAAE;4BACZ,QAAQ,CAAC,EAAE,CAAC,CAAC;4BACb,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;4BAC7B,OAAO,CAAC,SAAS,CAAC,CAAC;4BACnB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAC;4BACxB,OAAO,CAAC,MAAM,CAAC,CAAC;wBAClB,CAAC,YAEA,IAAI,CAAC,eAAe,CAAC,GACf,CACV,EACD,YAAG,SAAS,EAAE,IAAI,EAAE,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,gBAAgB,EAAE,IAAI,EAAC,QAAQ,eAAW,QAAQ,YAC5G,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAC9B,EACH,KAAK,IAAI,YAAG,SAAS,EAAC,gBAAgB,YAAE,IAAI,CAAC,IAAI,GAAK,IACnD,IACD,CACR,CAAC;AACJ,CAAC","sourcesContent":["import { create, type JsonObject, type JsonValue } from \"@bufbuild/protobuf\";\nimport { type DataSource, type Operations, fieldAsked, queryErrorInfo } from \"@surfaces-ui/data\";\nimport { FieldType, FormDefinitionSchema } from \"@surfaces-ui/proto\";\nimport { type FormEvent, type MouseEvent, type ReactNode, useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport type { OnContext } from \"../controls/context.js\";\nimport { useOptionalDataSource } from \"../data/DataSourceProvider.js\";\nimport { FieldInput } from \"../form/Form.js\";\nimport { label as text } from \"../locale/locale.js\";\nimport { type RecordOperation, type RecordRow, draftWith, fieldSpec, recordPlan, recordReader, recordSave } from \"./record.js\";\n\n/**\n * How the last save stands, as whoever ran the operation reports it. It is the shape of an app shell's run state\n * (`/@run/<id>`), so a renderer passes that straight in.\n */\nexport interface RecordSaveState {\n status: \"running\" | \"approving\" | \"done\" | \"partial\" | \"invalid\" | \"refused\" | \"stale\" | \"failed\";\n /** The server's sentence for the person. */\n message?: string;\n /** For `invalid`: what the server would not take, by argument. */\n errors?: Record<string, string>;\n /** When this was reported: a new answer is a new time. */\n at: string;\n}\n\nexport interface RecordFormProps {\n /** What the record is, for assistive technology: \"Ticket\". */\n label: string;\n /**\n * The operation that saves, as the backend defines it: its `args` are the fields (label, type, required, options,\n * limits, what waits on what). `null` when the backend has no such operation. Left out, it is asked for from\n * `operations`, and while there is neither the form waits.\n */\n definition?: RecordOperation | null;\n /** The operation's id, to ask `operations` for its definition when `definition` is not given. */\n operationId?: string;\n /** Where to ask for the definition. The form never runs an operation itself: saving calls `onSave`. */\n operations?: Pick<Operations, \"getOperation\">;\n /** Where the record is read from. With no `recordKey` the form is for a new record and reads nothing. */\n sourceId?: string;\n /** One read-only SELECT. The key is added as a filter, bound as a parameter. */\n sql?: string;\n /** The column that tells records apart, and the key of the one to show. No value (yet) is \"not found\". */\n recordKey?: { column: string; value: string | number | boolean | null | undefined };\n /** A record the host already read, shown at once (a server render); it is read again when `notBefore` changes. */\n record?: RecordRow;\n /** Which fields to show, in order: arguments of the operation to edit, other columns of the record to read. Left out: every argument. */\n fields?: readonly string[];\n /** The column that changes whenever the record does. Sent with a save, so the server can refuse a stale one. */\n version?: string;\n /** `read` shows the record with an Edit button; `edit` (the default) opens on the fields. */\n mode?: \"read\" | \"edit\";\n /** What the person changed and has not saved, by field: only the fields that differ from the record. Leave out to let the form keep its own. */\n draft?: JsonObject;\n onDraftChange?(draft: JsonObject): void;\n /** Saves: run the operation with these arguments, and report how it went through `save`. */\n onSave(args: JsonObject): void;\n /** How the last save stands. */\n save?: RecordSaveState;\n /** For a save that ended `stale`: have views of the same source read again, and clear the state. The form reads its own record again. */\n onReread?(): void;\n /** Told the record each time it is read, and `undefined` when there is none. */\n onRecord?(record: RecordRow | undefined): void;\n /** ISO 8601 time of the last change to the source: the record is read again when it changes. */\n notBefore?: string;\n /** Where \"not found\" links back to. */\n back?: { href: string; label?: string; onClick?(event: MouseEvent<HTMLAnchorElement>): void };\n saveLabel?: string;\n /** In place of the engine's text when the record cannot be read. */\n errorMessage?: string;\n /** Something above says each finished save in a live region of its own, so the form does not say \"Saved\" twice. */\n announced?: boolean;\n /** Told what the person did: which fields a save changed, never their values. */\n onContext?: OnContext;\n dataSource?: DataSource;\n className?: string;\n}\n\ntype Reading = { status: \"new\" } | { status: \"loading\" | \"missing\" | \"many\" } | { status: \"failed\"; error: string } | { status: \"ready\" };\n\nconst shownValue = (value: unknown, type?: FieldType): string => (value === null || value === undefined || value === \"\" ? \"–\" : type === FieldType.BOOLEAN || typeof value === \"boolean\" ? text(value === true ? \"record.yes\" : \"record.no\") : String(value));\n\n/**\n * One record, shown and changed. The fields come from the operation that saves it, so a field is described once\n * and what the form checks is what the server checks. The record is read once through the `DataSource`; what a\n * person changes is a draft holding only the changed fields; saving hands the arguments to `onSave`, which runs the\n * operation (an app shell's `run`, with its approvals and receipts), and the answer comes back through `save`: a\n * refused value is shown beside its field, a stale save keeps the draft and offers to read again.\n */\nexport function RecordForm(props: RecordFormProps) {\n const { label, fields, version, recordKey, sourceId, sql, save, notBefore } = props;\n const formId = useId();\n const source = useOptionalDataSource(props.dataSource);\n const isNew = recordKey === undefined;\n\n // The operation's definition: given, or asked for once.\n const [asked, setAsked] = useState<{ id: string; definition: RecordOperation | null }>();\n const { operations, operationId } = props;\n useEffect(() => {\n if (props.definition !== undefined || !operations || !operationId) return;\n let alive = true;\n operations.getOperation({ id: operationId }).then(\n (reply) => alive && setAsked({ id: operationId, definition: reply.operation ?? null }),\n () => alive && setAsked({ id: operationId, definition: null }),\n );\n return () => {\n alive = false;\n };\n }, [props.definition, operations, operationId]);\n const definition = props.definition !== undefined ? props.definition : asked && asked.id === operationId ? asked.definition : undefined;\n\n // The record: read once, and again when the source changed or the person asks.\n const [reloads, setReloads] = useState(0);\n const keyValue = recordKey?.value;\n const wanted = JSON.stringify([sourceId, sql, recordKey?.column, keyValue]);\n const [read, setRead] = useState<{ wanted: string; reading: Reading; row?: RecordRow }>(() => ({ wanted, reading: isNew ? { status: \"new\" } : props.record ? { status: \"ready\" } : { status: \"loading\" }, row: props.record }));\n const first = useRef(props.record !== undefined);\n useEffect(() => {\n if (isNew) return setRead({ wanted, reading: { status: \"new\" } });\n // A record the host handed over is what is shown until something says it changed.\n if (first.current) {\n first.current = false;\n return;\n }\n if (keyValue === null || keyValue === undefined || keyValue === \"\") return setRead({ wanted, reading: { status: \"missing\" } });\n if (!source || !sourceId || !sql) return setRead({ wanted, reading: { status: \"failed\", error: \"No DataSource, source or SQL to read the record with.\" } });\n const controller = new AbortController();\n // Reading the same record again keeps what is shown until the new row arrives.\n setRead((current) => (current.wanted === wanted && current.row ? current : { wanted, reading: { status: \"loading\" } }));\n recordReader(source)({ sourceId, sql, key: { column: recordKey!.column, value: keyValue }, notBefore, signal: controller.signal }).then(\n (rows) => {\n if (controller.signal.aborted) return;\n setRead(rows.length === 1 ? { wanted, reading: { status: \"ready\" }, row: rows[0] } : { wanted, reading: { status: rows.length === 0 ? \"missing\" : \"many\" } });\n },\n (error: unknown) => {\n if (!controller.signal.aborted) setRead({ wanted, reading: { status: \"failed\", error: queryErrorInfo(error).message } });\n },\n );\n return () => controller.abort();\n }, [source, wanted, notBefore, reloads]); // eslint-disable-line react-hooks/exhaustive-deps\n const reading: Reading = read.wanted === wanted ? read.reading : isNew ? { status: \"new\" } : { status: \"loading\" };\n const record = read.wanted === wanted && !isNew ? read.row : undefined;\n const onRecord = useRef(props.onRecord);\n onRecord.current = props.onRecord;\n useEffect(() => onRecord.current?.(record), [record]);\n\n // The draft: only what differs from the record.\n const [own, setOwn] = useState<JsonObject>({});\n const draft = props.draft ?? own;\n const setDraft = (next: JsonObject) => {\n if (props.draft === undefined) setOwn(next);\n props.onDraftChange?.(next);\n };\n const changes = Object.keys(draft).length;\n\n const [mode, setMode] = useState(props.mode ?? \"edit\");\n const [errors, setErrors] = useState<{ at: number; by: Record<string, string> }>({ at: 0, by: {} });\n const [note, setNote] = useState<{ kind: \"saved\" | \"attention\" | \"unchanged\"; text: string }>();\n const [compare, setCompare] = useState(false);\n const box = useRef<HTMLFormElement>(null);\n const summary = useRef<HTMLDivElement>(null);\n const editButton = useRef<HTMLButtonElement>(null);\n const moveTo = useRef<\"edit\" | \"first\" | undefined>(undefined);\n\n const plan = useMemo(() => (definition ? recordPlan(definition, { fields, key: recordKey?.column, version, record }) : undefined), [definition, fields, recordKey?.column, version, record]);\n const form = useMemo(() => create(FormDefinitionSchema, { fields: definition?.args ?? [] }), [definition]);\n const current: JsonObject = { ...Object.fromEntries(Object.entries(record ?? {}).filter(([name]) => plan?.editable.some((field) => field.name === name))), ...draft };\n const visible = (plan?.shown ?? []).filter((entry) => entry.kind === \"column\" || fieldAsked(form, entry.field, current));\n const fieldNames = new Set(visible.flatMap((entry) => (entry.kind === \"field\" ? [entry.field.name] : [])));\n const labelOf = (name: string) => definition?.args.find((field) => field.name === name)?.label || name;\n\n const inputOf = (name: string) => [...(box.current?.querySelectorAll<HTMLElement>(\"[data-field]\") ?? [])].find((element) => element.dataset.field === name)?.querySelector<HTMLElement>(\"input, select, textarea\");\n // One thing wrong: focus goes to it. Several: to the list of them, which links to each.\n useEffect(() => {\n if (errors.at === 0) return;\n const names = Object.keys(errors.by);\n if (names.length === 1 && fieldNames.has(names[0]!)) inputOf(names[0]!)?.focus();\n else summary.current?.focus();\n }, [errors.at]); // eslint-disable-line react-hooks/exhaustive-deps\n useEffect(() => {\n const to = moveTo.current;\n moveTo.current = undefined;\n if (to === \"edit\") editButton.current?.focus();\n else if (to === \"first\") box.current?.querySelector<HTMLElement>(\"[data-field] input, [data-field] select, [data-field] textarea\")?.focus();\n }, [mode]);\n\n // The answer to a save, once: what the server refused, or that it is done.\n const answered = useRef<string | undefined>(undefined);\n const sent = useRef<string[]>([]);\n useEffect(() => {\n if (!save || save.at === answered.current || save.status === \"running\" || save.status === \"approving\") return;\n answered.current = save.at;\n if (save.status === \"invalid\") {\n const by = save.errors ?? {};\n const count = Object.keys(by).length;\n setErrors({ at: Date.now(), by });\n setNote({ kind: \"attention\", text: count === 1 ? text(\"record.notSavedOne\") : text(\"record.notSaved\", { count }) });\n } else if (save.status === \"done\" || save.status === \"partial\") {\n setErrors({ at: 0, by: {} });\n setDraft({});\n setCompare(false);\n setNote({ kind: \"saved\", text: save.message || text(\"record.saved\") });\n setReloads((count) => count + 1);\n props.onContext?.({ kind: isNew ? \"record.created\" : \"record.saved\", summary: isNew ? `Created a ${label} record.` : `Saved changes to ${label}: ${sent.current.map(labelOf).join(\", \") || \"no fields\"}.`, subject: { record: label, fields: sent.current } });\n if (props.mode === \"read\") {\n moveTo.current = \"edit\";\n setMode(\"read\");\n }\n } else {\n // Refused, stale or failed: said beside the button, and whatever an earlier answer said about a field no longer stands.\n setErrors({ at: 0, by: {} });\n setNote(undefined);\n }\n }, [save?.at, save?.status]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const busy = save?.status === \"running\" || save?.status === \"approving\";\n const change = (name: string, value: JsonValue) => {\n const field = definition?.args.find((candidate) => candidate.name === name);\n if (!field) return;\n setDraft(draftWith(draft, record, field, value));\n if (errors.by[name]) setErrors(({ at, by: { [name]: _gone, ...rest } }) => ({ at: Object.keys(rest).length ? at : 0, by: rest }));\n };\n const submit = (event: FormEvent) => {\n event.preventDefault();\n if (busy || !definition) return;\n if (!isNew && changes === 0) return setNote({ kind: \"unchanged\", text: text(\"record.unchanged\") });\n const plan = recordSave(definition, { record, draft, key: recordKey && keyValue !== null && keyValue !== undefined ? { column: recordKey.column, value: keyValue } : undefined, version });\n const count = Object.keys(plan.errors).length;\n if (!plan.args) {\n setErrors({ at: Date.now(), by: plan.errors });\n setNote({ kind: \"attention\", text: count === 1 ? text(\"record.notSavedOne\") : text(\"record.notSaved\", { count }) });\n return;\n }\n setErrors({ at: 0, by: {} });\n setNote(undefined);\n sent.current = plan.changed;\n props.onSave(plan.args);\n };\n const reread = () => {\n setCompare(true);\n setReloads((count) => count + 1);\n props.onReread?.();\n };\n\n const className = [\"sf-form\", \"sf-record\", props.className].filter(Boolean).join(\" \");\n if (reading.status === \"missing\" || reading.status === \"many\" || reading.status === \"failed\") {\n return (\n <div className={className} data-record={reading.status}>\n <div className=\"sf-record-missing\" role=\"alert\" data-error={reading.status === \"failed\" ? reading.error : undefined}>\n <p>{reading.status === \"missing\" ? text(\"record.notFound\", { label }) : reading.status === \"many\" ? text(\"record.many\") : (props.errorMessage ?? text(\"record.unread\"))}</p>\n {props.back && (\n <p>\n <a className=\"sf-a2-link\" href={props.back.href} onClick={props.back.onClick}>\n {props.back.label ?? text(\"record.back\")}\n </a>\n </p>\n )}\n </div>\n </div>\n );\n }\n if (definition === null) {\n return (\n <div className={className} data-record=\"undefined\">\n <p className=\"sf-record-missing\" role=\"alert\">\n {text(\"record.noOperation\")}\n </p>\n </div>\n );\n }\n if (!definition || (reading.status === \"loading\" && !record)) {\n return (\n <div className={className} data-record=\"loading\" aria-busy=\"true\">\n <p className=\"sf-form-status\" role=\"status\">\n {text(\"record.reading\")}\n </p>\n </div>\n );\n }\n\n const alert = save && save.at === answered.current && (save.status === \"refused\" || save.status === \"stale\" || save.status === \"failed\") ? save : undefined;\n const alertBox: ReactNode = alert && (\n <div className=\"sf-run-alert\" role=\"alert\" data-status={alert.status}>\n <p>{alert.message}</p>\n {alert.status === \"stale\" && (\n <button type=\"button\" className=\"sf-button\" onClick={reread}>\n {text(\"run.reread\")}\n </button>\n )}\n </div>\n );\n\n if (mode === \"read\") {\n return (\n <div className={className} data-record=\"read\" role=\"group\" aria-label={label}>\n <dl className=\"sf-record-facts\">\n {visible.map((entry) => {\n const name = entry.kind === \"field\" ? entry.field.name : entry.name;\n return (\n <div key={name}>\n <dt>{entry.kind === \"field\" ? entry.field.label || name : entry.label}</dt>\n <dd>{shownValue(record?.[name], entry.kind === \"field\" ? entry.field.type : undefined)}</dd>\n </div>\n );\n })}\n </dl>\n <div className=\"sf-form-actions\">\n <button\n ref={editButton}\n type=\"button\"\n className=\"sf-button\"\n onClick={() => {\n moveTo.current = \"first\";\n setMode(\"edit\");\n }}\n >\n {text(\"record.edit\")}\n </button>\n <p className=\"sf-form-status\" role=\"status\" aria-live=\"polite\">\n {note?.kind === \"saved\" && !props.announced ? note.text : \"\"}\n </p>\n {note?.kind === \"saved\" && props.announced && <p className=\"sf-form-status\">{note.text}</p>}\n </div>\n </div>\n );\n }\n\n const problems = Object.entries(errors.by);\n const listed = problems.length > 1 || problems.some(([name]) => !fieldNames.has(name));\n const quiet = note?.kind === \"saved\" && props.announced;\n return (\n <form ref={box} className={className} data-record=\"edit\" onSubmit={submit} noValidate aria-label={label}>\n {listed && (\n <div ref={summary} className=\"sf-record-summary\" role=\"group\" aria-labelledby={`${formId}-problems`} tabIndex={-1}>\n <p id={`${formId}-problems`} className=\"sf-record-summary-title\">\n {problems.length === 1 ? text(\"record.problemsOne\") : text(\"record.problems\", { count: problems.length })}\n </p>\n <ul>\n {problems.map(([name, message]) => (\n <li key={name}>\n {fieldNames.has(name) ? (\n <a\n href={`#${formId}-${name}`}\n onClick={(event) => {\n event.preventDefault();\n inputOf(name)?.focus();\n }}\n >\n {`${labelOf(name)}: ${message}`}\n </a>\n ) : (\n `${labelOf(name)}: ${message}`\n )}\n </li>\n ))}\n </ul>\n </div>\n )}\n {visible.map((entry) => {\n if (entry.kind === \"column\") {\n return (\n <dl key={entry.name} className=\"sf-record-facts\">\n <div>\n <dt>{entry.label}</dt>\n <dd>{shownValue(record?.[entry.name])}</dd>\n </div>\n </dl>\n );\n }\n const spec = fieldSpec(entry.field);\n const name = spec.name;\n // After a stale save was read again, a changed field says what is saved now, so the person can compare.\n const was = compare && record && Object.hasOwn(draft, name) ? text(\"record.savedValue\", { value: shownValue(record[name], entry.field.type) }) : \"\";\n return (\n <div key={name} id={`${formId}-${name}`} className=\"sf-record-field\" data-field={name} data-changed={Object.hasOwn(draft, name) || undefined}>\n <FieldInput field={{ ...spec, help: [spec.help, was].filter(Boolean).join(\" \") || undefined }} value={current[name]} error={errors.by[name]} onChange={(value) => change(name, value)} />\n </div>\n );\n })}\n {alertBox}\n <div className=\"sf-form-actions\">\n <button type=\"submit\" className=\"sf-button\" data-variant=\"primary\" aria-disabled={busy || undefined}>\n {busy ? text(\"record.saving\") : (props.saveLabel ?? text(\"record.save\"))}\n </button>\n {props.mode === \"read\" && (\n <button\n type=\"button\"\n className=\"sf-button\"\n onClick={() => {\n setDraft({});\n setErrors({ at: 0, by: {} });\n setNote(undefined);\n moveTo.current = \"edit\";\n setMode(\"read\");\n }}\n >\n {text(\"record.cancel\")}\n </button>\n )}\n <p className={note?.kind === \"attention\" ? \"sf-form-error\" : \"sf-form-status\"} role=\"status\" aria-live=\"polite\">\n {note && !quiet ? note.text : \"\"}\n </p>\n {quiet && <p className=\"sf-form-status\">{note.text}</p>}\n </div>\n </form>\n );\n}\n"]}
@@ -0,0 +1,82 @@
1
+ import type { JsonObject, JsonValue } from "@bufbuild/protobuf";
2
+ import { type DataSource } from "@surfaces-ui/data";
3
+ import { FieldType, type FormField, type OperationDefinition } from "@surfaces-ui/proto";
4
+ import type { FormFieldSpec } from "../form/Form.js";
5
+ /** One record as plain values by column: numbers as numbers, dates and times as ISO text, a missing value as null. */
6
+ export type RecordRow = Record<string, string | number | boolean | null>;
7
+ /** What a record form reads of the operation that saves it: its arguments are the form's fields. */
8
+ export type RecordOperation = Pick<OperationDefinition, "args"> & Partial<Pick<OperationDefinition, "id" | "title">>;
9
+ /** One record to read: a read-only query and the key that picks the row. */
10
+ export interface RecordRequest {
11
+ sourceId: string;
12
+ sql: string;
13
+ key: {
14
+ column: string;
15
+ value: string | number | boolean;
16
+ };
17
+ notBefore?: string;
18
+ signal?: AbortSignal;
19
+ }
20
+ /**
21
+ * Reads the rows a key picks, over any `DataSource`: the base SQL with the key as a filter the engine binds as a
22
+ * parameter, never spliced into the text, and two rows at most (one is the record, two means the key is not one).
23
+ * It is what `RecordForm` reads with, and what an app shell is given to read a page's `record`.
24
+ */
25
+ export declare function recordReader(dataSource: DataSource): (request: RecordRequest) => Promise<RecordRow[]>;
26
+ /** Text longer than this is given a box of several lines: the contract has one text type and says only how long. */
27
+ export declare const LONG_TEXT = 120;
28
+ /** A field as the backend defines it (`FormField`), as the spec `FieldInput` draws. */
29
+ export declare function fieldSpec(field: FormField): FormFieldSpec;
30
+ /** Whether what a person entered is what the record already holds, so a field set back is no longer a change. */
31
+ export declare function sameValue(entered: unknown, held: unknown, type: FieldType): boolean;
32
+ /** The draft with one field changed: a value the record already holds is taken out, so the draft is only what changed. */
33
+ export declare function draftWith(draft: JsonObject, record: RecordRow | undefined, field: Pick<FormField, "name" | "type">, value: JsonValue): JsonObject;
34
+ export interface RecordPlan {
35
+ /** The operation's arguments a person may change here: every one but the key and the version. */
36
+ editable: FormField[];
37
+ /** What the form shows, in order: an argument to edit, or a column of the record to read. */
38
+ shown: ({
39
+ kind: "field";
40
+ field: FormField;
41
+ } | {
42
+ kind: "column";
43
+ name: string;
44
+ label: string;
45
+ })[];
46
+ }
47
+ /**
48
+ * Which fields a record form shows. `fields` chooses and orders them; left out, it is every argument a person may
49
+ * change. A name the operation takes is a field to edit; one it does not take (and the key and the version, which
50
+ * a person never edits) is a column of the record, shown to read. A new record has no columns to show.
51
+ */
52
+ export declare function recordPlan(definition: RecordOperation, options: {
53
+ fields?: readonly string[];
54
+ key?: string;
55
+ version?: string;
56
+ record?: RecordRow;
57
+ }): RecordPlan;
58
+ export interface RecordSave {
59
+ /** What to run the operation with. Nothing when there is something to correct first. */
60
+ args?: JsonObject;
61
+ /** What is wrong, by argument: the check every backend runs (`checkOperationArgs`), run here first. */
62
+ errors: Record<string, string>;
63
+ /** The fields a person changed, by name. */
64
+ changed: string[];
65
+ }
66
+ /**
67
+ * What saving sends: the record whole, as the operation takes it. Every argument goes, with what the person changed
68
+ * laid over what the record held, the key, and the version (so the server can refuse a stale edit). It is the whole
69
+ * record and not only the changes because every backend checks a call whole and hands the operation `null` for an
70
+ * argument that was not sent (`checkSubmission`), so an operation cannot tell "not sent" from "emptied". For the same
71
+ * reason an argument the record's query did not read is refused here: saving would empty it. The values are checked
72
+ * first, as the server will check them (`checkOperationArgs`). A new record sends everything entered.
73
+ */
74
+ export declare function recordSave(definition: RecordOperation, options: {
75
+ record?: RecordRow;
76
+ draft: JsonObject;
77
+ key?: {
78
+ column: string;
79
+ value: string | number | boolean;
80
+ };
81
+ version?: string;
82
+ }): RecordSave;
@@ -0,0 +1,125 @@
1
+ import { checkOperationArgs, collect, filtersFromSpec } from "@surfaces-ui/data";
2
+ import { FieldType } from "@surfaces-ui/proto";
3
+ import { plainValue } from "../data/format.js";
4
+ /**
5
+ * Reads the rows a key picks, over any `DataSource`: the base SQL with the key as a filter the engine binds as a
6
+ * parameter, never spliced into the text, and two rows at most (one is the record, two means the key is not one).
7
+ * It is what `RecordForm` reads with, and what an app shell is given to read a page's `record`.
8
+ */
9
+ export function recordReader(dataSource) {
10
+ return async ({ sourceId, sql, key, notBefore, signal }) => {
11
+ const result = await collect(dataSource.execute({ sourceId, notBefore, query: { baseSql: sql, filters: filtersFromSpec([{ column: key.column, op: "eq", values: [key.value] }]), page: { limit: 2 } } }, { signal }));
12
+ const fields = result.table.schema.fields;
13
+ const columns = fields.map((_, index) => result.table.getChildAt(index));
14
+ return Array.from({ length: result.table.numRows }, (_, row) => Object.fromEntries(fields.map((field, column) => [field.name, plainValue(columns[column].get(row), field.type)])));
15
+ };
16
+ }
17
+ const KINDS = {
18
+ [FieldType.TEXT]: "text",
19
+ [FieldType.NUMBER]: "number",
20
+ [FieldType.INTEGER]: "integer",
21
+ [FieldType.BOOLEAN]: "boolean",
22
+ [FieldType.DATE]: "date",
23
+ [FieldType.DATETIME]: "datetime",
24
+ [FieldType.CHOICE]: "choice",
25
+ };
26
+ /** Text longer than this is given a box of several lines: the contract has one text type and says only how long. */
27
+ export const LONG_TEXT = 120;
28
+ /** A field as the backend defines it (`FormField`), as the spec `FieldInput` draws. */
29
+ export function fieldSpec(field) {
30
+ const kind = KINDS[field.type] ?? "text";
31
+ return {
32
+ name: field.name,
33
+ label: field.label || field.name,
34
+ type: kind === "text" && (field.maxLength ?? 0) > LONG_TEXT ? "longtext" : kind,
35
+ ...(field.required ? { required: true } : {}),
36
+ ...(field.options.length ? { options: [...field.options] } : {}),
37
+ ...(field.min !== undefined ? { min: field.min } : {}),
38
+ ...(field.max !== undefined ? { max: field.max } : {}),
39
+ ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}),
40
+ ...(field.pattern ? { pattern: field.pattern } : {}),
41
+ ...(field.help ? { help: field.help } : {}),
42
+ };
43
+ }
44
+ const empty = (value) => value === null || value === undefined || value === "";
45
+ /** Whether what a person entered is what the record already holds, so a field set back is no longer a change. */
46
+ export function sameValue(entered, held, type) {
47
+ if (type === FieldType.BOOLEAN)
48
+ return (entered === true) === (held === true);
49
+ if (empty(entered) || empty(held))
50
+ return empty(entered) && empty(held);
51
+ if (type === FieldType.NUMBER || type === FieldType.INTEGER)
52
+ return Number(entered) === Number(held);
53
+ if (type === FieldType.DATETIME) {
54
+ const [a, b] = [Date.parse(String(entered)), Date.parse(String(held))];
55
+ return Number.isNaN(a) || Number.isNaN(b) ? String(entered) === String(held) : a === b;
56
+ }
57
+ if (type === FieldType.DATE)
58
+ return String(entered).slice(0, 10) === String(held).slice(0, 10);
59
+ return String(entered) === String(held);
60
+ }
61
+ /** The draft with one field changed: a value the record already holds is taken out, so the draft is only what changed. */
62
+ export function draftWith(draft, record, field, value) {
63
+ const { [field.name]: _gone, ...rest } = draft;
64
+ return sameValue(value, record?.[field.name], field.type) ? rest : { ...rest, [field.name]: value };
65
+ }
66
+ /** A column's name as a label, for a column the operation does not describe: "opened_at" is "Opened at". */
67
+ const columnLabel = (name) => {
68
+ const words = name.replace(/_+/g, " ").trim();
69
+ return words ? words[0].toUpperCase() + words.slice(1) : name;
70
+ };
71
+ /**
72
+ * Which fields a record form shows. `fields` chooses and orders them; left out, it is every argument a person may
73
+ * change. A name the operation takes is a field to edit; one it does not take (and the key and the version, which
74
+ * a person never edits) is a column of the record, shown to read. A new record has no columns to show.
75
+ */
76
+ export function recordPlan(definition, options) {
77
+ const fixed = new Set([options.key, options.version].filter((name) => typeof name === "string"));
78
+ const editable = definition.args.filter((field) => !fixed.has(field.name));
79
+ const names = options.fields ?? editable.map((field) => field.name);
80
+ const shown = [];
81
+ for (const name of new Set(names)) {
82
+ const field = editable.find((candidate) => candidate.name === name);
83
+ if (field)
84
+ shown.push({ kind: "field", field });
85
+ else if (options.record && Object.hasOwn(options.record, name))
86
+ shown.push({ kind: "column", name, label: definition.args.find((candidate) => candidate.name === name)?.label || columnLabel(name) });
87
+ }
88
+ return { editable, shown };
89
+ }
90
+ /**
91
+ * What saving sends: the record whole, as the operation takes it. Every argument goes, with what the person changed
92
+ * laid over what the record held, the key, and the version (so the server can refuse a stale edit). It is the whole
93
+ * record and not only the changes because every backend checks a call whole and hands the operation `null` for an
94
+ * argument that was not sent (`checkSubmission`), so an operation cannot tell "not sent" from "emptied". For the same
95
+ * reason an argument the record's query did not read is refused here: saving would empty it. The values are checked
96
+ * first, as the server will check them (`checkOperationArgs`). A new record sends everything entered.
97
+ */
98
+ export function recordSave(definition, options) {
99
+ const { record, draft, key, version } = options;
100
+ const takes = new Map(definition.args.map((field) => [field.name, field]));
101
+ const changed = Object.keys(draft).filter((name) => takes.has(name) && name !== key?.column && name !== version);
102
+ const whole = {};
103
+ const unread = [];
104
+ for (const field of definition.args) {
105
+ if (record && !Object.hasOwn(record, field.name) && field.name !== key?.column)
106
+ unread.push(field.name);
107
+ const held = record?.[field.name];
108
+ if (held !== undefined && held !== null)
109
+ whole[field.name] = held;
110
+ }
111
+ for (const name of changed)
112
+ whole[name] = draft[name];
113
+ if (key && takes.has(key.column))
114
+ whole[key.column] = key.value;
115
+ const checked = checkOperationArgs(definition, whole);
116
+ const errors = Object.fromEntries(checked.errors.map((error) => [error.field, error.message]));
117
+ for (const name of unread)
118
+ errors[name] = "The record's query does not read this, and the operation that saves it takes it, so saving would empty it. Nothing was sent.";
119
+ if (key && !takes.has(key.column))
120
+ errors[key.column] = "The operation that saves this takes no such argument, so it cannot be told which record to change.";
121
+ if (version && record && !takes.has(version))
122
+ errors[version] = "The operation that saves this takes no such argument, so it cannot be told which version was read.";
123
+ return Object.keys(errors).length > 0 ? { errors, changed } : { args: checked.values, errors, changed };
124
+ }
125
+ //# sourceMappingURL=record.js.map