@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
@@ -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.
@@ -22,9 +22,21 @@ my_module/
22
22
  ## BUILD.bazel Pattern
23
23
 
24
24
  ```python
25
+ load("@aspect_rules_ts//ts:defs.bzl", "ts_project")
26
+
27
+ # web_deps MUST be a ts_project — never use filegroup for web code.
25
28
  ts_project(
26
29
  name = "my_module_web",
27
- srcs = glob(["web/**/*.ts", "web/**/*.d.ts"]),
30
+ srcs = glob(
31
+ [
32
+ "web/**/*.ts",
33
+ "src/**/*.d.ts", # include if web code imports module type declarations
34
+ ],
35
+ exclude = ["web/**/*.d.ts"], # exclude to avoid TS5055 output collision with composite
36
+ ),
37
+ allow_js = True,
38
+ composite = True,
39
+ transpiler = "tsc", # required — aspect_rules_ts does not default it
28
40
  tsconfig = "web/tsconfig.json",
29
41
  visibility = ["//visibility:public"],
30
42
  )
@@ -45,24 +57,50 @@ valdi_module(
45
57
 
46
58
  ## Web Polyglot Entry Pattern
47
59
 
48
- Web entry files export view factories that are auto-registered with the `WebViewClassRegistry` at bundle time. Export a `webPolyglotViews` record mapping class names to factory functions:
60
+ Web entry files export view factories that are auto-registered with the `WebViewClassRegistry` at bundle time. Use typed TypeScript with an `AttributeHandler` interface:
49
61
 
50
62
  ```typescript
51
- export const webPolyglotViews: Record<string, (container: HTMLElement) => void> = {
63
+ interface AttributeHandler {
64
+ changeAttribute(name: string, value: unknown): void;
65
+ }
66
+
67
+ type ViewFactory = (container: HTMLElement) => AttributeHandler;
68
+
69
+ function createMyViewFactory(): ViewFactory {
70
+ return (container: HTMLElement): AttributeHandler => {
71
+ const element = document.createElement('div');
72
+ container.appendChild(element);
73
+
74
+ return {
75
+ changeAttribute(name: string, value: unknown): void {
76
+ if (name === 'myAttribute' && typeof value === 'number') {
77
+ element.textContent = String(value);
78
+ }
79
+ },
80
+ };
81
+ };
82
+ }
83
+
84
+ // Keys must match the webClass attribute in <custom-view webClass="MyCustomViewClass">
85
+ export const webPolyglotViews: Record<string, ViewFactory> = {
52
86
  MyCustomViewClass: createMyViewFactory(),
53
87
  };
54
88
  ```
55
89
 
56
- Each key must match the `webClass` attribute used in `<custom-view webClass="MyCustomViewClass">`.
90
+ ### Web `tsconfig.json`
57
91
 
58
- A factory receives an `HTMLElement` container and populates it with DOM content:
92
+ The `web/tsconfig.json` must be standalone — do not extend the module-level tsconfig (it has Valdi path mappings that don't apply to web builds):
59
93
 
60
- ```typescript
61
- function createMyViewFactory(): (container: HTMLElement) => void {
62
- return (container: HTMLElement) => {
63
- const element = document.createElement('div');
64
- container.appendChild(element);
65
- };
94
+ ```json
95
+ {
96
+ "compilerOptions": {
97
+ "target": "ES2016",
98
+ "module": "commonjs",
99
+ "strict": true,
100
+ "composite": true,
101
+ "allowJs": true,
102
+ "lib": ["dom", "ES2019"]
103
+ }
66
104
  }
67
105
  ```
68
106
 
@@ -70,7 +108,8 @@ function createMyViewFactory(): (container: HTMLElement) => void {
70
108
  - Compiled by `tsc` via `ts_project`, **not** the Valdi compiler
71
109
  - Do **NOT** use Valdi imports (`valdi_core/`, `valdi_tsx/`) — web files run in the browser, not the Valdi runtime
72
110
  - Do **NOT** manually call `globalThis.moduleLoader.resolveRequire()` — build system handles registration
73
- - The `tsconfig.json` in `web/` should target `DOM` + `ES2020` with `module: "commonjs"`
111
+ - The `web/tsconfig.json` must be standalone with `lib: ["dom", "ES2019"]` and `module: "commonjs"`
112
+ - Always use `transpiler = "tsc"` in the `ts_project` rule — aspect_rules_ts requires explicit transpiler selection
74
113
 
75
114
  ## Canonical Example
76
115
 
@@ -78,8 +117,88 @@ See `valdi_polyglot` module for a complete working example with all four platfor
78
117
  - `src/composer_modules/src/composer/valdi_polyglot/` (in the Snap monorepo)
79
118
  - Or the equivalent path in your project
80
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
+
81
198
  ## Common Mistakes
82
199
 
83
200
  - Putting `web/` files in `srcs` — they must go through `ts_project` + `web_deps`, not the Valdi compiler
84
201
  - Missing platform `_deps` — each platform impl must be wired via `android_deps`, `ios_deps`, `macos_deps`
85
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`