@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
@@ -1,5 +1,6 @@
1
- # No bzlmod yet
2
- common --noenable_bzlmod
1
+ # Valdi custom Bazel registry (patched rules_swift, rules_kotlin, etc.)
2
+ common --registry=https://raw.githubusercontent.com/Snapchat/Valdi/{{VALDI_RELEASE_TAG}}/registry
3
+ common --registry=https://bcr.bazel.build
3
4
 
4
5
  common --bes_instance_name=client
5
6
  common --enable_platform_specific_config
@@ -26,8 +27,10 @@ build:linux --sandbox_writable_path=/var/tmp
26
27
  # common cc configuration
27
28
  build --cxxopt=-std=c++20
28
29
  build --cxxopt=-Wno-ambiguous-reversed-operator
30
+ build --cxxopt=-Wno-nullability-extension
29
31
  build --cxxopt=-D_LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS
30
32
  build --host_cxxopt=-std=c++20
33
+ build --host_cxxopt=-Wno-nullability-extension
31
34
 
32
35
  ## we need to disable this due to a bug in bazel
33
36
  ## see https://github.com/bazelbuild/bazel/issues/12381
@@ -61,10 +64,8 @@ build --define=android_standalone_dexing_tool=d8_compat_dx
61
64
  build --incremental_dexing
62
65
 
63
66
  # Disable 3rd party libs warnings
64
- build --per_file_copt=external/com_github_grpc_grpc/.*\$@-Wno-everything
65
- build --per_file_copt=external/snap_protobuf/.*\$@-Wno-everything
67
+ build --per_file_copt=external/com_google_protobuf/.*\$@-Wno-everything
66
68
  build --per_file_copt=external/boringssl/.*\$@-Wno-everything
67
- build --per_file_copt=external/com_github_google_flatbuffers/.*\$@-Wno-everything
68
69
 
69
70
  # Enable persistent worker for Valdi compilation
70
71
  build --strategy=ValdiCompile=worker
@@ -0,0 +1,62 @@
1
+ module(name = "{{WORKSPACE_NAME}}", version = "0.1")
2
+
3
+ # -- Valdi framework (https://github.com/Snapchat/Valdi) ---------------------
4
+ VALDI_TAG = "{{VALDI_RELEASE_TAG}}"
5
+ VALDI_URL = "https://github.com/Snapchat/Valdi/archive/" + VALDI_TAG + ".tar.gz"
6
+ VALDI_PREFIX = "Valdi-" + VALDI_TAG
7
+
8
+ bazel_dep(name = "valdi", version = "0.1")
9
+ archive_override(
10
+ module_name = "valdi",
11
+ urls = [VALDI_URL],
12
+ strip_prefix = VALDI_PREFIX,
13
+ )
14
+
15
+ # Valdi internal sub-modules: local_path_override in Valdi's own MODULE.bazel
16
+ # only takes effect when Valdi is the root module. Consumers must provide
17
+ # archive_override entries that point into the Valdi release archive.
18
+ bazel_dep(name = "android_macros")
19
+ archive_override(module_name = "android_macros", urls = [VALDI_URL], strip_prefix = VALDI_PREFIX + "/bzl/macros")
20
+
21
+ bazel_dep(name = "snap_macros")
22
+ archive_override(module_name = "snap_macros", urls = [VALDI_URL], strip_prefix = VALDI_PREFIX + "/bzl/valdi/snap_macros")
23
+
24
+ bazel_dep(name = "snap_client_toolchains")
25
+ archive_override(module_name = "snap_client_toolchains", urls = [VALDI_URL], strip_prefix = VALDI_PREFIX + "/bzl/toolchains")
26
+
27
+ bazel_dep(name = "snap_platforms")
28
+ archive_override(module_name = "snap_platforms", urls = [VALDI_URL], strip_prefix = VALDI_PREFIX + "/bzl/platforms")
29
+
30
+ bazel_dep(name = "skia_user_config")
31
+ archive_override(module_name = "skia_user_config", urls = [VALDI_URL], strip_prefix = VALDI_PREFIX + "/third-party/skia_user_config")
32
+
33
+ bazel_dep(name = "rules_hdrs")
34
+ archive_override(module_name = "rules_hdrs", urls = [VALDI_URL], strip_prefix = VALDI_PREFIX + "/third-party/rules_hdrs")
35
+
36
+ bazel_dep(name = "valdi_toolchain")
37
+ archive_override(module_name = "valdi_toolchain", urls = [VALDI_URL], strip_prefix = VALDI_PREFIX + "/bin")
38
+
39
+ bazel_dep(name = "resvg_libs")
40
+ archive_override(module_name = "resvg_libs", urls = [VALDI_URL], strip_prefix = VALDI_PREFIX + "/third-party/resvg/resvg_libs")
41
+
42
+ # -- Valdi Widgets (https://github.com/Snapchat/Valdi_Widgets) ---------------
43
+ WIDGETS_TAG = "{{VALDI_WIDGETS_RELEASE_TAG}}"
44
+
45
+ bazel_dep(name = "valdi_widgets")
46
+ archive_override(
47
+ module_name = "valdi_widgets",
48
+ urls = ["https://github.com/Snapchat/Valdi_Widgets/archive/" + WIDGETS_TAG + ".tar.gz"],
49
+ strip_prefix = "Valdi_Widgets-" + WIDGETS_TAG,
50
+ )
51
+
52
+ # -- C++ toolchains (Apple CC before LLVM for ObjC priority) ------------------
53
+ valdi_toolchains = use_extension("@valdi//bzl:valdi_toolchains.bzl", "valdi_toolchains")
54
+ use_repo(valdi_toolchains, "local_config_apple_cc_toolchains", "local_config_apple_cc", "llvm_toolchain", "llvm_toolchain_llvm")
55
+ register_toolchains("@local_config_apple_cc_toolchains//:all")
56
+ register_toolchains("@llvm_toolchain//:all")
57
+
58
+ # -- Version pins (must match Valdi's MODULE.bazel) ---------------------------
59
+ single_version_override(module_name = "protobuf", version = "27.0")
60
+ single_version_override(module_name = "rules_apple", version = "4.0.0")
61
+ single_version_override(module_name = "rules_pkg", version = "0.9.1")
62
+ single_version_override(module_name = "zlib", version = "1.3.2")
@@ -12,10 +12,21 @@
12
12
  { "name": "valdi-custom-view", "description": "Valdi custom native view integration", "tags": ["custom-view", "native"], "path": "skills/valdi-custom-view/skill.md", "category": ["client"] },
13
13
  { "name": "valdi-overview", "description": "Valdi framework overview and project conventions", "tags": ["overview", "conventions"], "path": "skills/valdi-overview/skill.md", "category": ["client"] },
14
14
  { "name": "valdi-async", "description": "Valdi async lifecycle safety: CancelablePromise, registerDisposable, isDestroyed guards", "tags": ["async", "lifecycle", "http"], "path": "skills/valdi-async/skill.md", "category": ["client"] },
15
- { "name": "valdi-perf", "description": "Valdi performance: viewModel identity stability, createReusableCallback, layout vs view, Style interning", "tags": ["performance", "rendering"], "path": "skills/valdi-perf/skill.md", "category": ["client"] },
15
+ { "name": "valdi-perf", "description": "Valdi performance: viewModel identity stability, createReusableCallback, layout vs view, Style interning, deferring subscriptions to unblock first paint, lazy initialization with Lazy<T>, Provider<T>, dynamic import(), excessive setState calls and batching, caching expensive observables with cacheObservable to avoid switchMap re-subscription cost, when to offload heavy work to a Worker Service", "tags": ["performance", "rendering", "worker-service", "first-paint", "lazy", "deferred-init", "setState", "observables", "rxjs", "cacheObservable"], "path": "skills/valdi-perf/skill.md", "category": ["client"] },
16
16
  { "name": "valdi-component-tests", "description": "Valdi component test patterns: elementKeyFind, componentTypeFind, tapNodeWithKey, discriminated unions, arrays", "tags": ["testing", "components", "jasmine"], "path": "skills/valdi-component-tests/skill.md", "category": ["client"] },
17
17
  { "name": "valdi-setup", "description": "Valdi module setup: BUILD.bazel, valdi_module(), tsconfig, deps, ios_module_name, hot reload", "tags": ["setup", "bazel", "build"], "path": "skills/valdi-setup/skill.md", "category": ["client"] },
18
18
  { "name": "valdi-migrate", "description": "Migrate Flutter, React, or Jetpack Compose code to Valdi — component model, lifecycle, element mapping tables", "tags": ["migration", "flutter", "react", "compose"], "path": "skills/valdi-migrate/skill.md", "category": ["client"] },
19
- { "name": "valdi-inspect", "description": "Inspect a live Valdi app: contexts, component trees, screenshots, heap dumps via valdi inspect CLI", "tags": ["inspect", "debug", "runtime", "cli"], "path": "skills/valdi-inspect/skill.md", "category": ["client"] }
19
+ { "name": "valdi-inspect", "description": "Inspect a live Valdi app: contexts, component trees, screenshots, heap dumps via valdi inspect CLI", "tags": ["inspect", "debug", "runtime", "cli"], "path": "skills/valdi-inspect/skill.md", "category": ["client"] },
20
+ { "name": "valdi-preview", "description": "Preview a Valdi component: read its API, render it in the preview harness, inspect the view tree, and capture screenshots", "tags": ["preview", "inspect", "components", "widgets"], "path": "skills/valdi-preview/skill.md", "category": ["client"] },
21
+ { "name": "valdi-mock-breakdown", "description": "Generate Valdi TSX from a screenshot or design mock: analyze layout, decompose into components, produce code", "tags": ["mock", "codegen", "design", "screenshot", "ai"], "path": "skills/valdi-mock-breakdown/skill.md", "category": ["client"] },
22
+ { "name": "valdi-mock-iterate", "description": "Compare a design mock against a rendered Valdi screenshot and produce specific visual diff feedback", "tags": ["mock", "critique", "visual-diff", "iterate", "ai"], "path": "skills/valdi-mock-iterate/skill.md", "category": ["client"] },
23
+ { "name": "valdi-mock-to-module", "description": "Turn a screenshot into a running Valdi module: orchestrates breakdown, preview, and critic iteration loop", "tags": ["mock", "codegen", "pipeline", "orchestrator", "ai"], "path": "skills/valdi-mock-to-module/skill.md", "category": ["client"] },
24
+ { "name": "valdi-profile", "description": "Capture CPU profiles from a running Valdi app: diagnose slow renders, identify hot functions, understand JS thread activity", "tags": ["profile", "performance", "debug", "cli"], "path": "skills/valdi-profile/skill.md", "category": ["client"] },
25
+ { "name": "valdi-navigation", "description": "Multi-screen navigation: NavigationRoot, push/pop/present/dismiss, NavigationPageComponent, back button handling", "tags": ["navigation", "routing", "pages", "modal"], "path": "skills/valdi-navigation/skill.md", "category": ["client"] },
26
+ { "name": "valdi-animations", "description": "Imperative animation API: animate/animatePromise, AnimationOptions, spring physics, setStateAnimated", "tags": ["animation", "transitions", "spring"], "path": "skills/valdi-animations/skill.md", "category": ["client"] },
27
+ { "name": "valdi-gestures", "description": "Touch and gesture handling: onTap, onDrag, onPinch, onRotate, onLongPress, TouchEvent, gesture predicates", "tags": ["gestures", "touch", "input"], "path": "skills/valdi-gestures/skill.md", "category": ["client"] },
28
+ { "name": "valdi-localization", "description": "Internationalization: strings-en.json, Strings.d.ts generation, template variables, valdi projectsync", "tags": ["localization", "i18n", "strings"], "path": "skills/valdi-localization/skill.md", "category": ["client"] },
29
+ { "name": "valdi-error-handling", "description": "Error handling patterns: CancelablePromise safety, HTTPClient errors, isDestroyed guards, error UI states", "tags": ["errors", "async", "lifecycle", "safety"], "path": "skills/valdi-error-handling/skill.md", "category": ["client"] },
30
+ { "name": "valdi-component-dedup", "description": "Find and extract duplicated component patterns across Valdi modules into shared libraries", "tags": ["deduplication", "analysis", "refactoring", "ai"], "path": "skills/valdi-component-dedup/skill.md", "category": ["client"] }
20
31
  ]
21
32
  }
@@ -0,0 +1,197 @@
1
+ # Valdi Animations
2
+
3
+ Imperative animation API for animating element attributes and state changes.
4
+
5
+ ## When to use
6
+
7
+ When animating layout changes, view attributes, or state transitions. Almost all element attributes can be animated in Valdi.
8
+
9
+ ## Key concepts
10
+
11
+ Valdi uses an **imperative animation model** inspired by iOS's `animateWithDuration:animations:`. You call `this.animate()` or `this.animatePromise()` with options and a block of mutations — all changes inside the block are animated automatically.
12
+
13
+ **Not CSS transitions.** There is no `transition` property, no `@keyframes`, no `animation-duration`. Animations are triggered programmatically.
14
+
15
+ ## animate and animatePromise
16
+
17
+ Both methods are available on any `Component`:
18
+
19
+ ```tsx
20
+ // ✅ Fire-and-forget animation
21
+ this.animate({ duration: 0.3 }, () => {
22
+ this.myLabel.setAttribute('font', 'title');
23
+ this.myContainer.setAttribute('width', 200);
24
+ });
25
+
26
+ // ✅ Wait for animation to complete
27
+ await this.animatePromise({ duration: 0.5, curve: AnimationCurve.EaseOut }, () => {
28
+ this.setState({ expanded: true });
29
+ });
30
+ // Animation finished — safe to do next step
31
+ ```
32
+
33
+ ## AnimationOptions
34
+
35
+ Three curve types: preset, custom bezier, and spring.
36
+
37
+ ```tsx
38
+ import { AnimationCurve } from 'valdi_core/src/AnimationOptions';
39
+
40
+ // Preset curves
41
+ { duration: 0.3, curve: AnimationCurve.Linear }
42
+ { duration: 0.3, curve: AnimationCurve.EaseIn }
43
+ { duration: 0.3, curve: AnimationCurve.EaseOut }
44
+ { duration: 0.3, curve: AnimationCurve.EaseInOut } // default
45
+
46
+ // Custom bezier control points
47
+ { duration: 0.4, controlPoints: [0.25, 0.1, 0.25, 1.0] }
48
+
49
+ // Spring animation (no duration — spring physics determine timing)
50
+ { stiffness: 300, damping: 30 }
51
+
52
+ // Crossfade (alpha transition between old and new state)
53
+ { duration: 0.3, crossfade: true }
54
+
55
+ // Continue from current animation state
56
+ { duration: 0.3, beginFromCurrentState: true }
57
+
58
+ // Completion callback
59
+ { duration: 0.3, completion: (wasCancelled) => { /* done */ } }
60
+ ```
61
+
62
+ ## Animating element attributes via ElementRef
63
+
64
+ ```tsx
65
+ import { ElementRef } from 'valdi_core/src/ElementRef';
66
+
67
+ export class MyComponent extends Component {
68
+ private titleRef = new ElementRef();
69
+ private containerRef = new ElementRef();
70
+
71
+ onRender(): void {
72
+ <view ref={this.containerRef} width={100}>
73
+ <label ref={this.titleRef} value="Hello" font={systemFont(14)} />
74
+ </view>;
75
+ }
76
+
77
+ private expand = () => {
78
+ // ✅ Animate attribute changes via ElementRef
79
+ this.animate({ duration: 0.3 }, () => {
80
+ this.titleRef.setAttribute('font', systemBoldFont(17));
81
+ this.containerRef.setAttribute('width', 300);
82
+ });
83
+ };
84
+ }
85
+ ```
86
+
87
+ ## Animating state changes
88
+
89
+ ```tsx
90
+ interface State {
91
+ expanded: boolean;
92
+ text: string;
93
+ }
94
+
95
+ export class MyComponent extends StatefulComponent<{}, State> {
96
+ state = { expanded: false, text: 'Collapsed' };
97
+
98
+ onRender(): void {
99
+ <view width={this.state.expanded ? 300 : 100} height={this.state.expanded ? 200 : 50}>
100
+ <label value={this.state.text} />
101
+ </view>;
102
+ }
103
+
104
+ private toggle = () => {
105
+ // ✅ setStateAnimated — renders with new state, animates all resulting mutations
106
+ this.setStateAnimated(
107
+ { expanded: !this.state.expanded, text: this.state.expanded ? 'Collapsed' : 'Expanded' },
108
+ { duration: 0.3, curve: AnimationCurve.EaseInOut },
109
+ );
110
+ };
111
+ }
112
+ ```
113
+
114
+ ## Spring animations
115
+
116
+ ```tsx
117
+ // ✅ Bouncy spring — lower damping = more bounce
118
+ this.animate({ stiffness: 300, damping: 15 }, () => {
119
+ this.cardRef.setAttribute('scale', 1.0);
120
+ });
121
+
122
+ // ✅ Stiff spring — high damping = smooth settle
123
+ this.animate({ stiffness: 500, damping: 40 }, () => {
124
+ this.panelRef.setAttribute('translateY', 0);
125
+ });
126
+ ```
127
+
128
+ ## Common patterns
129
+
130
+ ### Show/hide with fade
131
+
132
+ ```tsx
133
+ private show = () => {
134
+ this.animate({ duration: 0.2 }, () => {
135
+ this.overlayRef.setAttribute('opacity', 1);
136
+ });
137
+ };
138
+
139
+ private hide = () => {
140
+ this.animate({ duration: 0.2 }, () => {
141
+ this.overlayRef.setAttribute('opacity', 0);
142
+ });
143
+ };
144
+ ```
145
+
146
+ ### Sequential animations
147
+
148
+ ```tsx
149
+ private async runSequence() {
150
+ await this.animatePromise({ duration: 0.2 }, () => {
151
+ this.step1Ref.setAttribute('opacity', 1);
152
+ });
153
+ await this.animatePromise({ duration: 0.3 }, () => {
154
+ this.step2Ref.setAttribute('translateY', 0);
155
+ });
156
+ }
157
+ ```
158
+
159
+ ## Common mistakes
160
+
161
+ ```tsx
162
+ // ❌ WRONG — CSS-style transitions don't exist
163
+ <view style={{ transition: 'all 0.3s ease' }} /> // ❌
164
+ <view className="animate-fade-in" /> // ❌
165
+
166
+ // ❌ WRONG — React-style animation libraries
167
+ import { animated, useSpring } from 'react-spring'; // ❌
168
+
169
+ // ❌ WRONG — Calling setState inside animate (use setStateAnimated instead)
170
+ this.animate({ duration: 0.3 }, () => {
171
+ this.setState({ expanded: true }); // ❌ Won't animate the re-render
172
+ });
173
+
174
+ // ✅ Correct — use setStateAnimated for state-driven animations
175
+ this.setStateAnimated({ expanded: true }, { duration: 0.3 });
176
+
177
+ // ❌ WRONG — Duration in milliseconds (it's seconds)
178
+ this.animate({ duration: 300 }, () => { ... }); // ❌ This is 300 seconds!
179
+
180
+ // ✅ Correct — Duration in seconds
181
+ this.animate({ duration: 0.3 }, () => { ... });
182
+ ```
183
+
184
+ ## CoreUI animation components
185
+
186
+ The `coreui` library includes pre-built animation components:
187
+
188
+ | Component | Purpose |
189
+ |-----------|---------|
190
+ | `AnimatableVisibilityView` | Animate show/hide transitions |
191
+ | `AnimationShimmer` | Loading shimmer effect |
192
+ | `AnimationSliding` | Slide in/out animations |
193
+ | `AnimationSquishy` | Press-and-squish feedback |
194
+ | `AnimationRotate` | Continuous rotation |
195
+ | `VerticallyOpenableComponent` | Expand/collapse vertically |
196
+
197
+ Import from `coreui/src/components/animation/`.
@@ -73,7 +73,7 @@ class LiveClock extends StatefulComponent<ClockViewModel, ClockState> {
73
73
  onCreate(): void {
74
74
  // ✅ Automatically cancelled on destroy — no onDestroy() needed
75
75
  const id = setInterval(() => this.tick(), 1000);
76
- this.registerDisposable({ cancel: () => clearInterval(id) });
76
+ this.registerDisposable({ unsubscribe: () => clearInterval(id) });
77
77
  }
78
78
 
79
79
  private tick = (): void => {
@@ -0,0 +1,263 @@
1
+ # Valdi Component Deduplication
2
+
3
+ Find and extract duplicated UI patterns across Valdi modules into shared components.
4
+
5
+ ## When to use
6
+
7
+ When you want to identify components that multiple modules have independently implemented, then extract them into a shared library so future modules can reuse them instead of reinventing.
8
+
9
+ ## Running the analysis
10
+
11
+ ```bash
12
+ # Full scan of all modules
13
+ valdi analyze duplicates
14
+
15
+ # Scope to one module
16
+ valdi analyze duplicates --module my_module
17
+
18
+ # Machine-readable output
19
+ valdi analyze duplicates --json
20
+
21
+ # Only check for a specific pattern
22
+ valdi analyze duplicates --pattern async
23
+
24
+ # Custom scan roots and shared libraries
25
+ valdi analyze duplicates --scan-root src/modules --shared-lib valdi_widgets
26
+ valdi analyze duplicates --scan-root src/modules --shared-lib my_shared_lib --shared-lib another_lib
27
+ ```
28
+
29
+ ### CLI flags
30
+
31
+ | Flag | Effect |
32
+ |---|---|
33
+ | `--module <name>` | Scope to one module |
34
+ | `--json` | Machine-readable JSON output |
35
+ | `--threshold <0-1>` | Similarity threshold (default 0.6) |
36
+ | `--pattern <name>` | Only detect: `async`, `button`, `shimmer` |
37
+ | `--output <path>` | Write JSON report to file |
38
+ | `--verbose` | Show per-file detail |
39
+ | `--scan-root <path>` | Root directory to scan (repeatable) |
40
+ | `--shared-lib <name>` | Shared component library name (repeatable) |
41
+
42
+ ## Understanding the report
43
+
44
+ The report has two sections:
45
+
46
+ **Known Patterns** — pre-built detectors for the most common duplication:
47
+ - **Async State Container**: Components that implement loading→error/content state machines
48
+ - **Button Wrapper**: Thin wrappers around a shared button with hardcoded sizing/coloring
49
+ - **Shimmer / Skeleton Layout**: Custom loading placeholder components
50
+
51
+ **Similar Clusters** — generic similarity analysis that finds groups of components with overlapping ViewModel props, render trees, and import signatures.
52
+
53
+ Each cluster shows:
54
+ - Number of files and average similarity score
55
+ - Shared ViewModel props across the cluster
56
+ - A suggested extraction approach
57
+
58
+ ## Extraction workflow
59
+
60
+ Once you identify a cluster worth extracting:
61
+
62
+ ### 1. Read the candidates
63
+
64
+ Read each file in the cluster. Identify:
65
+ - The shared ViewModel props (these become the new component's ViewModel)
66
+ - The shared render structure (this becomes the new component's `onRender`)
67
+ - Module-specific variations (these become optional props or render callbacks)
68
+
69
+ ### 2. Check for an existing shared component to extend
70
+
71
+ Before creating anything new, search the shared library for a component that already solves part of the problem. Often the right fix is adding props, a preset enum, or a render callback to an existing component rather than building from scratch.
72
+
73
+ ```bash
74
+ # Search the shared library for related components
75
+ grep -rl "Button\|Shimmer\|AsyncContent" <your-shared-lib>/src/components/
76
+ ```
77
+
78
+ If an existing component covers 70%+ of the use cases, extend it:
79
+ - Add optional props for the missing behavior
80
+ - Add a preset or variant enum if consumers just need different default combos
81
+ - Add a render callback slot if consumers need to inject custom UI
82
+
83
+ Only create a new component when nothing in the shared library is close enough to extend.
84
+
85
+ ### 3. Design or extend the shared component
86
+
87
+ **Extending an existing component** (preferred):
88
+
89
+ ```typescript
90
+ // Add a preset to an existing button component
91
+ export enum CoreButtonPreset {
92
+ PRIMARY_CTA,
93
+ SECONDARY_ACTION,
94
+ PILL_ACTION,
95
+ }
96
+
97
+ // Add an optional prop to the existing ViewModel
98
+ interface CoreButtonViewModel {
99
+ // ... existing props ...
100
+ preset?: CoreButtonPreset;
101
+ }
102
+ ```
103
+
104
+ **Creating a new component** (when nothing exists to extend):
105
+
106
+ ```typescript
107
+ import { Component } from 'valdi_core/src/Component';
108
+
109
+ interface SharedComponentViewModel {
110
+ commonProp: string;
111
+ optionalVariant?: VariantType;
112
+ renderCustomSection?: () => void;
113
+ }
114
+
115
+ export class SharedComponent extends Component<SharedComponentViewModel> {
116
+ onRender(): void {
117
+ <view>
118
+ <label value={this.viewModel.commonProp} />;
119
+ {this.viewModel.renderCustomSection?.()};
120
+ </view>;
121
+ }
122
+ }
123
+ ```
124
+
125
+ ### 4. Place it in the shared library
126
+
127
+ If you created a new component, place it in your project's shared component library
128
+ (e.g. `<shared-lib>/src/components/<category>/`). Follow your project's conventions
129
+ for directory structure and naming.
130
+
131
+ ### 5. Migrate consumers
132
+
133
+ For each file in the cluster:
134
+ 1. Replace the local component class with an import of the shared one
135
+ 2. Map the old ViewModel props to the new shared ViewModel
136
+ 3. Move module-specific rendering into render callbacks
137
+ 4. Delete the old local component file
138
+ 5. Run `valdi agent-check --module <name>` to verify
139
+
140
+ ### 6. Verify
141
+
142
+ ```bash
143
+ # Re-run analysis — the cluster should shrink or disappear
144
+ valdi analyze duplicates --pattern async
145
+
146
+ # Build and test affected modules
147
+ valdi agent-check --module module_a
148
+ valdi agent-check --module module_b
149
+ ```
150
+
151
+ ## Common extraction patterns
152
+
153
+ ### Async State Container
154
+
155
+ The most common duplication. Components that manage loading→loaded/error states:
156
+
157
+ ```typescript
158
+ import { StatefulComponent } from 'valdi_core/src/Component';
159
+ import { promiseToCancelablePromise } from 'valdi_core/src/CancelablePromise';
160
+
161
+ interface AsyncStateContainerViewModel<T> {
162
+ resultProvider: () => PromiseLike<T>;
163
+ renderLoading: () => void;
164
+ renderResult: (data: T) => void;
165
+ renderError: (error: string, retry: () => void) => void;
166
+ renderEmpty?: () => void;
167
+ }
168
+
169
+ type AsyncState<T> = { phase: 'loading' } | { phase: 'result'; data: T } | { phase: 'error'; message: string };
170
+
171
+ export class AsyncStateContainer<T> extends StatefulComponent<AsyncStateContainerViewModel<T>, { state: AsyncState<T> }> {
172
+ state = { state: { phase: 'loading' } as AsyncState<T> };
173
+
174
+ onCreate(): void {
175
+ this.load();
176
+ }
177
+
178
+ onRender(): void {
179
+ const s = this.state.state;
180
+ switch (s.phase) {
181
+ case 'loading': this.viewModel.renderLoading(); break;
182
+ case 'result': this.viewModel.renderResult(s.data); break;
183
+ case 'error': this.viewModel.renderError(s.message, () => this.load()); break;
184
+ }
185
+ }
186
+
187
+ private load(): void {
188
+ this.setState({ state: { phase: 'loading' } });
189
+ const cancelable = promiseToCancelablePromise(
190
+ Promise.resolve(this.viewModel.resultProvider()),
191
+ () => {},
192
+ );
193
+ this.registerDisposable(() => cancelable.cancel?.());
194
+ cancelable.then(
195
+ data => { this.setState({ state: { phase: 'result', data } }); },
196
+ error => { this.setState({ state: { phase: 'error', message: (error as Error).message } }); },
197
+ );
198
+ }
199
+ }
200
+ ```
201
+
202
+ ### Button Presets
203
+
204
+ Instead of per-module button wrappers, use preset enums:
205
+
206
+ ```typescript
207
+ // Instead of a new wrapper component, add presets to the existing shared button
208
+ enum ButtonPreset {
209
+ PRIMARY_CTA,
210
+ SECONDARY_ACTION,
211
+ PILL_ACTION,
212
+ }
213
+
214
+ function presetProps(preset: ButtonPreset): { sizing: ButtonSizing; coloring: ButtonColoring } {
215
+ switch (preset) {
216
+ case ButtonPreset.PRIMARY_CTA: return { sizing: ButtonSizing.XL, coloring: ButtonColoring.PRIMARY_BRAND };
217
+ case ButtonPreset.SECONDARY_ACTION: return { sizing: ButtonSizing.LARGE, coloring: ButtonColoring.SECONDARY };
218
+ case ButtonPreset.PILL_ACTION: return { sizing: ButtonSizing.SMALL, coloring: ButtonColoring.TERTIARY };
219
+ }
220
+ }
221
+ ```
222
+
223
+ ### Shimmer Layout
224
+
225
+ Configurable skeleton loading placeholder:
226
+
227
+ ```typescript
228
+ import { Component } from 'valdi_core/src/Component';
229
+
230
+ interface ShimmerRow {
231
+ widthRatio: number;
232
+ height: number;
233
+ borderRadius?: number;
234
+ }
235
+
236
+ interface ShimmerLayoutViewModel {
237
+ rows: ShimmerRow[];
238
+ spacing?: number;
239
+ }
240
+
241
+ export class ShimmerLayout extends Component<ShimmerLayoutViewModel> {
242
+ onRender(): void {
243
+ const spacing = this.viewModel.spacing ?? 8;
244
+ <view>
245
+ {this.viewModel.rows.forEach((row, i) => {
246
+ <AnimationShimmer
247
+ width={`${row.widthRatio * 100}%`}
248
+ height={row.height}
249
+ borderRadius={row.borderRadius ?? 4}
250
+ marginTop={i > 0 ? spacing : 0}
251
+ />;
252
+ })}
253
+ </view>;
254
+ }
255
+ }
256
+ ```
257
+
258
+ ## Tips
259
+
260
+ - Start with the highest-severity known patterns — they have the most impact
261
+ - Extract the simplest shared interface first, then iterate to handle edge cases
262
+ - Use render callbacks for module-specific UI instead of trying to generalize everything
263
+ - Run `valdi analyze duplicates --json --output report.json` to save a baseline, then re-run after extraction to measure impact
@@ -100,7 +100,7 @@ describe('ProfileCardTest', () => {
100
100
  componentGetElements(nodes[0].component!),
101
101
  'follow-button',
102
102
  )[0];
103
- button?.getAttribute('onTap')?.();
103
+ button?.getAttribute('onTap')?.({} as any);
104
104
  expect(onFollowTap).toHaveBeenCalled();
105
105
  });
106
106
 
@@ -55,10 +55,52 @@ class MyComponent extends Component<MyViewModel> {
55
55
 
56
56
  `viewFactory` and `*Class` attributes are mutually exclusive — use one or the other. `viewFactory` takes precedence when both are provided.
57
57
 
58
+ ## macOS Attribute Binding
59
+
60
+ macOS custom views can bind attributes (including callbacks) from TSX using `+bindAttributes:`. The view manager calls this class method at registration time.
61
+
62
+ ```objc
63
+ #import "valdi/macos/SCValdiMacOSAttributesBinder.h"
64
+ #import "valdi/macos/SCValdiMacOSFunction.h"
65
+
66
+ @interface SCMyView () {
67
+ SCValdiMacOSFunction *_onMyCallback;
68
+ }
69
+ @end
70
+
71
+ @implementation SCMyView
72
+ - (void)valdi_setOnMyCallback:(id)value { _onMyCallback = value; }
73
+
74
+ + (void)bindAttributes:(SCValdiMacOSAttributesBinder *)attributesBinder {
75
+ [attributesBinder bindUntypedAttribute:@"onMyCallback"
76
+ invalidateLayoutOnChange:NO
77
+ selector:@selector(valdi_setOnMyCallback:)];
78
+ }
79
+ @end
80
+ ```
81
+
82
+ **Binder methods:**
83
+ - `bindUntypedAttribute:invalidateLayoutOnChange:selector:` — binds any attribute (strings, numbers, functions)
84
+ - `bindColorAttribute:invalidateLayoutOnChange:selector:` — binds color attributes specifically
85
+
86
+ **Invoking callbacks:** Call `[_onMyCallback performWithParameters:@[@{@"key": @"value"}]]` — the NSArray/NSDictionary is auto-converted to JS objects.
87
+
88
+ ## Keyboard Input on macOS
89
+
90
+ Valdi doesn't have built-in keyboard event support. Use a polyglot `<custom-view>` with an NSView that:
91
+ 1. Overrides `acceptsFirstResponder` → `YES`
92
+ 2. Overrides `keyDown:` to map key codes to callback invocations
93
+ 3. Calls `[self.window makeFirstResponder:self]` in `viewDidMoveToWindow` to grab focus
94
+ 4. Has **non-zero dimensions** (wrap visible content inside it)
95
+
96
+ See the `valdi-polyglot-module` skill for a complete macOS attribute binding example with BUILD.bazel wiring.
97
+
58
98
  ## Common Mistakes
59
99
 
60
- - Using `<custom-view>` without checking the platform — wrap in `Device.isAndroid()` / `Device.isIOS()` etc. if not all platforms are supported
100
+ - Using `<custom-view>` without checking the platform — wrap in `Device.isAndroid()` / `Device.isIOS()` / `Device.isDesktop()` if not all platforms are supported
61
101
  - Forgetting to link native implementations — the class name string alone isn't enough; the native code must be compiled and linked via platform `_deps` in BUILD.bazel
62
102
  - Wrong package name in `androidClass` — must match the Kotlin/Java package exactly
63
103
  - Specifying `macosClass` when it's the same as `iosClass` — omit it and let the fallthrough handle it
64
104
  - Using a `filegroup` for `web_deps` — always use `ts_project` with `transpiler = "tsc"`
105
+ - Creating a 0×0 custom-view for keyboard focus — it won't become first responder; wrap content inside it
106
+ - **Duplicate ObjC class names across modules** — if two modules define the same native class (e.g. both have `SCKeyboardView`), the linker will fail with "duplicate symbol" errors. Always use a unique class name per module (e.g. prefix with module name: `SCSnakeGameKeyboardView`)