@kovca/glyph-react 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +98 -2
- 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 +10 -0
- package/dist/index.js +4 -0
- package/dist/overlay.d.ts +12 -0
- package/dist/overlay.js +12 -0
- package/dist/renderer.d.ts +25 -0
- package/dist/renderer.js +266 -0
- package/dist/surface.d.ts +29 -0
- package/dist/surface.js +51 -0
- package/dist/types.d.ts +113 -0
- package/dist/types.js +1 -0
- package/package.json +27 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kovca
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,99 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kovca/glyph-react
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
|
|
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
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx shadcn@latest add https://kovca.io/r/glyph-shadcn.json
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
It needs a Radix shadcn style in `components.json` (such as `radix-nova`). Base UI styles (`base-*`) aren't supported yet.
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
import { GlyphSurface } from '@/components/glyph/glyph-surface'
|
|
15
|
+
|
|
16
|
+
<GlyphSurface request={result.request} response={result.output} onAction={handleAction} />
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install @kovca/glyph-react
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Requires React 18.2 or later. The components are client components (`'use client'`).
|
|
26
|
+
|
|
27
|
+
## Render a response
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
import type { GlyphGeneration } from '@kovca/glyph'
|
|
31
|
+
import { GlyphSurface, type GlyphComponents } from '@kovca/glyph-react'
|
|
32
|
+
|
|
33
|
+
const components: GlyphComponents = {
|
|
34
|
+
Card: (p) => <section aria-label={p.label}>{p.children()}</section>,
|
|
35
|
+
Text: (p) => <p>{p.text('text')}</p>,
|
|
36
|
+
Button: (p) => {
|
|
37
|
+
const action = p.action()
|
|
38
|
+
return <button disabled={action.disabled} onClick={action.invoke}>{p.text('label')}</button>
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// result: the body of POST /v1/generate (https://kovca.io/docs/api)
|
|
43
|
+
export function Answer({ result }: { result: GlyphGeneration }) {
|
|
44
|
+
return (
|
|
45
|
+
<GlyphSurface
|
|
46
|
+
request={result.request}
|
|
47
|
+
response={result.output}
|
|
48
|
+
components={components}
|
|
49
|
+
onAction={(event) => console.log(event.name, event.context)}
|
|
50
|
+
renderRefusal={(reason) => <p role="status">{reason}</p>}
|
|
51
|
+
renderError={({ code }) => <p role="alert">This UI can't be shown ({code}).</p>}
|
|
52
|
+
/>
|
|
53
|
+
)
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
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`.
|
|
58
|
+
|
|
59
|
+
### `GlyphSurface` props
|
|
60
|
+
|
|
61
|
+
| Prop | |
|
|
62
|
+
| --- | --- |
|
|
63
|
+
| `request`, `response` | The API result's `request` and `output` (contract 0.3.0, or 0.2.0). Untrusted input is fine. |
|
|
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; return (or resolve to) `{ errors: [{ path?, message }] }` to show errors at their fields. |
|
|
66
|
+
| `onValuesChange(values)` | The data after each accepted edit. Edits are kept inside the surface until `request` changes. |
|
|
67
|
+
| `renderRefusal(reason)` | The model declined to build a UI. Default: nothing. |
|
|
68
|
+
| `renderError({ code, message })` | The response can't be shown. Default: nothing. |
|
|
69
|
+
|
|
70
|
+
`GlyphRenderer` is the lower-level renderer underneath: it takes an already validated pair, throws on anything invalid, and reports edits as `onDataChange(path, value)` without keeping them.
|
|
71
|
+
|
|
72
|
+
## Write a component
|
|
73
|
+
|
|
74
|
+
Every component receives `GlyphComponentProps`:
|
|
75
|
+
|
|
76
|
+
| Prop | |
|
|
77
|
+
| --- | --- |
|
|
78
|
+
| `node`, `nodeKey` | The raw component node and a stable React key. |
|
|
79
|
+
| `label`, `aria` | An accessible name for the node, and ready-made `aria-*` attributes. |
|
|
80
|
+
| `has(prop)` | Whether the node sets `prop`. |
|
|
81
|
+
| `text(prop)` | A prop as display text, with bindings resolved and formatted. |
|
|
82
|
+
| `value(prop)` | A prop's raw value. |
|
|
83
|
+
| `uri(prop)` | A safe `https` media URL, or `undefined`. |
|
|
84
|
+
| `children(prop = 'children')` | The rendered child components. |
|
|
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, 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. |
|
|
89
|
+
| `choices(prop = 'options')` | Option children as `{ id, label, value }`. |
|
|
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.
|
|
92
|
+
|
|
93
|
+
To test your components against what the API returns, render the real `glyph-1` pairs in `@kovca/glyph/conformance/examples`.
|
|
94
|
+
|
|
95
|
+
See [Build your own renderer](https://kovca.io/docs/rendering/custom) for the full guide.
|
|
96
|
+
|
|
97
|
+
## License
|
|
98
|
+
|
|
99
|
+
MIT
|
|
@@ -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
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { GlyphRenderer } from './renderer.tsx';
|
|
2
|
+
export type { GlyphRendererProps } from './renderer.tsx';
|
|
3
|
+
export { GlyphSurface } from './surface.tsx';
|
|
4
|
+
export type { GlyphSurfaceError, GlyphSurfaceProps } from './surface.tsx';
|
|
5
|
+
export { GlyphOverlayProvider, useGlyphOverlay } from './overlay.tsx';
|
|
6
|
+
export type { GlyphOverlay } from './overlay.tsx';
|
|
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
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
/** Lets a component inside an overlay (Dialog, Sheet, ...) close it, e.g. a Button after it fires its action. */
|
|
3
|
+
export type GlyphOverlay = {
|
|
4
|
+
close: () => void;
|
|
5
|
+
};
|
|
6
|
+
/** Provide this around an overlay's content so `useGlyphOverlay()` can close it. */
|
|
7
|
+
export declare function GlyphOverlayProvider({ value, children }: {
|
|
8
|
+
value: GlyphOverlay;
|
|
9
|
+
children: ReactNode;
|
|
10
|
+
}): import("react").JSX.Element;
|
|
11
|
+
/** The enclosing overlay, or null outside one. */
|
|
12
|
+
export declare function useGlyphOverlay(): GlyphOverlay | null;
|
package/dist/overlay.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
|
+
import { createContext, useContext } from 'react';
|
|
4
|
+
const OverlayContext = createContext(null);
|
|
5
|
+
/** Provide this around an overlay's content so `useGlyphOverlay()` can close it. */
|
|
6
|
+
export function GlyphOverlayProvider({ value, children }) {
|
|
7
|
+
return _jsx(OverlayContext.Provider, { value: value, children: children });
|
|
8
|
+
}
|
|
9
|
+
/** The enclosing overlay, or null outside one. */
|
|
10
|
+
export function useGlyphOverlay() {
|
|
11
|
+
return useContext(OverlayContext);
|
|
12
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { ActionEvent, GlyphRequest, GlyphResponse } from '@kovca/glyph';
|
|
2
|
+
import type { ReactNode } from 'react';
|
|
3
|
+
import type { FormController } from './forms.ts';
|
|
4
|
+
import type { GlyphActionResult, GlyphComponents } from './types.ts';
|
|
5
|
+
export type GlyphRendererProps = {
|
|
6
|
+
/** A validated-or-not Glyph request (0.2.0 or 0.3.0); it is validated again here. */
|
|
7
|
+
request: GlyphRequest;
|
|
8
|
+
response: GlyphResponse;
|
|
9
|
+
/** Implementations by catalog component name. */
|
|
10
|
+
components: GlyphComponents;
|
|
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>;
|
|
16
|
+
/** Receives edits to writable fields (absolute data path and the control's value). */
|
|
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;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Renders a Glyph pair with your components. Validates first and throws (`ContractError`, `RenderError`) instead of
|
|
23
|
+
* drawing anything unsafe, so wrap it in an error boundary, or use `GlyphSurface`, which does that for you.
|
|
24
|
+
*/
|
|
25
|
+
export declare function GlyphRenderer({ request, response, components, onAction, onDataChange, form }: GlyphRendererProps): ReactNode;
|
package/dist/renderer.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
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';
|
|
5
|
+
function lookup(engine, id) {
|
|
6
|
+
return engine.nodes.get(id) ?? fail(`missing component reference ${id}`);
|
|
7
|
+
}
|
|
8
|
+
function slotted(engine, value, scope) {
|
|
9
|
+
if (typeof value === 'string')
|
|
10
|
+
return [{ node: lookup(engine, value), scope, key: value }];
|
|
11
|
+
if (Array.isArray(value))
|
|
12
|
+
return value.map((id) => ({ node: lookup(engine, id), scope, key: id }));
|
|
13
|
+
if (!value || typeof value !== 'object' || !('path' in value) || !('componentId' in value))
|
|
14
|
+
return [];
|
|
15
|
+
const { path, componentId } = value;
|
|
16
|
+
const schema = engine.request.data.schema;
|
|
17
|
+
const list = resolvePath(path, engine.data, schema, scope);
|
|
18
|
+
if (list.field.type !== 'list')
|
|
19
|
+
fail('template path must be a list');
|
|
20
|
+
if (list.value === undefined)
|
|
21
|
+
return [];
|
|
22
|
+
if (!Array.isArray(list.value))
|
|
23
|
+
fail('template value must be a list');
|
|
24
|
+
const item = list.field.item;
|
|
25
|
+
const node = lookup(engine, componentId);
|
|
26
|
+
return list.value.map((value, index) => {
|
|
27
|
+
const itemPath = `${list.path}/${index}`;
|
|
28
|
+
return { node, scope: { value, field: item, path: itemPath }, key: itemPath };
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function element(engine, entry, parent, slot, inheritedLabel) {
|
|
32
|
+
const { node, scope, key } = entry;
|
|
33
|
+
const name = node.component;
|
|
34
|
+
const catalog = engine.request.catalog.components;
|
|
35
|
+
const definition = Object.hasOwn(catalog, name) ? catalog[name] : fail(`component ${name} is not in the catalog`);
|
|
36
|
+
if (definition.allowedParents && !definition.allowedParents.includes(parent))
|
|
37
|
+
fail(`unallowed parent for ${name}`);
|
|
38
|
+
if (parent !== 'Surface' && catalog[parent]?.allowedChildren && !catalog[parent].allowedChildren.includes(name)) {
|
|
39
|
+
fail(`unallowed child ${name}`);
|
|
40
|
+
}
|
|
41
|
+
const Component = Object.hasOwn(engine.components, name)
|
|
42
|
+
? engine.components[name]
|
|
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
|
+
}
|
|
47
|
+
return _jsx(Component, { ...nodeProps(engine, node, scope, key, parent, slot, inheritedLabel) }, key);
|
|
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
|
+
}
|
|
59
|
+
function nodeProps(engine, node, scope, nodeKey, parent, slot, inheritedLabel) {
|
|
60
|
+
const { request, data } = engine;
|
|
61
|
+
const schema = request.data.schema;
|
|
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;
|
|
66
|
+
const text = (prop) => textOf(node[prop], data, schema, scope);
|
|
67
|
+
const value = (prop) => {
|
|
68
|
+
const resolved = resolveValue(node[prop], data, schema, scope);
|
|
69
|
+
return resolved ? resolved.value : node[prop];
|
|
70
|
+
};
|
|
71
|
+
const items = (prop = 'children', label) => slotted(engine, node[prop], scope).map((entry) => ({
|
|
72
|
+
key: entry.key,
|
|
73
|
+
id: entry.node.id,
|
|
74
|
+
name: entry.node.component,
|
|
75
|
+
node: entry.node,
|
|
76
|
+
scope: entry.scope,
|
|
77
|
+
text: (field) => textOf(entry.node[field], data, schema, entry.scope),
|
|
78
|
+
value: (field) => {
|
|
79
|
+
const resolved = resolveValue(entry.node[field], data, schema, entry.scope);
|
|
80
|
+
return resolved ? resolved.value : entry.node[field];
|
|
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,
|
|
84
|
+
render: () => element(engine, entry, name, prop, inheritedLabel ?? label),
|
|
85
|
+
}));
|
|
86
|
+
const accessibility = node['@accessibility'];
|
|
87
|
+
const aria = {};
|
|
88
|
+
if (accessibility?.label !== undefined)
|
|
89
|
+
aria['aria-label'] = textOf(accessibility.label, data, schema, scope);
|
|
90
|
+
if (accessibility?.description !== undefined) {
|
|
91
|
+
aria['aria-description'] = textOf(accessibility.description, data, schema, scope);
|
|
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
|
+
};
|
|
132
|
+
return {
|
|
133
|
+
node,
|
|
134
|
+
nodeKey,
|
|
135
|
+
parent,
|
|
136
|
+
slot,
|
|
137
|
+
request,
|
|
138
|
+
scope,
|
|
139
|
+
label: text('label') || inheritedLabel || '',
|
|
140
|
+
aria,
|
|
141
|
+
has: (prop) => node[prop] !== undefined,
|
|
142
|
+
text,
|
|
143
|
+
value,
|
|
144
|
+
uri: (prop) => uriOf(node[prop], data, schema, scope),
|
|
145
|
+
children: (prop = 'children', options) => {
|
|
146
|
+
const rendered = items(prop, options?.label).map((item) => item.render());
|
|
147
|
+
return typeof node[prop] === 'string' ? rendered[0] : rendered;
|
|
148
|
+
},
|
|
149
|
+
items: (prop = 'children') => items(prop),
|
|
150
|
+
input: (prop = 'value') => {
|
|
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);
|
|
163
|
+
if (!target || target.field.type === 'object')
|
|
164
|
+
fail(`${name}.${prop} needs a data binding`);
|
|
165
|
+
const readOnly = engine.v3 && Boolean(spec?.readOnlyWith) && flag(spec.readOnlyWith);
|
|
166
|
+
if (!readOnly && !target.field.writable)
|
|
167
|
+
fail(`${name}.${prop} is not bound to a writable field`);
|
|
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
|
+
};
|
|
179
|
+
},
|
|
180
|
+
action,
|
|
181
|
+
choices: (prop = 'options') => items(prop).map((item) => {
|
|
182
|
+
if (item.name !== 'Option')
|
|
183
|
+
fail('choices must be Option components');
|
|
184
|
+
return { id: item.key, label: item.text('label'), value: item.text('value') };
|
|
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
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
const inertForm = () => ({
|
|
218
|
+
state: emptyFormState(),
|
|
219
|
+
setLocal: () => undefined,
|
|
220
|
+
attempt: () => undefined,
|
|
221
|
+
resetLocals: () => undefined,
|
|
222
|
+
setServerErrors: () => undefined,
|
|
223
|
+
});
|
|
224
|
+
/**
|
|
225
|
+
* Renders a Glyph pair with your components. Validates first and throws (`ContractError`, `RenderError`) instead of
|
|
226
|
+
* drawing anything unsafe, so wrap it in an error boundary, or use `GlyphSurface`, which does that for you.
|
|
227
|
+
*/
|
|
228
|
+
export function GlyphRenderer({ request, response, components, onAction, onDataChange, form }) {
|
|
229
|
+
validatePair(request, response);
|
|
230
|
+
if (!('components' in response.output))
|
|
231
|
+
fail('a refusal has no renderable surface');
|
|
232
|
+
for (const node of response.output.components) {
|
|
233
|
+
if (!Object.hasOwn(components, node.component))
|
|
234
|
+
fail(`component ${node.component} is not registered`);
|
|
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
|
+
}
|
|
252
|
+
const engine = {
|
|
253
|
+
request,
|
|
254
|
+
response,
|
|
255
|
+
nodes: new Map(response.output.components.map((node) => [node.id, node])),
|
|
256
|
+
data,
|
|
257
|
+
components,
|
|
258
|
+
onAction: onAction ?? (() => undefined),
|
|
259
|
+
onDataChange: onDataChange ?? (() => undefined),
|
|
260
|
+
v3,
|
|
261
|
+
form: form ?? inertForm(),
|
|
262
|
+
analysis,
|
|
263
|
+
events,
|
|
264
|
+
};
|
|
265
|
+
return element(engine, { node: lookup(engine, 'root'), key: 'root' }, 'Surface', 'root');
|
|
266
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ActionEvent } from '@kovca/glyph';
|
|
2
|
+
import type { ReactNode } from 'react';
|
|
3
|
+
import type { GlyphActionResult, GlyphComponents } from './types.ts';
|
|
4
|
+
/** Why nothing was rendered: a validation code from `validateGlyphPair`, or `render_rejected`. */
|
|
5
|
+
export type GlyphSurfaceError = {
|
|
6
|
+
code: string;
|
|
7
|
+
message: string;
|
|
8
|
+
};
|
|
9
|
+
export type GlyphSurfaceProps = {
|
|
10
|
+
/** The Glyph request (0.2.0 or 0.3.0), untrusted. */
|
|
11
|
+
request: unknown;
|
|
12
|
+
/** The model's response for it, untrusted. */
|
|
13
|
+
response: unknown;
|
|
14
|
+
components: GlyphComponents;
|
|
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>;
|
|
20
|
+
/** Called with the full data values after each accepted edit. */
|
|
21
|
+
onValuesChange?: (values: Record<string, unknown>) => void;
|
|
22
|
+
renderRefusal?: (reason: string) => ReactNode;
|
|
23
|
+
renderError?: (error: GlyphSurfaceError) => ReactNode;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Validates an untrusted pair and renders it with your components. Shows a refusal or an error instead of anything
|
|
27
|
+
* invalid, and never throws. Edits to writable fields are kept locally and validated before they apply.
|
|
28
|
+
*/
|
|
29
|
+
export declare function GlyphSurface({ request, response, components, onAction, onValuesChange, renderRefusal, renderError, }: GlyphSurfaceProps): string | number | bigint | boolean | import("react").JSX.Element | Iterable<ReactNode> | Promise<string | number | bigint | boolean | Iterable<ReactNode> | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | import("react").ReactPortal | null | undefined> | null | undefined;
|
package/dist/surface.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { applyEdit, validateGlyphPair } from '@kovca/glyph';
|
|
4
|
+
import { Component, useMemo, useState } from 'react';
|
|
5
|
+
import { useGlyphForm } from './form-state.js';
|
|
6
|
+
import { GlyphRenderer } from './renderer.js';
|
|
7
|
+
const defaultRefusal = (reason) => _jsxs("p", { role: "status", children: ["The model refused: ", reason] });
|
|
8
|
+
const defaultError = ({ code }) => _jsxs("div", { role: "alert", children: ["This UI can't be shown. The response didn't pass validation (", code, ")."] });
|
|
9
|
+
/**
|
|
10
|
+
* Validates an untrusted pair and renders it with your components. Shows a refusal or an error instead of anything
|
|
11
|
+
* invalid, and never throws. Edits to writable fields are kept locally and validated before they apply.
|
|
12
|
+
*/
|
|
13
|
+
export function GlyphSurface({ request, response, components, onAction, onValuesChange, renderRefusal = defaultRefusal, renderError = defaultError, }) {
|
|
14
|
+
const result = useMemo(() => validateGlyphPair(request, response, { components: Object.keys(components) }), [request, response, components]);
|
|
15
|
+
if (!result.ok)
|
|
16
|
+
return renderError({ code: result.code, message: result.message });
|
|
17
|
+
if (result.kind === 'refusal')
|
|
18
|
+
return renderRefusal(result.reason);
|
|
19
|
+
return _jsx(RenderBoundary, { pair: result.response, renderError: renderError, children: _jsx(EditableSurface, { request: result.request, response: result.response, components: components, onAction: onAction, onValuesChange: onValuesChange }) });
|
|
20
|
+
}
|
|
21
|
+
class RenderBoundary extends Component {
|
|
22
|
+
state = { pair: this.props.pair };
|
|
23
|
+
static getDerivedStateFromProps(props, state) {
|
|
24
|
+
return props.pair === state.pair ? null : { pair: props.pair, error: undefined };
|
|
25
|
+
}
|
|
26
|
+
static getDerivedStateFromError(error) {
|
|
27
|
+
return { error: { code: 'render_rejected', message: error instanceof Error ? error.message : 'render failed' } };
|
|
28
|
+
}
|
|
29
|
+
render() {
|
|
30
|
+
return this.state.error ? this.props.renderError(this.state.error) : this.props.children;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function EditableSurface({ request, response, components, onAction, onValuesChange }) {
|
|
34
|
+
const [source, setSource] = useState(request);
|
|
35
|
+
const [values, setValues] = useState(request.data.values);
|
|
36
|
+
if (source !== request) {
|
|
37
|
+
setSource(request);
|
|
38
|
+
setValues(request.data.values);
|
|
39
|
+
}
|
|
40
|
+
const current = useMemo(() => ({ ...request, data: { ...request.data, values } }), [request, values]);
|
|
41
|
+
const form = useGlyphForm(current, response);
|
|
42
|
+
function change(path, value) {
|
|
43
|
+
const next = applyEdit(request, response, values, path, value);
|
|
44
|
+
if (!next)
|
|
45
|
+
return;
|
|
46
|
+
form.edited(path);
|
|
47
|
+
setValues(next);
|
|
48
|
+
onValuesChange?.(next);
|
|
49
|
+
}
|
|
50
|
+
return _jsx(GlyphRenderer, { request: current, response: response, components: components, onAction: onAction, onDataChange: change, form: form.controller });
|
|
51
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { ActionEvent, ComponentNode, Field, GlyphRequest, Scope } from '@kovca/glyph';
|
|
3
|
+
/** A child in a slot, before it is rendered: use it when a component lays out each child itself. */
|
|
4
|
+
export type GlyphItem = {
|
|
5
|
+
/** Stable React key (the component ID, or its list path inside a template). */
|
|
6
|
+
key: string;
|
|
7
|
+
id: string;
|
|
8
|
+
/** The child's catalog component name. */
|
|
9
|
+
name: string;
|
|
10
|
+
node: ComponentNode;
|
|
11
|
+
scope?: Scope;
|
|
12
|
+
text: (prop: string) => string;
|
|
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;
|
|
16
|
+
render: () => ReactNode;
|
|
17
|
+
};
|
|
18
|
+
/** A writable field bound to a control. Call `change` with the user's value; invalid edits are ignored. */
|
|
19
|
+
export type GlyphInput = {
|
|
20
|
+
path: string;
|
|
21
|
+
value: unknown;
|
|
22
|
+
field: Field;
|
|
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
|
+
}[];
|
|
37
|
+
};
|
|
38
|
+
/** An authorized action. `invoke` hands the event to the host's `onAction`; it does nothing when disabled. */
|
|
39
|
+
export type GlyphAction = {
|
|
40
|
+
name: string;
|
|
41
|
+
disabled: boolean;
|
|
42
|
+
invoke: () => Promise<GlyphActionResult>;
|
|
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[];
|
|
50
|
+
};
|
|
51
|
+
/** An `Option` child of a choice control. */
|
|
52
|
+
export type GlyphChoice = {
|
|
53
|
+
id: string;
|
|
54
|
+
label: string;
|
|
55
|
+
value: string;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* What every component in a Glyph registry receives. Props are read through these helpers, which resolve data
|
|
59
|
+
* bindings and enforce the contract, so a component never touches raw model output.
|
|
60
|
+
*/
|
|
61
|
+
export type GlyphComponentProps = {
|
|
62
|
+
/** The validated component node (`node.component` is its catalog name). */
|
|
63
|
+
node: ComponentNode;
|
|
64
|
+
/** React key of this node; unique within the surface, also inside list templates. */
|
|
65
|
+
nodeKey: string;
|
|
66
|
+
/** The parent's component name (`"Surface"` for the root). */
|
|
67
|
+
parent: string;
|
|
68
|
+
/** The parent prop this node was placed in (`"children"`, `"header"`, `"cells"`, ...; `"root"` for the root). */
|
|
69
|
+
slot: string;
|
|
70
|
+
request: GlyphRequest;
|
|
71
|
+
/** The list item a template is rendering, if any. */
|
|
72
|
+
scope?: Scope;
|
|
73
|
+
/** The node's `label` prop, or the label of an enclosing `Field`. */
|
|
74
|
+
label: string;
|
|
75
|
+
/** `aria-label` / `aria-description` from the node's `@accessibility`. Spread it onto the root element. */
|
|
76
|
+
aria: {
|
|
77
|
+
'aria-label'?: string;
|
|
78
|
+
'aria-description'?: string;
|
|
79
|
+
};
|
|
80
|
+
/** True when the node sets this prop. */
|
|
81
|
+
has: (prop: string) => boolean;
|
|
82
|
+
/** The prop as display text: bindings resolved and formatted by their field's format. */
|
|
83
|
+
text: (prop: string) => string;
|
|
84
|
+
/** The prop's raw value: a binding's data value, or the literal. */
|
|
85
|
+
value: (prop: string) => unknown;
|
|
86
|
+
/** A `uri` prop: an https URL from a `format: "uri"` field, or undefined. */
|
|
87
|
+
uri: (prop: string) => string | undefined;
|
|
88
|
+
/** Renders a `child`/`children` slot. Pass `label` to give descendant controls a default label. */
|
|
89
|
+
children: (prop?: string, options?: {
|
|
90
|
+
label?: string;
|
|
91
|
+
}) => ReactNode;
|
|
92
|
+
/** The children in a slot, unrendered. */
|
|
93
|
+
items: (prop?: string) => GlyphItem[];
|
|
94
|
+
/** The writable field an `input` prop binds to. */
|
|
95
|
+
input: (prop?: string) => GlyphInput;
|
|
96
|
+
/** The authorized action in an `action` prop. */
|
|
97
|
+
action: (prop?: string) => GlyphAction;
|
|
98
|
+
/** The `Option` children of a slot (default `options`). */
|
|
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;
|
|
110
|
+
};
|
|
111
|
+
export type GlyphComponent = (props: GlyphComponentProps) => ReactNode;
|
|
112
|
+
/** Component implementations by catalog name. Responses using a name that isn't here are rejected. */
|
|
113
|
+
export type GlyphComponents = Record<string, GlyphComponent>;
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kovca/glyph-react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
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
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"homepage": "https://kovca.io/docs/rendering",
|
|
9
|
+
"keywords": ["glyph", "kovca", "react", "a2ui", "generative-ui", "renderer", "shadcn"],
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"files": ["dist", "LICENSE", "README.md"],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc -p tsconfig.build.json",
|
|
20
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
21
|
+
"test": "vitest run"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@kovca/glyph": "^0.2.0"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"react": "^18.2.0 || ^19.0.0"
|
|
28
|
+
}
|
|
29
|
+
}
|