@rocapine/react-native-onboarding 1.74.1 → 1.75.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.
Files changed (50) hide show
  1. package/dist/evaluateCondition.d.ts.map +1 -1
  2. package/dist/evaluateCondition.js +103 -4
  3. package/dist/evaluateCondition.js.map +1 -1
  4. package/dist/index.d.ts +6 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +25 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/onboarding-example.d.ts +235 -99
  9. package/dist/onboarding-example.d.ts.map +1 -1
  10. package/dist/onboarding-example.js +77 -0
  11. package/dist/onboarding-example.js.map +1 -1
  12. package/dist/screens/completingActions.d.ts +43 -0
  13. package/dist/screens/completingActions.d.ts.map +1 -0
  14. package/dist/screens/completingActions.js +108 -0
  15. package/dist/screens/completingActions.js.map +1 -0
  16. package/dist/screens/elementTypeRegistry.d.ts +31 -0
  17. package/dist/screens/elementTypeRegistry.d.ts.map +1 -0
  18. package/dist/screens/elementTypeRegistry.js +82 -0
  19. package/dist/screens/elementTypeRegistry.js.map +1 -0
  20. package/dist/screens/resolveRenderableStep.d.ts +42 -0
  21. package/dist/screens/resolveRenderableStep.d.ts.map +1 -0
  22. package/dist/screens/resolveRenderableStep.js +28 -0
  23. package/dist/screens/resolveRenderableStep.js.map +1 -0
  24. package/dist/screens/unknownElementTypes.d.ts +94 -0
  25. package/dist/screens/unknownElementTypes.d.ts.map +1 -0
  26. package/dist/screens/unknownElementTypes.js +141 -0
  27. package/dist/screens/unknownElementTypes.js.map +1 -0
  28. package/dist/screens/unknownKeys.d.ts +5 -2
  29. package/dist/screens/unknownKeys.d.ts.map +1 -1
  30. package/dist/screens/unknownKeys.js +7 -52
  31. package/dist/screens/unknownKeys.js.map +1 -1
  32. package/dist/steps/common.types.d.ts +84 -3
  33. package/dist/steps/common.types.d.ts.map +1 -1
  34. package/dist/steps/common.types.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/__tests__/completingActions.test.ts +139 -0
  37. package/src/__tests__/elementTypeRegistry.test.ts +48 -0
  38. package/src/__tests__/evaluateCondition.test.ts +228 -3
  39. package/src/__tests__/onboardingExampleElements.test.ts +27 -0
  40. package/src/__tests__/resolveRenderableStep.test.ts +117 -0
  41. package/src/__tests__/unknownElementTypes.test.ts +240 -0
  42. package/src/evaluateCondition.ts +107 -4
  43. package/src/index.ts +23 -0
  44. package/src/onboarding-example.ts +78 -0
  45. package/src/screens/completingActions.ts +108 -0
  46. package/src/screens/elementTypeRegistry.ts +88 -0
  47. package/src/screens/resolveRenderableStep.ts +59 -0
  48. package/src/screens/unknownElementTypes.ts +204 -0
  49. package/src/screens/unknownKeys.ts +7 -50
  50. package/src/steps/common.types.ts +84 -3
@@ -0,0 +1,240 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ KNOWN_ELEMENT_TYPES,
4
+ collectUnknownElementTypes,
5
+ collectUnknownElementTypesInSteps,
6
+ dropUnknownElementTypes,
7
+ dropUnknownElementTypesInStep,
8
+ formatUnknownElementTypes,
9
+ } from "../screens/unknownElementTypes";
10
+ import { ScreenElementsSchema } from "../screens/types";
11
+ import { ComposableScreenStepTypeSchema } from "../steps/ComposableScreen/types";
12
+
13
+ /**
14
+ * Forward compatibility for element TYPES (#209).
15
+ *
16
+ * `UIElementSchema` is a discriminated union of the types this SDK build knows.
17
+ * Before this, one element type published after an app shipped made the WHOLE
18
+ * screen fail to parse — and the ComposableScreen renderer's `.parse` threw
19
+ * inside its error boundary, whose fallback has no interactive control, so on a
20
+ * step with `displayProgressHeader: false` the user had no way forward OR back.
21
+ *
22
+ * The contract asserted here: an unrecognized element type is OMITTED (matching
23
+ * `renderElement`'s terminal `return null` and `buildAnimation`'s unknown-preset
24
+ * no-op), the rest of the screen renders, and a genuine data error on a KNOWN
25
+ * type still fails loudly.
26
+ */
27
+
28
+ const text = (id: string, content: string) => ({ id, type: "Text", props: { content } });
29
+ const stack = (id: string, children: unknown[]) => ({ id, type: "YStack", props: {}, children });
30
+ const unknown = (id: string, type = "HolographicCard") => ({ id, type, props: { magic: true } });
31
+
32
+ const step = (elements: unknown[]) => ({
33
+ id: "step-1",
34
+ name: "Step one",
35
+ type: "ComposableScreen",
36
+ displayProgressHeader: false,
37
+ payload: { elements },
38
+ });
39
+
40
+ describe("dropUnknownElementTypes", () => {
41
+ it("keeps the rest of the screen when a top-level element type is unknown", () => {
42
+ const parsed = ScreenElementsSchema.safeParse(
43
+ dropUnknownElementTypes([text("a", "before"), unknown("x"), text("b", "after")])
44
+ );
45
+ expect(parsed.success).toBe(true);
46
+ if (!parsed.success) return;
47
+ expect(parsed.data.map((e) => e.id)).toEqual(["a", "b"]);
48
+ });
49
+
50
+ it("keeps a container's known children when one child type is unknown", () => {
51
+ const parsed = ScreenElementsSchema.safeParse(
52
+ dropUnknownElementTypes([stack("root", [text("a", "hi"), unknown("x")])])
53
+ );
54
+ expect(parsed.success).toBe(true);
55
+ if (!parsed.success) return;
56
+ const [root] = parsed.data;
57
+ expect(root.type).toBe("YStack");
58
+ expect("children" in root ? root.children.map((c) => c.id) : []).toEqual(["a"]);
59
+ });
60
+
61
+ it("drops the whole subtree of an unknown element, never hoisting its children", () => {
62
+ // Matches the render half: `renderElement` returns null for an unrecognized
63
+ // type, so its children never render either. Hoisting them would invent a
64
+ // layout the author never wrote.
65
+ const parsed = ScreenElementsSchema.safeParse(
66
+ dropUnknownElementTypes([{ ...unknown("x"), children: [text("inner", "hidden")] }])
67
+ );
68
+ expect(parsed.success).toBe(true);
69
+ if (!parsed.success) return;
70
+ expect(parsed.data).toEqual([]);
71
+ });
72
+
73
+ it("drops an unknown type nested in a RichText's Text-only children", () => {
74
+ const parsed = ScreenElementsSchema.safeParse(
75
+ dropUnknownElementTypes([
76
+ { id: "rt", type: "RichText", props: {}, children: [text("w", "word"), unknown("x")] },
77
+ ])
78
+ );
79
+ expect(parsed.success).toBe(true);
80
+ });
81
+
82
+ it("still fails loudly on a bad prop of a KNOWN element type", () => {
83
+ // The forward-compat escape must not become a silence-everything escape:
84
+ // `variant: "plain"` is a CMS data bug the author has to fix.
85
+ const bad = { id: "b", type: "Button", props: { label: "Go", variant: "plain" } };
86
+ const parsed = ScreenElementsSchema.safeParse(dropUnknownElementTypes([bad]));
87
+ expect(parsed.success).toBe(false);
88
+ if (parsed.success) return;
89
+ expect(parsed.error.issues.some((i) => i.path.join(".").endsWith("props.variant"))).toBe(true);
90
+ });
91
+
92
+ it("still fails loudly on a KNOWN element type missing its `id`", () => {
93
+ const parsed = ScreenElementsSchema.safeParse(
94
+ dropUnknownElementTypes([{ type: "Text", props: { content: "x" } }])
95
+ );
96
+ expect(parsed.success).toBe(false);
97
+ });
98
+
99
+ it("leaves an element with no `type` for the parser to report", () => {
100
+ // A missing/non-string discriminator is a malformed payload, not a newer
101
+ // element — dropping it would hide the real error.
102
+ const parsed = ScreenElementsSchema.safeParse(dropUnknownElementTypes([{ id: "a", props: {} }]));
103
+ expect(parsed.success).toBe(false);
104
+ });
105
+
106
+ it("returns the input unchanged when it is not an array", () => {
107
+ expect(dropUnknownElementTypes(undefined)).toBeUndefined();
108
+ expect(dropUnknownElementTypes("nope")).toBe("nope");
109
+ });
110
+
111
+ it("does not mutate the payload it was given", () => {
112
+ const elements = [stack("root", [text("a", "hi"), unknown("x")])];
113
+ const before = JSON.stringify(elements);
114
+ dropUnknownElementTypes(elements);
115
+ expect(JSON.stringify(elements)).toBe(before);
116
+ });
117
+
118
+ it("keeps every element when the type registry cannot be built", () => {
119
+ // The registry is derived from zod's internals, so a future zod release can
120
+ // break it. It must degrade to "everything is known" (parse as today), never
121
+ // to "nothing is known" — which would blank every screen in every app.
122
+ const elements = [text("a", "hi"), unknown("x")];
123
+ expect(dropUnknownElementTypes(elements, new Set<string>())).toBe(elements);
124
+ });
125
+
126
+ it("returns the same array reference when nothing is unknown", () => {
127
+ // Structural sharing: the strip runs on every screen render, so a clean
128
+ // payload must not be cloned (and must stay `useMemo`-stable).
129
+ const elements = [stack("root", [text("a", "hi")])];
130
+ expect(dropUnknownElementTypes(elements)).toBe(elements);
131
+ });
132
+ });
133
+
134
+ describe("dropUnknownElementTypesInStep", () => {
135
+ it("makes the ComposableScreen step parse instead of throwing", () => {
136
+ // The exact call at ComposableScreen/Renderer.tsx: `.parse(step)`.
137
+ expect(() => ComposableScreenStepTypeSchema.parse(step([unknown("x")]))).toThrow();
138
+ const parsed = ComposableScreenStepTypeSchema.parse(
139
+ dropUnknownElementTypesInStep(step([text("a", "hi"), unknown("x")]))
140
+ );
141
+ expect(parsed.payload.elements.map((e) => e.id)).toEqual(["a"]);
142
+ });
143
+
144
+ it("passes a step through untouched when it carries no element payload", () => {
145
+ const ratings = { id: "r", type: "Ratings", payload: { title: "x" } };
146
+ expect(dropUnknownElementTypesInStep(ratings)).toBe(ratings);
147
+ });
148
+
149
+ it("returns the same step reference when every element type is known", () => {
150
+ const clean = step([text("a", "hi")]);
151
+ expect(dropUnknownElementTypesInStep(clean)).toBe(clean);
152
+ });
153
+ });
154
+
155
+ describe("collectUnknownElementTypes", () => {
156
+ it("reports the path, id and type of each unknown element", () => {
157
+ const found = collectUnknownElementTypes([
158
+ text("a", "hi"),
159
+ unknown("x", "HolographicCard"),
160
+ stack("root", [unknown("y", "TimeOfDayPicker")]),
161
+ ]);
162
+ expect(found).toEqual([
163
+ { path: "elements[1]", elementId: "x", elementType: "HolographicCard" },
164
+ { path: "elements[2].children[0]", elementId: "y", elementType: "TimeOfDayPicker" },
165
+ ]);
166
+ });
167
+
168
+ it("reports an unknown parent once, not its dropped descendants", () => {
169
+ const found = collectUnknownElementTypes([
170
+ { ...unknown("x"), children: [unknown("y", "AlsoUnknown")] },
171
+ ]);
172
+ expect(found).toHaveLength(1);
173
+ expect(found[0].elementId).toBe("x");
174
+ });
175
+
176
+ it("says nothing about a tree of known types", () => {
177
+ expect(collectUnknownElementTypes([stack("root", [text("a", "hi")])])).toEqual([]);
178
+ });
179
+
180
+ it("walks every step carrying an element payload", () => {
181
+ const found = collectUnknownElementTypesInSteps([
182
+ { id: "s1", type: "Ratings", payload: {} },
183
+ step([unknown("x")]),
184
+ ]);
185
+ expect(found).toHaveLength(1);
186
+ expect(found[0].path).toContain("step-1");
187
+ });
188
+ });
189
+
190
+ describe("formatUnknownElementTypes", () => {
191
+ it("says nothing when there is nothing to say", () => {
192
+ expect(formatUnknownElementTypes([])).toBe("");
193
+ });
194
+
195
+ it("names the type, the path and the omit contract", () => {
196
+ const report = formatUnknownElementTypes(
197
+ collectUnknownElementTypes([unknown("x", "HolographicCard")])
198
+ );
199
+ expect(report).toContain("HolographicCard");
200
+ expect(report).toContain("elements[0]");
201
+ expect(report).toMatch(/omitted/i);
202
+ expect(report).toMatch(/upgrade|newer|version/i);
203
+ });
204
+ });
205
+
206
+ describe("KNOWN_ELEMENT_TYPES", () => {
207
+ it("is derived from the schema, so it cannot drift as elements are added", () => {
208
+ // Every variant of the discriminated union, and nothing else.
209
+ expect(KNOWN_ELEMENT_TYPES).toContain("YStack");
210
+ expect(KNOWN_ELEMENT_TYPES).toContain("Slider");
211
+ expect(KNOWN_ELEMENT_TYPES).not.toContain("HolographicCard");
212
+ // No known type may be rejected on its own discriminator. Other issues are
213
+ // expected and fine: `props: {}` is incomplete for most variants.
214
+ const rejectedOnDiscriminator = KNOWN_ELEMENT_TYPES.filter((type) => {
215
+ const parsed = ScreenElementsSchema.safeParse([{ id: "a", type, props: {} }]);
216
+ return (
217
+ !parsed.success && parsed.error.issues.some((i) => i.path.join(".") === "0.type")
218
+ );
219
+ });
220
+ expect(rejectedOnDiscriminator).toEqual([]);
221
+ });
222
+
223
+ it("is sorted and free of duplicates, so it is usable as a capability list", () => {
224
+ expect([...KNOWN_ELEMENT_TYPES]).toEqual([...new Set(KNOWN_ELEMENT_TYPES)].sort());
225
+ });
226
+ });
227
+
228
+ describe("no backtracking is reintroduced", () => {
229
+ it("strips a deep tree and still fails fast on a pathological payload", () => {
230
+ // Canary for the discriminated union (screens/types.ts:296-348): a plain
231
+ // union of these recursive variants exhausted a 512 MB heap on a real
232
+ // 52-node paywall. The strip must stay a linear walk in front of it.
233
+ const nest = (depth: number, leaf: unknown): unknown =>
234
+ depth === 0 ? leaf : { name: "c", type: "YStack", props: {}, children: [nest(depth - 1, leaf)] };
235
+ const started = Date.now();
236
+ const parsed = ScreenElementsSchema.safeParse(dropUnknownElementTypes([nest(10, text("l", "x"))]));
237
+ expect(parsed.success).toBe(false);
238
+ expect(Date.now() - started).toBeLessThan(2000);
239
+ });
240
+ });
@@ -42,9 +42,112 @@ function isEmpty(v: unknown): boolean {
42
42
  return false;
43
43
  }
44
44
 
45
+ // A condition's right-hand side may reference other variables with `{{name}}`,
46
+ // which is what lets a condition compare two variables instead of a variable
47
+ // against an authored literal. `RepeatElement` documents exactly this shape to
48
+ // make `Repeat` subsume a `Match` — `{ variable: "item.sign", operator: "eq",
49
+ // value: "{{zodiacSign}}" }` — and without interpolation here that comparison
50
+ // tests against the 14-character literal and never matches.
51
+ //
52
+ // References resolve to the variable's raw value stringified, matching
53
+ // `Image mode:"expression"` (machine identifiers, not display labels); the map
54
+ // reaching this function is already flat primitives. An unknown reference
55
+ // resolves to the empty string rather than throwing, so a gate on a variable
56
+ // that has not been written yet simply does not match.
57
+ const REF = /\{\{([^}]+?)\}\}/g;
58
+
59
+ function interpolateRefs(value: unknown, variables: Record<string, unknown>): unknown {
60
+ if (Array.isArray(value)) return value.map((v) => interpolateRefs(v, variables));
61
+ if (typeof value !== "string" || !value.includes("{{")) return value;
62
+ return value.replace(REF, (_, key: string) => {
63
+ const resolved = variables[key.trim()];
64
+ return resolved === undefined || resolved === null ? "" : String(resolved);
65
+ });
66
+ }
67
+
68
+ // "No member" vs "a member that is empty". An unresolved `{{ref}}` interpolates
69
+ // to the empty string (`interpolateRefs`), and it reaches the comparison in both
70
+ // right-hand-side shapes identically — bare, or as the single member of the array
71
+ // Studio's condition editor emits. Keeping it as a member would make an
72
+ // empty-string variable a member of a list nobody has written (`in` matches,
73
+ // `not_in` does not — the opposite of the same gate written bare), and an
74
+ // empty-string variable is reachable: `InputElement` stores "" on clear and
75
+ // `Input.defaultValue: ""` is overlaid into the variable map. Nothing authorable
76
+ // is lost — Studio's value field drops empty members (`filter(Boolean)`), and
77
+ // `is_empty` is the operator for "the variable is blank".
78
+ function isAbsentMember(member: unknown): boolean {
79
+ return isNullish(member) || member === "";
80
+ }
81
+
82
+ // The membership operators (`in` / `not_in`, and `contains` against an array
83
+ // variable) need a real list and used to answer a CONSTANT without one —
84
+ // `in` false for every row, `not_in` true for every row, no warning (#225).
85
+ //
86
+ // Two right-hand-side shapes reach them without being `Array.isArray`, and both
87
+ // are the natural way to author a membership test now that a `{{ref}}` on the
88
+ // right-hand side resolves (#217):
89
+ //
90
+ // value: "{{selected}}" a reference to a multi-select variable, whose flat
91
+ // value is a JSON-encoded string ('["a","b"]' — see
92
+ // `decodeArrayValue`), so the ref interpolates to a
93
+ // string and `Array.isArray` is false.
94
+ // value: ["{{selected}}"] what Studio's condition editor emits: it splits the
95
+ // value field on commas, so the reference lands as
96
+ // the single member of a one-member array. That one
97
+ // IS an array, and used to reach the comparison as a
98
+ // list holding one JSON string — equally constant.
99
+ //
100
+ // So a member list is built by decoding the value itself AND each of its
101
+ // members, flattening one level. Only one level: nothing authorable nests
102
+ // deeper, and a deep flatten would silently merge a shape nobody wrote.
103
+ //
104
+ // `value: []` keeps its documented constants (`in` false / `not_in` true) — an
105
+ // empty Studio value field yields it, and an empty list legitimately has no
106
+ // members. So does a reference that resolves to nothing: an unresolved `{{ref}}`
107
+ // interpolates to the empty string (see `interpolateRefs`), and "not written
108
+ // yet" means "no members", not "a member that is the empty string".
109
+ //
110
+ // Anything else scalar (`in` against `"male"`) is an authoring mistake with no
111
+ // correct answer. It reads as a ONE-member list — the only reading that is not a
112
+ // silent constant, and what `in: "male"` plainly means — and warns, because the
113
+ // evaluator returns `boolean` and `renderWhen` has no third state, so a warning
114
+ // is the loudest a runtime can be. No Studio-authored payload can produce this
115
+ // shape (its editor always emits an array), so nothing that evaluates correctly
116
+ // today changes.
117
+ function toMemberList(value: unknown, operator: string): unknown[] {
118
+ const decoded = decodeArrayValue(value);
119
+ if (Array.isArray(decoded)) {
120
+ return decoded
121
+ .flatMap((member) => {
122
+ const inner = decodeArrayValue(member);
123
+ return Array.isArray(inner) ? inner : [inner];
124
+ })
125
+ .filter((member) => !isAbsentMember(member));
126
+ }
127
+ if (isAbsentMember(decoded)) return [];
128
+ console.warn(
129
+ `[onboarding] condition operator "${operator}" needs a list on its right-hand side, ` +
130
+ `got ${typeof decoded} ${JSON.stringify(decoded)}. Treating it as a single-member list. ` +
131
+ `Author an array (or a {{ref}} to a multi-select variable) instead.`
132
+ );
133
+ return [decoded];
134
+ }
135
+
136
+ // Members compare stringified. A decoded JSON array keeps its members typed, and
137
+ // `Repeat` keeps a numeric row field numeric on purpose (`repeatScope.buildRowFlat`,
138
+ // so `gt` compares numerically), so `1` and `"1"` have to be the same member —
139
+ // otherwise `not_in(1, [1, 2])` is true. Shared with the `contains` array branch,
140
+ // which coerced neither side, so the two operators would otherwise disagree about
141
+ // the same data.
142
+ function includesMember(members: unknown[], target: unknown): boolean {
143
+ const needle = String(target);
144
+ return members.some((member) => String(member) === needle);
145
+ }
146
+
45
147
  export function evaluateLeaf(condition: LeafCondition, variables: Record<string, unknown>): boolean {
46
148
  const raw = decodeArrayValue(variables[condition.variable]);
47
- const { operator, value } = condition;
149
+ const { operator } = condition;
150
+ const value = interpolateRefs(condition.value, variables) as typeof condition.value;
48
151
 
49
152
  switch (operator) {
50
153
  case "eq":
@@ -61,12 +164,12 @@ export function evaluateLeaf(condition: LeafCondition, variables: Record<string,
61
164
  return coerceToNumber(raw) <= coerceToNumber(value);
62
165
  case "contains":
63
166
  return Array.isArray(raw)
64
- ? raw.includes(value)
167
+ ? includesMember(raw, value)
65
168
  : String(raw).includes(String(value));
66
169
  case "in":
67
- return Array.isArray(value) ? value.includes(String(raw)) : false;
170
+ return includesMember(toMemberList(value, operator), raw);
68
171
  case "not_in":
69
- return Array.isArray(value) ? !value.includes(String(raw)) : true;
172
+ return !includesMember(toMemberList(value, operator), raw);
70
173
  case "is_empty":
71
174
  return isEmpty(raw);
72
175
  case "is_not_empty":
package/src/index.ts CHANGED
@@ -102,6 +102,29 @@ export {
102
102
  formatUnknownElementKeys,
103
103
  } from "./screens/unknownKeys";
104
104
  export type { UnknownElementKey } from "./screens/unknownKeys";
105
+ // Forward compatibility for element TYPES (#209): an element type published
106
+ // after this app shipped is OMITTED rather than failing the whole screen.
107
+ // `KNOWN_ELEMENT_TYPES` is the capability list of what this build can render.
108
+ export {
109
+ KNOWN_ELEMENT_TYPES,
110
+ dropUnknownElementTypes,
111
+ dropUnknownElementTypesInStep,
112
+ collectUnknownElementTypes,
113
+ collectUnknownElementTypesInSteps,
114
+ formatUnknownElementTypes,
115
+ } from "./screens/unknownElementTypes";
116
+ export type { UnknownElementType } from "./screens/unknownElementTypes";
117
+ // The whole render-boundary decision in one pure call: what to parse, what to
118
+ // log, and whether the renderer must supply its own way off the screen — a
119
+ // ComposableScreen authors its CTA INSIDE the element tree, so a strip can take
120
+ // it and leave a screen nobody can leave. `deriveElementTypeNames` is how a
121
+ // rendering package keys the strip on ITS OWN element union instead of this
122
+ // one's: what draws has to decide what is kept, and the two packages' installed
123
+ // versions can differ.
124
+ export { resolveRenderableStep } from "./screens/resolveRenderableStep";
125
+ export type { RenderableStep } from "./screens/resolveRenderableStep";
126
+ export { hasCompletingAction } from "./screens/completingActions";
127
+ export { deriveElementTypeNames } from "./screens/elementTypeRegistry";
105
128
  // Hooks and providers
106
129
  export * from "./infra";
107
130
  // Navigation adapter (dependency-injected navigation)
@@ -782,6 +782,84 @@ export const onboardingExample = {
782
782
  marginVertical: 4,
783
783
  },
784
784
  },
785
+ // Expression stdlib demo. Every function runs at PRESS time (the
786
+ // engine's only call site is a `setVariable` action), so a
787
+ // computed date or an assembled sentence is written into a
788
+ // variable here and then plainly interpolated by the Texts below.
789
+ {
790
+ id: "stdlib-compute",
791
+ type: "Button",
792
+ props: {
793
+ label: "Compute my plan",
794
+ variant: "outlined",
795
+ marginVertical: 8,
796
+ actions: [
797
+ {
798
+ type: "setVariable",
799
+ name: "goalDate",
800
+ // `"now"` is the same sentinel DatePicker accepts, and the
801
+ // format spec is the DatePicker `format` prop vocabulary.
802
+ value: 'format(addDays("now", 90), "medium")',
803
+ valueMode: "expression",
804
+ },
805
+ {
806
+ type: "setVariable",
807
+ name: "goalSentence",
808
+ // Grammatical listing over the CheckboxGroup member labels.
809
+ value: "list({{goals}})",
810
+ valueMode: "expression",
811
+ },
812
+ {
813
+ type: "setVariable",
814
+ name: "goalCount",
815
+ value: 'count({{goals}}) + " " + plural(count({{goals}}), "goal", "goals")',
816
+ valueMode: "expression",
817
+ },
818
+ {
819
+ type: "setVariable",
820
+ name: "weeklyPace",
821
+ // Rounds to nearest — not trunc — and holds the result
822
+ // inside an inclusive range. Over the slider's
823
+ // 0..1 / step-0.1 grid the reachable outputs are
824
+ // 1,1,1,1,2,2,2,3,3,3,3 — a 4/3/4 split, the most even
825
+ // available for eleven positions across three values, so
826
+ // no stretch of the slider is inert.
827
+ //
828
+ // The multiplier is chosen so the RAW value overshoots
829
+ // the bounds a little and not a lot: raw runs
830
+ // 0,0,1,1,2,2,2,3,3,4,4, so `clamp` is OBSERVABLE at both
831
+ // ends (0 -> 1 twice, 4 -> 3 twice). That is the whole
832
+ // constraint — an expression whose raw range already sits
833
+ // inside 1..3, like `round(1 + {{intensity}} * 2)`, makes
834
+ // clamp change no value at all and demonstrates an inert
835
+ // function; one that overshoots hard, like `* 5`, returns
836
+ // 3 at six of the eleven positions and leaves the upper
837
+ // half of the slider dead.
838
+ //
839
+ // What this shape does not cover: no reachable position
840
+ // lands on an exact .5 tie, so round-half-up is pinned in
841
+ // `expression.test.ts` rather than here. A trunc
842
+ // regression is still caught at 0.4 (1.6 -> 2, not 1) and
843
+ // 0.7 (2.8 -> 3, not 2).
844
+ value: "clamp(round({{intensity}} * 4), 1, 3)",
845
+ valueMode: "expression",
846
+ },
847
+ ],
848
+ },
849
+ },
850
+ {
851
+ id: "stdlib-display",
852
+ type: "Text",
853
+ props: {
854
+ content:
855
+ "{{goalCount}}: {{goalSentence}} — by {{goalDate}}, {{weeklyPace}}x / week",
856
+ mode: "expression",
857
+ fontSize: 14,
858
+ textAlign: "center",
859
+ opacity: 0.6,
860
+ marginVertical: 4,
861
+ },
862
+ },
785
863
  {
786
864
  id: "hero-date-picker",
787
865
  type: "DatePicker",
@@ -0,0 +1,108 @@
1
+ /**
2
+ * "Can the user still get off this screen?" — the guard the unknown-element
3
+ * strip needs (#209).
4
+ *
5
+ * A ComposableScreen's CTA is authored INSIDE the element tree.
6
+ * `ComposableScreenRenderer` passes no `button` to `OnboardingTemplate`, so
7
+ * `runActions` — reached only from something the user can press in that tree —
8
+ * is the single path to `onContinue`. Drop the element that happens to be the
9
+ * screen's root container and the payload still parses, to `elements: []`: a
10
+ * blank screen with no CTA, and on a `displayProgressHeader: false` step no back
11
+ * chevron either. Stripping would then have replaced a throw that at least
12
+ * reached `componentDidCatch` with a silent dead end, which is worse.
13
+ *
14
+ * So the renderer asks this before it renders a stripped tree, and supplies its
15
+ * own escape when the answer is no — the same choice the two existing
16
+ * boundaries make: an unknown *step* type renders a Continue button
17
+ * (`OnboardingPage`), and a paywall whose elements fail to parse calls
18
+ * `onContinue()` "so the user is not trapped" (`Pages/Paywall/Renderer`).
19
+ *
20
+ * WHAT COUNTS. `runActions` calls `onContinue` for exactly two actions —
21
+ * `"continue"` and `{type:"dismiss"}` — so those two, wherever a press can
22
+ * reach them, are the whole definition. Everything else (`setVariable`,
23
+ * `presentPaywall`, `custom`) leaves the user on the screen as far as this SDK
24
+ * can tell, and is not counted.
25
+ *
26
+ * The walk deliberately errs toward "no": an unrecognised action shape, or a
27
+ * `continue` somewhere the runtime would not actually run it, reads as no way
28
+ * forward. A redundant escape CTA on an already-degraded screen is a cosmetic
29
+ * cost; a missed one is the trap this exists to close.
30
+ *
31
+ * NOT CONSIDERED: `renderWhen`. A CTA the author gated behind a condition may
32
+ * be hidden at runtime, but that is authored intent evaluated against live
33
+ * variables, not something a static payload walk can or should second-guess.
34
+ */
35
+
36
+ const isRecord = (v: unknown): v is Record<string, unknown> =>
37
+ typeof v === "object" && v !== null && !Array.isArray(v);
38
+
39
+ /**
40
+ * Element types whose renderer owns its own press handling, so the generic
41
+ * `onPress` from `BaseBoxProps` is never wired for them.
42
+ *
43
+ * Mirrors `PRESS_HANDLED_TYPES` in `renderElement.tsx` — the UI package cannot
44
+ * be imported here, so the two lists are held equal by a source-level test in
45
+ * `packages/onboarding-ui/src/UI/Runtime/__tests__/unknownElementTypes.test.ts`.
46
+ * Counting an ignored `onPress` as a way forward would leave a user trapped on a
47
+ * screen whose only remaining "CTA" the runtime never dispatches.
48
+ */
49
+ const PRESS_HANDLED_TYPES: ReadonlySet<string> = new Set([
50
+ "Button",
51
+ "RadioGroup",
52
+ "CheckboxGroup",
53
+ "DatePicker",
54
+ "Input",
55
+ "WheelPicker",
56
+ "DrawingPad",
57
+ "Slider",
58
+ ]);
59
+
60
+ /**
61
+ * One action, or any action nested in one of its branch lists
62
+ * (`purchase.onSuccess`, `restore.onNothingToRestore`, …), completes the screen.
63
+ *
64
+ * Branch lists are found by shape rather than by name, so a branch added to
65
+ * `purchase`/`restore` later is covered without a change here.
66
+ */
67
+ const isCompletingAction = (action: unknown): boolean => {
68
+ // `ButtonActionSchema` declares continue as the string literal, not an
69
+ // object: `{type:"continue"}` is not an action the runtime runs.
70
+ if (action === "continue") return true;
71
+ if (!isRecord(action)) return false;
72
+ if (action.type === "dismiss") return true;
73
+ return Object.values(action).some(
74
+ (value) => Array.isArray(value) && value.some(isCompletingAction)
75
+ );
76
+ };
77
+
78
+ const nodeCanComplete = (node: unknown): boolean => {
79
+ if (!isRecord(node)) return false;
80
+ const props = isRecord(node.props) ? node.props : undefined;
81
+ if (props) {
82
+ if (props.actions != null) {
83
+ // `Button` reads `actions ?? (action === "continue" ? …)`, so a present
84
+ // `actions` shadows the deprecated shorthand — even when it is empty.
85
+ if (Array.isArray(props.actions) && props.actions.some(isCompletingAction)) return true;
86
+ } else if (props.action === "continue") {
87
+ return true;
88
+ }
89
+ if (
90
+ Array.isArray(props.onPress) &&
91
+ !PRESS_HANDLED_TYPES.has(String(node.type)) &&
92
+ props.onPress.some(isCompletingAction)
93
+ ) {
94
+ return true;
95
+ }
96
+ }
97
+ return Array.isArray(node.children) && node.children.some(nodeCanComplete);
98
+ };
99
+
100
+ /**
101
+ * Whether anything in this element tree can complete the screen.
102
+ *
103
+ * Pure, linear, and total: any malformed input (non-array, `null` nodes,
104
+ * non-record props) answers `false` rather than throwing, because it runs on a
105
+ * payload that has not been parsed yet.
106
+ */
107
+ export const hasCompletingAction = (elements: unknown): boolean =>
108
+ Array.isArray(elements) && elements.some(nodeCanComplete);