@snap/valdi 1.0.11 → 1.1.7

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 (74) hide show
  1. package/.metadata/.bazelrc.template +7 -6
  2. package/.metadata/MODULE.bazel.template +154 -0
  3. package/bundled-skills/registry.json +13 -2
  4. package/bundled-skills/skills/valdi-animations/skill.md +197 -0
  5. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +1 -1
  6. package/bundled-skills/skills/valdi-compiler/skill.md +4 -4
  7. package/bundled-skills/skills/valdi-component-dedup/skill.md +263 -0
  8. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
  9. package/bundled-skills/skills/valdi-custom-view/skill.md +43 -1
  10. package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
  11. package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
  12. package/bundled-skills/skills/valdi-inspect/skill.md +19 -1
  13. package/bundled-skills/skills/valdi-localization/skill.md +142 -0
  14. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
  15. package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
  16. package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
  17. package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
  18. package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
  19. package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
  20. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
  21. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
  22. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
  23. package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
  24. package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
  25. package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
  26. package/bundled-skills/skills/valdi-overview/skill.md +7 -4
  27. package/bundled-skills/skills/valdi-perf/skill.md +223 -0
  28. package/bundled-skills/skills/valdi-polyglot-module/skill.md +80 -0
  29. package/bundled-skills/skills/valdi-preview/skill.md +303 -0
  30. package/bundled-skills/skills/valdi-setup/skill.md +55 -5
  31. package/bundled-skills/skills/valdi-testing/skill.md +23 -7
  32. package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
  33. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
  34. package/dist/commands/agentCheck.js +184 -0
  35. package/dist/commands/analyze.js +16 -0
  36. package/dist/commands/analyze_commands/duplicates.js +134 -0
  37. package/dist/commands/bootstrap.js +57 -73
  38. package/dist/commands/build.js +6 -0
  39. package/dist/commands/doctor.js +42 -266
  40. package/dist/commands/hotreload.js +15 -0
  41. package/dist/commands/inspect_commands/snapshot.js +71 -6
  42. package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
  43. package/dist/commands/install.js +6 -0
  44. package/dist/commands/preview.js +81 -0
  45. package/dist/commands/projectsync.js +9 -7
  46. package/dist/commands/skills_commands/install.js +6 -1
  47. package/dist/commands/skills_commands/update.js +2 -1
  48. package/dist/core/analyze/clusterer.js +150 -0
  49. package/dist/core/analyze/fingerprint.js +2 -0
  50. package/dist/core/analyze/knownPatterns.js +76 -0
  51. package/dist/core/analyze/parser.js +177 -0
  52. package/dist/core/analyze/reporter.js +83 -0
  53. package/dist/core/analyze/scanner.js +172 -0
  54. package/dist/core/analyze/similarity.js +56 -0
  55. package/dist/core/constants.js +6 -3
  56. package/dist/core/packageFiles.spec.js +1 -1
  57. package/dist/preview/previewGenerator.js +240 -0
  58. package/dist/preview/previewGenerator.spec.js +203 -0
  59. package/dist/preview/viewModelParser.js +86 -0
  60. package/dist/preview/viewModelParser.spec.js +171 -0
  61. package/dist/setup/DevSetupHelper.js +0 -54
  62. package/dist/setup/linuxSetup.js +0 -16
  63. package/dist/setup/macOSSetup.js +1 -5
  64. package/dist/utils/BazelClient.js +15 -0
  65. package/dist/utils/applicationUtils.js +15 -0
  66. package/dist/utils/daemonClient.js +3 -1
  67. package/dist/utils/linuxDistro.js +0 -21
  68. package/dist/utils/linuxDistro.spec.js +0 -48
  69. package/dist/utils/skillsAdapters.js +126 -19
  70. package/dist/utils/skillsAdapters.spec.js +141 -0
  71. package/dist/utils/skillsRegistry.js +8 -0
  72. package/package.json +16 -8
  73. package/.metadata/WORKSPACE.template +0 -57
  74. package/dist/setup/versions.js +0 -8
@@ -0,0 +1,263 @@
1
+ # Valdi Component Deduplication
2
+
3
+ Find and extract duplicated UI patterns across Valdi modules into shared components.
4
+
5
+ ## When to use
6
+
7
+ When you want to identify components that multiple modules have independently implemented, then extract them into a shared library so future modules can reuse them instead of reinventing.
8
+
9
+ ## Running the analysis
10
+
11
+ ```bash
12
+ # Full scan of all modules
13
+ valdi analyze duplicates
14
+
15
+ # Scope to one module
16
+ valdi analyze duplicates --module my_module
17
+
18
+ # Machine-readable output
19
+ valdi analyze duplicates --json
20
+
21
+ # Only check for a specific pattern
22
+ valdi analyze duplicates --pattern async
23
+
24
+ # Custom scan roots and shared libraries
25
+ valdi analyze duplicates --scan-root src/modules --shared-lib valdi_widgets
26
+ valdi analyze duplicates --scan-root src/modules --shared-lib my_shared_lib --shared-lib another_lib
27
+ ```
28
+
29
+ ### CLI flags
30
+
31
+ | Flag | Effect |
32
+ |---|---|
33
+ | `--module <name>` | Scope to one module |
34
+ | `--json` | Machine-readable JSON output |
35
+ | `--threshold <0-1>` | Similarity threshold (default 0.6) |
36
+ | `--pattern <name>` | Only detect: `async`, `button`, `shimmer` |
37
+ | `--output <path>` | Write JSON report to file |
38
+ | `--verbose` | Show per-file detail |
39
+ | `--scan-root <path>` | Root directory to scan (repeatable) |
40
+ | `--shared-lib <name>` | Shared component library name (repeatable) |
41
+
42
+ ## Understanding the report
43
+
44
+ The report has two sections:
45
+
46
+ **Known Patterns** — pre-built detectors for the most common duplication:
47
+ - **Async State Container**: Components that implement loading→error/content state machines
48
+ - **Button Wrapper**: Thin wrappers around a shared button with hardcoded sizing/coloring
49
+ - **Shimmer / Skeleton Layout**: Custom loading placeholder components
50
+
51
+ **Similar Clusters** — generic similarity analysis that finds groups of components with overlapping ViewModel props, render trees, and import signatures.
52
+
53
+ Each cluster shows:
54
+ - Number of files and average similarity score
55
+ - Shared ViewModel props across the cluster
56
+ - A suggested extraction approach
57
+
58
+ ## Extraction workflow
59
+
60
+ Once you identify a cluster worth extracting:
61
+
62
+ ### 1. Read the candidates
63
+
64
+ Read each file in the cluster. Identify:
65
+ - The shared ViewModel props (these become the new component's ViewModel)
66
+ - The shared render structure (this becomes the new component's `onRender`)
67
+ - Module-specific variations (these become optional props or render callbacks)
68
+
69
+ ### 2. Check for an existing shared component to extend
70
+
71
+ Before creating anything new, search the shared library for a component that already solves part of the problem. Often the right fix is adding props, a preset enum, or a render callback to an existing component rather than building from scratch.
72
+
73
+ ```bash
74
+ # Search the shared library for related components
75
+ grep -rl "Button\|Shimmer\|AsyncContent" <your-shared-lib>/src/components/
76
+ ```
77
+
78
+ If an existing component covers 70%+ of the use cases, extend it:
79
+ - Add optional props for the missing behavior
80
+ - Add a preset or variant enum if consumers just need different default combos
81
+ - Add a render callback slot if consumers need to inject custom UI
82
+
83
+ Only create a new component when nothing in the shared library is close enough to extend.
84
+
85
+ ### 3. Design or extend the shared component
86
+
87
+ **Extending an existing component** (preferred):
88
+
89
+ ```typescript
90
+ // Add a preset to an existing button component
91
+ export enum CoreButtonPreset {
92
+ PRIMARY_CTA,
93
+ SECONDARY_ACTION,
94
+ PILL_ACTION,
95
+ }
96
+
97
+ // Add an optional prop to the existing ViewModel
98
+ interface CoreButtonViewModel {
99
+ // ... existing props ...
100
+ preset?: CoreButtonPreset;
101
+ }
102
+ ```
103
+
104
+ **Creating a new component** (when nothing exists to extend):
105
+
106
+ ```typescript
107
+ import { Component } from 'valdi_core/src/Component';
108
+
109
+ interface SharedComponentViewModel {
110
+ commonProp: string;
111
+ optionalVariant?: VariantType;
112
+ renderCustomSection?: () => void;
113
+ }
114
+
115
+ export class SharedComponent extends Component<SharedComponentViewModel> {
116
+ onRender(): void {
117
+ <view>
118
+ <label value={this.viewModel.commonProp} />;
119
+ {this.viewModel.renderCustomSection?.()};
120
+ </view>;
121
+ }
122
+ }
123
+ ```
124
+
125
+ ### 4. Place it in the shared library
126
+
127
+ If you created a new component, place it in your project's shared component library
128
+ (e.g. `<shared-lib>/src/components/<category>/`). Follow your project's conventions
129
+ for directory structure and naming.
130
+
131
+ ### 5. Migrate consumers
132
+
133
+ For each file in the cluster:
134
+ 1. Replace the local component class with an import of the shared one
135
+ 2. Map the old ViewModel props to the new shared ViewModel
136
+ 3. Move module-specific rendering into render callbacks
137
+ 4. Delete the old local component file
138
+ 5. Run `valdi agent-check --module <name>` to verify
139
+
140
+ ### 6. Verify
141
+
142
+ ```bash
143
+ # Re-run analysis — the cluster should shrink or disappear
144
+ valdi analyze duplicates --pattern async
145
+
146
+ # Build and test affected modules
147
+ valdi agent-check --module module_a
148
+ valdi agent-check --module module_b
149
+ ```
150
+
151
+ ## Common extraction patterns
152
+
153
+ ### Async State Container
154
+
155
+ The most common duplication. Components that manage loading→loaded/error states:
156
+
157
+ ```typescript
158
+ import { StatefulComponent } from 'valdi_core/src/Component';
159
+ import { promiseToCancelablePromise } from 'valdi_core/src/CancelablePromise';
160
+
161
+ interface AsyncStateContainerViewModel<T> {
162
+ resultProvider: () => PromiseLike<T>;
163
+ renderLoading: () => void;
164
+ renderResult: (data: T) => void;
165
+ renderError: (error: string, retry: () => void) => void;
166
+ renderEmpty?: () => void;
167
+ }
168
+
169
+ type AsyncState<T> = { phase: 'loading' } | { phase: 'result'; data: T } | { phase: 'error'; message: string };
170
+
171
+ export class AsyncStateContainer<T> extends StatefulComponent<AsyncStateContainerViewModel<T>, { state: AsyncState<T> }> {
172
+ state = { state: { phase: 'loading' } as AsyncState<T> };
173
+
174
+ onCreate(): void {
175
+ this.load();
176
+ }
177
+
178
+ onRender(): void {
179
+ const s = this.state.state;
180
+ switch (s.phase) {
181
+ case 'loading': this.viewModel.renderLoading(); break;
182
+ case 'result': this.viewModel.renderResult(s.data); break;
183
+ case 'error': this.viewModel.renderError(s.message, () => this.load()); break;
184
+ }
185
+ }
186
+
187
+ private load(): void {
188
+ this.setState({ state: { phase: 'loading' } });
189
+ const cancelable = promiseToCancelablePromise(
190
+ Promise.resolve(this.viewModel.resultProvider()),
191
+ () => {},
192
+ );
193
+ this.registerDisposable(() => cancelable.cancel?.());
194
+ cancelable.then(
195
+ data => { this.setState({ state: { phase: 'result', data } }); },
196
+ error => { this.setState({ state: { phase: 'error', message: (error as Error).message } }); },
197
+ );
198
+ }
199
+ }
200
+ ```
201
+
202
+ ### Button Presets
203
+
204
+ Instead of per-module button wrappers, use preset enums:
205
+
206
+ ```typescript
207
+ // Instead of a new wrapper component, add presets to the existing shared button
208
+ enum ButtonPreset {
209
+ PRIMARY_CTA,
210
+ SECONDARY_ACTION,
211
+ PILL_ACTION,
212
+ }
213
+
214
+ function presetProps(preset: ButtonPreset): { sizing: ButtonSizing; coloring: ButtonColoring } {
215
+ switch (preset) {
216
+ case ButtonPreset.PRIMARY_CTA: return { sizing: ButtonSizing.XL, coloring: ButtonColoring.PRIMARY_BRAND };
217
+ case ButtonPreset.SECONDARY_ACTION: return { sizing: ButtonSizing.LARGE, coloring: ButtonColoring.SECONDARY };
218
+ case ButtonPreset.PILL_ACTION: return { sizing: ButtonSizing.SMALL, coloring: ButtonColoring.TERTIARY };
219
+ }
220
+ }
221
+ ```
222
+
223
+ ### Shimmer Layout
224
+
225
+ Configurable skeleton loading placeholder:
226
+
227
+ ```typescript
228
+ import { Component } from 'valdi_core/src/Component';
229
+
230
+ interface ShimmerRow {
231
+ widthRatio: number;
232
+ height: number;
233
+ borderRadius?: number;
234
+ }
235
+
236
+ interface ShimmerLayoutViewModel {
237
+ rows: ShimmerRow[];
238
+ spacing?: number;
239
+ }
240
+
241
+ export class ShimmerLayout extends Component<ShimmerLayoutViewModel> {
242
+ onRender(): void {
243
+ const spacing = this.viewModel.spacing ?? 8;
244
+ <view>
245
+ {this.viewModel.rows.forEach((row, i) => {
246
+ <AnimationShimmer
247
+ width={`${row.widthRatio * 100}%`}
248
+ height={row.height}
249
+ borderRadius={row.borderRadius ?? 4}
250
+ marginTop={i > 0 ? spacing : 0}
251
+ />;
252
+ })}
253
+ </view>;
254
+ }
255
+ }
256
+ ```
257
+
258
+ ## Tips
259
+
260
+ - Start with the highest-severity known patterns — they have the most impact
261
+ - Extract the simplest shared interface first, then iterate to handle edge cases
262
+ - Use render callbacks for module-specific UI instead of trying to generalize everything
263
+ - Run `valdi analyze duplicates --json --output report.json` to save a baseline, then re-run after extraction to measure impact
@@ -100,7 +100,7 @@ describe('ProfileCardTest', () => {
100
100
  componentGetElements(nodes[0].component!),
101
101
  'follow-button',
102
102
  )[0];
103
- button?.getAttribute('onTap')?.();
103
+ button?.getAttribute('onTap')?.({} as any);
104
104
  expect(onFollowTap).toHaveBeenCalled();
105
105
  });
106
106
 
@@ -55,10 +55,52 @@ class MyComponent extends Component<MyViewModel> {
55
55
 
56
56
  `viewFactory` and `*Class` attributes are mutually exclusive — use one or the other. `viewFactory` takes precedence when both are provided.
57
57
 
58
+ ## macOS Attribute Binding
59
+
60
+ macOS custom views can bind attributes (including callbacks) from TSX using `+bindAttributes:`. The view manager calls this class method at registration time.
61
+
62
+ ```objc
63
+ #import "valdi/macos/SCValdiMacOSAttributesBinder.h"
64
+ #import "valdi/macos/SCValdiMacOSFunction.h"
65
+
66
+ @interface SCMyView () {
67
+ SCValdiMacOSFunction *_onMyCallback;
68
+ }
69
+ @end
70
+
71
+ @implementation SCMyView
72
+ - (void)valdi_setOnMyCallback:(id)value { _onMyCallback = value; }
73
+
74
+ + (void)bindAttributes:(SCValdiMacOSAttributesBinder *)attributesBinder {
75
+ [attributesBinder bindUntypedAttribute:@"onMyCallback"
76
+ invalidateLayoutOnChange:NO
77
+ selector:@selector(valdi_setOnMyCallback:)];
78
+ }
79
+ @end
80
+ ```
81
+
82
+ **Binder methods:**
83
+ - `bindUntypedAttribute:invalidateLayoutOnChange:selector:` — binds any attribute (strings, numbers, functions)
84
+ - `bindColorAttribute:invalidateLayoutOnChange:selector:` — binds color attributes specifically
85
+
86
+ **Invoking callbacks:** Call `[_onMyCallback performWithParameters:@[@{@"key": @"value"}]]` — the NSArray/NSDictionary is auto-converted to JS objects.
87
+
88
+ ## Keyboard Input on macOS
89
+
90
+ Valdi doesn't have built-in keyboard event support. Use a polyglot `<custom-view>` with an NSView that:
91
+ 1. Overrides `acceptsFirstResponder` → `YES`
92
+ 2. Overrides `keyDown:` to map key codes to callback invocations
93
+ 3. Calls `[self.window makeFirstResponder:self]` in `viewDidMoveToWindow` to grab focus
94
+ 4. Has **non-zero dimensions** (wrap visible content inside it)
95
+
96
+ See the `valdi-polyglot-module` skill for a complete macOS attribute binding example with BUILD.bazel wiring.
97
+
58
98
  ## Common Mistakes
59
99
 
60
- - Using `<custom-view>` without checking the platform — wrap in `Device.isAndroid()` / `Device.isIOS()` etc. if not all platforms are supported
100
+ - Using `<custom-view>` without checking the platform — wrap in `Device.isAndroid()` / `Device.isIOS()` / `Device.isDesktop()` if not all platforms are supported
61
101
  - Forgetting to link native implementations — the class name string alone isn't enough; the native code must be compiled and linked via platform `_deps` in BUILD.bazel
62
102
  - Wrong package name in `androidClass` — must match the Kotlin/Java package exactly
63
103
  - Specifying `macosClass` when it's the same as `iosClass` — omit it and let the fallthrough handle it
64
104
  - Using a `filegroup` for `web_deps` — always use `ts_project` with `transpiler = "tsc"`
105
+ - Creating a 0×0 custom-view for keyboard focus — it won't become first responder; wrap content inside it
106
+ - **Duplicate ObjC class names across modules** — if two modules define the same native class (e.g. both have `SCKeyboardView`), the linker will fail with "duplicate symbol" errors. Always use a unique class name per module (e.g. prefix with module name: `SCSnakeGameKeyboardView`)
@@ -0,0 +1,238 @@
1
+ # Valdi Error Handling
2
+
3
+ Error handling, promise rejection, and lifecycle safety patterns.
4
+
5
+ ## When to use
6
+
7
+ When dealing with async operations, network requests, component lifecycle boundaries, or any code that can fail at runtime.
8
+
9
+ ## Key concepts
10
+
11
+ Valdi runs on a JavaScript runtime (Hermes/V8) with native platform integration. Unhandled errors crash the app. The primary error sources are:
12
+
13
+ 1. **Async operations** completing after component destruction
14
+ 2. **Network failures** from HTTPClient
15
+ 3. **Uncaught promise rejections**
16
+ 4. **Type mismatches** from native/JS boundary
17
+
18
+ ## CancelablePromise — the first line of defense
19
+
20
+ Most Valdi errors stem from async work completing after a component is destroyed. `CancelablePromise` + `registerDisposable` prevents this entirely:
21
+
22
+ ```tsx
23
+ import { promiseToCancelablePromise } from 'valdi_core/src/CancelablePromise';
24
+
25
+ // ✅ Safe async — cancelled on component destruction
26
+ onCreate() {
27
+ const cancelable = promiseToCancelablePromise(this.fetchData(), () => {});
28
+ this.registerDisposable(() => cancelable.cancel?.());
29
+ cancelable.then(
30
+ data => { this.setState({ data, loading: false }); },
31
+ error => { this.setState({ error: error.message, loading: false }); },
32
+ );
33
+ }
34
+ ```
35
+
36
+ ```tsx
37
+ // ❌ WRONG — Raw promise with no lifecycle safety
38
+ onCreate() {
39
+ this.fetchData().then(data => {
40
+ this.setState({ data }); // Crashes if component is destroyed
41
+ });
42
+ }
43
+ ```
44
+
45
+ See the `valdi-async` skill for comprehensive CancelablePromise patterns.
46
+
47
+ ## HTTPClient error handling
48
+
49
+ `HTTPClient` is an instance, not static. Methods return `CancelablePromise<HTTPResponse>`.
50
+
51
+ ```tsx
52
+ import { HTTPClient } from 'valdi_http/src/HTTPClient';
53
+
54
+ private httpClient = new HTTPClient('https://api.example.com');
55
+
56
+ // ✅ Handle network errors with lifecycle safety
57
+ private fetchData = () => {
58
+ const cancelable = this.httpClient.get('/data');
59
+ this.registerDisposable(() => cancelable.cancel?.());
60
+ cancelable.then(
61
+ response => {
62
+ if (response.statusCode !== 200) {
63
+ this.setState({ error: `HTTP ${response.statusCode}`, loading: false });
64
+ return;
65
+ }
66
+ const decoder = new TextDecoder();
67
+ const data = JSON.parse(decoder.decode(response.body));
68
+ this.setState({ data, loading: false });
69
+ },
70
+ error => {
71
+ this.setState({ error: (error as Error).message, loading: false });
72
+ },
73
+ );
74
+ };
75
+ ```
76
+
77
+ `HTTPResponse` shape: `{ statusCode: number, headers: StringMap<string>, body?: Uint8Array }`. Decode `body` with `TextDecoder` before parsing.
78
+
79
+ ## isDestroyed() guard
80
+
81
+ For callbacks that can't use CancelablePromise (e.g., native callbacks, timers):
82
+
83
+ ```tsx
84
+ // ✅ Guard against use-after-destroy
85
+ private onNativeCallback = (result: string) => {
86
+ if (this.isDestroyed()) return;
87
+ this.setState({ result });
88
+ };
89
+ ```
90
+
91
+ `isDestroyed()` is a method — always call with parentheses.
92
+
93
+ ## try/catch in async methods
94
+
95
+ ```tsx
96
+ import { promiseToCancelablePromise } from 'valdi_core/src/CancelablePromise';
97
+
98
+ // ✅ Catch errors from async operations
99
+ private loadProfile = () => {
100
+ const cancelable = promiseToCancelablePromise(
101
+ (async () => {
102
+ try {
103
+ const profile = await this.api.getProfile();
104
+ return { profile, error: undefined };
105
+ } catch (e) {
106
+ return { profile: undefined, error: (e as Error).message };
107
+ }
108
+ })(),
109
+ () => {},
110
+ );
111
+ this.registerDisposable(() => cancelable.cancel?.());
112
+
113
+ cancelable.then(result => {
114
+ this.setState({
115
+ profile: result.profile,
116
+ error: result.error,
117
+ loading: false,
118
+ });
119
+ });
120
+ };
121
+ ```
122
+
123
+ ## Error states in UI
124
+
125
+ ```tsx
126
+ // ✅ Show error state to the user
127
+ onRender(): void {
128
+ if (this.state.loading) {
129
+ <AnimationShimmer width="100%" height={200} />;
130
+ return;
131
+ }
132
+
133
+ if (this.state.error) {
134
+ <view alignItems="center" justifyContent="center" padding={16}>
135
+ <label value="Something went wrong" font={systemBoldFont(16)} />
136
+ <label value={this.state.error} color="#999" />
137
+ <CoreButton text="Retry" onTap={this.handleRetry} />
138
+ </view>;
139
+ return;
140
+ }
141
+
142
+ <label value={this.state.data.name} />;
143
+ }
144
+ ```
145
+
146
+ ## Defensive ViewModel access
147
+
148
+ ViewModels come from parent components and may have optional fields:
149
+
150
+ ```tsx
151
+ // ✅ Defensive access with defaults
152
+ onRender(): void {
153
+ const title = this.viewModel.title ?? 'Untitled';
154
+ const items = this.viewModel.items ?? [];
155
+
156
+ <view>
157
+ <label value={title} />
158
+ {items.forEach(item => { <label value={item.name} />; })}
159
+ </view>;
160
+ }
161
+ ```
162
+
163
+ ## Timer cleanup
164
+
165
+ ```tsx
166
+ // ✅ Use setTimeoutDisposable for automatic cleanup
167
+ onCreate() {
168
+ this.setTimeoutDisposable(this.tick, 1000);
169
+ }
170
+ ```
171
+
172
+ ```tsx
173
+ // ✅ Manual cleanup for setInterval
174
+ private timerId?: number;
175
+
176
+ onCreate() {
177
+ this.timerId = setInterval(this.tick, 1000);
178
+ }
179
+
180
+ onDestroy() {
181
+ if (this.timerId !== undefined) {
182
+ clearInterval(this.timerId);
183
+ }
184
+ }
185
+ ```
186
+
187
+ Or use `registerDisposable` with a disposable wrapper — see `valdi-async` skill.
188
+
189
+ ## Common mistakes
190
+
191
+ ```tsx
192
+ // ❌ WRONG — HTTPClient is not static
193
+ const data = await HTTPClient.send(request); // No static send() method
194
+
195
+ // ✅ Correct — instantiate then call methods
196
+ const client = new HTTPClient('https://api.example.com');
197
+ const cancelable = client.get('/data');
198
+
199
+ // ❌ WRONG — .catch() is not available on CancelablePromise
200
+ cancelable.catch(error => { ... }); // CancelablePromise only has .then()
201
+
202
+ // ✅ Correct — use second argument of .then() for error handling
203
+ cancelable.then(
204
+ response => { /* success */ },
205
+ error => { /* failure */ },
206
+ );
207
+
208
+ // ❌ WRONG — React error boundaries don't exist
209
+ <ErrorBoundary fallback={<Error />}> // Not a Valdi concept
210
+ <MyComponent />
211
+ </ErrorBoundary>
212
+
213
+ // ❌ WRONG — window.onerror / global error handlers
214
+ window.addEventListener('error', handler); // No window object
215
+
216
+ // ❌ WRONG — isDestroyed without parentheses
217
+ if (this.isDestroyed) return; // It's a method, not a property
218
+
219
+ // ✅ Correct
220
+ if (this.isDestroyed()) return;
221
+
222
+ // ❌ WRONG — Passing CancelablePromise directly to registerDisposable
223
+ this.registerDisposable(cancelable); // Wrong type
224
+
225
+ // ✅ Correct — wrap cancel in a callback
226
+ this.registerDisposable(() => cancelable.cancel?.());
227
+ ```
228
+
229
+ ## Summary
230
+
231
+ | Pattern | When to use |
232
+ |---------|------------|
233
+ | `promiseToCancelablePromise` + `registerDisposable` | Any async work in a component |
234
+ | `isDestroyed()` guard | Native callbacks, external event handlers |
235
+ | `try/catch` | Operations that can throw |
236
+ | Error state in UI | User-facing failure recovery |
237
+ | `onDestroy` cleanup | Timers, subscriptions, manual resources |
238
+ | `setTimeoutDisposable` | One-shot timers (auto-cleaned) |