@snap/valdi 1.0.11 → 1.1.5

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 (68) hide show
  1. package/.metadata/.bazelrc.template +6 -5
  2. package/.metadata/MODULE.bazel.template +62 -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-component-dedup/skill.md +263 -0
  7. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
  8. package/bundled-skills/skills/valdi-custom-view/skill.md +43 -1
  9. package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
  10. package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
  11. package/bundled-skills/skills/valdi-inspect/skill.md +19 -1
  12. package/bundled-skills/skills/valdi-localization/skill.md +142 -0
  13. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
  14. package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
  15. package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
  16. package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
  17. package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
  18. package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
  19. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
  20. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
  21. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
  22. package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
  23. package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
  24. package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
  25. package/bundled-skills/skills/valdi-overview/skill.md +7 -4
  26. package/bundled-skills/skills/valdi-perf/skill.md +223 -0
  27. package/bundled-skills/skills/valdi-polyglot-module/skill.md +80 -0
  28. package/bundled-skills/skills/valdi-preview/skill.md +303 -0
  29. package/bundled-skills/skills/valdi-setup/skill.md +55 -5
  30. package/bundled-skills/skills/valdi-testing/skill.md +23 -7
  31. package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
  32. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
  33. package/dist/commands/agentCheck.js +184 -0
  34. package/dist/commands/analyze.js +16 -0
  35. package/dist/commands/analyze_commands/duplicates.js +134 -0
  36. package/dist/commands/bootstrap.js +57 -73
  37. package/dist/commands/doctor.js +40 -203
  38. package/dist/commands/hotreload.js +15 -0
  39. package/dist/commands/inspect_commands/snapshot.js +71 -6
  40. package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
  41. package/dist/commands/preview.js +81 -0
  42. package/dist/commands/projectsync.js +9 -7
  43. package/dist/commands/skills_commands/install.js +6 -1
  44. package/dist/commands/skills_commands/update.js +2 -1
  45. package/dist/core/analyze/clusterer.js +150 -0
  46. package/dist/core/analyze/fingerprint.js +2 -0
  47. package/dist/core/analyze/knownPatterns.js +76 -0
  48. package/dist/core/analyze/parser.js +177 -0
  49. package/dist/core/analyze/reporter.js +83 -0
  50. package/dist/core/analyze/scanner.js +172 -0
  51. package/dist/core/analyze/similarity.js +56 -0
  52. package/dist/core/constants.js +1 -1
  53. package/dist/core/packageFiles.spec.js +1 -1
  54. package/dist/preview/previewGenerator.js +240 -0
  55. package/dist/preview/previewGenerator.spec.js +203 -0
  56. package/dist/preview/viewModelParser.js +86 -0
  57. package/dist/preview/viewModelParser.spec.js +171 -0
  58. package/dist/setup/DevSetupHelper.js +0 -51
  59. package/dist/setup/linuxSetup.js +0 -2
  60. package/dist/setup/macOSSetup.js +1 -4
  61. package/dist/utils/BazelClient.js +15 -0
  62. package/dist/utils/daemonClient.js +3 -1
  63. package/dist/utils/skillsAdapters.js +86 -5
  64. package/dist/utils/skillsAdapters.spec.js +60 -0
  65. package/dist/utils/skillsRegistry.js +8 -0
  66. package/package.json +16 -8
  67. package/.metadata/WORKSPACE.template +0 -57
  68. package/dist/setup/versions.js +0 -8
@@ -195,3 +195,226 @@ class MyCard extends Component<MyViewModel> {
195
195
  ```
196
196
 
197
197
  Group styles in a `const styles = {}` object after the class definition.
198
+
199
+ ## Observable Subscriptions in `onCreate()` Block First Paint
200
+
201
+ Calling `.subscribe()` on a BridgeObservable during `onCreate()` creates the
202
+ native bridge and runs the initial value flow synchronously, delaying first
203
+ paint. Each subscription compounds the delay, and `combineLatest` over several
204
+ sources makes it worse because every bridge is established before the
205
+ component can paint.
206
+
207
+ ```typescript
208
+ // ❌ Each subscription adds synchronous work before first paint
209
+ onCreate(): void {
210
+ this.registerDisposable(this.context.dataUpdates.subscribe(d => this.setState({ data: d })));
211
+ this.registerDisposable(this.context.statusUpdates.subscribe(s => this.setState({ status: s })));
212
+ }
213
+ ```
214
+
215
+ Defer subscriptions whose data isn't needed for first paint by wrapping in
216
+ `setTimeout(0)`, pushing them to the next tick:
217
+
218
+ ```typescript
219
+ // ✅ Critical stays synchronous; non-critical deferred to next tick
220
+ onCreate(): void {
221
+ this.registerDisposable(this.context.essentialData.subscribe(d => this.setState({ data: d })));
222
+
223
+ const tag = setTimeout(() => {
224
+ this.registerDisposable(this.context.badgeCount.subscribe(c => this.setState({ badgeCount: c })));
225
+ }, 0);
226
+ this.registerDisposable({ unsubscribe: () => clearTimeout(tag) });
227
+ }
228
+ ```
229
+
230
+ Only defer subscriptions whose data isn't needed for the initial render.
231
+ Deferring something the first paint depends on (primary content, user identity)
232
+ causes a visible empty-then-populated flash.
233
+
234
+ ## Moving heavy computation to a Worker Service
235
+
236
+ TypeScript in Valdi runs on a single-threaded event loop. Inherently expensive
237
+ TypeScript work competes with Valdi rendering on that same thread. A Worker
238
+ Service moves the work to a separate Worker thread with its own JS heap, so the
239
+ host thread stays free.
240
+
241
+ **When to reach for it:** business logic that involves expensive synchronous
242
+ TypeScript (parsing, transforms, in-language computation) and the caller can
243
+ tolerate an asynchronous API. All host↔worker calls are promise-based.
244
+
245
+ **Why it isn't free:**
246
+ - Workers have their own memory heap. Arguments and return values are deep-copied
247
+ across the boundary on every call. Design APIs to send infrequent, coarse-grained
248
+ batches rather than many small calls.
249
+ - Bridged TypeScript functions cannot return values synchronously. Anything that
250
+ needs an inline value cannot live on a worker.
251
+ - Only own properties of an object are copied across the boundary. Instance
252
+ methods on plain TypeScript classes are stripped; use `@ExportProxy`-backed
253
+ native objects when methods must survive the crossing.
254
+ - Each `WorkerServiceExecutors` value is its own thread + heap. Adding executors
255
+ raises overall memory usage; passing objects across different executors also
256
+ clones.
257
+ - Mutex-protected shared mutable state across threads (as in C++/Swift/Kotlin)
258
+ is not supported.
259
+
260
+ **Don't confuse with `setTimeout(0)`.** `setTimeout(0)` reschedules work to a
261
+ later tick on the same JS thread, so the work still runs on the rendering
262
+ thread, just later. A Worker Service moves the work to a different thread.
263
+
264
+ **API entry points:** `startWorkerService`, `useOrStartWorkerService`,
265
+ `startWorkerServiceInForeground`, `useWorkerService`, `useWorkerServiceSingleton`.
266
+ A service is declared by a `WorkerServiceEntryPoint` subclass annotated with
267
+ `@workerService(executor, module)`. See the Valdi docs for the full API.
268
+ Always call `dispose()` on the returned client; the service otherwise stays in
269
+ memory.
270
+
271
+ ## Deferring construction until it's needed
272
+
273
+ Three Valdi-supported ways to push work past startup, from a single field to
274
+ a whole module:
275
+
276
+ ### Field-level: `Lazy<T>`
277
+
278
+ Wrap construction of an expensive instance field in `Lazy<T>` from
279
+ `foundation/src/Lazy`. The thunk runs once on first read of `.target`, then
280
+ caches the result and drops itself so captured closure refs become GC-eligible.
281
+ Use for fields needed only on conditional code paths (taps, modal openings,
282
+ error flows).
283
+
284
+ ```typescript
285
+ import { Lazy } from 'foundation/src/Lazy';
286
+
287
+ // ❌ Pays construction cost at instantiation, even if never read
288
+ private readonly defaultStatus = this.statusProvider.getDefaultStatus();
289
+
290
+ // ✅ Constructed on first .target read, then cached
291
+ private readonly defaultStatus = new Lazy(() => this.statusProvider.getDefaultStatus());
292
+
293
+ // Read site:
294
+ const status = this.defaultStatus.target;
295
+ ```
296
+
297
+ Good fits: expensive dependency resolution, derived collections, formatters,
298
+ parsers, anything you would otherwise build in the constructor "just in case".
299
+
300
+ ### Context dependencies: `Provider<T>`
301
+
302
+ Type a context field as `Provider<T>` (from `foundation/src/Provider`) instead
303
+ of `T` to defer native DI construction until the component calls `.get()`. Use
304
+ for context dependencies that are expensive to construct natively and only
305
+ needed on conditional code paths.
306
+
307
+ ```typescript
308
+ import { Provider } from 'foundation/src/Provider';
309
+
310
+ export interface MyContext {
311
+ storyPlayer: IStoryPlayer; // ❌ Built at context creation
312
+ storyPlayer: Provider<IStoryPlayer>; // ✅ Built on first .get() call
313
+ }
314
+
315
+ // Read site:
316
+ const player = this.context.storyPlayer.get();
317
+ ```
318
+
319
+ Wrap with `providerToLazy` for a TS-side cache when `.get()` is read repeatedly:
320
+
321
+ ```typescript
322
+ import { providerToLazy } from 'foundation/src/Provider';
323
+
324
+ private readonly storyPlayer = providerToLazy(this.context.storyPlayer);
325
+ const player = this.storyPlayer.target; // first read invokes Provider.get(), cached
326
+ ```
327
+
328
+ ### Whole modules: dynamic `import()`
329
+
330
+ The Valdi compiler supports `await import('module/path')` for code-splitting.
331
+ The imported module is parsed and initialised on first use, then cached.
332
+
333
+ ```typescript
334
+ // ❌ Top-of-file: pays parse + init cost at startup, even if never used
335
+ import { HeavyScreen } from './HeavyScreen';
336
+ this.navigationController.target?.present(HeavyScreen, ...);
337
+
338
+ // ✅ Dynamic: module loads on first call, then cached
339
+ const { HeavyScreen } = await import('./HeavyScreen');
340
+ this.navigationController.target?.present(HeavyScreen, ...);
341
+ ```
342
+
343
+ **Pays off when:** the module is large or has expensive top-level initialisation
344
+ and the code path is conditional (modals, edit flows, error views) where most
345
+ users never hit it.
346
+
347
+ **Skip when:** the module is needed on the initial render path (dynamic import
348
+ adds an async tick) or the module is tiny (savings are negligible).
349
+
350
+ ## Excessive `setState` calls
351
+
352
+ `setState` runs synchronously: each call merges state and immediately
353
+ re-renders. There is no frame-level batching, so N calls in a row produce
354
+ N renders.
355
+
356
+ ```typescript
357
+ // ❌ Three renders for one logical update
358
+ this.setState({ items });
359
+ this.setState({ loading: false });
360
+ this.setState({ lastFetchedAt: now });
361
+
362
+ // ✅ One render
363
+ this.setState({ items, loading: false, lastFetchedAt: now });
364
+ ```
365
+
366
+ Common high-frequency sources:
367
+ - **Frequently-emitting Observables (especially BridgeObservables).** A single
368
+ `setState` inside `.subscribe()` looks innocent but renders N times if the
369
+ Observable emits N times for the same logical change. Fix upstream of the
370
+ subscribe call: `distinctUntilChanged(arrayEquals)` / `distinctUntilChanged(setsEquivalent)`
371
+ for object emissions (default identity check won't dedup freshly-allocated
372
+ arrays/sets), or `debounceTime(...)` for chatty streams that would cause
373
+ visible flicker. For a BridgeObservable, also check whether the native
374
+ producer is emitting per-field instead of batching related changes; the real
375
+ fix may live there.
376
+ - Scroll, drag, and animation-tick callbacks. Throttle, debounce, or use
377
+ `setStateAnimated` rather than per-frame `setState`.
378
+ - Loops that emit items as they arrive. Accumulate locally and `setState` once
379
+ at the end of the batch.
380
+ - `onViewModelUpdate` that calls `setState` unconditionally. Guard with
381
+ `if (this.viewModel.x !== previous?.x)` so unrelated viewModel updates don't
382
+ trigger work.
383
+
384
+ ## Re-subscribing to expensive observables
385
+
386
+ Each `.subscribe()` runs the producer chain from scratch (HTTP, query, expensive
387
+ transform). Two callsite patterns make this costly:
388
+ - Multiple subscribers to the same source.
389
+ - A `switchMap` that swaps inner observables. Each switch tears down the
390
+ previous subscription and starts a fresh producer chain.
391
+
392
+ `cacheObservable(disposable)` from
393
+ `rxjs_extensions/src/operators/cacheObservable` shares a single subscription
394
+ behind `shareReplaySafe`. The disposable (usually the owning class's lifetime)
395
+ keeps the cache alive; all subscribers and `switchMap` re-subscriptions get
396
+ the cached emission instead of re-running the producer.
397
+
398
+ ```typescript
399
+ import { cacheObservable } from 'rxjs_extensions/src/operators/cacheObservable';
400
+ import { startWithTimeout } from 'rxjs_extensions/src/operators/startWithTimeout';
401
+
402
+ class FriendSearcher {
403
+ // ❌ Every subscriber re-runs the whole producer chain
404
+ private readonly results$ = this.source$.pipe(
405
+ map(friends => buildIndex(friends)),
406
+ );
407
+
408
+ // ✅ Producer runs once; downstream subscribers and switchMap
409
+ // re-subscriptions hit the cache.
410
+ private readonly results$ = this.source$.pipe(
411
+ map(friends => buildIndex(friends)),
412
+ startWithTimeout([], 500),
413
+ cacheObservable(this.disposable),
414
+ );
415
+ }
416
+ ```
417
+
418
+ Smell: a `switchMap` whose inner observable does HTTP or expensive computation
419
+ with no caching upstream. Each switch tears down the previous subscription
420
+ and starts a fresh producer chain.
@@ -117,8 +117,88 @@ See `valdi_polyglot` module for a complete working example with all four platfor
117
117
  - `src/composer_modules/src/composer/valdi_polyglot/` (in the Snap monorepo)
118
118
  - Or the equivalent path in your project
119
119
 
120
+ ## macOS Native View with Attribute Binding
121
+
122
+ macOS `<custom-view>` implementations can receive callback attributes from TSX via `SCValdiMacOSFunction`. This is how you bridge events (like keyboard input) from native AppKit views back to Valdi components.
123
+
124
+ ### Native Side (Objective-C)
125
+
126
+ ```objc
127
+ // macos/SCMyView.h
128
+ #import <AppKit/AppKit.h>
129
+ @class SCValdiMacOSAttributesBinder;
130
+
131
+ @interface SCMyView : NSView
132
+ + (void)bindAttributes:(SCValdiMacOSAttributesBinder *)attributesBinder;
133
+ @end
134
+
135
+ // macos/SCMyView.m
136
+ #import "SCMyView.h"
137
+ #import "valdi/macos/SCValdiMacOSAttributesBinder.h"
138
+ #import "valdi/macos/SCValdiMacOSFunction.h"
139
+
140
+ @interface SCMyView () {
141
+ SCValdiMacOSFunction *_onEvent;
142
+ }
143
+ @end
144
+
145
+ @implementation SCMyView
146
+
147
+ - (void)valdi_setOnEvent:(id)value {
148
+ _onEvent = value;
149
+ }
150
+
151
+ // Call the Valdi callback with a dictionary parameter:
152
+ // [_onEvent performWithParameters:@[@{@"key": @"ArrowUp"}]];
153
+
154
+ + (void)bindAttributes:(SCValdiMacOSAttributesBinder *)attributesBinder {
155
+ [attributesBinder bindUntypedAttribute:@"onEvent"
156
+ invalidateLayoutOnChange:NO
157
+ selector:@selector(valdi_setOnEvent:)];
158
+ }
159
+ @end
160
+ ```
161
+
162
+ ### TSX Side
163
+
164
+ ```typescript
165
+ <custom-view
166
+ macosClass='SCMyView'
167
+ onEvent={this.handleEvent}
168
+ width={200}
169
+ height={200}
170
+ >
171
+ {/* child elements render inside the custom-view */}
172
+ </custom-view>
173
+ ```
174
+
175
+ ### BUILD.bazel
176
+
177
+ ```python
178
+ objc_library(
179
+ name = "macos_impl",
180
+ srcs = glob(["macos/**/*.m"]),
181
+ hdrs = glob(["macos/**/*.h"]),
182
+ copts = ["-I."],
183
+ sdk_frameworks = ["AppKit"],
184
+ visibility = ["//visibility:public"],
185
+ deps = ["@valdi//valdi:valdi_macos_desktop_lib"],
186
+ )
187
+ ```
188
+
189
+ ### Key Points
190
+
191
+ - The attribute name in `bindUntypedAttribute:` must match the TSX attribute name exactly (e.g. `"onEvent"` ↔ `onEvent={...}`)
192
+ - Callback values arrive as `SCValdiMacOSFunction` objects — call `[callback performWithParameters:@[...]]` to invoke the Valdi/JS function
193
+ - Parameters are passed as an `NSArray` of `NSDictionary`/`NSString`/`NSNumber` — they're auto-converted to JS objects
194
+ - **The custom-view must have non-zero dimensions** to participate in the responder chain (for keyboard focus, etc.)
195
+ - For keyboard input: override `acceptsFirstResponder` → `YES`, `keyDown:`, and call `[self.window makeFirstResponder:self]` in `viewDidMoveToWindow`
196
+ - Add `bazel_build_file_generation_disabled: true` to `module.yaml` when hand-maintaining the BUILD file (prevents the regenerate script from overwriting it)
197
+
120
198
  ## Common Mistakes
121
199
 
122
200
  - Putting `web/` files in `srcs` — they must go through `ts_project` + `web_deps`, not the Valdi compiler
123
201
  - Missing platform `_deps` — each platform impl must be wired via `android_deps`, `ios_deps`, `macos_deps`
124
202
  - Using Valdi imports in `web/` — they don't exist in the browser bundle
203
+ - Creating a 0×0 custom-view for keyboard input — macOS won't give it first responder status; wrap visible content inside it instead
204
+ - Forgetting `bazel_build_file_generation_disabled: true` in module.yaml — the regenerate script will overwrite your hand-maintained BUILD and drop the `macos_deps`/`ios_deps`
@@ -0,0 +1,303 @@
1
+ # valdi-preview
2
+
3
+ Use this skill to **understand and visually preview a Valdi module or component** — read its API, render it in the preview harness app, inspect the view hierarchy, and capture a screenshot.
4
+
5
+ ## When to use
6
+
7
+ - You need to understand what a Valdi component looks like before using it
8
+ - You want to see a component's rendered output to verify your code
9
+ - User asks "what does X component look like?" or "show me how X renders"
10
+ - You're building a UI and need to evaluate which widget to use
11
+ - You want to explore a component's API (viewModel, slots, styling)
12
+
13
+ ## Overview
14
+
15
+ The workflow has two phases:
16
+
17
+ 1. **Static analysis** — read source files to understand the component's API
18
+ 2. **Live preview** (optional) — render it in the preview harness, inspect the tree, screenshot it
19
+
20
+ You can stop after phase 1 if you only need API understanding. Phase 2 requires a running app.
21
+
22
+ ---
23
+
24
+ ## Phase 1: Understand the component
25
+
26
+ ### Step 1: Find the module source
27
+
28
+ Given a component name or module path, locate its source files:
29
+
30
+ ```bash
31
+ # Find by component class name
32
+ grep -r "export class CoreButton" --include="*.tsx" --include="*.ts"
33
+
34
+ # Find by module name in BUILD.bazel
35
+ grep -r "name = \"valdi_widgets_core\"" --include="BUILD.bazel"
36
+ ```
37
+
38
+ ### Step 2: Read the API surface
39
+
40
+ Read the component's main `.tsx` file and look for:
41
+
42
+ 1. **ViewModel interface** — the props the component accepts. Look for `@ViewModel` JSDoc tag:
43
+ ```typescript
44
+ /**
45
+ * @ViewModel
46
+ */
47
+ export interface CoreButtonViewModel {
48
+ title: string;
49
+ onPress: () => void;
50
+ disabled?: boolean;
51
+ }
52
+ ```
53
+
54
+ 2. **Component class** — the rendering logic. Look for `@Component` JSDoc tag and the `onRender()` method.
55
+
56
+ 3. **Slots** — child content areas. Look for `AnyRenderFunction` or `$slot` usage in the viewModel or render.
57
+
58
+ 4. **JSDoc** — descriptions, `@example` tags, parameter docs.
59
+
60
+ 5. **State interface** — if it's a `StatefulComponent`, read the state shape.
61
+
62
+ ### Step 3: Find usage examples
63
+
64
+ Search the codebase for real usage of the component:
65
+
66
+ ```bash
67
+ # Find files that import this component
68
+ grep -r "import.*CoreButton" --include="*.tsx" --include="*.ts" -l
69
+
70
+ # Find JSX usage
71
+ grep -r "<CoreButton" --include="*.tsx"
72
+ ```
73
+
74
+ Pick 2-3 representative usages to understand common prop combinations.
75
+
76
+ ### Step 4: Summarize
77
+
78
+ Report to the user:
79
+ - Component name and location
80
+ - ViewModel props (required and optional)
81
+ - What it renders (layout structure from `onRender()`)
82
+ - How it's typically used (from real examples)
83
+
84
+ ---
85
+
86
+ ## Phase 2: Live preview
87
+
88
+ ### Option A: `valdi preview` CLI (recommended)
89
+
90
+ The fastest path — automatically generates the preview harness and builds:
91
+
92
+ ```bash
93
+ # By import path
94
+ valdi preview widgets/src/components/button/Checkbox
95
+
96
+ # By file path
97
+ valdi preview ./valdi_modules/widgets/src/components/button/Checkbox.tsx
98
+ ```
99
+
100
+ This command:
101
+ 1. Resolves the component file
102
+ 2. Parses the ViewModel to extract props
103
+ 3. Generates `apps/preview/PreviewRoot.tsx` with sample props and interactive state
104
+ 4. Generates `apps/preview/BUILD.bazel` with correct deps
105
+ 5. Generates `apps/preview/tsconfig.json` with correct path mappings
106
+ 6. Builds and launches `//apps/preview:preview_app_macos`
107
+
108
+ First build takes 2-5 minutes; subsequent builds ~5-15 seconds.
109
+
110
+ ### Option B: Manual harness setup
111
+
112
+ For full control or when `valdi preview` doesn't support your use case.
113
+
114
+ Requires a running Valdi app. If no app is running, tell the user to start one first.
115
+
116
+ ### Step 1: Edit the preview harness
117
+
118
+ The preview harness app lives at `apps/preview/` in the Valdi repo. It has three files:
119
+
120
+ | File | Purpose |
121
+ |------|---------|
122
+ | `PreviewRoot.tsx` | Root component — **edit this** to render your target |
123
+ | `BUILD.bazel` | Module deps — **add deps here** if the target is in another module |
124
+ | `tsconfig.json` | Path mappings — **add path entries** for new module deps |
125
+
126
+ **Edit `PreviewRoot.tsx`** to import and render the target component:
127
+
128
+ ```typescript
129
+ import { Component } from 'valdi_core/src/Component';
130
+ import { CoreButton } from 'valdi_widgets_core/src/components/button/CoreButton';
131
+
132
+ /**
133
+ * @ViewModel
134
+ * @ExportModel
135
+ */
136
+ export interface ViewModel {}
137
+
138
+ /**
139
+ * @Context
140
+ * @ExportModel
141
+ */
142
+ export interface ComponentContext {}
143
+
144
+ /**
145
+ * @Component
146
+ * @ExportModel
147
+ */
148
+ export class PreviewRoot extends Component<ViewModel, ComponentContext> {
149
+ onRender(): void {
150
+ <view backgroundColor="#ffffff" width="100%" height="100%" padding={24}
151
+ alignItems="center" justifyContent="center">
152
+ <CoreButton title="Example Button" onPress={() => {}} />
153
+ </view>;
154
+ }
155
+ }
156
+ ```
157
+
158
+ **If the component is in another module**, add it to `BUILD.bazel` deps:
159
+
160
+ ```python
161
+ deps = [
162
+ "//src/valdi_modules/src/valdi/valdi_core",
163
+ "//src/valdi_modules/src/valdi/valdi_tsx",
164
+ "//path/to/target_module", # Add this
165
+ ],
166
+ ```
167
+
168
+ And add the path mapping to `tsconfig.json`:
169
+
170
+ ```json
171
+ {
172
+ "compilerOptions": {
173
+ "paths": {
174
+ "target_module/*": ["../../path/to/target_module/*"]
175
+ }
176
+ }
177
+ }
178
+ ```
179
+
180
+ ### Step 2: Build and hot-reload
181
+
182
+ **Recommended workflow** — build once, then use hot-reload for instant iteration:
183
+
184
+ ```bash
185
+ # 1. Build the macOS app once
186
+ bazel build //apps/preview:preview_app_macos
187
+
188
+ # 2. Launch it directly (stays alive as background process)
189
+ open bazel-bin/apps/preview/preview_app_macos_archive-root/Valdi\ Preview.app
190
+
191
+ # 3. Start the hot-reloader
192
+ valdi hotreload --target //apps/preview:preview_app_hotreload
193
+ ```
194
+
195
+ Now any edit to `PreviewRoot.tsx` is automatically recompiled and pushed to the running app in ~1s.
196
+
197
+ **Alternative** — full rebuild (slower but simpler):
198
+
199
+ ```bash
200
+ # macOS (fastest for preview)
201
+ bazel run //apps/preview:preview_app_macos
202
+
203
+ # iOS simulator
204
+ bazel run //apps/preview:preview_app_ios_sim
205
+ ```
206
+
207
+ ### Step 3: Inspect the rendered output
208
+
209
+ Once the component is on screen, use **port 13591** for standalone macOS apps:
210
+
211
+ ```bash
212
+ # Capture a screenshot by component name (stable across hot-reloads)
213
+ valdi inspect snapshot --key PreviewRoot --port 13591
214
+
215
+ # Or by a custom key prop you set on an element
216
+ valdi inspect snapshot --key my-card --port 13591
217
+
218
+ # Or by numeric element ID (from tree output — changes on each hot-reload)
219
+ valdi inspect snapshot <elementId> 2 --port 13591
220
+ ```
221
+
222
+ **Prefer `--key`** — it resolves the component tag or element key to its numeric ID automatically, so you don't need to re-query the tree after every hot-reload.
223
+
224
+ If you're previewing inside a mobile app (Snapchat, etc.), use the default port 13592 instead.
225
+
226
+ Then read the PNG file to see what it looks like.
227
+
228
+ ### Step 4: Iterate
229
+
230
+ If the rendering doesn't look right:
231
+
232
+ 1. Adjust props, styles, or container layout in `PreviewRoot.tsx`
233
+ 2. Hot-reload picks up the change automatically (~1s)
234
+ 3. Re-query tree for new element IDs, then `valdi inspect snapshot`
235
+ 4. Repeat until the component renders as expected
236
+
237
+ **Iteration priority** — for fastest convergence, fix in this order:
238
+ 1. Font sizes (almost always too small on first pass)
239
+ 2. Vertical spacing between sections
240
+ 3. Text colors
241
+ 4. Element sizing (padding, border radius)
242
+ 5. Decorative elements (fills, shadows)
243
+
244
+ ---
245
+
246
+ ## Previewing multiple components
247
+
248
+ To compare several components side by side, render them all in `PreviewRoot.tsx`:
249
+
250
+ ```typescript
251
+ onRender(): void {
252
+ <view backgroundColor="#ffffff" width="100%" height="100%" padding={24}>
253
+ <scroll height="100%" width="100%">
254
+ <label value="CoreButton" font="system-bold 14" color="#666" marginBottom={8} />
255
+ <CoreButton title="Primary" onPress={() => {}} />
256
+
257
+ <view height={24} />
258
+
259
+ <label value="PillButton" font="system-bold 14" color="#666" marginBottom={8} />
260
+ <PillButton title="Secondary" onPress={() => {}} />
261
+ </scroll>
262
+ </view>;
263
+ }
264
+ ```
265
+
266
+ ---
267
+
268
+ ## Previewing with sample data
269
+
270
+ When a component needs complex viewModel data, create realistic sample data:
271
+
272
+ ```typescript
273
+ // For a component that needs a list of items
274
+ const sampleItems = [
275
+ { id: '1', title: 'First item', subtitle: 'Description' },
276
+ { id: '2', title: 'Second item', subtitle: 'Another one' },
277
+ { id: '3', title: 'Third item', subtitle: 'And another' },
278
+ ];
279
+
280
+ onRender(): void {
281
+ <MyListComponent items={sampleItems} onItemTap={() => {}} />;
282
+ }
283
+ ```
284
+
285
+ ---
286
+
287
+ ## Cleanup
288
+
289
+ After previewing, restore `PreviewRoot.tsx` to its placeholder state so the harness is ready for the next preview. Revert any deps added to `BUILD.bazel` and `tsconfig.json` unless the user wants to keep them.
290
+
291
+ ---
292
+
293
+ ## Troubleshooting
294
+
295
+ **"Module not found"** — You forgot to add the dep to `BUILD.bazel` or the path mapping to `tsconfig.json`.
296
+
297
+ **"Cannot resolve import"** — The tsconfig path is wrong. Check the relative path from `apps/preview/` to the target module.
298
+
299
+ **Hot-reload not picking up changes** — Stop and restart `valdi hotreload`. If that doesn't work, do a full `bazel run`.
300
+
301
+ **"Valdi daemon not running"** — The app isn't running. Build and launch it first with `bazel run`.
302
+
303
+ **Component renders blank** — Check that you're passing all required viewModel props. Read the ViewModel interface again.