@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,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
@@ -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`