@kayr/umbika-react 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kayr
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,43 @@
1
- # Temporary Holding Version
1
+ # @kayr/umbika-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Experimental headless React 19 bindings for Umbika. Your application owns the
4
+ JSX and widgets; the form engine owns answers and rules.
5
+
6
+ ```sh
7
+ npm install @kayr/umbika-core @kayr/umbika-react react@19 react-dom@19
8
+ ```
9
+
10
+ ```tsx
11
+ import { createForm } from "@kayr/umbika-core";
12
+ import { Field, UmbikaForm, type FieldWidgetProps } from "@kayr/umbika-react";
13
+ import { useEffect, useState } from "react";
14
+
15
+ const form = createForm({
16
+ schema: [{ type: "text", id: "name", label: "Name" }],
17
+ });
18
+
19
+ function TextInput({ label, value, commit, touch }: FieldWidgetProps) {
20
+ const committed = typeof value === "string" ? value : "";
21
+ const [draft, setDraft] = useState(committed);
22
+ useEffect(() => setDraft(committed), [value, committed, commit]);
23
+
24
+ return (
25
+ <label>
26
+ {label}
27
+ <input
28
+ value={draft}
29
+ onChange={(event) => setDraft(event.target.value)}
30
+ onBlur={() => (draft === committed ? touch() : commit(draft))}
31
+ />
32
+ </label>
33
+ );
34
+ }
35
+
36
+ export function App() {
37
+ return (
38
+ <UmbikaForm engine={form}>
39
+ <Field path={["name"]} widget={TextInput} />
40
+ </UmbikaForm>
41
+ );
42
+ }
43
+ ```
@@ -0,0 +1,20 @@
1
+ import type { FieldPath, InputPayload } from "@kayr/umbika-core";
2
+ import { type ComponentType } from "react";
3
+ import { type FieldSnapshot, type UnavailableSnapshot } from "./snapshot.js";
4
+ export type FieldWidgetProps = Omit<FieldSnapshot, "type"> & {
5
+ readonly type: Exclude<FieldSnapshot["type"], "calculated">;
6
+ readonly commit: (payload: InputPayload) => void;
7
+ readonly touch: () => void;
8
+ };
9
+ export type CalculatedFieldBinding = Omit<FieldSnapshot, "type" | "touched"> & {
10
+ readonly type: "calculated";
11
+ };
12
+ export type FieldBinding = FieldWidgetProps | CalculatedFieldBinding | Readonly<{
13
+ status: "missing";
14
+ }> | UnavailableSnapshot;
15
+ export declare function useField(path: FieldPath): FieldBinding;
16
+ export interface FieldProps {
17
+ path: FieldPath;
18
+ widget: ComponentType<FieldWidgetProps>;
19
+ }
20
+ export declare function Field({ path, widget: Widget }: FieldProps): import("react").JSX.Element | null;
package/dist/field.js ADDED
@@ -0,0 +1,49 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useMemo } from "react";
3
+ import { useBoundPath, useFormStore } from "./provider.js";
4
+ import { pathKey, } from "./snapshot.js";
5
+ function requireEditable(form, path) {
6
+ const state = form.getFieldState(path);
7
+ if (!state.relevant)
8
+ throw new Error(`Field ${pathKey(path)} is irrelevant`);
9
+ if (state.readOnly || state.field.type === "calculated")
10
+ throw new Error(`Field ${pathKey(path)} is read-only`);
11
+ }
12
+ export function useField(path) {
13
+ const { store, concretePath, snapshot } = useBoundPath(path, "field");
14
+ const actions = useMemo(() => ({
15
+ commit(payload) {
16
+ store.mutate((form) => {
17
+ requireEditable(form, concretePath);
18
+ form.input(concretePath, payload);
19
+ form.touch(concretePath);
20
+ });
21
+ },
22
+ touch() {
23
+ store.mutate((form) => {
24
+ requireEditable(form, concretePath);
25
+ form.touch(concretePath);
26
+ });
27
+ },
28
+ }), [store, concretePath]);
29
+ return useMemo(() => {
30
+ if (snapshot.status !== "ready")
31
+ return snapshot;
32
+ if (snapshot.kind !== "field")
33
+ throw new Error(`Path ${pathKey(concretePath)} does not identify a field`);
34
+ if (snapshot.type === "calculated") {
35
+ const { touched, ...facts } = snapshot;
36
+ return { ...facts, type: "calculated" };
37
+ }
38
+ return { ...snapshot, type: snapshot.type, ...actions };
39
+ }, [concretePath, snapshot, actions]);
40
+ }
41
+ export function Field({ path, widget: Widget }) {
42
+ const { identity } = useFormStore();
43
+ const field = useField(path);
44
+ if (field.status !== "ready")
45
+ return null;
46
+ if (field.type === "calculated")
47
+ throw new Error(`Field ${pathKey(field.path)} is calculated; use useField for display`);
48
+ return _jsx(Widget, { ...field }, `${identity}:${pathKey(field.path)}`);
49
+ }
@@ -0,0 +1,8 @@
1
+ export { UmbikaForm, useForm } from "./provider.js";
2
+ export type { FormBinding, UmbikaFormProps } from "./provider.js";
3
+ export { Field, useField } from "./field.js";
4
+ export type { FieldBinding, FieldProps, FieldWidgetProps, CalculatedFieldBinding, } from "./field.js";
5
+ export { Scope } from "./scope.js";
6
+ export type { ScopeProps } from "./scope.js";
7
+ export { useSection, useRepeat, usePathsValid } from "./section.js";
8
+ export type { SectionBinding, RepeatBinding } from "./section.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { UmbikaForm, useForm } from "./provider.js";
2
+ export { Field, useField } from "./field.js";
3
+ export { Scope } from "./scope.js";
4
+ export { useSection, useRepeat, usePathsValid } from "./section.js";
@@ -0,0 +1,33 @@
1
+ import type { FieldPath, Form, ValidationResult } from "@kayr/umbika-core";
2
+ import { type ReactNode } from "react";
3
+ import { type FormSnapshot, type PathResult } from "./snapshot.js";
4
+ import { type FormStore } from "./store.js";
5
+ export interface UmbikaFormProps {
6
+ engine: Form;
7
+ children?: ReactNode;
8
+ }
9
+ export declare function UmbikaForm({ engine, children }: UmbikaFormProps): import("react").JSX.Element;
10
+ export declare function useFormStore(): FormStore;
11
+ export declare function usePathSnapshot(path: FieldPath): PathResult;
12
+ export declare function useBoundPath(path: FieldPath, target: "field" | "section" | "table"): {
13
+ store: {
14
+ identity: number;
15
+ subscribe(listener: () => void): () => void;
16
+ getFormSnapshot: () => FormSnapshot;
17
+ getPathSnapshot(path: FieldPath): PathResult;
18
+ attach(): () => void;
19
+ refresh: () => void;
20
+ run: <T>(action: (form: Form) => T) => T;
21
+ mutate: <T>(action: (form: Form) => T) => T;
22
+ validate: () => ValidationResult;
23
+ getSubmissionData: () => Record<string, unknown>;
24
+ };
25
+ concretePath: FieldPath;
26
+ snapshot: PathResult;
27
+ };
28
+ export type FormBinding = FormSnapshot & {
29
+ readonly refresh: () => void;
30
+ readonly validate: () => ValidationResult;
31
+ readonly getSubmissionData: () => Record<string, unknown>;
32
+ };
33
+ export declare function useForm(): FormBinding;
@@ -0,0 +1,51 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useInsertionEffect, useLayoutEffect, useMemo, useRef, useSyncExternalStore, } from "react";
3
+ import { PathContext, useConcretePath } from "./scope.js";
4
+ import { pathKey } from "./snapshot.js";
5
+ import { createFormStore } from "./store.js";
6
+ const FormContext = createContext(null);
7
+ export function UmbikaForm({ engine, children }) {
8
+ const store = useMemo(() => createFormStore(engine), [engine]);
9
+ // Tie action lifetime to the provider commit, not Strict Mode's replay of
10
+ // layout effects. Descendant layout effects can use the form immediately.
11
+ useInsertionEffect(store.attach, [store]);
12
+ return (_jsx(FormContext.Provider, { value: store, children: _jsx(PathContext.Provider, { value: undefined, children: children }) }));
13
+ }
14
+ export function useFormStore() {
15
+ const store = useContext(FormContext);
16
+ if (!store)
17
+ throw new Error("Form bindings require an UmbikaForm provider");
18
+ return store;
19
+ }
20
+ export function usePathSnapshot(path) {
21
+ const store = useFormStore();
22
+ return useSyncExternalStore(store.subscribe, () => store.getPathSnapshot(path));
23
+ }
24
+ // A known path that disappears with a row is different from an initial typo.
25
+ // Remember only this hook's last committed path, not a global path history.
26
+ export function useBoundPath(path, target) {
27
+ const store = useFormStore();
28
+ const concretePath = useConcretePath(path);
29
+ const snapshot = usePathSnapshot(concretePath);
30
+ const known = useRef(null);
31
+ useLayoutEffect(() => {
32
+ if (snapshot.status === "ready")
33
+ known.current = { store, path: concretePath };
34
+ }, [store, concretePath, snapshot]);
35
+ if (snapshot.status === "missing") {
36
+ const previous = known.current;
37
+ if (previous?.store !== store || previous.path !== concretePath)
38
+ throw new Error(`Unknown ${target} path ${pathKey(concretePath)}`);
39
+ }
40
+ return { store, concretePath, snapshot };
41
+ }
42
+ export function useForm() {
43
+ const store = useFormStore();
44
+ const snapshot = useSyncExternalStore(store.subscribe, store.getFormSnapshot);
45
+ return useMemo(() => ({
46
+ ...snapshot,
47
+ refresh: store.refresh,
48
+ validate: store.validate,
49
+ getSubmissionData: store.getSubmissionData,
50
+ }), [store, snapshot]);
51
+ }
@@ -0,0 +1,11 @@
1
+ import type { FieldPath } from "@kayr/umbika-core";
2
+ import { type ReactNode } from "react";
3
+ export declare const PathContext: import("react").Context<FieldPath | undefined>;
4
+ export declare function resolvePath(path: FieldPath, parent?: FieldPath): FieldPath;
5
+ export declare function useConcretePath(path: FieldPath, absolute?: boolean): FieldPath;
6
+ export interface ScopeProps {
7
+ path: FieldPath;
8
+ absolute?: boolean;
9
+ children?: ReactNode;
10
+ }
11
+ export declare function Scope({ path, absolute, children }: ScopeProps): import("react").JSX.Element;
package/dist/scope.js ADDED
@@ -0,0 +1,23 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useMemo } from "react";
3
+ import { pathKey } from "./snapshot.js";
4
+ export const PathContext = createContext(undefined);
5
+ export function resolvePath(path, parent) {
6
+ if (!Array.isArray(path) || path.length === 0)
7
+ throw new TypeError("Path must be a non-empty array of ID segments");
8
+ for (const segment of path) {
9
+ if (typeof segment !== "string" || !segment)
10
+ throw new TypeError("Path must be a non-empty array of ID segments");
11
+ }
12
+ return parent ? [...parent, ...path] : [path[0], ...path.slice(1)];
13
+ }
14
+ export function useConcretePath(path, absolute = false) {
15
+ const parent = useContext(PathContext);
16
+ const concrete = resolvePath(path, absolute ? undefined : parent);
17
+ const key = pathKey(concrete);
18
+ return useMemo(() => concrete, [key]);
19
+ }
20
+ export function Scope({ path, absolute = false, children }) {
21
+ const concrete = useConcretePath(path, absolute);
22
+ return (_jsx(PathContext.Provider, { value: concrete, children: children }));
23
+ }
@@ -0,0 +1,18 @@
1
+ import type { FieldPath, FormValues, ValidationResult } from "@kayr/umbika-core";
2
+ import { type SectionSnapshot, type UnavailableSnapshot } from "./snapshot.js";
3
+ type MissingOrUnavailable = Readonly<{
4
+ status: "missing";
5
+ }> | UnavailableSnapshot;
6
+ export type SectionBinding = (SectionSnapshot & {
7
+ readonly validate: () => ValidationResult;
8
+ }) | MissingOrUnavailable;
9
+ export declare function useSection(path: FieldPath): SectionBinding;
10
+ export type RepeatBinding = (Extract<SectionSnapshot, {
11
+ kind: "table";
12
+ }> & {
13
+ readonly append: (initialData?: FormValues) => string;
14
+ readonly remove: (rowId: string) => void;
15
+ }) | MissingOrUnavailable;
16
+ export declare function useRepeat(path: FieldPath): RepeatBinding;
17
+ export declare function usePathsValid(paths: readonly FieldPath[]): boolean;
18
+ export {};
@@ -0,0 +1,63 @@
1
+ import { useContext, useMemo, useSyncExternalStore } from "react";
2
+ import { useBoundPath, useFormStore } from "./provider.js";
3
+ import { PathContext, resolvePath } from "./scope.js";
4
+ import { pathKey, } from "./snapshot.js";
5
+ export function useSection(path) {
6
+ const { store, concretePath, snapshot } = useBoundPath(path, "section");
7
+ const validate = useMemo(() => () => store.mutate((form) => form.validateSection(concretePath)), [store, concretePath]);
8
+ return useMemo(() => {
9
+ if (snapshot.status !== "ready")
10
+ return snapshot;
11
+ if (snapshot.kind === "field")
12
+ throw new Error(`Path ${pathKey(concretePath)} does not identify a section`);
13
+ return { ...snapshot, validate };
14
+ }, [snapshot, concretePath, validate]);
15
+ }
16
+ function requireActiveTable(form, path) {
17
+ const section = form.getSectionState(path);
18
+ if (section.kind !== "table")
19
+ throw new Error(`Path ${pathKey(path)} does not identify a table`);
20
+ if (!section.relevant)
21
+ throw new Error(`Table ${pathKey(path)} is irrelevant`);
22
+ return section;
23
+ }
24
+ export function useRepeat(path) {
25
+ const { store, concretePath, snapshot } = useBoundPath(path, "table");
26
+ const actions = useMemo(() => ({
27
+ append(initialData) {
28
+ return store.mutate((form) => {
29
+ requireActiveTable(form, concretePath);
30
+ return form.appendRow(concretePath, initialData);
31
+ });
32
+ },
33
+ remove(rowId) {
34
+ store.mutate((form) => {
35
+ const table = requireActiveTable(form, concretePath);
36
+ const row = table.rows.find((item) => item.id === rowId);
37
+ if (!row)
38
+ throw new Error(`Unknown row ${JSON.stringify(rowId)} in table ${pathKey(concretePath)}`);
39
+ form.removeRow(row.path);
40
+ });
41
+ },
42
+ }), [store, concretePath]);
43
+ return useMemo(() => {
44
+ if (snapshot.status !== "ready")
45
+ return snapshot;
46
+ if (snapshot.kind !== "table")
47
+ throw new Error(`Path ${pathKey(concretePath)} does not identify a table`);
48
+ return { ...snapshot, ...actions };
49
+ }, [snapshot, concretePath, actions]);
50
+ }
51
+ export function usePathsValid(paths) {
52
+ const store = useFormStore();
53
+ const parent = useContext(PathContext);
54
+ const concretePaths = paths.map((path) => resolvePath(path, parent));
55
+ return useSyncExternalStore(store.subscribe, () => {
56
+ if (store.getFormSnapshot().status === "unavailable")
57
+ return false;
58
+ return concretePaths.every((path) => {
59
+ const snapshot = store.getPathSnapshot(path);
60
+ return snapshot.status === "ready" && snapshot.valid;
61
+ });
62
+ });
63
+ }
@@ -0,0 +1,49 @@
1
+ import type { FieldPath, Form, FormField, SectionRow, SelectOption, ValidationError } from "@kayr/umbika-core";
2
+ export type UnavailableSnapshot = Readonly<{
3
+ status: "unavailable";
4
+ valid: false;
5
+ error: string;
6
+ }>;
7
+ export type FormSnapshot = Readonly<{
8
+ status: "ready";
9
+ valid: boolean;
10
+ }> | UnavailableSnapshot;
11
+ interface PathFacts {
12
+ readonly status: "ready";
13
+ readonly path: FieldPath;
14
+ readonly relevant: boolean;
15
+ readonly valid: boolean;
16
+ readonly errors: readonly Readonly<ValidationError>[];
17
+ }
18
+ export interface FieldSnapshot extends PathFacts {
19
+ readonly kind: "field";
20
+ readonly type: FormField["type"];
21
+ readonly label: string;
22
+ readonly value: unknown;
23
+ readonly required: boolean;
24
+ readonly readOnly: boolean;
25
+ readonly touched: boolean;
26
+ readonly options?: readonly Readonly<SelectOption>[];
27
+ }
28
+ export type SectionSnapshot = PathFacts & {
29
+ readonly ownValid: boolean;
30
+ readonly subtreeErrors: readonly Readonly<ValidationError>[];
31
+ } & ({
32
+ readonly kind: "object" | "row";
33
+ } | {
34
+ readonly kind: "table";
35
+ readonly rows: readonly Readonly<SectionRow>[];
36
+ });
37
+ export type PathSnapshot = FieldSnapshot | SectionSnapshot;
38
+ export declare const missingSnapshot: Readonly<{
39
+ status: "missing";
40
+ }>;
41
+ export type PathResult = PathSnapshot | typeof missingSnapshot | UnavailableSnapshot;
42
+ export interface CompleteSnapshot {
43
+ readonly form: FormSnapshot;
44
+ readonly paths: ReadonlyMap<string, PathSnapshot>;
45
+ }
46
+ export declare function pathKey(path: FieldPath): string;
47
+ export declare function unavailableSnapshot(cause: unknown, previous?: CompleteSnapshot): CompleteSnapshot;
48
+ export declare function readSnapshot(engine: Form, previous?: CompleteSnapshot): CompleteSnapshot;
49
+ export {};
@@ -0,0 +1,110 @@
1
+ export const missingSnapshot = Object.freeze({ status: "missing" });
2
+ export function pathKey(path) {
3
+ return JSON.stringify(path);
4
+ }
5
+ // Project only presentation facts, never copied schema callbacks. Inactive
6
+ // sections and their retained rows are visited in exactly the same way.
7
+ function visitPathStates(engine, schema, add, parent) {
8
+ for (const node of schema) {
9
+ const path = parent ? [...parent, node.id] : [node.id];
10
+ if (node.type !== "object" && node.type !== "table") {
11
+ const { field, ...facts } = engine.getFieldState(path);
12
+ add({
13
+ ...facts,
14
+ status: "ready",
15
+ kind: "field",
16
+ type: field.type,
17
+ label: field.label,
18
+ });
19
+ continue;
20
+ }
21
+ const section = engine.getSectionState(path);
22
+ add({ status: "ready", ...section });
23
+ if (section.kind !== "table") {
24
+ visitPathStates(engine, node.children, add, path);
25
+ continue;
26
+ }
27
+ for (const row of section.rows) {
28
+ add({ status: "ready", ...engine.getSectionState(row.path) });
29
+ visitPathStates(engine, node.children, add, row.path);
30
+ }
31
+ }
32
+ }
33
+ export function unavailableSnapshot(cause, previous) {
34
+ const error = cause instanceof Error ? cause.message : String(cause);
35
+ if (previous?.form.status === "unavailable" && previous.form.error === error)
36
+ return previous;
37
+ return {
38
+ form: Object.freeze({ status: "unavailable", valid: false, error }),
39
+ paths: new Map(),
40
+ };
41
+ }
42
+ export function readSnapshot(engine, previous) {
43
+ try {
44
+ const valid = engine.isValid();
45
+ const form = previous?.form.status === "ready" && previous.form.valid === valid
46
+ ? previous.form
47
+ : Object.freeze({ status: "ready", valid });
48
+ const paths = new Map();
49
+ let unchanged = previous?.form === form;
50
+ visitPathStates(engine, engine.getFields(), (snapshot) => {
51
+ const key = pathKey(snapshot.path);
52
+ const prior = previous?.paths.get(key);
53
+ if (prior && samePlainData(prior, snapshot)) {
54
+ paths.set(key, prior);
55
+ }
56
+ else {
57
+ paths.set(key, freezePlainData(snapshot));
58
+ unchanged = false;
59
+ }
60
+ });
61
+ if (previous && unchanged && paths.size === previous.paths.size)
62
+ return previous;
63
+ return { form, paths };
64
+ }
65
+ catch (cause) {
66
+ return unavailableSnapshot(cause, previous);
67
+ }
68
+ }
69
+ // Engine values and option metadata are cloneable, not necessarily JSON. Only
70
+ // reuse a snapshot when equality is known; exotic objects are conservative
71
+ // changes rather than silently hiding updated metadata from a widget.
72
+ function isPlainData(value) {
73
+ if (typeof value !== "object" || value === null)
74
+ return false;
75
+ if (Array.isArray(value))
76
+ return true;
77
+ const prototype = Object.getPrototypeOf(value);
78
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
79
+ }
80
+ function samePlainData(left, right, seenLeft = new Map(), seenRight = new Map()) {
81
+ if (Object.is(left, right))
82
+ return true;
83
+ if (!isPlainData(left) || !isPlainData(right))
84
+ return false;
85
+ if (Object.getPrototypeOf(left) !== Object.getPrototypeOf(right))
86
+ return false;
87
+ if (Array.isArray(left) && left.length !== right.length)
88
+ return false;
89
+ if (seenLeft.has(left) || seenRight.has(right)) {
90
+ return seenLeft.get(left) === right && seenRight.get(right) === left;
91
+ }
92
+ seenLeft.set(left, right);
93
+ seenRight.set(right, left);
94
+ const keys = Object.keys(left);
95
+ const rightKeys = Object.keys(right);
96
+ return (keys.length === rightKeys.length &&
97
+ keys.every((key, index) => key === rightKeys[index] &&
98
+ samePlainData(left[key], right[key], seenLeft, seenRight)));
99
+ }
100
+ // Paths, errors, rows and ordinary nested metadata are immutable once exposed.
101
+ // Other cloneable values still follow the borrowed read-only snapshot contract.
102
+ function freezePlainData(value, seen = new Set()) {
103
+ if (!isPlainData(value) || seen.has(value))
104
+ return value;
105
+ seen.add(value);
106
+ for (const child of Object.values(value))
107
+ freezePlainData(child, seen);
108
+ Object.freeze(value);
109
+ return value;
110
+ }
@@ -0,0 +1,15 @@
1
+ import type { FieldPath, Form } from "@kayr/umbika-core";
2
+ import { type PathResult } from "./snapshot.js";
3
+ export declare function createFormStore(engine: Form): {
4
+ identity: number;
5
+ subscribe(listener: () => void): () => void;
6
+ getFormSnapshot: () => import("./snapshot.js").FormSnapshot;
7
+ getPathSnapshot(path: FieldPath): PathResult;
8
+ attach(): () => void;
9
+ refresh: () => void;
10
+ run: <T>(action: (form: Form) => T) => T;
11
+ mutate: <T>(action: (form: Form) => T) => T;
12
+ validate: () => import("@kayr/umbika-core").ValidationResult;
13
+ getSubmissionData: () => Record<string, unknown>;
14
+ };
15
+ export type FormStore = ReturnType<typeof createFormStore>;
package/dist/store.js ADDED
@@ -0,0 +1,72 @@
1
+ import { missingSnapshot, pathKey, readSnapshot, unavailableSnapshot, } from "./snapshot.js";
2
+ let nextStoreIdentity = 0;
3
+ export function createFormStore(engine) {
4
+ let current = readSnapshot(engine);
5
+ const listeners = new Set();
6
+ let active = true;
7
+ function publish(next) {
8
+ if (next === current)
9
+ return;
10
+ current = next;
11
+ for (const listener of listeners)
12
+ listener();
13
+ }
14
+ function requireActive() {
15
+ if (!active)
16
+ throw new Error("UmbikaForm provider is no longer mounted");
17
+ }
18
+ function refresh() {
19
+ requireActive();
20
+ publish(readSnapshot(engine, current));
21
+ }
22
+ // Actions run against live engine state, never the published presentation
23
+ // snapshot. On failure expose unavailable evaluation but do not publish an
24
+ // unrelated host edit after a rejected operation against a still-valid form.
25
+ function run(action) {
26
+ requireActive();
27
+ try {
28
+ return action(engine);
29
+ }
30
+ catch (cause) {
31
+ try {
32
+ engine.isValid();
33
+ }
34
+ catch (failure) {
35
+ publish(unavailableSnapshot(failure, current));
36
+ }
37
+ throw cause;
38
+ }
39
+ }
40
+ function mutate(action) {
41
+ const result = run(action);
42
+ refresh();
43
+ return result;
44
+ }
45
+ return {
46
+ identity: nextStoreIdentity++,
47
+ subscribe(listener) {
48
+ listeners.add(listener);
49
+ return () => {
50
+ listeners.delete(listener);
51
+ };
52
+ },
53
+ getFormSnapshot: () => current.form,
54
+ getPathSnapshot(path) {
55
+ if (current.form.status === "unavailable")
56
+ return current.form;
57
+ return current.paths.get(pathKey(path)) ?? missingSnapshot;
58
+ },
59
+ // Commit cleanup retires actions without destroying the host's engine.
60
+ attach() {
61
+ active = true;
62
+ return () => {
63
+ active = false;
64
+ };
65
+ },
66
+ refresh,
67
+ run,
68
+ mutate,
69
+ validate: () => mutate((form) => form.validate()),
70
+ getSubmissionData: () => run((form) => form.getSubmissionData()),
71
+ };
72
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@kayr/umbika-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "description": "Headless React bindings for @kayr/umbika-core.",
9
+ "type": "module",
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
22
+ "scripts": {
23
+ "prebuild": "npm run build -w @kayr/umbika-core",
24
+ "build": "node scripts/clean-output.mjs && tsc -p tsconfig.json",
25
+ "prepack": "npm run build",
26
+ "pretest": "npm run build",
27
+ "test": "vitest run --config vitest.config.js",
28
+ "pretypecheck": "npm run build",
29
+ "typecheck": "tsc -p tsconfig.test.json",
30
+ "preshowcase": "npm run build",
31
+ "showcase": "vite --config showcase/vite.config.js",
32
+ "preshowcase:build": "npm run build",
33
+ "showcase:build": "vite build --config showcase/vite.config.js",
34
+ "test:browser": "playwright test --config showcase/playwright.config.js"
35
+ },
36
+ "dependencies": {
37
+ "@kayr/umbika-core": "^0.1.0"
38
+ },
39
+ "peerDependencies": {
40
+ "react": "^19.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "@playwright/test": "1.58.1",
44
+ "@testing-library/dom": "10.4.2",
45
+ "@testing-library/react": "16.3.3",
46
+ "@types/react": "19.3.3",
47
+ "@types/react-dom": "19.3.0",
48
+ "jsdom": "^20.0.3",
49
+ "react": "19.3.0",
50
+ "react-dom": "19.3.0",
51
+ "vite": "5.4.21"
52
+ }
53
+ }