@developer_tribe/react-builder 1.2.44-test.2 → 1.2.44

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 (75) hide show
  1. package/dist/attributes-editor/Field.d.ts +1 -3
  2. package/dist/attributes-editor/attributesEditorModelTypes.d.ts +0 -3
  3. package/dist/attributes-editor/useAttributesEditorModel.d.ts +1 -1
  4. package/dist/build-components/FormSubmitButton/FormSubmitButtonProps.generated.d.ts +3 -8
  5. package/dist/build-components/OnboardButton/OnboardButtonProps.generated.d.ts +3 -8
  6. package/dist/build-components/OnboardProvider/OnboardProviderProps.generated.d.ts +0 -2
  7. package/dist/build-components/PaywallProvider/PaywallProviderProps.generated.d.ts +0 -2
  8. package/dist/build-components/SystemButton/SystemButtonProps.generated.d.ts +3 -8
  9. package/dist/build-components/SystemButton/usePlacementButtonEvents.d.ts +2 -15
  10. package/dist/build-components/index.d.ts +1 -3
  11. package/dist/build-components/patterns.generated.d.ts +1334 -2129
  12. package/dist/index.cjs.js +1 -1
  13. package/dist/index.cjs.js.map +1 -1
  14. package/dist/index.esm.js +1 -1
  15. package/dist/index.esm.js.map +1 -1
  16. package/dist/index.web.cjs.js +4 -4
  17. package/dist/index.web.cjs.js.map +1 -1
  18. package/dist/index.web.esm.js +3 -3
  19. package/dist/index.web.esm.js.map +1 -1
  20. package/dist/styles.css +1 -1
  21. package/dist/utils/nodeTree.d.ts +0 -18
  22. package/package.json +1 -1
  23. package/scripts/prebuild/utils/validateAllComponentsOrThrow.js +4 -68
  24. package/src/assets/meta.json +1 -1
  25. package/src/assets/prompt-scheme-onboard.generated.ts +1 -1
  26. package/src/assets/prompt-scheme-paywall.generated.ts +1 -1
  27. package/src/assets/samples/getSamples.ts +0 -2
  28. package/src/assets/samples/terms-and-privacy-no-form.json +1 -1
  29. package/src/assets/samples/terms-and-privacy.json +1 -1
  30. package/src/attributes-editor/AttributesEditorView.tsx +0 -3
  31. package/src/attributes-editor/Field.tsx +2 -91
  32. package/src/attributes-editor/attributesEditorModelTypes.ts +0 -3
  33. package/src/attributes-editor/useAttributesEditorModel.ts +0 -8
  34. package/src/build-components/FormCheckbox/FormCheckbox.tsx +1 -3
  35. package/src/build-components/FormSubmitButton/FormSubmitButton.tsx +0 -6
  36. package/src/build-components/FormSubmitButton/FormSubmitButtonProps.generated.ts +3 -26
  37. package/src/build-components/OnboardButton/OnboardButton.tsx +1 -8
  38. package/src/build-components/OnboardButton/OnboardButtonProps.generated.ts +3 -26
  39. package/src/build-components/OnboardButton/pattern.json +3 -5
  40. package/src/build-components/OnboardProvider/OnboardProviderProps.generated.ts +0 -12
  41. package/src/build-components/OnboardProvider/pattern.json +1 -9
  42. package/src/build-components/PaywallProvider/PaywallProviderProps.generated.ts +0 -12
  43. package/src/build-components/PaywallProvider/pattern.json +1 -9
  44. package/src/build-components/RenderNode.generated.tsx +0 -10
  45. package/src/build-components/SystemButton/SystemButton.tsx +0 -6
  46. package/src/build-components/SystemButton/SystemButtonProps.generated.ts +3 -26
  47. package/src/build-components/SystemButton/pattern.json +3 -5
  48. package/src/build-components/SystemButton/usePlacementButtonEvents.ts +27 -51
  49. package/src/build-components/index.ts +0 -10
  50. package/src/build-components/patterns.generated.ts +1379 -2270
  51. package/src/components/AttributesEditorPanel.tsx +0 -1
  52. package/src/styles/index.scss +0 -1
  53. package/src/utils/analyseNodeByPatterns.ts +2 -5
  54. package/src/utils/nodeTree.ts +0 -115
  55. package/dist/build-components/GlobalProvider/GlobalContext.d.ts +0 -28
  56. package/dist/build-components/GlobalProvider/GlobalProvider.d.ts +0 -5
  57. package/dist/build-components/GlobalProvider/GlobalProviderProps.generated.d.ts +0 -60
  58. package/dist/build-components/GlobalProvider/globalProviderUtils.d.ts +0 -28
  59. package/dist/build-components/GlobalProvider/useGlobalNavigation.d.ts +0 -19
  60. package/dist/build-components/GlobalProvider/useGlobalProviderLogic.d.ts +0 -15
  61. package/dist/build-components/TermsProvider/TermsProvider.d.ts +0 -5
  62. package/dist/build-components/TermsProvider/TermsProviderProps.generated.d.ts +0 -55
  63. package/src/assets/samples/global-onboard-flow.json +0 -735
  64. package/src/build-components/GlobalProvider/GlobalContext.ts +0 -48
  65. package/src/build-components/GlobalProvider/GlobalProvider.tsx +0 -51
  66. package/src/build-components/GlobalProvider/GlobalProviderProps.generated.ts +0 -78
  67. package/src/build-components/GlobalProvider/globalProviderUtils.ts +0 -204
  68. package/src/build-components/GlobalProvider/pattern.json +0 -55
  69. package/src/build-components/GlobalProvider/useGlobalNavigation.ts +0 -65
  70. package/src/build-components/GlobalProvider/useGlobalProviderLogic.ts +0 -172
  71. package/src/build-components/TermsProvider/TermsProvider.tsx +0 -45
  72. package/src/build-components/TermsProvider/TermsProviderProps.generated.ts +0 -82
  73. package/src/build-components/TermsProvider/pattern.json +0 -35
  74. package/src/patterns/event-constants.json +0 -19
  75. package/src/styles/components/_global-provider.scss +0 -131
@@ -1,48 +0,0 @@
1
- import { createContext, useContext } from 'react';
2
- import type { NodeData } from '../../types/Node';
3
-
4
- /** Supported transition animations when navigating to this page (platform-style names).
5
- * rn stack transition animations
6
- */
7
- export const GLOBAL_PAGE_ANIMATIONS = [
8
- 'default',
9
- 'fade',
10
- 'fade_from_bottom',
11
- 'fade_from_right',
12
- 'reveal_from_bottom',
13
- 'scale_from_center',
14
- 'slide_from_right',
15
- 'slide_from_left',
16
- 'slide_from_bottom',
17
- 'none',
18
- ] as const;
19
-
20
- export type GlobalPageAnimationType = (typeof GLOBAL_PAGE_ANIMATIONS)[number];
21
-
22
- export interface GlobalPage {
23
- key: string;
24
- node: NodeData;
25
- /** Condition key: this page is skipped when conditions[skipIf] === true */
26
- skipIf?: string;
27
- /** Optional transition animation when this page is shown (push/enter). */
28
- animation?: string;
29
- index: number;
30
- }
31
-
32
- export interface GlobalContextValue {
33
- currentPageKey: string;
34
- pages: GlobalPage[];
35
- pageStack: string[];
36
- navigate: (key: string) => void;
37
- goNext: () => void;
38
- goBack: () => boolean;
39
- /** Runtime boolean conditions (e.g. termsAccepted) */
40
- conditions: Record<string, boolean>;
41
- setCondition: (key: string, value: boolean) => void;
42
- }
43
-
44
- export const GlobalContext = createContext<GlobalContextValue | null>(null);
45
-
46
- export function useGlobalContext(): GlobalContextValue | null {
47
- return useContext(GlobalContext);
48
- }
@@ -1,51 +0,0 @@
1
- import React from 'react';
2
- import type { GlobalProviderComponentProps } from './GlobalProviderProps.generated';
3
- import { GlobalContext } from './GlobalContext';
4
- import { useGlobalProviderLogic } from './useGlobalProviderLogic';
5
- import RenderNode from '../RenderNode.generated';
6
- import { useLogRender } from '../../utils/useLogRender';
7
-
8
- function GlobalProvider({ node }: GlobalProviderComponentProps) {
9
- useLogRender('GlobalProvider');
10
-
11
- const { attributeName, attributeKey, attrs, activePage, contextValue } =
12
- useGlobalProviderLogic({ node });
13
-
14
- const animationClass = (() => {
15
- const a = activePage?.animation;
16
- if (a === 'default') return 'global-provider-page--default';
17
- if (!a || a === 'none') return ''; // No modifier: no animation at all
18
- return `global-provider-page--${a}`;
19
- })();
20
-
21
- return (
22
- <GlobalContext.Provider value={contextValue}>
23
- <div
24
- attribute-name={attributeName}
25
- attribute-key={attributeKey}
26
- {...(attrs?.testID ? { 'data-testid': attrs.testID } : {})}
27
- style={{
28
- flex: 1,
29
- display: 'flex',
30
- flexDirection: 'column',
31
- height: '100%',
32
- }}
33
- >
34
- {activePage ? (
35
- <div
36
- key={activePage.key}
37
- className={
38
- animationClass
39
- ? `global-provider-page ${animationClass}`
40
- : 'global-provider-page'
41
- }
42
- >
43
- <RenderNode node={activePage.node} />
44
- </div>
45
- ) : null}
46
- </div>
47
- </GlobalContext.Provider>
48
- );
49
- }
50
-
51
- export default React.memo(GlobalProvider);
@@ -1,78 +0,0 @@
1
- /* AUTO-GENERATED FILE - DO NOT EDIT */
2
-
3
- import type { NodeData } from '../../types/Node';
4
-
5
- export type FlexDirectionOptionType = 'row' | 'column';
6
- export type FlexWrapOptionType = 'nowrap' | 'wrap' | 'wrap-reverse';
7
- export type AlignItemsOptionType =
8
- | 'flex-start'
9
- | 'center'
10
- | 'flex-end'
11
- | 'stretch'
12
- | 'baseline';
13
- export type JustifyContentOptionType =
14
- | 'flex-start'
15
- | 'center'
16
- | 'flex-end'
17
- | 'space-between'
18
- | 'space-around'
19
- | 'space-evenly';
20
- export type PositionOptionType = 'relative' | 'absolute';
21
-
22
- export interface SkipConditionEntryGenerated {
23
- pageKey?: string;
24
- conditionKey?: string;
25
- }
26
-
27
- export interface GlobalProviderStyleGenerated {
28
- flexDirection?: FlexDirectionOptionType;
29
- flexWrap?: FlexWrapOptionType;
30
- alignItems?: AlignItemsOptionType;
31
- justifyContent?: JustifyContentOptionType;
32
- gap?: string;
33
- padding?: string;
34
- paddingHorizontal?: string;
35
- paddingVertical?: string;
36
- paddingTop?: string;
37
- paddingBottom?: string;
38
- paddingLeft?: string;
39
- paddingRight?: string;
40
- margin?: string;
41
- marginHorizontal?: string;
42
- marginVertical?: string;
43
- marginTop?: string;
44
- marginBottom?: string;
45
- marginLeft?: string;
46
- marginRight?: string;
47
- backgroundColor?: string;
48
- borderRadius?: string;
49
- width?: string;
50
- minWidth?: string;
51
- maxWidth?: string;
52
- height?: string;
53
- minHeight?: string;
54
- maxHeight?: string;
55
- flex?: number;
56
- position?: PositionOptionType;
57
- top?: string;
58
- bottom?: string;
59
- left?: string;
60
- right?: string;
61
- zIndex?: number;
62
- }
63
-
64
- export interface GlobalProviderPropsGenerated {
65
- child: string;
66
- attributes: {
67
- styles?: GlobalProviderStyleGenerated;
68
- scrollable?: boolean;
69
- testID?: string;
70
- initialPage?: string;
71
- persistProgress?: boolean;
72
- skipConditions?: SkipConditionEntryGenerated[];
73
- };
74
- }
75
-
76
- export interface GlobalProviderComponentProps {
77
- node: NodeData<GlobalProviderPropsGenerated['attributes']>;
78
- }
@@ -1,204 +0,0 @@
1
- import type { NodeData } from '../../types/Node';
2
- import type { GlobalPage } from './GlobalContext';
3
-
4
- /** Maps node type to a canonical page key when no explicit pageKey attribute is provided. */
5
- const TYPE_KEY_MAP: Record<string, string> = {
6
- TermsProvider: 'terms',
7
- OnboardProvider: 'onboard',
8
- PaywallProvider: 'paywall',
9
- FormProvider: 'form',
10
- CarouselProvider: 'carousel',
11
- };
12
-
13
- /**
14
- * Derives a stable and unique page key for a child node.
15
- * Priority: node.key → TYPE_KEY_MAP → "${type}-${index}"
16
- */
17
- export function derivePageKey(
18
- node: NodeData,
19
- index: number,
20
- existingKeys: Set<string>,
21
- ): string {
22
- let baseKey = '';
23
- if (typeof node.key === 'string' && node.key.trim()) {
24
- baseKey = node.key.trim();
25
- } else {
26
- baseKey = TYPE_KEY_MAP[node.type] || node.type?.toLowerCase?.() || 'page';
27
- }
28
-
29
- let finalKey = baseKey;
30
- let counter = 1;
31
-
32
- // Ensure uniqueness among siblings
33
- while (existingKeys.has(finalKey)) {
34
- finalKey = `${baseKey}-${index + counter}`;
35
- counter++;
36
- }
37
-
38
- existingKeys.add(finalKey);
39
- return finalKey;
40
- }
41
-
42
- /** Runtime shape of a SkipConditionEntry (mirrors the types block in pattern.json). */
43
- export interface SkipConditionEntry {
44
- pageKey: string;
45
- conditionKey: string;
46
- }
47
-
48
- /**
49
- * Converts SkipConditionEntry[] (from pattern schema) to a lookup map for fast access.
50
- */
51
- export function normalizeSkipConditions(raw: unknown): Record<string, string> {
52
- if (!Array.isArray(raw)) return {};
53
- const result: Record<string, string> = {};
54
- for (const entry of raw) {
55
- if (
56
- entry &&
57
- typeof entry === 'object' &&
58
- typeof (entry as SkipConditionEntry).pageKey === 'string' &&
59
- typeof (entry as SkipConditionEntry).conditionKey === 'string'
60
- ) {
61
- result[(entry as SkipConditionEntry).pageKey] = (
62
- entry as SkipConditionEntry
63
- ).conditionKey;
64
- }
65
- }
66
- return result;
67
- }
68
-
69
- /**
70
- * Builds the page list for GlobalProvider.
71
- */
72
- export function buildPages(
73
- children: NodeData[],
74
- skipConditions: Record<string, string> = {},
75
- ): GlobalPage[] {
76
- const existingKeys = new Set<string>();
77
- return children.map((node, index) => {
78
- const key = derivePageKey(node, index, existingKeys);
79
- const skipIf = skipConditions[key] ?? undefined;
80
- const animation =
81
- typeof (node.attributes as Record<string, unknown>)?.animation ===
82
- 'string'
83
- ? (node.attributes as Record<string, string>).animation
84
- : undefined;
85
- return {
86
- key,
87
- node,
88
- skipIf,
89
- animation,
90
- index,
91
- };
92
- });
93
- }
94
-
95
- /** Returns the first non-skipped page key, starting from the requested key. */
96
- export function resolveEffectivePage(
97
- targetKey: string,
98
- pages: GlobalPage[],
99
- conditions: Record<string, boolean>,
100
- ): string | null {
101
- const targetIdx = pages.findIndex((p) => p.key === targetKey);
102
- if (targetIdx === -1) {
103
- // If target not found, start from the first non-skipped page
104
- return resolveFirstNonSkippedPage(pages, conditions);
105
- }
106
-
107
- // Walk forward from target, skipping pages whose condition is met
108
- for (let i = targetIdx; i < pages.length; i++) {
109
- const page = pages[i];
110
- if (!page) break;
111
- if (page.skipIf && conditions[page.skipIf] === true) {
112
- continue;
113
- }
114
- return page.key;
115
- }
116
-
117
- // If all remaining pages are skipped, return null instead of falling back to the last page.
118
- // This allows the caller to handle the "no available pages" state explicitly.
119
- return null;
120
- }
121
-
122
- function resolveFirstNonSkippedPage(
123
- pages: GlobalPage[],
124
- conditions: Record<string, boolean>,
125
- ): string | null {
126
- for (const page of pages) {
127
- if (!(page.skipIf && conditions[page.skipIf] === true)) {
128
- return page.key;
129
- }
130
- }
131
- return null;
132
- }
133
-
134
- const STORAGE_KEY_PREFIX = 'global-provider-progress';
135
-
136
- /**
137
- * Internal storage abstraction. In a real RN environment, this would be swapped
138
- * for AsyncStorage. For now, it defaults to localStorage with safe checks.
139
- */
140
- const storage = {
141
- getItem: (key: string) => {
142
- try {
143
- return typeof localStorage !== 'undefined'
144
- ? localStorage.getItem(key)
145
- : null;
146
- } catch {
147
- return null;
148
- }
149
- },
150
- setItem: (key: string, value: string) => {
151
- try {
152
- if (typeof localStorage !== 'undefined') localStorage.setItem(key, value);
153
- } catch {
154
- // ignore
155
- }
156
- },
157
- removeItem: (key: string) => {
158
- try {
159
- if (typeof localStorage !== 'undefined') localStorage.removeItem(key);
160
- } catch {
161
- // ignore
162
- }
163
- },
164
- };
165
-
166
- export function persistProgress(
167
- storageKey: string,
168
- currentPageKey: string,
169
- conditions: Record<string, boolean>,
170
- ): void {
171
- storage.setItem(
172
- `${STORAGE_KEY_PREFIX}-${storageKey}`,
173
- JSON.stringify({ currentPageKey, conditions }),
174
- );
175
- }
176
-
177
- export function loadProgress(storageKey: string): {
178
- currentPageKey: string;
179
- conditions: Record<string, boolean>;
180
- } | null {
181
- const raw = storage.getItem(`${STORAGE_KEY_PREFIX}-${storageKey}`);
182
- if (!raw) return null;
183
- try {
184
- const parsed = JSON.parse(raw) as unknown;
185
- if (
186
- parsed &&
187
- typeof parsed === 'object' &&
188
- !Array.isArray(parsed) &&
189
- typeof (parsed as Record<string, unknown>).currentPageKey === 'string'
190
- ) {
191
- return parsed as {
192
- currentPageKey: string;
193
- conditions: Record<string, boolean>;
194
- };
195
- }
196
- } catch {
197
- // parse error
198
- }
199
- return null;
200
- }
201
-
202
- export function clearProgress(storageKey: string): void {
203
- storage.removeItem(`${STORAGE_KEY_PREFIX}-${storageKey}`);
204
- }
@@ -1,55 +0,0 @@
1
- {
2
- "schemaVersion": 2,
3
- "types": {
4
- "SkipConditionEntry": {
5
- "pageKey": "string",
6
- "conditionKey": "string"
7
- }
8
- },
9
- "pattern": {
10
- "type": "GlobalProvider",
11
- "title": "title",
12
- "description": "description",
13
- "children": "node",
14
- "extends": "View",
15
- "attributes": {
16
- "initialPage": "string",
17
- "persistProgress": "boolean",
18
- "skipConditions": "SkipConditionEntry[]"
19
- }
20
- },
21
- "defaults": {
22
- "styles": {
23
- "flex": 1
24
- }
25
- },
26
- "meta": {
27
- "desiredParent": ["root"],
28
- "label": "Global Provider",
29
- "description": "Top-level provider that manages multi-page flow (Terms → Onboard → Paywall). Each direct child is treated as a page.",
30
- "attributes": {
31
- "initialPage": {
32
- "label": "Initial Page Key",
33
- "description": "The page key to show first. Defaults to the first child.",
34
- "category": "other",
35
- "specialCategory": null,
36
- "sort": 1
37
- },
38
- "persistProgress": {
39
- "label": "Persist Progress",
40
- "description": "Save current page and conditions to localStorage so the user continues from where they left off.",
41
- "category": "other",
42
- "specialCategory": null,
43
- "sort": 2
44
- },
45
- "skipConditions": {
46
- "label": "Skip Conditions",
47
- "description": "List of page skip rules. Each entry maps a pageKey to a conditionKey: when conditions[conditionKey] is true, that page is skipped on navigate.",
48
- "category": "other",
49
- "specialCategory": null,
50
- "sort": 3
51
- }
52
- },
53
- "styles": {}
54
- }
55
- }
@@ -1,65 +0,0 @@
1
- import { useCallback } from 'react';
2
- import { useGlobalContext } from './GlobalContext';
3
- import { useMockOSContext } from '../../mockOS/context/MockOSContextBase';
4
- import type { RouteType } from '../../mockOS/context/MockOSContextBase';
5
-
6
- /**
7
- * Maps route/placement aliases to their canonical GlobalProvider page keys.
8
- *
9
- * Add entries here when a new alias should resolve to an existing page key.
10
- * Keys are the incoming target strings (from JSON events / usePlacementButtonEvents).
11
- * Values are the canonical page key that GlobalContext.navigate() will receive.
12
- *
13
- * Exported so other modules (e.g. a navigation-flow visualiser) can inspect
14
- * which aliases exist without duplicating this logic.
15
- */
16
- export const GLOBAL_ROUTE_ALIASES: Record<string, string> = {
17
- subscription: 'paywall',
18
- paywall: 'paywall',
19
- onboard: 'onboard',
20
- terms: 'terms',
21
- home: 'home',
22
- };
23
-
24
- /**
25
- * Returns a navigate function that first attempts to route within GlobalContext
26
- * (when a GlobalProvider is active), then falls back to MockOSContext navigation.
27
- *
28
- * Used by SystemButton and OnboardButton so that events defined in JSON work
29
- * transparently whether rendered inside a GlobalProvider or standalone.
30
- */
31
- export function useGlobalNavigation(): (target: string) => boolean {
32
- const globalCtx = useGlobalContext();
33
- const mockOS = useMockOSContext();
34
-
35
- return useCallback(
36
- (target: string): boolean => {
37
- if (globalCtx) {
38
- // Direct page key match
39
- if (globalCtx.pages.some((p) => p.key === target)) {
40
- globalCtx.navigate(target);
41
- return true;
42
- }
43
-
44
- // Alias resolution: map incoming target to canonical page key
45
- const canonicalKey = GLOBAL_ROUTE_ALIASES[target];
46
- if (
47
- canonicalKey &&
48
- globalCtx.pages.some((p) => p.key === canonicalKey)
49
- ) {
50
- globalCtx.navigate(canonicalKey);
51
- return true;
52
- }
53
- }
54
-
55
- // Fallback: delegate to MockOSContext
56
- if (mockOS) {
57
- mockOS.navigation(target as RouteType);
58
- return true;
59
- }
60
-
61
- return false;
62
- },
63
- [globalCtx, mockOS],
64
- );
65
- }
@@ -1,172 +0,0 @@
1
- import { useCallback, useId, useMemo, useRef, useState } from 'react';
2
- import type { GlobalContextValue } from './GlobalContext';
3
- import {
4
- buildPages,
5
- loadProgress,
6
- normalizeSkipConditions,
7
- persistProgress,
8
- resolveEffectivePage,
9
- } from './globalProviderUtils';
10
- import useNode from '../useNode';
11
- import type { NodeData } from '../../types/Node';
12
-
13
- export interface UseGlobalProviderLogicOptions {
14
- node: NodeData;
15
- }
16
-
17
- export function useGlobalProviderLogic({
18
- node: rawNode,
19
- }: UseGlobalProviderLogicOptions) {
20
- const node = useNode(rawNode);
21
-
22
- const generatedId = useId();
23
- const attributeName = node.sourceType ?? node.type ?? 'GlobalProvider';
24
- const attributeKey = node.key ?? generatedId;
25
- const attrs = node.attributes;
26
- const shouldPersist = attrs?.persistProgress === true;
27
-
28
- const childNodes = useMemo((): NodeData[] => {
29
- const raw = node.children;
30
- if (!raw) return [];
31
- if (Array.isArray(raw)) return raw as NodeData[];
32
- return [raw as NodeData];
33
- }, [node.children]);
34
-
35
- const skipConditions = useMemo(
36
- () => normalizeSkipConditions(attrs?.skipConditions),
37
- [attrs?.skipConditions],
38
- );
39
-
40
- const pages = useMemo(
41
- () => buildPages(childNodes, skipConditions),
42
- [childNodes, skipConditions],
43
- );
44
-
45
- const storageKey = attributeKey;
46
-
47
- const [conditions, setConditions] = useState<Record<string, boolean>>(() => {
48
- if (shouldPersist) {
49
- return loadProgress(storageKey)?.conditions ?? {};
50
- }
51
- return {};
52
- });
53
-
54
- const [pageStack, setPageStack] = useState<string[]>(() => {
55
- const saved = shouldPersist ? loadProgress(storageKey) : null;
56
- const initialConditions = saved?.conditions ?? {};
57
-
58
- const firstEffective = (() => {
59
- if (saved?.currentPageKey) {
60
- return resolveEffectivePage(
61
- saved.currentPageKey,
62
- pages,
63
- initialConditions,
64
- );
65
- }
66
-
67
- const requestedKey =
68
- typeof attrs?.initialPage === 'string'
69
- ? attrs.initialPage
70
- : (pages[0]?.key ?? '');
71
- return resolveEffectivePage(requestedKey, pages, initialConditions);
72
- })();
73
- return firstEffective ? [firstEffective] : [];
74
- });
75
-
76
- const currentPageKey = pageStack[pageStack.length - 1] ?? '';
77
-
78
- const conditionsRef = useRef(conditions);
79
- conditionsRef.current = conditions;
80
-
81
- const setCondition = useCallback(
82
- (key: string, value: boolean) => {
83
- setConditions((prev) => {
84
- const next = { ...prev, [key]: value };
85
- if (shouldPersist) {
86
- const currentKey = pageStack[pageStack.length - 1] ?? '';
87
- persistProgress(storageKey, currentKey, next);
88
- }
89
- return next;
90
- });
91
- },
92
- [shouldPersist, storageKey, pageStack],
93
- );
94
-
95
- const navigate = useCallback(
96
- (key: string) => {
97
- const effective = resolveEffectivePage(key, pages, conditionsRef.current);
98
- if (!effective) return;
99
-
100
- setPageStack((prev) => {
101
- const last = prev[prev.length - 1];
102
- if (last === effective) return prev;
103
- const next = [...prev, effective];
104
- if (shouldPersist) {
105
- persistProgress(storageKey, effective, conditionsRef.current);
106
- }
107
- return next;
108
- });
109
- },
110
- [pages, shouldPersist, storageKey],
111
- );
112
-
113
- const goNext = useCallback(() => {
114
- const currentIdx = pages.findIndex((p) => p.key === currentPageKey);
115
- if (currentIdx === -1 || currentIdx >= pages.length - 1) return;
116
- const nextPage = pages[currentIdx + 1];
117
- if (!nextPage) return;
118
- navigate(nextPage.key);
119
- }, [pages, currentPageKey, navigate]);
120
-
121
- const goBack = useCallback((): boolean => {
122
- if (pageStack.length <= 1) return false;
123
- setPageStack((prev) => {
124
- const next = prev.slice(0, -1);
125
- const prevKey = next[next.length - 1] ?? '';
126
- if (shouldPersist) {
127
- persistProgress(storageKey, prevKey, conditionsRef.current);
128
- }
129
- return next;
130
- });
131
- return true;
132
- }, [pageStack.length, shouldPersist, storageKey]);
133
-
134
- const activePage = useMemo(
135
- () => pages.find((p) => p.key === currentPageKey),
136
- [pages, currentPageKey],
137
- );
138
-
139
- const contextValue = useMemo<GlobalContextValue>(
140
- () => ({
141
- currentPageKey,
142
- pages,
143
- pageStack,
144
- navigate,
145
- goNext,
146
- goBack,
147
- conditions,
148
- setCondition,
149
- }),
150
- [
151
- currentPageKey,
152
- pages,
153
- pageStack,
154
- navigate,
155
- goNext,
156
- goBack,
157
- conditions,
158
- setCondition,
159
- ],
160
- );
161
-
162
- return {
163
- node,
164
- attributeName,
165
- attributeKey,
166
- attrs,
167
- pages,
168
- currentPageKey,
169
- activePage,
170
- contextValue,
171
- };
172
- }