@kovca/glyph-react 0.1.0 → 0.2.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.
- package/README.md +15 -12
- package/dist/form-state.d.ts +14 -0
- package/dist/form-state.js +68 -0
- package/dist/forms.d.ts +72 -0
- package/dist/forms.js +217 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1 -0
- package/dist/renderer.d.ts +11 -5
- package/dist/renderer.js +143 -10
- package/dist/surface.d.ts +7 -4
- package/dist/surface.js +4 -1
- package/dist/types.d.ts +32 -1
- package/package.json +4 -9
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @kovca/glyph-react
|
|
2
2
|
|
|
3
|
-
A headless React renderer for [Kovca Glyph](https://kovca.io/docs/rendering) UI. You supply a React component for each Glyph component name; this package validates the model's response, walks the component tree, resolves bindings and actions, and keeps the user's edits.
|
|
3
|
+
A headless React renderer for [Kovca Glyph](https://kovca.io/docs/rendering) UI: the A2UI-style component lists the hosted model `glyph-1` returns (contract 0.3.0, catalog `glyph:standard-3`). You supply a React component for each Glyph component name; this package validates the model's response, walks the component tree, resolves bindings, conditions and actions, and keeps the user's edits and form state.
|
|
4
4
|
|
|
5
5
|
Want styled components out of the box? Install the shadcn/ui set into your app. It's built on this package, and its source is yours to change:
|
|
6
6
|
|
|
@@ -13,7 +13,7 @@ It needs a Radix shadcn style in `components.json` (such as `radix-nova`). Base
|
|
|
13
13
|
```tsx
|
|
14
14
|
import { GlyphSurface } from '@/components/glyph/glyph-surface'
|
|
15
15
|
|
|
16
|
-
<GlyphSurface request={request} response={
|
|
16
|
+
<GlyphSurface request={result.request} response={result.output} onAction={handleAction} />
|
|
17
17
|
```
|
|
18
18
|
|
|
19
19
|
## Install
|
|
@@ -27,6 +27,7 @@ Requires React 18.2 or later. The components are client components (`'use client
|
|
|
27
27
|
## Render a response
|
|
28
28
|
|
|
29
29
|
```tsx
|
|
30
|
+
import type { GlyphGeneration } from '@kovca/glyph'
|
|
30
31
|
import { GlyphSurface, type GlyphComponents } from '@kovca/glyph-react'
|
|
31
32
|
|
|
32
33
|
const components: GlyphComponents = {
|
|
@@ -34,15 +35,16 @@ const components: GlyphComponents = {
|
|
|
34
35
|
Text: (p) => <p>{p.text('text')}</p>,
|
|
35
36
|
Button: (p) => {
|
|
36
37
|
const action = p.action()
|
|
37
|
-
return <button disabled={action.disabled} onClick={action.invoke}>{p.
|
|
38
|
+
return <button disabled={action.disabled} onClick={action.invoke}>{p.text('label')}</button>
|
|
38
39
|
},
|
|
39
40
|
}
|
|
40
41
|
|
|
41
|
-
|
|
42
|
+
// result: the body of POST /v1/generate (https://kovca.io/docs/api)
|
|
43
|
+
export function Answer({ result }: { result: GlyphGeneration }) {
|
|
42
44
|
return (
|
|
43
45
|
<GlyphSurface
|
|
44
|
-
request={request}
|
|
45
|
-
response={
|
|
46
|
+
request={result.request}
|
|
47
|
+
response={result.output}
|
|
46
48
|
components={components}
|
|
47
49
|
onAction={(event) => console.log(event.name, event.context)}
|
|
48
50
|
renderRefusal={(reason) => <p role="status">{reason}</p>}
|
|
@@ -54,15 +56,13 @@ export function Answer({ request, response }: { request: unknown; response: unkn
|
|
|
54
56
|
|
|
55
57
|
`GlyphSurface` validates the pair first (with `@kovca/glyph`). A response that uses a component missing from `components`, or that fails validation, renders `renderError` and nothing else. A component that throws while rendering does the same, with the code `render_rejected`.
|
|
56
58
|
|
|
57
|
-
For `glyph-1-oui`, compile the program first: `response = fromOpenUI(result.openui, result.request)` from `@kovca/glyph`.
|
|
58
|
-
|
|
59
59
|
### `GlyphSurface` props
|
|
60
60
|
|
|
61
61
|
| Prop | |
|
|
62
62
|
| --- | --- |
|
|
63
|
-
| `request`, `response` | The
|
|
63
|
+
| `request`, `response` | The API result's `request` and `output` (contract 0.3.0, or 0.2.0). Untrusted input is fine. |
|
|
64
64
|
| `components` | A component for every Glyph component name you render. |
|
|
65
|
-
| `onAction(event)` | A user triggered an action: `{ name, context, sourceComponentId }`. Your app decides what it does. |
|
|
65
|
+
| `onAction(event)` | A user triggered an action: `{ name, context, sourceComponentId }`. Your app decides what it does; return (or resolve to) `{ errors: [{ path?, message }] }` to show errors at their fields. |
|
|
66
66
|
| `onValuesChange(values)` | The data after each accepted edit. Edits are kept inside the surface until `request` changes. |
|
|
67
67
|
| `renderRefusal(reason)` | The model declined to build a UI. Default: nothing. |
|
|
68
68
|
| `renderError({ code, message })` | The response can't be shown. Default: nothing. |
|
|
@@ -83,12 +83,15 @@ Every component receives `GlyphComponentProps`:
|
|
|
83
83
|
| `uri(prop)` | A safe `https` media URL, or `undefined`. |
|
|
84
84
|
| `children(prop = 'children')` | The rendered child components. |
|
|
85
85
|
| `items(prop = 'children')` | The children as `{ key, id, name, node, text, value, render }`, for components that wrap each child (tabs, lists, tables). |
|
|
86
|
-
| `input(prop = 'value')` | The bound field: `{ path, value, field, change }`. Call `change(next)` when the user edits it. |
|
|
87
|
-
| `action(prop = 'action')` | `{ name, disabled, invoke, event }`. Call `invoke()` to send it to `onAction
|
|
86
|
+
| `input(prop = 'value')` | The bound field: `{ path, value, field, change, readOnly, required, errors }`. Call `change(next)` when the user edits it; show `errors` at the field. |
|
|
87
|
+
| `action(prop = 'action')` | `{ name, disabled, invoke, event, blocked, submit, messages }`. Call `invoke()` to send it to `onAction`; a blocked action reveals its check messages instead. |
|
|
88
|
+
| `flag(prop)`, `option(prop)` | A boolean prop (literal, binding or condition) and any prop, with the catalog default when omitted. |
|
|
88
89
|
| `choices(prop = 'options')` | Option children as `{ id, label, value }`. |
|
|
89
90
|
|
|
90
91
|
Overlays (dialogs, sheets) can wrap their content in `GlyphOverlayProvider value={{ close }}` so a component inside can call `useGlyphOverlay()?.close()` after it fires its action.
|
|
91
92
|
|
|
93
|
+
To test your components against what the API returns, render the real `glyph-1` pairs in `@kovca/glyph/conformance/examples`.
|
|
94
|
+
|
|
92
95
|
See [Build your own renderer](https://kovca.io/docs/rendering/custom) for the full guide.
|
|
93
96
|
|
|
94
97
|
## License
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { GlyphRequest, GlyphResponse } from '@kovca/glyph';
|
|
2
|
+
import type { FormController } from './forms.ts';
|
|
3
|
+
export type GlyphForm = {
|
|
4
|
+
/** Pass as `form` to `GlyphRenderer`. */
|
|
5
|
+
controller: FormController;
|
|
6
|
+
/** Call from your `onDataChange` before applying the edit: records it, resets locals tied to it, clears its host error. */
|
|
7
|
+
edited: (path: string) => void;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Edit-time state for a 0.3.0 pair (locals, touched fields, submit attempts, host errors) for pages that manage
|
|
11
|
+
* data edits themselves. Values replaced from outside (not through `edited`, e.g. another record) reset every
|
|
12
|
+
* local, attempt and host error. Harmless for 0.2.0 pairs.
|
|
13
|
+
*/
|
|
14
|
+
export declare function useGlyphForm(request: GlyphRequest, response: GlyphResponse): GlyphForm;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useRef, useState } from 'react';
|
|
3
|
+
import { analyze, emptyFormState, emptyLocal } from './forms.js';
|
|
4
|
+
/**
|
|
5
|
+
* Edit-time state for a 0.3.0 pair (locals, touched fields, submit attempts, host errors) for pages that manage
|
|
6
|
+
* data edits themselves. Values replaced from outside (not through `edited`, e.g. another record) reset every
|
|
7
|
+
* local, attempt and host error. Harmless for 0.2.0 pairs.
|
|
8
|
+
*/
|
|
9
|
+
export function useGlyphForm(request, response) {
|
|
10
|
+
const [form, setForm] = useState(emptyFormState);
|
|
11
|
+
const seen = useRef({ values: request.data.values, response });
|
|
12
|
+
const pendingEdit = useRef(false);
|
|
13
|
+
if (seen.current.response !== response || seen.current.values !== request.data.values) {
|
|
14
|
+
const external = seen.current.response !== response || !pendingEdit.current;
|
|
15
|
+
seen.current = { values: request.data.values, response };
|
|
16
|
+
pendingEdit.current = false;
|
|
17
|
+
if (external && (form.touched.size || form.attempted.size || Object.keys(form.locals).length
|
|
18
|
+
|| Object.keys(form.serverErrors).length)) {
|
|
19
|
+
setForm(emptyFormState());
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const controller = {
|
|
23
|
+
state: form,
|
|
24
|
+
setLocal: (name, value) => setForm((state) => {
|
|
25
|
+
const serverErrors = { ...state.serverErrors };
|
|
26
|
+
delete serverErrors[`local:${name}`];
|
|
27
|
+
return { ...state, locals: { ...state.locals, [name]: value }, touched: new Set(state.touched).add(`local:${name}`), serverErrors };
|
|
28
|
+
}),
|
|
29
|
+
attempt: (keys) => setForm((state) => ({ ...state, attempted: new Set([...state.attempted, ...keys]) })),
|
|
30
|
+
resetLocals: (names) => setForm((state) => {
|
|
31
|
+
const locals = { ...state.locals };
|
|
32
|
+
const touched = new Set(state.touched);
|
|
33
|
+
for (const name of names) {
|
|
34
|
+
locals[name] = emptyLocal(response, name);
|
|
35
|
+
touched.delete(`local:${name}`);
|
|
36
|
+
}
|
|
37
|
+
return { ...state, locals, touched, attempted: new Set() };
|
|
38
|
+
}),
|
|
39
|
+
setServerErrors: (errors) => setForm((state) => {
|
|
40
|
+
const serverErrors = {};
|
|
41
|
+
for (const error of errors) {
|
|
42
|
+
const key = error.path ?? '';
|
|
43
|
+
serverErrors[key] = [...(serverErrors[key] ?? []), error.message];
|
|
44
|
+
}
|
|
45
|
+
return { ...state, serverErrors };
|
|
46
|
+
}),
|
|
47
|
+
};
|
|
48
|
+
const edited = (path) => {
|
|
49
|
+
pendingEdit.current = true;
|
|
50
|
+
const { localDeps } = analyze(request, response, request.data.values ?? {});
|
|
51
|
+
setForm((state) => {
|
|
52
|
+
const locals = { ...state.locals };
|
|
53
|
+
const touched = new Set(state.touched);
|
|
54
|
+
touched.add(path);
|
|
55
|
+
// A local compared with data that just changed resets (a typed confirmation for another record).
|
|
56
|
+
for (const [name, deps] of localDeps) {
|
|
57
|
+
if ([...deps].some((dep) => dep === path || dep.startsWith(`${path}/`) || path.startsWith(`${dep}/`))) {
|
|
58
|
+
locals[name] = emptyLocal(response, name);
|
|
59
|
+
touched.delete(`local:${name}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const serverErrors = { ...state.serverErrors };
|
|
63
|
+
delete serverErrors[path];
|
|
64
|
+
return { ...state, locals, touched, serverErrors };
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
return { controller, edited };
|
|
68
|
+
}
|
package/dist/forms.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { ActionEvent, ComponentNode, Field, GlyphRequest, GlyphResponse, OperandRef, Scalar, Scope } from '@kovca/glyph';
|
|
2
|
+
/**
|
|
3
|
+
* Contract 0.3.0 form model (ADR 0006): reactive props, checks, required fields, regions, local fields and host
|
|
4
|
+
* rules, evaluated locally from the current values. Nothing here calls the model or the host.
|
|
5
|
+
*/
|
|
6
|
+
/** A message concerning a field (`/data/path` or `local:name`), or the control itself when `key` is absent. */
|
|
7
|
+
export type FormMessage = {
|
|
8
|
+
key?: string;
|
|
9
|
+
message: string;
|
|
10
|
+
deps: string[];
|
|
11
|
+
};
|
|
12
|
+
/** The edit-time state a surface keeps for a 0.3.0 pair. */
|
|
13
|
+
export type FormState = {
|
|
14
|
+
locals: Record<string, Scalar | undefined>;
|
|
15
|
+
/** Field keys the user edited (`/a/b` or `local:name`). */
|
|
16
|
+
touched: ReadonlySet<string>;
|
|
17
|
+
/** Region and control keys where a submit was attempted. */
|
|
18
|
+
attempted: ReadonlySet<string>;
|
|
19
|
+
/** Errors the host returned for a field key; cleared when that field is edited. */
|
|
20
|
+
serverErrors: Readonly<Record<string, string[]>>;
|
|
21
|
+
};
|
|
22
|
+
export type FormController = {
|
|
23
|
+
state: FormState;
|
|
24
|
+
setLocal: (name: string, value: Scalar) => void;
|
|
25
|
+
attempt: (keys: string[]) => void;
|
|
26
|
+
resetLocals: (names: string[]) => void;
|
|
27
|
+
setServerErrors: (errors: {
|
|
28
|
+
path?: string;
|
|
29
|
+
message: string;
|
|
30
|
+
}[]) => void;
|
|
31
|
+
};
|
|
32
|
+
export declare const emptyFormState: () => FormState;
|
|
33
|
+
type Instance = {
|
|
34
|
+
key: string;
|
|
35
|
+
node: ComponentNode;
|
|
36
|
+
scope?: Scope;
|
|
37
|
+
region: string;
|
|
38
|
+
/** Every instance key below this one (inclusive). */
|
|
39
|
+
subtree: string[];
|
|
40
|
+
};
|
|
41
|
+
export type FormAnalysis = {
|
|
42
|
+
instances: Map<string, Instance>;
|
|
43
|
+
regions: Map<string, string[]>;
|
|
44
|
+
/** Local name -> non-local field keys read by a condition that also reads the local. */
|
|
45
|
+
localDeps: Map<string, Set<string>>;
|
|
46
|
+
};
|
|
47
|
+
export declare const instanceKey: (node: ComponentNode, scope?: Scope) => string;
|
|
48
|
+
/** Walks every rendered instance once: regions, subtrees and the locals each condition ties to data. */
|
|
49
|
+
export declare function analyze(request: GlyphRequest, response: GlyphResponse, data: Record<string, unknown>): FormAnalysis;
|
|
50
|
+
/** `/abs/path` for a data reference (row-relative paths resolved), `local:name` for a local. */
|
|
51
|
+
export declare function fieldKey(ref: OperandRef | {
|
|
52
|
+
'@path': string;
|
|
53
|
+
} | {
|
|
54
|
+
'@local': string;
|
|
55
|
+
}, request: GlyphRequest, data: Record<string, unknown>, scope?: Scope): string;
|
|
56
|
+
export declare function lookupFor(request: GlyphRequest, data: Record<string, unknown>, state: FormState, scope?: Scope): (ref: OperandRef) => unknown;
|
|
57
|
+
/** A boolean prop: literal, binding or (0.3.0 reactive) condition, falling back to the catalog default. */
|
|
58
|
+
export declare function flagOf(request: GlyphRequest, node: ComponentNode, prop: string, data: Record<string, unknown>, state: FormState, scope?: Scope): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Why an action control cannot act now: its own checks; for a `type: "submit"` control, every required input and
|
|
61
|
+
* input check in its region; and the host rules for its action.
|
|
62
|
+
*/
|
|
63
|
+
export declare function blockersFor(request: GlyphRequest, analysis: FormAnalysis, key: string, event: ActionEvent | undefined, data: Record<string, unknown>, state: FormState): FormMessage[];
|
|
64
|
+
/** Messages shown now: a message appears once a field it depends on was edited, or after a submit attempt. */
|
|
65
|
+
export declare function visible(message: FormMessage, state: FormState, attemptKeys: string[]): boolean;
|
|
66
|
+
/** Every visible message for a field key across all action controls and input checks of the surface. */
|
|
67
|
+
export declare function fieldMessages(request: GlyphRequest, analysis: FormAnalysis, fieldKeyValue: string, events: Map<string, ActionEvent | undefined>, data: Record<string, unknown>, state: FormState): string[];
|
|
68
|
+
/** Locals referenced anywhere in an instance's subtree (to reset when an overlay opens or closes). */
|
|
69
|
+
export declare function localsIn(analysis: FormAnalysis, key: string): string[];
|
|
70
|
+
/** The empty value of a local (`""`, unset number, `false`). */
|
|
71
|
+
export declare function emptyLocal(response: GlyphResponse, name: string): Scalar | undefined;
|
|
72
|
+
export type { Field };
|
package/dist/forms.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { conditionReferences, evaluateCondition, failedRules, isCondition, present, resolvePath } from '@kovca/glyph';
|
|
2
|
+
export const emptyFormState = () => ({ locals: {}, touched: new Set(), attempted: new Set(), serverErrors: {} });
|
|
3
|
+
export const instanceKey = (node, scope) => scope ? `${scope.path}#${node.id}` : node.id;
|
|
4
|
+
const isV3 = (request) => request.version === '0.3.0';
|
|
5
|
+
function children(request, nodes, node, data, scope) {
|
|
6
|
+
const out = [];
|
|
7
|
+
const props = request.catalog.components[node.component]?.props ?? {};
|
|
8
|
+
for (const [name, spec] of Object.entries(props)) {
|
|
9
|
+
const value = node[name];
|
|
10
|
+
if (value === undefined || (spec.type !== 'child' && spec.type !== 'children'))
|
|
11
|
+
continue;
|
|
12
|
+
if (typeof value === 'string')
|
|
13
|
+
out.push({ node: nodes.get(value), scope });
|
|
14
|
+
else if (Array.isArray(value))
|
|
15
|
+
out.push(...value.map((id) => ({ node: nodes.get(id), scope })));
|
|
16
|
+
else if (typeof value === 'object' && value !== null && 'componentId' in value) {
|
|
17
|
+
const { path, componentId } = value;
|
|
18
|
+
const list = resolvePath(path, data, request.data.schema, scope);
|
|
19
|
+
if (!Array.isArray(list.value) || list.field.type !== 'list')
|
|
20
|
+
continue;
|
|
21
|
+
const item = list.field.item;
|
|
22
|
+
list.value.forEach((itemValue, index) => out.push({
|
|
23
|
+
node: nodes.get(componentId), scope: { value: itemValue, field: item, path: `${list.path}/${index}` },
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return out.filter((entry) => entry.node);
|
|
28
|
+
}
|
|
29
|
+
/** Walks every rendered instance once: regions, subtrees and the locals each condition ties to data. */
|
|
30
|
+
export function analyze(request, response, data) {
|
|
31
|
+
const instances = new Map();
|
|
32
|
+
const regions = new Map([['surface', []]]);
|
|
33
|
+
const localDeps = new Map();
|
|
34
|
+
if (!('components' in response.output))
|
|
35
|
+
return { instances, regions, localDeps };
|
|
36
|
+
const nodes = new Map(response.output.components.map((node) => [node.id, node]));
|
|
37
|
+
const walk = (node, scope, region) => {
|
|
38
|
+
const key = instanceKey(node, scope);
|
|
39
|
+
const own = request.catalog.components[node.component]?.region ? key : region;
|
|
40
|
+
if (own === key)
|
|
41
|
+
regions.set(key, []);
|
|
42
|
+
regions.get(region).push(key);
|
|
43
|
+
const entry = { key, node, scope, region, subtree: [key] };
|
|
44
|
+
instances.set(key, entry);
|
|
45
|
+
for (const child of children(request, nodes, node, data, scope))
|
|
46
|
+
entry.subtree.push(...walk(child.node, child.scope, own));
|
|
47
|
+
for (const condition of conditionsOf(node)) {
|
|
48
|
+
const refs = conditionReferences(condition);
|
|
49
|
+
const locals = refs.filter((ref) => '@local' in ref).map((ref) => ref['@local']);
|
|
50
|
+
const deps = refs.filter((ref) => '@path' in ref).map((ref) => fieldKey(ref, request, data, scope));
|
|
51
|
+
for (const name of locals) {
|
|
52
|
+
const set = localDeps.get(name) ?? new Set();
|
|
53
|
+
deps.forEach((dep) => set.add(dep));
|
|
54
|
+
localDeps.set(name, set);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return entry.subtree;
|
|
58
|
+
};
|
|
59
|
+
const root = nodes.get('root');
|
|
60
|
+
if (root)
|
|
61
|
+
walk(root, undefined, 'surface');
|
|
62
|
+
return { instances, regions, localDeps };
|
|
63
|
+
}
|
|
64
|
+
function conditionsOf(node) {
|
|
65
|
+
const found = [];
|
|
66
|
+
for (const value of Object.values(node)) {
|
|
67
|
+
if (isCondition(value))
|
|
68
|
+
found.push(value);
|
|
69
|
+
else if (Array.isArray(value)) {
|
|
70
|
+
for (const item of value)
|
|
71
|
+
if (item && typeof item === 'object' && isCondition(item.condition)) {
|
|
72
|
+
found.push(item.condition);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return found;
|
|
77
|
+
}
|
|
78
|
+
/** `/abs/path` for a data reference (row-relative paths resolved), `local:name` for a local. */
|
|
79
|
+
export function fieldKey(ref, request, data, scope) {
|
|
80
|
+
if ('@local' in ref)
|
|
81
|
+
return `local:${ref['@local']}`;
|
|
82
|
+
if ('@path' in ref)
|
|
83
|
+
return resolvePath(ref['@path'], data, request.data.schema, scope).path;
|
|
84
|
+
return `arg:${ref['@arg']}`;
|
|
85
|
+
}
|
|
86
|
+
export function lookupFor(request, data, state, scope) {
|
|
87
|
+
return (ref) => {
|
|
88
|
+
if ('@local' in ref)
|
|
89
|
+
return state.locals[ref['@local']];
|
|
90
|
+
if ('@path' in ref)
|
|
91
|
+
return resolvePath(ref['@path'], data, request.data.schema, scope).value;
|
|
92
|
+
return undefined;
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/** A boolean prop: literal, binding or (0.3.0 reactive) condition, falling back to the catalog default. */
|
|
96
|
+
export function flagOf(request, node, prop, data, state, scope) {
|
|
97
|
+
const value = node[prop];
|
|
98
|
+
if (value === undefined)
|
|
99
|
+
return request.catalog.components[node.component]?.props?.[prop]?.default === true;
|
|
100
|
+
if (isCondition(value))
|
|
101
|
+
return evaluateCondition(value, lookupFor(request, data, state, scope));
|
|
102
|
+
if (typeof value === 'object' && value !== null && '@path' in value) {
|
|
103
|
+
return resolvePath(value['@path'], data, request.data.schema, scope).value === true;
|
|
104
|
+
}
|
|
105
|
+
return value === true;
|
|
106
|
+
}
|
|
107
|
+
function inputsOf(request, instance, data, state) {
|
|
108
|
+
const props = request.catalog.components[instance.node.component]?.props ?? {};
|
|
109
|
+
const out = [];
|
|
110
|
+
for (const [prop, spec] of Object.entries(props)) {
|
|
111
|
+
const value = instance.node[prop];
|
|
112
|
+
if (spec.type !== 'input' || !value || typeof value !== 'object')
|
|
113
|
+
continue;
|
|
114
|
+
const key = fieldKey(value, request, data, instance.scope);
|
|
115
|
+
const current = lookupFor(request, data, state, instance.scope)(value);
|
|
116
|
+
const required = props.required !== undefined && flagOf(request, instance.node, 'required', data, state, instance.scope)
|
|
117
|
+
&& !flagOf(request, instance.node, 'disabled', data, state, instance.scope);
|
|
118
|
+
// A required boolean (Checkbox, Switch) must be on, as in HTML; other values must be present.
|
|
119
|
+
out.push({ prop, key, required, empty: spec.of === 'boolean' ? current !== true : !present(current) });
|
|
120
|
+
}
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
function checkMessages(request, instance, data, state) {
|
|
124
|
+
const checks = instance.node.checks;
|
|
125
|
+
if (!Array.isArray(checks))
|
|
126
|
+
return [];
|
|
127
|
+
const lookup = lookupFor(request, data, state, instance.scope);
|
|
128
|
+
const out = [];
|
|
129
|
+
for (const check of checks) {
|
|
130
|
+
if (evaluateCondition(check.condition, lookup))
|
|
131
|
+
continue;
|
|
132
|
+
const message = typeof check.message === 'string' ? check.message
|
|
133
|
+
: String(resolvePath(check.message['@path'], data, request.data.schema, instance.scope).value ?? '');
|
|
134
|
+
const deps = conditionReferences(check.condition).map((ref) => fieldKey(ref, request, data, instance.scope));
|
|
135
|
+
out.push({ key: check.field ? fieldKey(check.field, request, data, instance.scope) : undefined, message, deps });
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Why an action control cannot act now: its own checks; for a `type: "submit"` control, every required input and
|
|
141
|
+
* input check in its region; and the host rules for its action.
|
|
142
|
+
*/
|
|
143
|
+
export function blockersFor(request, analysis, key, event, data, state) {
|
|
144
|
+
const instance = analysis.instances.get(key);
|
|
145
|
+
if (!instance || !isV3(request))
|
|
146
|
+
return [];
|
|
147
|
+
const messages = checkMessages(request, instance, data, state);
|
|
148
|
+
if (instance.node.type === 'submit') {
|
|
149
|
+
for (const member of analysis.regions.get(instance.region) ?? []) {
|
|
150
|
+
const other = analysis.instances.get(member);
|
|
151
|
+
if (!other || other.key === key)
|
|
152
|
+
continue;
|
|
153
|
+
if (flagOf(request, other.node, 'hidden', data, state, other.scope))
|
|
154
|
+
continue;
|
|
155
|
+
for (const input of inputsOf(request, other, data, state)) {
|
|
156
|
+
if (input.required && input.empty)
|
|
157
|
+
messages.push({ key: input.key, message: 'Required.', deps: [input.key] });
|
|
158
|
+
}
|
|
159
|
+
if (request.catalog.components[other.node.component]?.props?.action === undefined) {
|
|
160
|
+
messages.push(...checkMessages(request, other, data, state));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (event) {
|
|
165
|
+
for (const error of failedRules(request, event, data)) {
|
|
166
|
+
messages.push({ key: error.path, message: error.message, deps: error.path ? [error.path] : [] });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return messages;
|
|
170
|
+
}
|
|
171
|
+
/** Messages shown now: a message appears once a field it depends on was edited, or after a submit attempt. */
|
|
172
|
+
export function visible(message, state, attemptKeys) {
|
|
173
|
+
return attemptKeys.some((key) => state.attempted.has(key)) || message.deps.some((dep) => state.touched.has(dep));
|
|
174
|
+
}
|
|
175
|
+
/** Every visible message for a field key across all action controls and input checks of the surface. */
|
|
176
|
+
export function fieldMessages(request, analysis, fieldKeyValue, events, data, state) {
|
|
177
|
+
const shown = new Set();
|
|
178
|
+
for (const [key, instance] of analysis.instances) {
|
|
179
|
+
const hasAction = request.catalog.components[instance.node.component]?.props?.action !== undefined;
|
|
180
|
+
const messages = hasAction ? blockersFor(request, analysis, key, events.get(key), data, state)
|
|
181
|
+
: checkMessages(request, instance, data, state).map((message) => message.key ? message : { ...message, key: inputsOf(request, instance, data, state)[0]?.key });
|
|
182
|
+
for (const message of messages) {
|
|
183
|
+
if (message.key === fieldKeyValue && visible(message, state, [key, instance.region]))
|
|
184
|
+
shown.add(message.message);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
for (const message of state.serverErrors[fieldKeyValue] ?? [])
|
|
188
|
+
shown.add(message);
|
|
189
|
+
return [...shown];
|
|
190
|
+
}
|
|
191
|
+
/** Locals referenced anywhere in an instance's subtree (to reset when an overlay opens or closes). */
|
|
192
|
+
export function localsIn(analysis, key) {
|
|
193
|
+
const names = new Set();
|
|
194
|
+
for (const member of analysis.instances.get(key)?.subtree ?? []) {
|
|
195
|
+
const node = analysis.instances.get(member)?.node;
|
|
196
|
+
if (!node)
|
|
197
|
+
continue;
|
|
198
|
+
const pending = [node];
|
|
199
|
+
while (pending.length) {
|
|
200
|
+
const value = pending.pop();
|
|
201
|
+
if (Array.isArray(value))
|
|
202
|
+
pending.push(...value);
|
|
203
|
+
else if (value && typeof value === 'object') {
|
|
204
|
+
if (Object.keys(value).length === 1 && typeof value['@local'] === 'string') {
|
|
205
|
+
names.add(value['@local']);
|
|
206
|
+
}
|
|
207
|
+
pending.push(...Object.values(value));
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return [...names];
|
|
212
|
+
}
|
|
213
|
+
/** The empty value of a local (`""`, unset number, `false`). */
|
|
214
|
+
export function emptyLocal(response, name) {
|
|
215
|
+
const type = 'components' in response.output ? response.output.locals?.[name]?.type : undefined;
|
|
216
|
+
return type === 'boolean' ? false : type === 'string' ? '' : undefined;
|
|
217
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -4,4 +4,7 @@ export { GlyphSurface } from './surface.tsx';
|
|
|
4
4
|
export type { GlyphSurfaceError, GlyphSurfaceProps } from './surface.tsx';
|
|
5
5
|
export { GlyphOverlayProvider, useGlyphOverlay } from './overlay.tsx';
|
|
6
6
|
export type { GlyphOverlay } from './overlay.tsx';
|
|
7
|
-
export type { GlyphAction, GlyphChoice, GlyphComponent, GlyphComponentProps, GlyphComponents, GlyphInput, GlyphItem, } from './types.ts';
|
|
7
|
+
export type { GlyphAction, GlyphActionResult, GlyphChoice, GlyphComponent, GlyphComponentProps, GlyphComponents, GlyphInput, GlyphItem, } from './types.ts';
|
|
8
|
+
export type { FormController, FormState } from './forms.ts';
|
|
9
|
+
export { useGlyphForm } from './form-state.ts';
|
|
10
|
+
export type { GlyphForm } from './form-state.ts';
|
package/dist/index.js
CHANGED
package/dist/renderer.d.ts
CHANGED
|
@@ -1,19 +1,25 @@
|
|
|
1
1
|
import type { ActionEvent, GlyphRequest, GlyphResponse } from '@kovca/glyph';
|
|
2
2
|
import type { ReactNode } from 'react';
|
|
3
|
-
import type {
|
|
3
|
+
import type { FormController } from './forms.ts';
|
|
4
|
+
import type { GlyphActionResult, GlyphComponents } from './types.ts';
|
|
4
5
|
export type GlyphRendererProps = {
|
|
5
|
-
/** A validated-or-not Glyph 0.2.0
|
|
6
|
+
/** A validated-or-not Glyph request (0.2.0 or 0.3.0); it is validated again here. */
|
|
6
7
|
request: GlyphRequest;
|
|
7
8
|
response: GlyphResponse;
|
|
8
9
|
/** Implementations by catalog component name. */
|
|
9
10
|
components: GlyphComponents;
|
|
10
|
-
/**
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Receives authorized action events. Glyph never runs actions itself. With contract 0.3.0 it may return (a promise
|
|
13
|
+
* of) `{ errors: [{ path, message }] }`; the messages are shown at their fields and every edit is kept.
|
|
14
|
+
*/
|
|
15
|
+
onAction?: (event: ActionEvent) => GlyphActionResult | Promise<GlyphActionResult>;
|
|
12
16
|
/** Receives edits to writable fields (absolute data path and the control's value). */
|
|
13
17
|
onDataChange?: (path: string, value: unknown) => void;
|
|
18
|
+
/** 0.3.0 edit-time state (locals, touched fields, attempts, host errors). `GlyphSurface` supplies it. */
|
|
19
|
+
form?: FormController;
|
|
14
20
|
};
|
|
15
21
|
/**
|
|
16
22
|
* Renders a Glyph pair with your components. Validates first and throws (`ContractError`, `RenderError`) instead of
|
|
17
23
|
* drawing anything unsafe, so wrap it in an error boundary, or use `GlyphSurface`, which does that for you.
|
|
18
24
|
*/
|
|
19
|
-
export declare function GlyphRenderer({ request, response, components, onAction, onDataChange }: GlyphRendererProps): ReactNode;
|
|
25
|
+
export declare function GlyphRenderer({ request, response, components, onAction, onDataChange, form }: GlyphRendererProps): ReactNode;
|
package/dist/renderer.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
3
|
import { fail, resolveAction, resolvePath, resolveValue, textOf, uriOf, validatePair } from '@kovca/glyph';
|
|
4
|
+
import { analyze, blockersFor, emptyFormState, fieldKey, fieldMessages, flagOf, instanceKey, localsIn, visible, } from './forms.js';
|
|
4
5
|
function lookup(engine, id) {
|
|
5
6
|
return engine.nodes.get(id) ?? fail(`missing component reference ${id}`);
|
|
6
7
|
}
|
|
@@ -40,12 +41,28 @@ function element(engine, entry, parent, slot, inheritedLabel) {
|
|
|
40
41
|
const Component = Object.hasOwn(engine.components, name)
|
|
41
42
|
? engine.components[name]
|
|
42
43
|
: fail(`component ${name} is not registered`);
|
|
44
|
+
if (engine.v3 && definition.props?.hidden && flagOf(engine.request, node, 'hidden', engine.data, engine.form.state, scope)) {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
43
47
|
return _jsx(Component, { ...nodeProps(engine, node, scope, key, parent, slot, inheritedLabel) }, key);
|
|
44
48
|
}
|
|
49
|
+
function setLocalValue(engine, name, value) {
|
|
50
|
+
const type = 'components' in engine.response.output ? engine.response.output.locals?.[name]?.type : undefined;
|
|
51
|
+
if (type === 'number' && typeof value === 'string') {
|
|
52
|
+
const number = Number(value);
|
|
53
|
+
engine.form.setLocal(name, (value.trim() !== '' && Number.isFinite(number) ? number : undefined));
|
|
54
|
+
}
|
|
55
|
+
else if (type !== undefined && (typeof value === type || value === undefined)) {
|
|
56
|
+
engine.form.setLocal(name, value);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
45
59
|
function nodeProps(engine, node, scope, nodeKey, parent, slot, inheritedLabel) {
|
|
46
60
|
const { request, data } = engine;
|
|
47
61
|
const schema = request.data.schema;
|
|
48
62
|
const name = node.component;
|
|
63
|
+
const specs = request.catalog.components[name]?.props ?? {};
|
|
64
|
+
const instance = instanceKey(node, scope);
|
|
65
|
+
const state = engine.form.state;
|
|
49
66
|
const text = (prop) => textOf(node[prop], data, schema, scope);
|
|
50
67
|
const value = (prop) => {
|
|
51
68
|
const resolved = resolveValue(node[prop], data, schema, scope);
|
|
@@ -62,6 +79,8 @@ function nodeProps(engine, node, scope, nodeKey, parent, slot, inheritedLabel) {
|
|
|
62
79
|
const resolved = resolveValue(entry.node[field], data, schema, entry.scope);
|
|
63
80
|
return resolved ? resolved.value : entry.node[field];
|
|
64
81
|
},
|
|
82
|
+
flag: (field) => engine.v3 ? flagOf(request, entry.node, field, data, state, entry.scope)
|
|
83
|
+
: (resolveValue(entry.node[field], data, schema, entry.scope)?.value ?? entry.node[field]) === true,
|
|
65
84
|
render: () => element(engine, entry, name, prop, inheritedLabel ?? label),
|
|
66
85
|
}));
|
|
67
86
|
const accessibility = node['@accessibility'];
|
|
@@ -71,6 +90,45 @@ function nodeProps(engine, node, scope, nodeKey, parent, slot, inheritedLabel) {
|
|
|
71
90
|
if (accessibility?.description !== undefined) {
|
|
72
91
|
aria['aria-description'] = textOf(accessibility.description, data, schema, scope);
|
|
73
92
|
}
|
|
93
|
+
const flag = (prop) => engine.v3
|
|
94
|
+
? flagOf(request, node, prop, data, state, scope)
|
|
95
|
+
: value(prop) === true;
|
|
96
|
+
const region = engine.analysis.instances.get(instance)?.region ?? 'surface';
|
|
97
|
+
const action = (prop = 'action') => {
|
|
98
|
+
const resolved = resolveAction(node, prop, request, data, scope);
|
|
99
|
+
if (!engine.v3) {
|
|
100
|
+
return {
|
|
101
|
+
...resolved, blocked: false, submit: false, messages: [],
|
|
102
|
+
invoke: async () => { if (!resolved.disabled)
|
|
103
|
+
return engine.onAction(resolved.event); },
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
const explicit = flag('disabled');
|
|
107
|
+
const blockers = blockersFor(request, engine.analysis, instance, resolved.event, data, state);
|
|
108
|
+
const submit = node.type === 'submit';
|
|
109
|
+
const attemptKeys = [instance, ...(submit ? [region] : [])];
|
|
110
|
+
const blocked = blockers.length > 0 || (resolved.disabled && !explicit);
|
|
111
|
+
const invoke = async () => {
|
|
112
|
+
if (explicit)
|
|
113
|
+
return;
|
|
114
|
+
if (blocked) {
|
|
115
|
+
engine.form.attempt(attemptKeys);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const result = await engine.onAction(resolved.event);
|
|
119
|
+
engine.form.setServerErrors(result && result.errors ? result.errors : []);
|
|
120
|
+
return result;
|
|
121
|
+
};
|
|
122
|
+
return {
|
|
123
|
+
name: resolved.name,
|
|
124
|
+
event: resolved.event,
|
|
125
|
+
disabled: explicit || blocked,
|
|
126
|
+
blocked,
|
|
127
|
+
submit,
|
|
128
|
+
invoke,
|
|
129
|
+
messages: blockers.filter((m) => !m.key && visible(m, state, attemptKeys)).map((m) => m.message),
|
|
130
|
+
};
|
|
131
|
+
};
|
|
74
132
|
return {
|
|
75
133
|
node,
|
|
76
134
|
nodeKey,
|
|
@@ -90,30 +148,84 @@ function nodeProps(engine, node, scope, nodeKey, parent, slot, inheritedLabel) {
|
|
|
90
148
|
},
|
|
91
149
|
items: (prop = 'children') => items(prop),
|
|
92
150
|
input: (prop = 'value') => {
|
|
93
|
-
const
|
|
151
|
+
const bound = node[prop];
|
|
152
|
+
const spec = specs[prop];
|
|
153
|
+
if (engine.v3 && bound && typeof bound === 'object' && '@local' in bound) {
|
|
154
|
+
const local = bound['@local'];
|
|
155
|
+
const type = 'components' in engine.response.output ? engine.response.output.locals?.[local]?.type ?? 'string' : 'string';
|
|
156
|
+
return {
|
|
157
|
+
path: `local:${local}`, value: state.locals[local], field: { type }, readOnly: false,
|
|
158
|
+
required: flag('required'), errors: fieldMessages(request, engine.analysis, `local:${local}`, engine.events, data, state),
|
|
159
|
+
change: (next) => setLocalValue(engine, local, next),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
const target = resolveValue(bound, data, schema, scope);
|
|
94
163
|
if (!target || target.field.type === 'object')
|
|
95
164
|
fail(`${name}.${prop} needs a data binding`);
|
|
96
|
-
|
|
165
|
+
const readOnly = engine.v3 && Boolean(spec?.readOnlyWith) && flag(spec.readOnlyWith);
|
|
166
|
+
if (!readOnly && !target.field.writable)
|
|
97
167
|
fail(`${name}.${prop} is not bound to a writable field`);
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
168
|
+
const key = engine.v3 ? fieldKey({ '@path': target.path }, request, data) : target.path;
|
|
169
|
+
return {
|
|
170
|
+
path: target.path,
|
|
171
|
+
value: target.value,
|
|
172
|
+
field: target.field,
|
|
173
|
+
readOnly,
|
|
174
|
+
required: engine.v3 && flag('required'),
|
|
175
|
+
errors: engine.v3 ? fieldMessages(request, engine.analysis, key, engine.events, data, state) : [],
|
|
176
|
+
change: (next) => { if (!readOnly)
|
|
177
|
+
engine.onDataChange(target.path, next); },
|
|
178
|
+
};
|
|
104
179
|
},
|
|
180
|
+
action,
|
|
105
181
|
choices: (prop = 'options') => items(prop).map((item) => {
|
|
106
182
|
if (item.name !== 'Option')
|
|
107
183
|
fail('choices must be Option components');
|
|
108
184
|
return { id: item.key, label: item.text('label'), value: item.text('value') };
|
|
109
185
|
}),
|
|
186
|
+
instance,
|
|
187
|
+
flag,
|
|
188
|
+
option: (prop) => node[prop] === undefined ? specs[prop]?.default : value(prop),
|
|
189
|
+
submit: () => {
|
|
190
|
+
if (!engine.v3)
|
|
191
|
+
return;
|
|
192
|
+
for (const member of engine.analysis.regions.get(region) ?? []) {
|
|
193
|
+
const target = engine.analysis.instances.get(member);
|
|
194
|
+
if (!target || target.node.type !== 'submit' || target.node.action === undefined)
|
|
195
|
+
continue;
|
|
196
|
+
if (flagOf(request, target.node, 'disabled', data, state, target.scope))
|
|
197
|
+
return;
|
|
198
|
+
const resolved = resolveAction(target.node, 'action', request, data, target.scope);
|
|
199
|
+
const blockers = blockersFor(request, engine.analysis, member, resolved.event, data, state);
|
|
200
|
+
if (blockers.length || resolved.disabled) {
|
|
201
|
+
engine.form.attempt([member, region]);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
void Promise.resolve(engine.onAction(resolved.event)).then((result) => engine.form.setServerErrors(result && result.errors ? result.errors : []));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
resetLocals: () => {
|
|
209
|
+
if (!engine.v3)
|
|
210
|
+
return;
|
|
211
|
+
const names = localsIn(engine.analysis, instance);
|
|
212
|
+
if (names.length)
|
|
213
|
+
engine.form.resetLocals(names);
|
|
214
|
+
},
|
|
110
215
|
};
|
|
111
216
|
}
|
|
217
|
+
const inertForm = () => ({
|
|
218
|
+
state: emptyFormState(),
|
|
219
|
+
setLocal: () => undefined,
|
|
220
|
+
attempt: () => undefined,
|
|
221
|
+
resetLocals: () => undefined,
|
|
222
|
+
setServerErrors: () => undefined,
|
|
223
|
+
});
|
|
112
224
|
/**
|
|
113
225
|
* Renders a Glyph pair with your components. Validates first and throws (`ContractError`, `RenderError`) instead of
|
|
114
226
|
* drawing anything unsafe, so wrap it in an error boundary, or use `GlyphSurface`, which does that for you.
|
|
115
227
|
*/
|
|
116
|
-
export function GlyphRenderer({ request, response, components, onAction, onDataChange }) {
|
|
228
|
+
export function GlyphRenderer({ request, response, components, onAction, onDataChange, form }) {
|
|
117
229
|
validatePair(request, response);
|
|
118
230
|
if (!('components' in response.output))
|
|
119
231
|
fail('a refusal has no renderable surface');
|
|
@@ -121,13 +233,34 @@ export function GlyphRenderer({ request, response, components, onAction, onDataC
|
|
|
121
233
|
if (!Object.hasOwn(components, node.component))
|
|
122
234
|
fail(`component ${node.component} is not registered`);
|
|
123
235
|
}
|
|
236
|
+
const data = request.data.values ?? {};
|
|
237
|
+
const v3 = request.version === '0.3.0';
|
|
238
|
+
const analysis = analyze(request, response, data);
|
|
239
|
+
const events = new Map();
|
|
240
|
+
if (v3) {
|
|
241
|
+
for (const [key, instance] of analysis.instances) {
|
|
242
|
+
if (instance.node.action === undefined)
|
|
243
|
+
continue;
|
|
244
|
+
try {
|
|
245
|
+
events.set(key, resolveAction(instance.node, 'action', request, data, instance.scope).event);
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
events.set(key, undefined);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
124
252
|
const engine = {
|
|
125
253
|
request,
|
|
254
|
+
response,
|
|
126
255
|
nodes: new Map(response.output.components.map((node) => [node.id, node])),
|
|
127
|
-
data
|
|
256
|
+
data,
|
|
128
257
|
components,
|
|
129
258
|
onAction: onAction ?? (() => undefined),
|
|
130
259
|
onDataChange: onDataChange ?? (() => undefined),
|
|
260
|
+
v3,
|
|
261
|
+
form: form ?? inertForm(),
|
|
262
|
+
analysis,
|
|
263
|
+
events,
|
|
131
264
|
};
|
|
132
265
|
return element(engine, { node: lookup(engine, 'root'), key: 'root' }, 'Surface', 'root');
|
|
133
266
|
}
|
package/dist/surface.d.ts
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
import type { ActionEvent } from '@kovca/glyph';
|
|
2
2
|
import type { ReactNode } from 'react';
|
|
3
|
-
import type { GlyphComponents } from './types.ts';
|
|
3
|
+
import type { GlyphActionResult, GlyphComponents } from './types.ts';
|
|
4
4
|
/** Why nothing was rendered: a validation code from `validateGlyphPair`, or `render_rejected`. */
|
|
5
5
|
export type GlyphSurfaceError = {
|
|
6
6
|
code: string;
|
|
7
7
|
message: string;
|
|
8
8
|
};
|
|
9
9
|
export type GlyphSurfaceProps = {
|
|
10
|
-
/** The Glyph 0.2.0
|
|
10
|
+
/** The Glyph request (0.2.0 or 0.3.0), untrusted. */
|
|
11
11
|
request: unknown;
|
|
12
12
|
/** The model's response for it, untrusted. */
|
|
13
13
|
response: unknown;
|
|
14
14
|
components: GlyphComponents;
|
|
15
|
-
/**
|
|
16
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Receives authorized action events. Authorize and run them on your side. With contract 0.3.0, return (a promise
|
|
17
|
+
* of) `{ errors: [{ path, message }] }` to show field errors; edits are kept.
|
|
18
|
+
*/
|
|
19
|
+
onAction?: (event: ActionEvent) => GlyphActionResult | Promise<GlyphActionResult>;
|
|
17
20
|
/** Called with the full data values after each accepted edit. */
|
|
18
21
|
onValuesChange?: (values: Record<string, unknown>) => void;
|
|
19
22
|
renderRefusal?: (reason: string) => ReactNode;
|
package/dist/surface.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
3
|
import { applyEdit, validateGlyphPair } from '@kovca/glyph';
|
|
4
4
|
import { Component, useMemo, useState } from 'react';
|
|
5
|
+
import { useGlyphForm } from './form-state.js';
|
|
5
6
|
import { GlyphRenderer } from './renderer.js';
|
|
6
7
|
const defaultRefusal = (reason) => _jsxs("p", { role: "status", children: ["The model refused: ", reason] });
|
|
7
8
|
const defaultError = ({ code }) => _jsxs("div", { role: "alert", children: ["This UI can't be shown. The response didn't pass validation (", code, ")."] });
|
|
@@ -37,12 +38,14 @@ function EditableSurface({ request, response, components, onAction, onValuesChan
|
|
|
37
38
|
setValues(request.data.values);
|
|
38
39
|
}
|
|
39
40
|
const current = useMemo(() => ({ ...request, data: { ...request.data, values } }), [request, values]);
|
|
41
|
+
const form = useGlyphForm(current, response);
|
|
40
42
|
function change(path, value) {
|
|
41
43
|
const next = applyEdit(request, response, values, path, value);
|
|
42
44
|
if (!next)
|
|
43
45
|
return;
|
|
46
|
+
form.edited(path);
|
|
44
47
|
setValues(next);
|
|
45
48
|
onValuesChange?.(next);
|
|
46
49
|
}
|
|
47
|
-
return _jsx(GlyphRenderer, { request: current, response: response, components: components, onAction: onAction, onDataChange: change });
|
|
50
|
+
return _jsx(GlyphRenderer, { request: current, response: response, components: components, onAction: onAction, onDataChange: change, form: form.controller });
|
|
48
51
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export type GlyphItem = {
|
|
|
11
11
|
scope?: Scope;
|
|
12
12
|
text: (prop: string) => string;
|
|
13
13
|
value: (prop: string) => unknown;
|
|
14
|
+
/** A boolean prop of the child: literal, binding or reactive condition, or its catalog default. */
|
|
15
|
+
flag: (prop: string) => boolean;
|
|
14
16
|
render: () => ReactNode;
|
|
15
17
|
};
|
|
16
18
|
/** A writable field bound to a control. Call `change` with the user's value; invalid edits are ignored. */
|
|
@@ -19,13 +21,32 @@ export type GlyphInput = {
|
|
|
19
21
|
value: unknown;
|
|
20
22
|
field: Field;
|
|
21
23
|
change: (value: unknown) => void;
|
|
24
|
+
/** 0.3.0: shown but never editable (the control's readOnly prop); `change` does nothing. */
|
|
25
|
+
readOnly: boolean;
|
|
26
|
+
/** 0.3.0: the control's required prop, evaluated now. */
|
|
27
|
+
required: boolean;
|
|
28
|
+
/** 0.3.0: visible rule, required and host messages for this field. */
|
|
29
|
+
errors: string[];
|
|
30
|
+
};
|
|
31
|
+
/** What the host's `onAction` may resolve to. Field errors are shown at their field; edits are kept. */
|
|
32
|
+
export type GlyphActionResult = void | {
|
|
33
|
+
errors?: {
|
|
34
|
+
path?: string;
|
|
35
|
+
message: string;
|
|
36
|
+
}[];
|
|
22
37
|
};
|
|
23
38
|
/** An authorized action. `invoke` hands the event to the host's `onAction`; it does nothing when disabled. */
|
|
24
39
|
export type GlyphAction = {
|
|
25
40
|
name: string;
|
|
26
41
|
disabled: boolean;
|
|
27
|
-
invoke: () =>
|
|
42
|
+
invoke: () => Promise<GlyphActionResult>;
|
|
28
43
|
event: ActionEvent;
|
|
44
|
+
/** 0.3.0: a check, required field or host rule fails now; invoking reveals the messages and emits nothing. */
|
|
45
|
+
blocked: boolean;
|
|
46
|
+
/** 0.3.0: `type: "submit"`; it validates its region and answers Enter. */
|
|
47
|
+
submit: boolean;
|
|
48
|
+
/** 0.3.0: visible messages not attributed to a field. */
|
|
49
|
+
messages: string[];
|
|
29
50
|
};
|
|
30
51
|
/** An `Option` child of a choice control. */
|
|
31
52
|
export type GlyphChoice = {
|
|
@@ -76,6 +97,16 @@ export type GlyphComponentProps = {
|
|
|
76
97
|
action: (prop?: string) => GlyphAction;
|
|
77
98
|
/** The `Option` children of a slot (default `options`). */
|
|
78
99
|
choices: (prop?: string) => GlyphChoice[];
|
|
100
|
+
/** 0.3.0: this instance's unique key (component ID, prefixed by its list item path inside a template). */
|
|
101
|
+
instance: string;
|
|
102
|
+
/** A boolean prop: literal, binding or reactive condition, or the catalog default when omitted. */
|
|
103
|
+
flag: (prop: string) => boolean;
|
|
104
|
+
/** A literal or bound prop's value, or the catalog default when omitted. */
|
|
105
|
+
option: (prop: string) => unknown;
|
|
106
|
+
/** 0.3.0: attempts the first submit control of this node's region (Enter in a text input). */
|
|
107
|
+
submit: () => void;
|
|
108
|
+
/** 0.3.0: resets the local fields used in this node's subtree (an overlay calls it when it opens or closes). */
|
|
109
|
+
resetLocals: () => void;
|
|
79
110
|
};
|
|
80
111
|
export type GlyphComponent = (props: GlyphComponentProps) => ReactNode;
|
|
81
112
|
/** Component implementations by catalog name. Responses using a name that isn't here are rejected. */
|
package/package.json
CHANGED
|
@@ -1,17 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kovca/glyph-react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Headless React renderer for Kovca Glyph UI: bring your own components, or install the shadcn/ui set.",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Headless React renderer for Kovca Glyph UI (glyph-1, A2UI contract 0.3.0): bring your own components, or install the shadcn/ui set.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"sideEffects": false,
|
|
8
|
-
"repository": {
|
|
9
|
-
"type": "git",
|
|
10
|
-
"url": "git+https://github.com/CMoyle336/Glyph.git",
|
|
11
|
-
"directory": "packages/glyph-react"
|
|
12
|
-
},
|
|
13
8
|
"homepage": "https://kovca.io/docs/rendering",
|
|
14
|
-
"keywords": ["glyph", "kovca", "react", "a2ui", "
|
|
9
|
+
"keywords": ["glyph", "kovca", "react", "a2ui", "generative-ui", "renderer", "shadcn"],
|
|
15
10
|
"exports": {
|
|
16
11
|
".": {
|
|
17
12
|
"types": "./dist/index.d.ts",
|
|
@@ -26,7 +21,7 @@
|
|
|
26
21
|
"test": "vitest run"
|
|
27
22
|
},
|
|
28
23
|
"dependencies": {
|
|
29
|
-
"@kovca/glyph": "^0.
|
|
24
|
+
"@kovca/glyph": "^0.2.0"
|
|
30
25
|
},
|
|
31
26
|
"peerDependencies": {
|
|
32
27
|
"react": "^18.2.0 || ^19.0.0"
|