@snap/valdi 1.0.8 → 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 (121) hide show
  1. package/.bootstrap/apps/cli_application/BUILD.bazel.template +7 -0
  2. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +11 -0
  3. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +1 -0
  4. package/.bootstrap/apps/ui_application/.eslint.rc +27 -0
  5. package/.bootstrap/apps/ui_application/BUILD.bazel.template +19 -0
  6. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +21 -0
  7. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  8. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +133 -0
  9. package/.bootstrap/apps/ui_application/package.json +24 -0
  10. package/.bootstrap/modules/polyglot_bridge_module/BUILD.bazel.template +54 -0
  11. package/.bootstrap/modules/polyglot_bridge_module/android/CalculatorModuleFactory.kt.template +18 -0
  12. package/.bootstrap/modules/polyglot_bridge_module/ios/SCCCalculatorModuleFactory.m.template +31 -0
  13. package/.bootstrap/modules/polyglot_bridge_module/src/Calculator.d.ts +4 -0
  14. package/.bootstrap/modules/polyglot_bridge_module/web/Calculator.ts +11 -0
  15. package/.bootstrap/modules/polyglot_bridge_module/web/tsconfig.json +16 -0
  16. package/.bootstrap/modules/polyglot_view_module/BUILD.bazel.template +75 -0
  17. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeView.kt.template +41 -0
  18. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeViewAttributesBinder.kt.template +17 -0
  19. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.h +8 -0
  20. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.m +23 -0
  21. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.h +8 -0
  22. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.m +23 -0
  23. package/.bootstrap/modules/polyglot_view_module/src/PolyglotCustomView.tsx.template +23 -0
  24. package/.bootstrap/modules/polyglot_view_module/web/PolyglotWeb.ts.template +30 -0
  25. package/.bootstrap/modules/polyglot_view_module/web/tsconfig.json +16 -0
  26. package/.bootstrap/modules/ui_component/BUILD.bazel.template +34 -0
  27. package/.bootstrap/modules/ui_component/src/NewModuleComponent.tsx +45 -0
  28. package/.metadata/.bazelrc.template +92 -0
  29. package/.metadata/.bazelversion.template +1 -0
  30. package/.metadata/.editorconfig.template +37 -0
  31. package/.metadata/.eslintrc.js.template +27 -0
  32. package/.metadata/.gitignore.template +4 -0
  33. package/.metadata/.prettierrc.json.template +7 -0
  34. package/.metadata/.watchmanconfig.template +8 -0
  35. package/.metadata/AGENTS.md.template +16 -0
  36. package/.metadata/MODULE.bazel.template +62 -0
  37. package/.metadata/README.md.template +31 -0
  38. package/.metadata/config.yaml.template +1 -0
  39. package/.metadata/package.json.template +23 -0
  40. package/.metadata/skill-reference.tsx.template +8 -0
  41. package/.metadata/skill-tests-BUILD.bazel.template +21 -0
  42. package/.metadata/skill-tests-README.md.template +17 -0
  43. package/.metadata/skill.md.template +27 -0
  44. package/bundled-skills/registry.json +14 -2
  45. package/bundled-skills/skills/valdi-animations/skill.md +197 -0
  46. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +1 -1
  47. package/bundled-skills/skills/valdi-bazel/skill.md +21 -2
  48. package/bundled-skills/skills/valdi-component-dedup/skill.md +263 -0
  49. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
  50. package/bundled-skills/skills/valdi-custom-view/skill.md +49 -5
  51. package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
  52. package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
  53. package/bundled-skills/skills/valdi-inspect/skill.md +217 -0
  54. package/bundled-skills/skills/valdi-localization/skill.md +142 -0
  55. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
  56. package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
  57. package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
  58. package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
  59. package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
  60. package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
  61. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
  62. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
  63. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
  64. package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
  65. package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
  66. package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
  67. package/bundled-skills/skills/valdi-overview/skill.md +7 -4
  68. package/bundled-skills/skills/valdi-perf/skill.md +223 -0
  69. package/bundled-skills/skills/valdi-polyglot-module/skill.md +131 -12
  70. package/bundled-skills/skills/valdi-preview/skill.md +303 -0
  71. package/bundled-skills/skills/valdi-profile/skill.md +126 -0
  72. package/bundled-skills/skills/valdi-setup/skill.md +55 -5
  73. package/bundled-skills/skills/valdi-testing/skill.md +23 -7
  74. package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
  75. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
  76. package/dist/commands/agentCheck.js +184 -0
  77. package/dist/commands/analyze.js +16 -0
  78. package/dist/commands/analyze_commands/duplicates.js +134 -0
  79. package/dist/commands/bootstrap.js +57 -73
  80. package/dist/commands/doctor.js +40 -203
  81. package/dist/commands/hotreload.js +15 -0
  82. package/dist/commands/inspect.js +16 -0
  83. package/dist/commands/inspect_commands/contexts.js +55 -0
  84. package/dist/commands/inspect_commands/devices.js +53 -0
  85. package/dist/commands/inspect_commands/heap.js +59 -0
  86. package/dist/commands/inspect_commands/select.js +43 -0
  87. package/dist/commands/inspect_commands/snapshot.js +129 -0
  88. package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
  89. package/dist/commands/inspect_commands/status.js +68 -0
  90. package/dist/commands/inspect_commands/tree.js +86 -0
  91. package/dist/commands/preview.js +81 -0
  92. package/dist/commands/profile.js +16 -0
  93. package/dist/commands/profile_commands/capture.js +106 -0
  94. package/dist/commands/projectsync.js +9 -7
  95. package/dist/commands/skills_commands/install.js +6 -1
  96. package/dist/commands/skills_commands/update.js +2 -1
  97. package/dist/core/analyze/clusterer.js +150 -0
  98. package/dist/core/analyze/fingerprint.js +2 -0
  99. package/dist/core/analyze/knownPatterns.js +76 -0
  100. package/dist/core/analyze/parser.js +177 -0
  101. package/dist/core/analyze/reporter.js +83 -0
  102. package/dist/core/analyze/scanner.js +172 -0
  103. package/dist/core/analyze/similarity.js +56 -0
  104. package/dist/core/constants.js +1 -1
  105. package/dist/core/packageFiles.spec.js +29 -0
  106. package/dist/preview/previewGenerator.js +240 -0
  107. package/dist/preview/previewGenerator.spec.js +203 -0
  108. package/dist/preview/viewModelParser.js +86 -0
  109. package/dist/preview/viewModelParser.spec.js +171 -0
  110. package/dist/setup/DevSetupHelper.js +0 -51
  111. package/dist/setup/linuxSetup.js +0 -2
  112. package/dist/setup/macOSSetup.js +1 -4
  113. package/dist/utils/BazelClient.js +15 -0
  114. package/dist/utils/daemonClient.js +344 -0
  115. package/dist/utils/hermesClient.js +252 -0
  116. package/dist/utils/skillsAdapters.js +86 -5
  117. package/dist/utils/skillsAdapters.spec.js +60 -0
  118. package/dist/utils/skillsRegistry.js +8 -0
  119. package/dist/utils/stringUtils.spec.js +1 -1
  120. package/package.json +30 -12
  121. package/dist/setup/versions.js +0 -8
@@ -0,0 +1,451 @@
1
+ # valdi-mock-to-module
2
+
3
+ Turn a screenshot or design mock into a running Valdi module. Two-phase pipeline: get something visible fast (Phase 1), then refine with parallel specialist agents and pixel diff (Phase 2).
4
+
5
+ ## When to use
6
+
7
+ - User provides a screenshot or mock and says "build this" or "turn this into a Valdi component"
8
+ - User wants to go from visual design to running code
9
+ - User invokes `/valdi-mock-to-module`
10
+
11
+ ## Prerequisites
12
+
13
+ - A Valdi workspace (Valdi repo, Valdi_Widgets, or any repo with `valdi_modules/`)
14
+ - The `valdi` CLI installed and on PATH
15
+ - For live preview: macOS (uses `valdi_application` -> `_macos` target)
16
+ - Pillow for pixel diff: `pip3 install Pillow`
17
+
18
+ ---
19
+
20
+ ## CRITICAL RULES
21
+
22
+ These rules were learned the hard way. Violating them wastes time.
23
+
24
+ ### 1. NEVER kill the running app — ever
25
+
26
+ **Never** kill the macOS preview app or port 13591. The user keeps the app running across sessions. Killing it forces a slow rebuild/relaunch and loses window positioning.
27
+
28
+ At the start of the pipeline, only kill **hot-reloader processes** (valdi_compiler, valdi_companion, run_hotreloader, "valdi hotreload", port 9010). **Never** kill port 13591 or the app process.
29
+
30
+ During iteration, don't kill anything — just edit files and let hot-reload push changes.
31
+
32
+ ### 2. Check hot-reload log after EVERY edit
33
+
34
+ After EVERY file edit, immediately check compilation:
35
+
36
+ ```bash
37
+ tail -5 /tmp/hotreload.log
38
+ ```
39
+
40
+ - ✅ `Recompilation pass finished` with recent timestamp → success
41
+ - ❌ Error in YOUR file → fix before making more edits
42
+ - ⚠️ Errors in OTHER modules → ignore (pre-existing)
43
+
44
+ ### 3. Batch edits, then check once
45
+
46
+ Apply ALL specialist agent fixes in a single batch edit. Check the hot-reload log once after the batch. Then take one snapshot + diff. This is much faster than one-at-a-time edits. Only split edits if a batch fails to compile — then bisect to find the broken change.
47
+
48
+ ### 4. Phone-width frame for accurate proportions
49
+
50
+ PreviewRoot MUST wrap the component in a fixed 390px-wide container. Without this, the desktop window stretches the layout wider than a phone screen, making pixel diff useless.
51
+
52
+ ```tsx
53
+ onRender(): void {
54
+ <view key="PreviewRoot" style={styles.root}>
55
+ <view style={styles.phoneFrame}>
56
+ <YourComponent />
57
+ </view>
58
+ </view>;
59
+ }
60
+
61
+ const styles = {
62
+ root: new Style<View>({
63
+ width: '100%', height: '100%',
64
+ backgroundColor: '#333333', alignItems: 'center',
65
+ }),
66
+ phoneFrame: new Style<View>({
67
+ width: '390', height: '100%', backgroundColor: '#FFFFFF',
68
+ }),
69
+ };
70
+ ```
71
+
72
+ ### 5. BUILD.bazel dep changes require a full recompile
73
+
74
+ If you change `BUILD.bazel` (e.g. adding a new dependency), you **must kill the app and do a full rebuild**. Hot-reload only recompiles TypeScript within the existing dependency graph — the running binary doesn't have the new dependency's compiled code.
75
+
76
+ After any BUILD.bazel dep change:
77
+ 1. Kill hot-reloader processes
78
+ 2. Kill the app
79
+ 3. Rebuild and relaunch
80
+ 4. Restart hot-reload
81
+
82
+ **Plan your deps up front** to avoid mid-iteration rebuilds.
83
+
84
+ ---
85
+
86
+ ## Pipeline overview
87
+
88
+ ```
89
+ Mock image
90
+ |
91
+ v
92
+ [Phase 1: Bare-bones]
93
+ |-- 1. Breakdown (analyze layout)
94
+ |-- 2. Generate (write TSX — rough structure, placeholder styles)
95
+ |-- 3. Build + launch + hot-reload
96
+ |-- 4. First snapshot + pixel diff
97
+ |
98
+ v
99
+ [Phase 2: Parallel refinement]
100
+ |-- Spin up 3 specialist agents (research only, no edits):
101
+ | |-- Text Agent (fonts, sizes, colors, content, positioning)
102
+ | |-- Icons Agent (icon selection, stroke/fill, tints)
103
+ | |-- Widgets Agent (widget library replacements for raw primitives)
104
+ |
105
+ |-- Diff Coordinator (main agent):
106
+ | |-- Batch all specialist fixes into a single edit
107
+ | |-- Check hot-reload once after the batch
108
+ | |-- Re-diff with --auto-mask after each batch
109
+ | |-- Repeat until MATCH or 5 iterations
110
+ |
111
+ v
112
+ Done — present final render + diff
113
+ ```
114
+
115
+ **Phase 1 goal**: Something visible on screen fast. Don't perfect anything.
116
+
117
+ **Phase 2 goal**: Converge on the mock. Specialists research in parallel; main agent applies edits.
118
+
119
+ ---
120
+
121
+ ## Step 1: Breakdown
122
+
123
+ Analyze the mock image. **Follow the `/valdi-mock-breakdown` skill**.
124
+
125
+ 1. **Copy mock to stable path**: `cp /path/to/mock.png /tmp/mock.png` (Desktop screenshots can disappear)
126
+ 2. **Extract colors programmatically** — NEVER guess. Use the bundled `extract_colors.py`:
127
+ ```bash
128
+ # Auto-detect thumbnail regions (left column) + ALL colored regions (entire image)
129
+ python3 <skill_dir>/scripts/extract_colors.py /tmp/mock.png --auto-thumbnails --auto-colors
130
+
131
+ # Sample specific pixel colors
132
+ python3 <skill_dir>/scripts/extract_colors.py /tmp/mock.png \
133
+ --sample "badge:305,60" "green_dot:90,355"
134
+ ```
135
+ **Always use BOTH `--auto-thumbnails` AND `--auto-colors`** — thumbnails only scans the left column; colors scans the entire image for buttons, badges, and icons.
136
+ **Watch for colored pill badges** — mocks often contain small colored pill badges (e.g., blue "New Chats", red "LIVE") that look like plain text at low resolution. The pixel diff dilutes them across segment averages. Do a manual visual pass through each row looking for colored elements beyond icons/dots. Use `--sample` to extract exact badge colors.
137
+ 3. Describe the visual layout (structure, sections, components)
138
+ 4. Identify which Valdi primitives and widgets to use
139
+ 5. Plan the component tree before writing code
140
+
141
+ Share your analysis with the user before proceeding.
142
+
143
+ ---
144
+
145
+ ## Step 2: Generate the preview harness
146
+
147
+ The preview harness lives at `apps/preview/` in the workspace root.
148
+
149
+ ### PreviewRoot.tsx
150
+
151
+ Write a `StatefulComponent` that renders the target UI, wrapped in a 390px phone frame:
152
+ - Empty `ViewModel` and `ComponentContext`
153
+ - All styles in a `const styles` object at the bottom
154
+ - Sample data hardcoded as constants
155
+
156
+ ### BUILD.bazel
157
+
158
+ ```python
159
+ load("@valdi//bzl/valdi:valdi_application.bzl", "valdi_application")
160
+ load("@valdi//bzl/valdi:valdi_module.bzl", "valdi_module")
161
+
162
+ valdi_module(
163
+ name = "preview",
164
+ srcs = glob(["**/*.ts", "**/*.tsx"]),
165
+ visibility = ["//visibility:public"],
166
+ deps = [
167
+ "@valdi//src/valdi_modules/src/valdi/valdi_core",
168
+ "@valdi//src/valdi_modules/src/valdi/valdi_tsx",
169
+ ],
170
+ )
171
+
172
+ valdi_application(
173
+ name = "preview_app",
174
+ root_component_path = "PreviewRoot@preview/PreviewRoot",
175
+ title = "Valdi Preview",
176
+ deps = [":preview"],
177
+ )
178
+ ```
179
+
180
+ **Workspace detection**: If `WORKSPACE` contains `workspace(name = "valdi")`, use `//` prefix. Otherwise `@valdi//`.
181
+
182
+ ### tsconfig.json
183
+
184
+ For **external repos**:
185
+ ```json
186
+ {
187
+ "extends": "../../valdi_modules/_configs/base.tsconfig.json",
188
+ "compilerOptions": { "paths": { "preview/*": ["./*"] } }
189
+ }
190
+ ```
191
+
192
+ For the **Valdi repo**:
193
+ ```json
194
+ {
195
+ "extends": "../../src/valdi_modules/_configs/base.tsconfig.json",
196
+ "compilerOptions": {
197
+ "paths": {
198
+ "preview/*": ["./*"],
199
+ "valdi_core/*": ["../../src/valdi_modules/src/valdi/valdi_core/*"],
200
+ "valdi_tsx/*": ["../../src/valdi_modules/src/valdi/valdi_tsx/*"]
201
+ }
202
+ }
203
+ }
204
+ ```
205
+
206
+ ### Style pitfalls (causes silent failures)
207
+
208
+ ```tsx
209
+ // opacity must be a number, not a string
210
+ opacity: 0.3 // CORRECT
211
+ opacity: '0.3' // WRONG — TypeScript error
212
+
213
+ // No overflow: 'hidden' on View
214
+ overflow: 'visible' // CORRECT
215
+ overflow: 'hidden' // WRONG — only 'visible' or 'scroll'
216
+
217
+ // Only system, system-bold, system-italic font weights
218
+ font: 'system-bold 16' // CORRECT
219
+ font: 'system-semibold 16' // WRONG — falls back to regular at runtime
220
+
221
+ // flexGrow is a number
222
+ flexGrow: 1 // CORRECT
223
+ flexGrow: '1' // WRONG
224
+
225
+ // boxShadow format
226
+ boxShadow: '0 2 8 rgba(0,0,0,0.12)' // xOffset yOffset blur color
227
+
228
+ // WRONG: <scrollview> doesn't exist
229
+ <scrollview>...</scrollview>
230
+ // CORRECT: The element is <scroll>
231
+ <scroll>...</scroll>
232
+
233
+ // WRONG: scrollDirection prop doesn't exist
234
+ <scroll scrollDirection="horizontal">
235
+ // CORRECT: Use horizontal boolean
236
+ <scroll horizontal={true}>
237
+
238
+ // WRONG: padding on Label
239
+ new Style<Label>({ padding: '10' })
240
+ // CORRECT: Label doesn't support padding — use margin
241
+ new Style<Label>({ margin: '10' })
242
+
243
+ // WRONG: importing Image from NativeTemplateElements
244
+ import { Image } from 'valdi_tsx/src/NativeTemplateElements';
245
+ // CORRECT: <image> is a JSX intrinsic, not an importable class
246
+ // Use Style<View> for image container styles
247
+
248
+ // WRONG: gap property (doesn't exist on View)
249
+ new Style<View>({ flexDirection: 'row', gap: '8' })
250
+ // CORRECT: use margin on child elements instead
251
+ // In JSX: <view marginRight={8}> or margin="0 8 0 0"
252
+
253
+ // WRONG: icon typed as string
254
+ rightIcon?: string;
255
+ <image src={vm.rightIcon} /> // Type error: Asset not assignable to string
256
+ // CORRECT: icon values are Asset type
257
+ import { Asset } from 'valdi_core/src/Asset';
258
+ rightIcon?: Asset;
259
+ ```
260
+
261
+ ---
262
+
263
+ ## Step 3: Build, launch, and set up hot-reload
264
+
265
+ ### Kill stale processes first (ONLY at start, not during iteration)
266
+
267
+ ```bash
268
+ pkill -f valdi_compiler
269
+ pkill -f valdi_companion
270
+ pkill -f run_hotreloader
271
+ pkill -f "valdi hotreload"
272
+ lsof -ti:9010 | xargs kill
273
+ # NEVER kill port 13591 — that's the running app. Leave it open.
274
+ ```
275
+
276
+ ### First build
277
+
278
+ ```bash
279
+ cd <workspace_root>
280
+
281
+ # External repos:
282
+ bazel build //apps/preview:preview_app_macos
283
+ open bazel-bin/apps/preview/preview_app_macos_archive-root/Valdi\ Preview.app
284
+
285
+ # Start hot-reload
286
+ valdi hotreload --target //apps/preview:preview_app_hotreload > /tmp/hotreload.log 2>&1 &
287
+ ```
288
+
289
+ **CRITICAL: Never use `bazel run` with hot-reload.** `bazel run` holds the bazel server lock, blocking hot-reload. Use `bazel build` + `open` separately.
290
+
291
+ Wait for the app to connect:
292
+ ```bash
293
+ valdi inspect status --port 13591
294
+ # Should show {"connected":true}
295
+ ```
296
+
297
+ ---
298
+
299
+ ## Step 4: Capture a screenshot
300
+
301
+ ```bash
302
+ valdi inspect snapshot --key PreviewRoot --port 13591
303
+ ```
304
+
305
+ The `--key` flag resolves a component tag name or element `key` prop to its element ID automatically. **Stable across hot-reloads** — no need to re-query the tree.
306
+
307
+ **Port 13591** = standalone app. Port 13592 = mobile/in-app.
308
+
309
+ Read the PNG file to view the rendered output.
310
+
311
+ ---
312
+
313
+ ## Step 5: Pixel diff
314
+
315
+ **Generate a real pixel diff** — don't eyeball. Use the bundled scripts:
316
+
317
+ ```bash
318
+ # One-shot: capture snapshot + generate diff (ALWAYS use --auto-mask)
319
+ bash <skill_dir>/scripts/snapshot-and-diff.sh /tmp/mock.png --key <ComponentKey> --port 13591
320
+
321
+ # Or just the diff (if you already have a snapshot):
322
+ python3 <skill_dir>/scripts/diff.py /tmp/mock.png /path/to/snapshot.png --auto-mask
323
+
324
+ # For iOS simulator screenshots, also mask the status bar:
325
+ python3 <skill_dir>/scripts/diff.py /tmp/mock.png /path/to/snapshot.png --auto-mask --mask "0,0,400,30"
326
+
327
+ # Auto-watch mode: monitors hot-reload and auto-diffs on each recompile
328
+ bash <skill_dir>/scripts/watch-and-diff.sh /tmp/mock.png --key <ComponentKey> --port 13591
329
+ ```
330
+
331
+ **ALWAYS use `--auto-mask`** on every diff. This auto-detects avatar/thumbnail/Bitmoji regions and excludes them from the match score. These are image-based content that the component renders as colored placeholder circles — penalizing the score for them is misleading and makes progress harder to track. For iOS simulator screenshots, also mask the status bar (`"0,0,400,30"` in resized coords) since the component can't reproduce the clock/battery/signal UI.
332
+
333
+ Output:
334
+ - `/tmp/mock-vs-render-diff.png` — side-by-side: mock | render | amplified diff | shadow diff
335
+ - Match percentage (pixels within threshold)
336
+ - `--mask` regions shown as red-tinted overlays on all panels (exclude thumbnails/photos from diff)
337
+ - `--segments N` adds per-region breakdown showing which vertical band needs the most work
338
+ - Shadow match percentage reported alongside pixel match percentage
339
+
340
+ **IMPORTANT: Always show the user the diff.** After every pixel diff, use the Read tool to display three images:
341
+ 1. The mock image (`/tmp/mock.png`)
342
+ 2. The render snapshot
343
+ 3. The diff image (`/tmp/mock-vs-render-diff.png`)
344
+ 4. **Open the diff image** so it's visible on screen: `open /tmp/mock-vs-render-diff.png`
345
+
346
+ **Bright spots in the third panel = areas that don't match.** This catches background color mismatches, spacing differences, and drop shadow issues that eyeballing misses.
347
+
348
+ ---
349
+
350
+ ## Step 6: Parallel refinement agents
351
+
352
+ After the first diff, spin up **three specialist agents in parallel** (research only, no edits).
353
+
354
+ ### Specialist memory (cross-iteration persistence)
355
+
356
+ Specialists lose context between iterations. Each agent reads/appends to `/tmp/mock-specialist-findings.json` to avoid re-researching resolved issues.
357
+
358
+ Initialize before first run:
359
+ ```bash
360
+ echo '{"text": [], "icons": [], "widgets": [], "iteration": 1}' > /tmp/mock-specialist-findings.json
361
+ ```
362
+
363
+ Include in every specialist prompt:
364
+ ```
365
+ MEMORY: Read /tmp/mock-specialist-findings.json if it exists. Skip RESOLVED issues.
366
+ After analysis, append new findings under your key. Mark fixed issues RESOLVED.
367
+ ```
368
+
369
+ ### Text Agent
370
+ Audits fonts, sizes, weights, colors, content, positioning. Checks every label against the mock.
371
+
372
+ ### Icons Agent
373
+ Audits icon names, stroke vs fill, tints, sizes, icon circle backgrounds. If the project has an icon library, **use `find_icon.py`** for fuzzy matching:
374
+ ```bash
375
+ python3 <skill_dir>/scripts/find_icon.py "chat bubble" --icons-file <path>/Icons.tsx
376
+ ```
377
+
378
+ ### Widgets Agent
379
+ Finds widget library components that could replace raw primitive constructions. Check the workspace for a shared widget/component library and use those instead of hand-building with `<view>` + `<label>`.
380
+
381
+ Each agent outputs structured fix recommendations with specific code changes.
382
+
383
+ ---
384
+
385
+ ## Step 7: Apply fixes (diff coordinator)
386
+
387
+ You are the diff coordinator. After the specialist agents report back:
388
+
389
+ 1. **Triage**: Merge all three reports into a prioritized fix list. Group by visual impact.
390
+ 2. **Batch all fixes**: Apply ALL fixes from the specialist reports in a single edit. Then check hot-reload log once: `tail -5 /tmp/hotreload.log` — confirm `Recompilation pass finished` with a recent timestamp, no errors in your file. Pre-existing errors in other modules can be ignored. If there's an error, bisect to find the broken change.
391
+ 3. **Show the pixel diff after each batch**: Run the diff script with `--auto-mask --segments 4`. **ALWAYS use `--auto-mask`** to exclude avatar/thumbnail regions:
392
+ ```bash
393
+ bash <skill_dir>/scripts/snapshot-and-diff.sh /tmp/mock.png --key <ComponentKey> --port 13591
394
+ # Or with auto-masking and segments:
395
+ python3 <skill_dir>/scripts/diff.py /tmp/mock.png <snapshot_path> --segments 4 --auto-mask --mask "0,0,400,30"
396
+ ```
397
+ Then **Read all three images** (mock, render, diff) to show the side-by-side comparison, and **open the diff image**: `open /tmp/mock-vs-render-diff.png`. The per-region breakdown tells you exactly which band of the screen needs the most work.
398
+ 4. **Read the new diff image**: Use the per-region breakdown to identify which vertical band has the lowest match %. Send that info back to the relevant specialist agent for targeted fixes.
399
+ 5. **Update specialist memory**: Increment iteration counter before re-launching specialists
400
+ 6. **Repeat** until match > 85% or 5 iterations
401
+
402
+ ### Diminishing returns (~84% ceiling)
403
+
404
+ After ~84% match on complex layouts, component tweaks yield <0.5% improvement. Remaining differences come from aspect ratio distortion (cumulative vertical drift), shadow differences, and anti-aliasing. Focus on **semantic accuracy** (correct elements, badges, colors) over pixel perfection. Don't try preserving the render's aspect ratio in the diff — forced resize to the mock's aspect ratio is correct (preserving was tested and worse).
405
+
406
+ ### Specialist semantic gap
407
+
408
+ The pixel diff misses small semantic differences (e.g., gray icon vs blue badge) because segment averages dilute small features. Specialists should **compare element-by-element** against the mock, not just audit broad categories.
409
+
410
+ ### Fix priority order
411
+
412
+ 1. **Structure** — wrong layout, missing sections
413
+ 2. **Widget replacements** — widget library components fix shadows/spacing/fonts in one shot
414
+ 3. **Text** — content, font sizes, weights, colors
415
+ 4. **Icons** — icon names, stroke/fill, tints
416
+ 5. **Colors/shadows** — backgrounds, box shadows, borders
417
+ 6. **Fine-tuning** — sub-pixel spacing, opacity
418
+
419
+ ---
420
+
421
+ ## Troubleshooting
422
+
423
+ **Build fails with "module not found"** -- Missing dep in BUILD.bazel.
424
+
425
+ **`valdi inspect` connects to wrong device** -- adb may forward port 13591. Run `adb forward --remove-all`.
426
+
427
+ **Component renders blank** -- Check `onRender()` renders elements (not returns them).
428
+
429
+ **Hot-reload not compiling** -- Check `tail -20 /tmp/hotreload.log`. Fix TypeScript errors in your file.
430
+
431
+ **`opacity: '0.3'` error** -- Must be a number: `opacity: 0.3`.
432
+
433
+ **`overflow: 'hidden'` error** -- Only `'visible'` or `'scroll'` supported.
434
+
435
+ **`font: 'system-semibold'` renders as regular** -- Only `system`, `system-bold`, `system-italic` work natively.
436
+
437
+ **Pixel diff shows stretched layout** -- Missing 390px phone frame in PreviewRoot.
438
+
439
+ **`<scrollview>` build error** — The element is `<scroll>`, not `<scrollview>`. Valdi uses `<scroll>`.
440
+
441
+ **`scrollDirection` build error** — Use `horizontal={true}` on `<scroll>`, not `scrollDirection="horizontal"`.
442
+
443
+ **`padding` on Label build error** — `Label` doesn't support `padding`. Use `margin` instead.
444
+
445
+ **`Image` import error** — `<image>` is a JSX intrinsic, not an importable class. Don't import Image.
446
+
447
+ **Widget component crashes** — Some widget components only accept a subset of layout props. Check the component's ViewModel interface for available props before passing layout properties.
448
+
449
+ **ErrorBoundary stuck after hot-reload** — If an error persists after fixing code, kill and relaunch the app. The ErrorBoundary caches error state that hot-reload can't clear.
450
+
451
+ **snapshot-and-diff.sh hangs on context selector** — When the app has multiple Valdi contexts, pass `--context <device_idx> <context_idx>` to bypass the interactive selector.
@@ -0,0 +1,187 @@
1
+ # Valdi Navigation
2
+
3
+ Multi-screen navigation patterns using the `valdi_navigation` module.
4
+
5
+ ## When to use
6
+
7
+ When building apps with multiple screens/pages, modal presentations, or any push/pop navigation flow.
8
+
9
+ ## Key concepts
10
+
11
+ Valdi navigation follows an **iOS-style model**: a `NavigationRoot` manages a stack of pages. Pages are pushed (horizontal slide) or presented (vertical modal). Each page component must be annotated with `@NavigationPage(module)`.
12
+
13
+ **Not React Router.** There is no `<Route>`, no URL-based routing, no `useNavigate()`. Navigation is imperative via `NavigationController`.
14
+
15
+ ## Setup
16
+
17
+ Add `valdi_navigation` to your module's `BUILD.bazel` deps:
18
+
19
+ ```python
20
+ deps = [
21
+ "//src/valdi_modules/src/valdi/valdi_navigation",
22
+ ]
23
+ ```
24
+
25
+ ## NavigationRoot
26
+
27
+ The root of your navigation tree. Exposes a `NavigationController` via a slot:
28
+
29
+ ```tsx
30
+ // ✅ Correct — NavigationRoot with slot pattern
31
+ import { NavigationRoot } from 'valdi_navigation/src/NavigationRoot';
32
+ import { NavigationController } from 'valdi_navigation/src/NavigationController';
33
+
34
+ export class App extends Component {
35
+ private navController?: NavigationController;
36
+
37
+ onRender(): void {
38
+ <NavigationRoot>
39
+ {$slot(navController => {
40
+ this.navController = navController;
41
+ <view width="100%" height="100%">
42
+ <CoreButton text="Go to Settings" onTap={this.openSettings} />
43
+ </view>;
44
+ })}
45
+ </NavigationRoot>;
46
+ }
47
+
48
+ private openSettings = () => {
49
+ this.navController?.push(SettingsPage, { title: 'Settings' }, {});
50
+ };
51
+ }
52
+ ```
53
+
54
+ ```tsx
55
+ // ❌ WRONG — React Router patterns don't exist
56
+ <Router>
57
+ <Route path="/settings" component={SettingsPage} /> // ❌
58
+ </Router>
59
+ const navigate = useNavigate(); // ❌
60
+ navigate('/settings'); // ❌
61
+ ```
62
+
63
+ ## NavigationPageComponent
64
+
65
+ Pages must extend `NavigationPageComponent` or `NavigationPageStatefulComponent` and use the `@NavigationPage` decorator:
66
+
67
+ ```tsx
68
+ // ✅ Correct — page with @NavigationPage decorator
69
+ import { NavigationPage } from 'valdi_navigation/src/NavigationPage';
70
+ import { NavigationPageStatefulComponent } from 'valdi_navigation/src/NavigationPageComponent';
71
+
72
+ interface SettingsViewModel {
73
+ title: string;
74
+ }
75
+
76
+ interface SettingsState {
77
+ darkMode: boolean;
78
+ }
79
+
80
+ @NavigationPage(module)
81
+ export class SettingsPage extends NavigationPageStatefulComponent<SettingsViewModel, SettingsState> {
82
+ state = { darkMode: false };
83
+
84
+ onRender(): void {
85
+ <view width="100%" height="100%" backgroundColor="white">
86
+ <label value={this.viewModel.title} />
87
+ <CoreButton text="Back" onTap={this.handleBack} />
88
+ <CoreButton text="Open Detail" onTap={this.handleOpenDetail} />
89
+ </view>;
90
+ }
91
+
92
+ private handleBack = () => {
93
+ this.navigationController.pop();
94
+ };
95
+
96
+ private handleOpenDetail = () => {
97
+ this.navigationController.push(DetailPage, { id: '123' }, {});
98
+ };
99
+ }
100
+ ```
101
+
102
+ ## Navigation operations
103
+
104
+ | Method | Animation | Use case |
105
+ |--------|-----------|----------|
106
+ | `push(Component, viewModel, context, options?)` | Horizontal slide right | Drill-down navigation |
107
+ | `pop(animated?)` | Horizontal slide left | Go back one level |
108
+ | `popToSelf(animated?)` | Unwinds stack | Return to this page |
109
+ | `popToRoot(animated?)` | Unwinds full stack | Return to root |
110
+ | `present(Component, viewModel, context, options?)` | Vertical slide up | Modal presentation |
111
+ | `dismiss(animated)` | Vertical slide down | Close modal |
112
+
113
+ ## Navigation options
114
+
115
+ ```tsx
116
+ // Push with custom options
117
+ this.navController?.push(DetailPage, viewModel, context, {
118
+ animated: true, // default: true
119
+ pageBackgroundColor: '#FFFFFF', // page container color
120
+ });
121
+
122
+ // Present as modal with nested push/pop support (iOS)
123
+ this.navController?.present(ModalPage, viewModel, context, {
124
+ animated: true,
125
+ wrapInPlatformNavigationController: true, // default: true, enables push/pop inside modal
126
+ });
127
+ ```
128
+
129
+ ## Android back button
130
+
131
+ ```tsx
132
+ // ✅ Handle Android hardware back button
133
+ onCreate() {
134
+ this.unregisterBack = this.navigationController.registerBackButtonObserver(() => {
135
+ // Custom back behavior
136
+ this.saveAndGoBack();
137
+ });
138
+ }
139
+
140
+ onDestroy() {
141
+ this.unregisterBack?.();
142
+ }
143
+ ```
144
+
145
+ ## Page visibility
146
+
147
+ ```tsx
148
+ // ✅ Know when page becomes visible/hidden (e.g., after pop returns to this page)
149
+ onCreate() {
150
+ this.navigationController.addPageVisibilityObserver(this.onVisibilityChange);
151
+ }
152
+
153
+ private onVisibilityChange = (visibility: INavigatorPageVisibility) => {
154
+ // React to page becoming visible again
155
+ };
156
+
157
+ onDestroy() {
158
+ this.navigationController.removePageVisibilityObserver(this.onVisibilityChange);
159
+ }
160
+ ```
161
+
162
+ ## Common mistakes
163
+
164
+ ```tsx
165
+ // ❌ WRONG — Forgetting @NavigationPage decorator
166
+ export class MyPage extends NavigationPageComponent<{}> { ... }
167
+ // Runtime error: "Component has not been decorated with @NavigationPage"
168
+
169
+ // ❌ WRONG — Using NavigationPageComponent outside a NavigationRoot
170
+ // Pages must be rendered inside a NavigationRoot's stack
171
+
172
+ // ❌ WRONG — Passing navigator in context manually
173
+ navController.push(Page, vm, { navigator: navController }); // ❌
174
+ // Navigator is injected automatically — don't pass it in context
175
+
176
+ // ✅ Correct — pass empty context if page needs no extra context
177
+ navController.push(Page, vm, {});
178
+ ```
179
+
180
+ ## Disable interactive dismissal
181
+
182
+ ```tsx
183
+ // Prevent swipe-to-dismiss on a modal (e.g., during form editing)
184
+ const reenable = this.navigationController.disableDismissalGesture();
185
+ // Later, when safe to dismiss:
186
+ reenable();
187
+ ```
@@ -49,10 +49,13 @@ Skills available (`valdi skills list`):
49
49
  ## Quick Commands
50
50
 
51
51
  ```bash
52
- bazel build //... # Build everything
53
- bazel test //... # Run all tests
54
- valdi install ios # Build & install iOS app
55
- valdi hotreload # Start hot reload
52
+ bazel build //... # Build everything
53
+ bazel test //... # Run all tests
54
+ valdi install ios # Build & install iOS app
55
+ valdi hotreload # Start hot reload
56
+ valdi agent-check --module X # Full validation (build + lint + test)
57
+ valdi agent-check --module X --quick # Quick check (lint + test, no build)
58
+ valdi agent-check --module X --quick --json # Quick check with machine-readable output
56
59
  ```
57
60
 
58
61
  ## More Information