@kayr/umbika-flow 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,21 @@
1
- # Temporary Holding Version
1
+ # @kayr/umbika-flow
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 question-by-question navigation over an Umbika form. Your
4
+ application renders the current question or review view.
5
+
6
+ ```sh
7
+ npm install @kayr/umbika-core @kayr/umbika-flow
8
+ ```
9
+
10
+ ```js
11
+ import { createForm } from "@kayr/umbika-core";
12
+ import { createFlow } from "@kayr/umbika-flow";
13
+
14
+ const form = createForm({
15
+ schema: [{ type: "text", id: "name", label: "Name", required: true }],
16
+ });
17
+ const flow = createFlow(form);
18
+
19
+ console.log(flow.getView()); // Current question
20
+ console.log(flow.answer("Ada")); // Completed review
21
+ ```
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Drive a form flow through line-oriented input and output.
3
+ *
4
+ * @param {import("@kayr/umbika-core").Form} form
5
+ * @param {import("./types.js").ConsoleIO} io
6
+ * @returns {Promise<import("./types.js").ConsoleRunResult>}
7
+ */
8
+ export declare function runConsole(form: import("@kayr/umbika-core").Form, { readLine, write }: import("./types.js").ConsoleIO): Promise<import("./types.js").ConsoleRunResult>;
9
+ //# sourceMappingURL=console.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console.d.ts","sourceRoot":"","sources":["../src/console.js"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAJ1B,OAAO,mBAAmB,EAAE,IAIF,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,EAH/C,OAAO,YAAY,EAAE,SAG0B,GAF7C,OAAO,CAAC,OAAO,YAAY,EAAE,gBAAgB,CAAC,CAiG1D"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @param {import("@kayr/umbika-core").ActiveField} field
3
+ * @returns {field is import("./types.js").EditableActiveField}
4
+ */
5
+ export declare function isEditableField(field: import("@kayr/umbika-core").ActiveField): field is import("./types.js").EditableActiveField;
6
+ //# sourceMappingURL=field-editability.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"field-editability.d.ts","sourceRoot":"","sources":["../src/field-editability.js"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAH1B,OAAO,mBAAmB,EAAE,WAGF,GAFxB,KAAK,IAAI,OAAO,YAAY,EAAE,mBAAmB,CAI7D"}
package/dist/flow.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Create a deterministic, single-question flow over a form.
3
+ *
4
+ * @param {import("@kayr/umbika-core").Form} form
5
+ * @returns {import("./types.js").Flow}
6
+ */
7
+ export declare function createFlow(form: import("@kayr/umbika-core").Form): import("./types.js").Flow;
8
+ //# sourceMappingURL=flow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow.d.ts","sourceRoot":"","sources":["../src/flow.js"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAHpB,OAAO,mBAAmB,EAAE,IAGR,GAFlB,OAAO,YAAY,EAAE,IAAI,CAyJrC"}
@@ -0,0 +1,4 @@
1
+ export * from "./console.js";
2
+ export * from "./flow.js";
3
+ export * from "./types.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC"}
@@ -0,0 +1,158 @@
1
+ /**
2
+ * @typedef {object} OptionView
3
+ * @property {string} key One-based input key.
4
+ * @property {string} value Stored option value.
5
+ * @property {string} label Human-readable option label.
6
+ */
7
+ export type OptionView = {
8
+ /**
9
+ * One-based input key.
10
+ */
11
+ key: string;
12
+ /**
13
+ * Stored option value.
14
+ */
15
+ value: string;
16
+ /**
17
+ * Human-readable option label.
18
+ */
19
+ label: string;
20
+ };
21
+ export type EditableActiveField = import("@kayr/umbika-core").ActiveTextField | import("@kayr/umbika-core").ActiveSelectField | import("@kayr/umbika-core").ActiveMultiSelectField;
22
+ export type QuestionView = {
23
+ kind: "question";
24
+ finished: false;
25
+ ready: false;
26
+ /**
27
+ * One-based question position.
28
+ */
29
+ position: number;
30
+ total: number;
31
+ /**
32
+ * Field declaration identity.
33
+ */
34
+ id: string;
35
+ /**
36
+ * Concrete answer path.
37
+ */
38
+ path: import("@kayr/umbika-core").FieldPath;
39
+ label: string;
40
+ type: "text" | "select" | "multi-select";
41
+ value: unknown;
42
+ errors: import("@kayr/umbika-core").ValidationError[];
43
+ /**
44
+ * Renderer-owned input guidance.
45
+ */
46
+ inputError: string | null;
47
+ options: OptionView[];
48
+ /**
49
+ * Stored selections absent from current choices.
50
+ */
51
+ unavailableSelections: string[];
52
+ };
53
+ export type ReviewAnswer = {
54
+ /**
55
+ * Field declaration identity.
56
+ */
57
+ id: string;
58
+ /**
59
+ * Concrete answer path.
60
+ */
61
+ path: import("@kayr/umbika-core").FieldPath;
62
+ label: string;
63
+ value: unknown;
64
+ displayValue: string;
65
+ /**
66
+ * Whether the value is calculated or currently locked.
67
+ */
68
+ readOnly: boolean;
69
+ /**
70
+ * Visible field errors.
71
+ */
72
+ errors: import("@kayr/umbika-core").ValidationError[];
73
+ };
74
+ export type ReviewView = {
75
+ kind: "review";
76
+ finished: true;
77
+ ready: boolean;
78
+ answers: ReviewAnswer[];
79
+ /**
80
+ * Visible errors owned by objects and tables.
81
+ */
82
+ structuralErrors: import("@kayr/umbika-core").ValidationError[];
83
+ };
84
+ export type FlowView = QuestionView | ReviewView;
85
+ export type Flow = {
86
+ getView: () => FlowView;
87
+ answer: (input: string) => FlowView;
88
+ back: () => FlowView;
89
+ };
90
+ export type ConsoleIO = {
91
+ /**
92
+ * Read a line, or return null at end of input.
93
+ */
94
+ readLine: () => Promise<string | null>;
95
+ /**
96
+ * Write console output.
97
+ */
98
+ write: (text: string) => void;
99
+ };
100
+ export type ConsoleRunResult = {
101
+ status: "completed" | "quit" | "input-ended";
102
+ ready: boolean;
103
+ };
104
+ /** @typedef {import("@kayr/umbika-core").ActiveTextField | import("@kayr/umbika-core").ActiveSelectField | import("@kayr/umbika-core").ActiveMultiSelectField} EditableActiveField */
105
+ /**
106
+ * @typedef {object} QuestionView
107
+ * @property {"question"} kind
108
+ * @property {false} finished
109
+ * @property {false} ready
110
+ * @property {number} position One-based question position.
111
+ * @property {number} total
112
+ * @property {string} id Field declaration identity.
113
+ * @property {import("@kayr/umbika-core").FieldPath} path Concrete answer path.
114
+ * @property {string} label
115
+ * @property {"text" | "select" | "multi-select"} type
116
+ * @property {unknown} value
117
+ * @property {import("@kayr/umbika-core").ValidationError[]} errors
118
+ * @property {string | null} inputError Renderer-owned input guidance.
119
+ * @property {OptionView[]} options
120
+ * @property {string[]} unavailableSelections Stored selections absent from current choices.
121
+ */
122
+ /**
123
+ * @typedef {object} ReviewAnswer
124
+ * @property {string} id Field declaration identity.
125
+ * @property {import("@kayr/umbika-core").FieldPath} path Concrete answer path.
126
+ * @property {string} label
127
+ * @property {unknown} value
128
+ * @property {string} displayValue
129
+ * @property {boolean} readOnly Whether the value is calculated or currently locked.
130
+ * @property {import("@kayr/umbika-core").ValidationError[]} errors Visible field errors.
131
+ */
132
+ /**
133
+ * @typedef {object} ReviewView
134
+ * @property {"review"} kind
135
+ * @property {true} finished
136
+ * @property {boolean} ready
137
+ * @property {ReviewAnswer[]} answers
138
+ * @property {import("@kayr/umbika-core").ValidationError[]} structuralErrors Visible errors owned by objects and tables.
139
+ */
140
+ /** @typedef {QuestionView | ReviewView} FlowView */
141
+ /**
142
+ * @typedef {object} Flow
143
+ * @property {() => FlowView} getView
144
+ * @property {(input: string) => FlowView} answer
145
+ * @property {() => FlowView} back
146
+ */
147
+ /**
148
+ * @typedef {object} ConsoleIO
149
+ * @property {() => Promise<string | null>} readLine Read a line, or return null at end of input.
150
+ * @property {(text: string) => void} write Write console output.
151
+ */
152
+ /**
153
+ * @typedef {object} ConsoleRunResult
154
+ * @property {"completed" | "quit" | "input-ended"} status
155
+ * @property {boolean} ready
156
+ */
157
+ export {};
158
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.js"],"names":[],"mappings":"AAAA;;;;;GAKG;AAJA,YAAkB,UAAU,GAC5B;;;;IAAmB,GAAG,EAAX,MAAM,CACjB;;;;IAAmB,KAAK,EAAb,MAAM,CACjB;;;;IAAmB,KAAK,EAAb,MAAM,CACnB;CAAA,CAAA;AAEG,YAA4J,mBAAmB,GAArK,OAAO,mBAAmB,EAAE,eAAe,GAAG,OAAO,mBAAmB,EAAE,iBAAiB,GAAG,OAAO,mBAAmB,EAAE,sBAAsB,CAAqB;AAGhL,YAAkB,YAAY,GAC9B;IAAuB,IAAI,EAAhB,UAAU,CACrB;IAAkB,QAAQ,EAAf,KAAK,CAChB;IAAkB,KAAK,EAAZ,KAAK,CAChB;;;;IAAmB,QAAQ,EAAhB,MAAM,CACjB;IAAmB,KAAK,EAAb,MAAM,CACjB;;;;IAAmB,EAAE,EAAV,MAAM,CACjB;;;;IAAkD,IAAI,EAA3C,OAAO,mBAAmB,EAAE,SAAS,CAChD;IAAmB,KAAK,EAAb,MAAM,CACjB;IAA+C,IAAI,EAAxC,MAAM,GAAG,QAAQ,GAAG,cAAc,CAC7C;IAAoB,KAAK,EAAd,OAAO,CAClB;IAA0D,MAAM,EAArD,OAAO,mBAAmB,EAAE,eAAe,EAAE,CACxD;;;;IAA0B,UAAU,EAAzB,MAAM,GAAG,IAAI,CACxB;IAAyB,OAAO,EAArB,UAAU,EAAE,CACvB;;;;IAAqB,qBAAqB,EAA/B,MAAM,EAAE,CACrB;CAAA,CAAA;AAGE,YAAkB,YAAY,GAC9B;;;;IAAmB,EAAE,EAAV,MAAM,CACjB;;;;IAAkD,IAAI,EAA3C,OAAO,mBAAmB,EAAE,SAAS,CAChD;IAAmB,KAAK,EAAb,MAAM,CACjB;IAAoB,KAAK,EAAd,OAAO,CAClB;IAAmB,YAAY,EAApB,MAAM,CACjB;;;;IAAoB,QAAQ,EAAjB,OAAO,CAClB;;;;IAA0D,MAAM,EAArD,OAAO,mBAAmB,EAAE,eAAe,EAAE,CAC1D;CAAA,CAAA;AAGE,YAAkB,UAAU,GAC5B;IAAqB,IAAI,EAAd,QAAQ,CACnB;IAAiB,QAAQ,EAAd,IAAI,CACf;IAAoB,KAAK,EAAd,OAAO,CAClB;IAA2B,OAAO,EAAvB,YAAY,EAAE,CACzB;;;;IAA0D,gBAAgB,EAA/D,OAAO,mBAAmB,EAAE,eAAe,EAAE,CAC1D;CAAA,CAAA;AAEG,YAAqC,QAAQ,GAAnC,YAAY,GAAG,UAAU,CAAU;AAG9C,YAAkB,IAAI,GACtB;IAA2B,OAAO,EAAvB,MAAM,QAAQ,CACzB;IAAwC,MAAM,EAAnC,CAAC,KAAK,EAAE,MAAM,KAAK,QAAQ,CACtC;IAA2B,IAAI,EAApB,MAAM,QAAQ,CAC3B;CAAA,CAAA;AAGE,YAAkB,SAAS,GAC3B;;;;IAAyC,QAAQ,EAAtC,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CACvC;;;;IAAmC,KAAK,EAA7B,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CACnC;CAAA,CAAA;AAGE,YAAkB,gBAAgB,GAClC;IAAiD,MAAM,EAA5C,WAAW,GAAG,MAAM,GAAG,aAAa,CAC/C;IAAoB,KAAK,EAAd,OAAO,CACpB;CAAA,CAAA;AA3DD,sLAAsL;AAEtL;;;;;;;;;;;;;;;;GAgBG;AAEH;;;;;;;;;GASG;AAEH;;;;;;;GAOG;AAEH,oDAAoD;AAEpD;;;;;GAKG;AAEH;;;;GAIG;AAEH;;;;GAIG;AAEH,OAAO,EAAE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@kayr/umbika-flow",
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": "A deterministic ID-based flow over @kayr/umbika-core.",
9
+ "type": "module",
10
+ "main": "./src/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./src/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "src",
20
+ "dist"
21
+ ],
22
+ "scripts": {
23
+ "prebuild": "npm run build -w @kayr/umbika-core",
24
+ "build": "tsc -p tsconfig.json",
25
+ "prepack": "npm run build",
26
+ "preconsole": "npm run build -w @kayr/umbika-core",
27
+ "console": "node ./examples/console.js",
28
+ "test": "vitest run --config vitest.config.js",
29
+ "pretypecheck": "npm run build -w @kayr/umbika-core",
30
+ "typecheck": "tsc -p tsconfig.json --noEmit"
31
+ },
32
+ "dependencies": {
33
+ "@kayr/umbika-core": "^0.1.0"
34
+ }
35
+ }
package/src/console.js ADDED
@@ -0,0 +1,282 @@
1
+ import { createFlow } from "./flow.js";
2
+ import { isEditableField } from "./field-editability.js";
3
+
4
+ /**
5
+ * Drive a form flow through line-oriented input and output.
6
+ *
7
+ * @param {import("@kayr/umbika-core").Form} form
8
+ * @param {import("./types.js").ConsoleIO} io
9
+ * @returns {Promise<import("./types.js").ConsoleRunResult>}
10
+ */
11
+ export async function runConsole(form, { readLine, write }) {
12
+ const flow = createFlow(form);
13
+ const declinedTables = new Set();
14
+ let view = flow.getView();
15
+ let boundaryStart = null;
16
+ let checkBoundaries = true;
17
+
18
+ while (true) {
19
+ if (checkBoundaries) {
20
+ const outline = createPromptOutline(form.getActiveFields());
21
+ forgetInactiveTables(declinedTables, outline.tablePrompts);
22
+ const prompt = nextTablePrompt(
23
+ outline,
24
+ boundaryStart,
25
+ view.kind === "question" ? view.path : null,
26
+ declinedTables,
27
+ );
28
+
29
+ if (prompt) {
30
+ write(renderTablePrompt(prompt));
31
+ write("> ");
32
+
33
+ const input = await readLine();
34
+ if (input === null) return { status: "input-ended", ready: false };
35
+ if (input === ":quit") {
36
+ write("Quit.\n");
37
+ return { status: "quit", ready: false };
38
+ }
39
+ if (input === ":back") {
40
+ const previousView = view;
41
+ view = flow.back();
42
+ if (sameLocation(view, previousView)) continue;
43
+ boundaryStart = null;
44
+ checkBoundaries = false;
45
+ continue;
46
+ }
47
+
48
+ const choice = input.trim().toLowerCase();
49
+ if (choice === "y" || choice === "yes") {
50
+ form.appendRow(prompt.path);
51
+ view = flow.getView();
52
+ continue;
53
+ }
54
+ if (choice === "" || choice === "n" || choice === "no") {
55
+ declinedTables.add(pathKey(prompt.path));
56
+ continue;
57
+ }
58
+
59
+ write("Error: Enter y or n.\n");
60
+ continue;
61
+ }
62
+
63
+ checkBoundaries = false;
64
+ }
65
+
66
+ if (view.kind === "review") {
67
+ form.validate();
68
+ view = flow.getView();
69
+ if (view.kind !== "review") continue;
70
+ write(renderReview(view));
71
+ return { status: "completed", ready: view.ready };
72
+ }
73
+
74
+ write(renderQuestion(view));
75
+ write("> ");
76
+
77
+ const input = await readLine();
78
+ if (input === null) return { status: "input-ended", ready: false };
79
+ if (input === ":quit") {
80
+ write("Quit.\n");
81
+ return { status: "quit", ready: false };
82
+ }
83
+
84
+ if (input === ":back") {
85
+ view = flow.back();
86
+ boundaryStart = null;
87
+ checkBoundaries = false;
88
+ continue;
89
+ }
90
+
91
+ const currentView = flow.getView();
92
+ if (!sameQuestionPrompt(view, currentView)) {
93
+ view = currentView;
94
+ boundaryStart = null;
95
+ checkBoundaries = true;
96
+ continue;
97
+ }
98
+
99
+ const answeredPath = view.path;
100
+ view = flow.answer(input);
101
+ const accepted =
102
+ view.kind === "review" || !pathsEqual(view.path, answeredPath);
103
+ boundaryStart = accepted ? answeredPath : null;
104
+ checkBoundaries = accepted;
105
+ }
106
+ }
107
+
108
+ /** @param {import("@kayr/umbika-core").ActiveFieldNode[]} nodes */
109
+ function createPromptOutline(nodes) {
110
+ /** @type {import("@kayr/umbika-core").FieldPath[]} */
111
+ const leafPaths = [];
112
+ /** @type {{ path: import("@kayr/umbika-core").FieldPath, label: string, hasRows: boolean, position: number }[]} */
113
+ const tablePrompts = [];
114
+
115
+ /** @param {import("@kayr/umbika-core").ActiveFieldNode[]} current */
116
+ function visit(current) {
117
+ for (const node of current) {
118
+ if (node.type === "object") {
119
+ visit(node.children);
120
+ continue;
121
+ }
122
+ if (node.type === "table") {
123
+ for (const row of node.rows) visit(row.children);
124
+ tablePrompts.push({
125
+ path: node.path,
126
+ label: node.label ?? node.id,
127
+ hasRows: node.rows.length > 0,
128
+ position: leafPaths.length,
129
+ });
130
+ continue;
131
+ }
132
+ if (isEditableField(node)) leafPaths.push(node.path);
133
+ }
134
+ }
135
+
136
+ visit(nodes);
137
+ return { leafPaths, tablePrompts };
138
+ }
139
+
140
+ /**
141
+ * @param {ReturnType<typeof createPromptOutline>} outline
142
+ * @param {import("@kayr/umbika-core").FieldPath | null} afterPath
143
+ * @param {import("@kayr/umbika-core").FieldPath | null} beforePath
144
+ * @param {Set<string>} declinedTables
145
+ */
146
+ function nextTablePrompt(
147
+ { leafPaths, tablePrompts },
148
+ afterPath,
149
+ beforePath,
150
+ declinedTables,
151
+ ) {
152
+ const afterIndex = leafPaths.findIndex((path) => pathsEqual(path, afterPath));
153
+ const beforeIndex = leafPaths.findIndex((path) =>
154
+ pathsEqual(path, beforePath),
155
+ );
156
+ let firstPosition =
157
+ beforePath === null || afterIndex < 0 ? 0 : afterIndex + 1;
158
+ const lastPosition = beforeIndex < 0 ? leafPaths.length : beforeIndex;
159
+
160
+ if (lastPosition < firstPosition) firstPosition = 0;
161
+
162
+ return tablePrompts.find(
163
+ ({ path, position }) =>
164
+ position >= firstPosition &&
165
+ position <= lastPosition &&
166
+ !declinedTables.has(pathKey(path)),
167
+ );
168
+ }
169
+
170
+ /**
171
+ * @param {Set<string>} declinedTables
172
+ * @param {ReturnType<typeof createPromptOutline>["tablePrompts"]} tablePrompts
173
+ */
174
+ function forgetInactiveTables(declinedTables, tablePrompts) {
175
+ const activeTables = new Set(tablePrompts.map(({ path }) => pathKey(path)));
176
+ for (const key of declinedTables) {
177
+ if (!activeTables.has(key)) declinedTables.delete(key);
178
+ }
179
+ }
180
+
181
+ /** @param {{ label: string, hasRows: boolean }} prompt */
182
+ function renderTablePrompt(prompt) {
183
+ const action = prompt.hasRows ? "another row" : "a row";
184
+ return `Add ${action} to ${prompt.label}? [y/N]\n`;
185
+ }
186
+
187
+ /** @param {import("./types.js").QuestionView} view */
188
+ function renderQuestion(view) {
189
+ const lines = [
190
+ `Question ${view.position} of ${view.total}: ${displayLabel(view)}`,
191
+ ];
192
+
193
+ for (const option of view.options) {
194
+ lines.push(` ${option.key}. ${option.label}`);
195
+ }
196
+ for (const value of view.unavailableSelections)
197
+ lines.push(`Unavailable selection: ${value}`);
198
+ if (view.type === "multi-select") {
199
+ lines.push("Enter comma-separated keys, or leave blank for none.");
200
+ }
201
+ for (const error of view.errors) {
202
+ lines.push(`Error: ${error.message}`);
203
+ }
204
+ if (view.inputError) lines.push(`Error: ${view.inputError}`);
205
+
206
+ return `${lines.join("\n")}\n`;
207
+ }
208
+
209
+ /** @param {import("./types.js").ReviewView} view */
210
+ function renderReview(view) {
211
+ const lines = ["Review"];
212
+ for (const answer of view.answers) {
213
+ lines.push(`${displayLabel(answer)}: ${answer.displayValue}`);
214
+ for (const error of answer.errors) {
215
+ lines.push(`Error: ${error.message}`);
216
+ }
217
+ }
218
+ for (const error of view.structuralErrors) {
219
+ lines.push(`Error at ${error.path.join(".")}: ${error.message}`);
220
+ }
221
+ lines.push(view.ready ? "Ready to submit." : "Not ready to submit.");
222
+ return `${lines.join("\n")}\n`;
223
+ }
224
+
225
+ /**
226
+ * Include a concrete path when a leaf is nested so repeated child IDs and
227
+ * labels remain distinguishable without changing form semantics.
228
+ *
229
+ * @param {{ label: string, path: import("@kayr/umbika-core").FieldPath }} field
230
+ */
231
+ function displayLabel(field) {
232
+ return field.path.length > 1
233
+ ? `${field.label} (${field.path.join(".")})`
234
+ : field.label;
235
+ }
236
+
237
+ /** @param {import("@kayr/umbika-core").FieldPath} path */
238
+ function pathKey(path) {
239
+ return JSON.stringify(path);
240
+ }
241
+
242
+ /**
243
+ * @param {import("@kayr/umbika-core").FieldPath} left
244
+ * @param {import("@kayr/umbika-core").FieldPath | null} right
245
+ */
246
+ function pathsEqual(left, right) {
247
+ return (
248
+ right !== null &&
249
+ left.length === right.length &&
250
+ left.every((segment, index) => segment === right[index])
251
+ );
252
+ }
253
+
254
+ /**
255
+ * @param {import("./types.js").FlowView} left
256
+ * @param {import("./types.js").FlowView} right
257
+ */
258
+ function sameLocation(left, right) {
259
+ if (left.kind === "review" || right.kind === "review") {
260
+ return left.kind === right.kind;
261
+ }
262
+ return pathsEqual(left.path, right.path);
263
+ }
264
+
265
+ /**
266
+ * @param {import("./types.js").QuestionView} prompted
267
+ * @param {import("./types.js").FlowView} current
268
+ */
269
+ function sameQuestionPrompt(prompted, current) {
270
+ return (
271
+ current.kind === "question" &&
272
+ sameLocation(prompted, current) &&
273
+ prompted.type === current.type &&
274
+ prompted.options.length === current.options.length &&
275
+ prompted.options.every(({ key, value, label }, index) => {
276
+ const option = current.options[index];
277
+ return (
278
+ option?.key === key && option.value === value && option.label === label
279
+ );
280
+ })
281
+ );
282
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @param {import("@kayr/umbika-core").ActiveField} field
3
+ * @returns {field is import("./types.js").EditableActiveField}
4
+ */
5
+ export function isEditableField(field) {
6
+ return field.type !== "calculated" && !field.readOnly;
7
+ }
package/src/flow.js ADDED
@@ -0,0 +1,332 @@
1
+ import { isEditableField } from "./field-editability.js";
2
+
3
+ /**
4
+ * Create a deterministic, single-question flow over a form.
5
+ *
6
+ * @param {import("@kayr/umbika-core").Form} form
7
+ * @returns {import("./types.js").Flow}
8
+ */
9
+ export function createFlow(form) {
10
+ /** @type {import("@kayr/umbika-core").FieldPath[]} */
11
+ const visited = [];
12
+ /** @type {import("@kayr/umbika-core").FieldPath[]} */
13
+ const history = [];
14
+ /** @type {import("@kayr/umbika-core").FieldPath | null} */
15
+ let currentPath = null;
16
+ /** @type {string | null} */
17
+ let inputError = null;
18
+
19
+ function currentFlowFields() {
20
+ const activeFields = form.getActiveFields();
21
+ const leaves = flattenActiveFields(activeFields);
22
+ return {
23
+ leaves,
24
+ editableFields: leaves.filter(isEditableField),
25
+ structuralErrors: collectStructuralErrors(activeFields),
26
+ };
27
+ }
28
+
29
+ /** @param {import("./types.js").EditableActiveField[]} fields */
30
+ function resolveCurrentField(fields) {
31
+ const pinnedField = fields.find(({ path }) =>
32
+ pathsEqual(path, currentPath),
33
+ );
34
+ if (pinnedField) return pinnedField;
35
+
36
+ currentPath = null;
37
+ inputError = null;
38
+ return fields.find(({ path }) => !containsPath(visited, path));
39
+ }
40
+
41
+ /**
42
+ * @param {import("@kayr/umbika-core").ActiveField[]} leaves
43
+ * @param {import("./types.js").EditableActiveField[]} editableFields
44
+ * @param {import("@kayr/umbika-core").ValidationError[]} structuralErrors
45
+ */
46
+ function viewFor(leaves, editableFields, structuralErrors) {
47
+ const field = resolveCurrentField(editableFields);
48
+
49
+ if (!field)
50
+ return reviewView(
51
+ form,
52
+ leaves,
53
+ editableFields,
54
+ visited,
55
+ structuralErrors,
56
+ );
57
+
58
+ return {
59
+ kind: /** @type {const} */ ("question"),
60
+ finished: /** @type {const} */ (false),
61
+ ready: /** @type {const} */ (false),
62
+ position: editableFields.indexOf(field) + 1,
63
+ total: editableFields.length,
64
+ id: field.id,
65
+ path: copyPath(field.path),
66
+ label: field.label,
67
+ type: field.type,
68
+ value: field.value,
69
+ errors: field.errors,
70
+ inputError,
71
+ unavailableSelections: unavailableSelections(field),
72
+ options:
73
+ field.type === "select" || field.type === "multi-select"
74
+ ? field.options.map((option, index) => ({
75
+ key: String(index + 1),
76
+ value: option.value,
77
+ label: option.label,
78
+ }))
79
+ : [],
80
+ };
81
+ }
82
+
83
+ function getView() {
84
+ const { leaves, editableFields, structuralErrors } = currentFlowFields();
85
+ return viewFor(leaves, editableFields, structuralErrors);
86
+ }
87
+
88
+ /** @param {string} input */
89
+ function answer(input) {
90
+ if (typeof input !== "string")
91
+ throw new TypeError("input must be a string");
92
+
93
+ const { editableFields } = currentFlowFields();
94
+ const field = resolveCurrentField(editableFields);
95
+ if (!field) throw new Error("flow is already finished");
96
+
97
+ inputError = null;
98
+ currentPath = copyPath(field.path);
99
+
100
+ if (field.type === "multi-select") {
101
+ const selectedValues = parseMultiSelect(input, field.options);
102
+ if (selectedValues === null) {
103
+ form.touch(field.path);
104
+ currentPath = copyPath(field.path);
105
+ inputError = multiSelectGuidance(field.options.length);
106
+ return getView();
107
+ }
108
+ form.input(field.path, {
109
+ value: selectedValues,
110
+ items: selectedValues.map((value) =>
111
+ field.options.find((option) => option.value === value),
112
+ ),
113
+ });
114
+ } else if (field.type === "select") {
115
+ const selected = field.options[Number(input) - 1];
116
+ if (
117
+ input.trim() !== "" &&
118
+ (!selected || input !== String(field.options.indexOf(selected) + 1))
119
+ ) {
120
+ form.touch(field.path);
121
+ currentPath = copyPath(field.path);
122
+ inputError = `Choose a key from 1 to ${field.options.length}.`;
123
+ return getView();
124
+ }
125
+ form.input(field.path, input.trim() === "" ? undefined : selected);
126
+ } else {
127
+ form.input(field.path, input);
128
+ }
129
+
130
+ form.touch(field.path);
131
+ if (form.getFieldState(field.path).valid) {
132
+ if (!containsPath(visited, field.path))
133
+ visited.push(copyPath(field.path));
134
+ history.push(copyPath(field.path));
135
+ currentPath = null;
136
+ } else {
137
+ currentPath = copyPath(field.path);
138
+ }
139
+
140
+ return getView();
141
+ }
142
+
143
+ function back() {
144
+ inputError = null;
145
+ const { leaves, editableFields, structuralErrors } = currentFlowFields();
146
+
147
+ while (history.length > 0) {
148
+ const previousPath = history.pop();
149
+ if (previousPath === undefined) break;
150
+ if (editableFields.some(({ path }) => pathsEqual(path, previousPath))) {
151
+ currentPath = copyPath(previousPath);
152
+ break;
153
+ }
154
+ }
155
+
156
+ return viewFor(leaves, editableFields, structuralErrors);
157
+ }
158
+
159
+ return { getView, answer, back };
160
+ }
161
+
162
+ /**
163
+ * @param {import("@kayr/umbika-core").ActiveFieldNode[]} nodes
164
+ * @returns {import("@kayr/umbika-core").ActiveField[]}
165
+ */
166
+ function flattenActiveFields(nodes) {
167
+ return nodes.flatMap((node) => {
168
+ switch (node.type) {
169
+ case "object":
170
+ return flattenActiveFields(node.children);
171
+ case "table":
172
+ return node.rows.flatMap((row) => flattenActiveFields(row.children));
173
+ default:
174
+ return [node];
175
+ }
176
+ });
177
+ }
178
+
179
+ /**
180
+ * Collect visible object and table errors in depth-first schema and row order.
181
+ * @param {import("@kayr/umbika-core").ActiveFieldNode[]} nodes
182
+ * @returns {import("@kayr/umbika-core").ValidationError[]}
183
+ */
184
+ function collectStructuralErrors(nodes) {
185
+ const errors = [];
186
+ for (const node of nodes) {
187
+ if (node.type === "object") {
188
+ errors.push(...node.errors);
189
+ errors.push(...collectStructuralErrors(node.children));
190
+ continue;
191
+ }
192
+ if (node.type !== "table") continue;
193
+ errors.push(...node.errors);
194
+ for (const row of node.rows) {
195
+ errors.push(...collectStructuralErrors(row.children));
196
+ }
197
+ }
198
+ return errors;
199
+ }
200
+
201
+ /**
202
+ * @param {import("@kayr/umbika-core").Form} form
203
+ * @param {import("@kayr/umbika-core").ActiveField[]} leaves
204
+ * @param {import("./types.js").EditableActiveField[]} editableFields
205
+ * @param {readonly import("@kayr/umbika-core").FieldPath[]} visited
206
+ * @param {import("@kayr/umbika-core").ValidationError[]} structuralErrors
207
+ * @returns {import("./types.js").ReviewView}
208
+ */
209
+ function reviewView(form, leaves, editableFields, visited, structuralErrors) {
210
+ return {
211
+ kind: "review",
212
+ finished: true,
213
+ ready:
214
+ editableFields.every(({ path }) => containsPath(visited, path)) &&
215
+ form.isValid(),
216
+ answers: leaves.map((field) => {
217
+ const value = field.value;
218
+ return {
219
+ id: field.id,
220
+ path: copyPath(field.path),
221
+ label: field.label,
222
+ value,
223
+ displayValue: displayValue(field, value),
224
+ readOnly: !isEditableField(field),
225
+ errors: copyErrors(field.errors),
226
+ };
227
+ }),
228
+ structuralErrors: copyErrors(structuralErrors),
229
+ };
230
+ }
231
+
232
+ /** @param {readonly import("@kayr/umbika-core").ValidationError[]} errors */
233
+ function copyErrors(errors) {
234
+ return errors.map((error) => ({ ...error, path: copyPath(error.path) }));
235
+ }
236
+
237
+ /**
238
+ * @param {readonly import("@kayr/umbika-core").FieldPath[]} paths
239
+ * @param {import("@kayr/umbika-core").FieldPath} target
240
+ */
241
+ function containsPath(paths, target) {
242
+ return paths.some((path) => pathsEqual(path, target));
243
+ }
244
+
245
+ /**
246
+ * @param {import("@kayr/umbika-core").FieldPath} left
247
+ * @param {import("@kayr/umbika-core").FieldPath | null} right
248
+ */
249
+ function pathsEqual(left, right) {
250
+ return (
251
+ right !== null &&
252
+ left.length === right.length &&
253
+ left.every((segment, index) => segment === right[index])
254
+ );
255
+ }
256
+
257
+ /** @param {import("@kayr/umbika-core").FieldPath} path */
258
+ function copyPath(path) {
259
+ return /** @type {import("@kayr/umbika-core").FieldPath} */ ([...path]);
260
+ }
261
+
262
+ /**
263
+ * @param {import("@kayr/umbika-core").ActiveField} field
264
+ * @param {unknown} value
265
+ */
266
+ function displayValue(field, value) {
267
+ if (value === undefined || value === null || value === "") return "—";
268
+ if (field.type === "multi-select") {
269
+ if (Array.isArray(value) && value.length === 0) return "—";
270
+ if (Array.isArray(value)) {
271
+ return value
272
+ .map(
273
+ (selectedValue) =>
274
+ field.options.find((option) => option.value === selectedValue)
275
+ ?.label ?? `${String(selectedValue)} (unavailable)`,
276
+ )
277
+ .join(", ");
278
+ }
279
+ }
280
+ if (field.type === "select") {
281
+ return (
282
+ field.options.find((option) => option.value === value)?.label ??
283
+ `${String(value)} (unavailable)`
284
+ );
285
+ }
286
+ return String(value);
287
+ }
288
+
289
+ /** @param {import('./types.js').EditableActiveField} field */
290
+ function unavailableSelections(field) {
291
+ if (field.type !== "select" && field.type !== "multi-select") return [];
292
+ const selected = field.type === "multi-select" ? field.value : [field.value];
293
+ if (!Array.isArray(selected)) return [];
294
+ return selected.filter(
295
+ (value) =>
296
+ typeof value === "string" &&
297
+ value !== "" &&
298
+ !field.options.some((option) => option.value === value),
299
+ );
300
+ }
301
+
302
+ /**
303
+ * Translate renderer-owned positional input into one ordered engine value.
304
+ *
305
+ * @param {string} input
306
+ * @param {readonly import("@kayr/umbika-core").SelectOption[]} options
307
+ * @returns {string[] | null}
308
+ */
309
+ function parseMultiSelect(input, options) {
310
+ if (input.trim() === "") return [];
311
+
312
+ const keys = input.split(",").map((key) => key.trim());
313
+ const seen = new Set();
314
+ const values = [];
315
+
316
+ for (const key of keys) {
317
+ const option = options[Number(key) - 1];
318
+ const canonicalKey = option
319
+ ? String(options.indexOf(option) + 1)
320
+ : undefined;
321
+ if (!option || key !== canonicalKey || seen.has(key)) return null;
322
+ seen.add(key);
323
+ values.push(option.value);
324
+ }
325
+
326
+ return values;
327
+ }
328
+
329
+ /** @param {number} optionCount */
330
+ function multiSelectGuidance(optionCount) {
331
+ return `Choose unique keys from 1 to ${optionCount}, separated by commas, or leave blank.`;
332
+ }
package/src/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./console.js";
2
+ export * from "./flow.js";
3
+ export * from "./types.js";
package/src/types.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @typedef {object} OptionView
3
+ * @property {string} key One-based input key.
4
+ * @property {string} value Stored option value.
5
+ * @property {string} label Human-readable option label.
6
+ */
7
+
8
+ /** @typedef {import("@kayr/umbika-core").ActiveTextField | import("@kayr/umbika-core").ActiveSelectField | import("@kayr/umbika-core").ActiveMultiSelectField} EditableActiveField */
9
+
10
+ /**
11
+ * @typedef {object} QuestionView
12
+ * @property {"question"} kind
13
+ * @property {false} finished
14
+ * @property {false} ready
15
+ * @property {number} position One-based question position.
16
+ * @property {number} total
17
+ * @property {string} id Field declaration identity.
18
+ * @property {import("@kayr/umbika-core").FieldPath} path Concrete answer path.
19
+ * @property {string} label
20
+ * @property {"text" | "select" | "multi-select"} type
21
+ * @property {unknown} value
22
+ * @property {import("@kayr/umbika-core").ValidationError[]} errors
23
+ * @property {string | null} inputError Renderer-owned input guidance.
24
+ * @property {OptionView[]} options
25
+ * @property {string[]} unavailableSelections Stored selections absent from current choices.
26
+ */
27
+
28
+ /**
29
+ * @typedef {object} ReviewAnswer
30
+ * @property {string} id Field declaration identity.
31
+ * @property {import("@kayr/umbika-core").FieldPath} path Concrete answer path.
32
+ * @property {string} label
33
+ * @property {unknown} value
34
+ * @property {string} displayValue
35
+ * @property {boolean} readOnly Whether the value is calculated or currently locked.
36
+ * @property {import("@kayr/umbika-core").ValidationError[]} errors Visible field errors.
37
+ */
38
+
39
+ /**
40
+ * @typedef {object} ReviewView
41
+ * @property {"review"} kind
42
+ * @property {true} finished
43
+ * @property {boolean} ready
44
+ * @property {ReviewAnswer[]} answers
45
+ * @property {import("@kayr/umbika-core").ValidationError[]} structuralErrors Visible errors owned by objects and tables.
46
+ */
47
+
48
+ /** @typedef {QuestionView | ReviewView} FlowView */
49
+
50
+ /**
51
+ * @typedef {object} Flow
52
+ * @property {() => FlowView} getView
53
+ * @property {(input: string) => FlowView} answer
54
+ * @property {() => FlowView} back
55
+ */
56
+
57
+ /**
58
+ * @typedef {object} ConsoleIO
59
+ * @property {() => Promise<string | null>} readLine Read a line, or return null at end of input.
60
+ * @property {(text: string) => void} write Write console output.
61
+ */
62
+
63
+ /**
64
+ * @typedef {object} ConsoleRunResult
65
+ * @property {"completed" | "quit" | "input-ended"} status
66
+ * @property {boolean} ready
67
+ */
68
+
69
+ export {};