@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,277 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Extract dominant colors from regions of a mock image using k-means clustering.
4
+
5
+ Usage:
6
+ # Auto-detect thumbnail regions in a list UI
7
+ python3 extract_colors.py <mock_path> --auto-thumbnails
8
+
9
+ # Extract from specific bounding boxes (x,y,w,h)
10
+ python3 extract_colors.py <mock_path> --regions "dodgers:45,50,70,70" "larams:45,145,70,70"
11
+
12
+ # Extract UI element colors by clicking coordinates
13
+ python3 extract_colors.py <mock_path> --sample "live_badge:230,135" "green_dot:90,360"
14
+ """
15
+
16
+ import argparse
17
+ import os
18
+ import sys
19
+
20
+ try:
21
+ from PIL import Image
22
+ except ImportError:
23
+ print("Pillow not installed. Run: pip3 install Pillow", file=sys.stderr)
24
+ sys.exit(1)
25
+
26
+
27
+ def _resolve_macos_path(path: str) -> str:
28
+ """Handle macOS screenshot filenames with Unicode narrow no-break space (U+202F)."""
29
+ if os.path.exists(path):
30
+ return path
31
+ for marker in (' AM', ' PM'):
32
+ fixed = path.replace(marker, '\u202f' + marker[1:])
33
+ if os.path.exists(fixed):
34
+ return fixed
35
+ return path
36
+
37
+
38
+ def dominant_color_kmeans(pixels: list[tuple[int, int, int]], k: int = 3) -> str:
39
+ """
40
+ Find the dominant color using a simple k-means implementation.
41
+ Returns the hex color of the largest cluster, preferring saturated colors.
42
+ No numpy/scipy dependency.
43
+ """
44
+ if not pixels:
45
+ return '#000000'
46
+
47
+ if len(pixels) < k:
48
+ r = sum(p[0] for p in pixels) // len(pixels)
49
+ g = sum(p[1] for p in pixels) // len(pixels)
50
+ b = sum(p[2] for p in pixels) // len(pixels)
51
+ return f'#{r:02X}{g:02X}{b:02X}'
52
+
53
+ # Initialize centroids by spreading across the pixel range
54
+ import random
55
+ random.seed(42)
56
+ centroids = random.sample(pixels, k)
57
+
58
+ for _ in range(20): # iterations
59
+ clusters: list[list[tuple[int, int, int]]] = [[] for _ in range(k)]
60
+
61
+ for p in pixels:
62
+ dists = [sum((p[c] - centroids[i][c]) ** 2 for c in range(3)) for i in range(k)]
63
+ clusters[dists.index(min(dists))].append(p)
64
+
65
+ new_centroids = []
66
+ for cluster in clusters:
67
+ if cluster:
68
+ r = sum(p[0] for p in cluster) // len(cluster)
69
+ g = sum(p[1] for p in cluster) // len(cluster)
70
+ b = sum(p[2] for p in cluster) // len(cluster)
71
+ new_centroids.append((r, g, b))
72
+ else:
73
+ new_centroids.append(random.choice(pixels))
74
+
75
+ if new_centroids == centroids:
76
+ break
77
+ centroids = new_centroids
78
+
79
+ # Score each cluster: prefer larger + more saturated
80
+ best = None
81
+ best_score = -1
82
+ for i, cluster in enumerate(clusters):
83
+ if not cluster:
84
+ continue
85
+ r, g, b = centroids[i]
86
+ # Saturation = how far from gray
87
+ mean_val = (r + g + b) / 3
88
+ saturation = (abs(r - mean_val) + abs(g - mean_val) + abs(b - mean_val)) / 3
89
+ # Score = size * (1 + saturation bonus)
90
+ score = len(cluster) * (1 + saturation / 128)
91
+ # Penalty for near-white and near-black (these are usually background)
92
+ if mean_val > 240 or mean_val < 15:
93
+ score *= 0.1
94
+ if score > best_score:
95
+ best_score = score
96
+ best = centroids[i]
97
+
98
+ if best is None:
99
+ best = centroids[0]
100
+ return f'#{best[0]:02X}{best[1]:02X}{best[2]:02X}'
101
+
102
+
103
+ def sample_point(img: Image.Image, x: int, y: int, radius: int = 3) -> str:
104
+ """Sample a small area around a point and return the median color."""
105
+ colors = []
106
+ w, h = img.size
107
+ for dy in range(-radius, radius + 1):
108
+ for dx in range(-radius, radius + 1):
109
+ px = max(0, min(x + dx, w - 1))
110
+ py = max(0, min(y + dy, h - 1))
111
+ colors.append(img.getpixel((px, py)))
112
+ colors.sort(key=lambda c: c[0] + c[1] + c[2])
113
+ mid = colors[len(colors) // 2]
114
+ return f'#{mid[0]:02X}{mid[1]:02X}{mid[2]:02X}'
115
+
116
+
117
+ def extract_region(img: Image.Image, x: int, y: int, w: int, h: int) -> str:
118
+ """Extract dominant color from a rectangular region."""
119
+ pixels = []
120
+ img_w, img_h = img.size
121
+ for py in range(max(0, y), min(y + h, img_h)):
122
+ for px in range(max(0, x), min(x + w, img_w)):
123
+ pixels.append(img.getpixel((px, py)))
124
+ return dominant_color_kmeans(pixels)
125
+
126
+
127
+ def auto_detect_thumbnails(img: Image.Image) -> list[tuple[str, int, int, int, int]]:
128
+ """
129
+ Auto-detect thumbnail regions in a list UI.
130
+ Scans for rectangular non-white blocks in the left column.
131
+ Returns list of (name, x, y, w, h).
132
+ """
133
+ w, h = img.size
134
+ # Scan vertical center of typical thumbnail column (x=50-90 range)
135
+ scan_x = int(w * 0.11) # ~11% from left
136
+
137
+ # Find vertical segments of non-white pixels
138
+ segments = []
139
+ in_thumb = False
140
+ start_y = 0
141
+ threshold = 230
142
+
143
+ for y in range(0, h):
144
+ r, g, b = img.getpixel((scan_x, y))
145
+ is_content = r < threshold or g < threshold or b < threshold
146
+
147
+ if is_content and not in_thumb:
148
+ start_y = y
149
+ in_thumb = True
150
+ elif not is_content and in_thumb:
151
+ seg_h = y - start_y
152
+ if seg_h > 20: # minimum thumbnail height
153
+ segments.append((start_y, y))
154
+ in_thumb = False
155
+
156
+ if in_thumb:
157
+ segments.append((start_y, h))
158
+
159
+ # Now find horizontal extent for each segment
160
+ results = []
161
+ for idx, (y_start, y_end) in enumerate(segments):
162
+ mid_y = (y_start + y_end) // 2
163
+ # Scan horizontally to find left and right edges
164
+ left = None
165
+ right = None
166
+ for x in range(0, w // 3):
167
+ r, g, b = img.getpixel((x, mid_y))
168
+ if r < threshold or g < threshold or b < threshold:
169
+ if left is None:
170
+ left = x
171
+ right = x
172
+
173
+ if left is not None and right is not None:
174
+ thumb_w = right - left + 1
175
+ thumb_h = y_end - y_start
176
+ results.append((f'thumb_{idx}', left, y_start, thumb_w, thumb_h))
177
+
178
+ return results
179
+
180
+
181
+ def auto_detect_colored_regions(img: Image.Image) -> list[tuple[str, int, int, int, int]]:
182
+ """
183
+ Auto-detect ALL saturated/colored regions in the image (buttons, badges, icons).
184
+ Scans the entire image for clusters of non-white, non-black, saturated pixels.
185
+ Returns list of (name, x, y, w, h).
186
+ """
187
+ w, h = img.size
188
+ threshold_sat = 25 # minimum saturation to be "colored"
189
+ step = 3
190
+
191
+ # Find all saturated pixels
192
+ colored_pixels = []
193
+ for y in range(0, h, step):
194
+ for x in range(0, w, step):
195
+ r, g, b = img.getpixel((x, y))
196
+ mean = (r + g + b) / 3
197
+ sat = max(abs(r - mean), abs(g - mean), abs(b - mean))
198
+ if sat > threshold_sat and 20 < mean < 245:
199
+ colored_pixels.append((x, y))
200
+
201
+ if not colored_pixels:
202
+ return []
203
+
204
+ # Simple flood-fill clustering: group nearby pixels
205
+ clusters: list[list[tuple[int, int]]] = []
206
+ used = set()
207
+ for px, py in colored_pixels:
208
+ if (px, py) in used:
209
+ continue
210
+ # BFS to find connected colored pixels
211
+ cluster = [(px, py)]
212
+ queue = [(px, py)]
213
+ used.add((px, py))
214
+ while queue:
215
+ cx, cy = queue.pop(0)
216
+ for nx, ny in colored_pixels:
217
+ if (nx, ny) not in used and abs(nx - cx) <= step * 2 and abs(ny - cy) <= step * 2:
218
+ used.add((nx, ny))
219
+ cluster.append((nx, ny))
220
+ queue.append((nx, ny))
221
+ if len(cluster) >= 3: # minimum cluster size
222
+ clusters.append(cluster)
223
+
224
+ results = []
225
+ for idx, cluster in enumerate(clusters):
226
+ xs = [p[0] for p in cluster]
227
+ ys = [p[1] for p in cluster]
228
+ x_min, x_max = min(xs), max(xs)
229
+ y_min, y_max = min(ys), max(ys)
230
+ cw = x_max - x_min + step
231
+ ch = y_max - y_min + step
232
+ results.append((f'region_{idx}', x_min, y_min, cw, ch))
233
+
234
+ return results
235
+
236
+
237
+ if __name__ == '__main__':
238
+ parser = argparse.ArgumentParser(description='Extract colors from a mock image')
239
+ parser.add_argument('mock', help='Path to mock image')
240
+ parser.add_argument('--auto-thumbnails', action='store_true',
241
+ help='Auto-detect thumbnail regions')
242
+ parser.add_argument('--auto-colors', action='store_true',
243
+ help='Auto-detect ALL colored regions (buttons, badges, icons)')
244
+ parser.add_argument('--regions', nargs='*', default=[],
245
+ help='Named regions: "name:x,y,w,h"')
246
+ parser.add_argument('--sample', nargs='*', default=[],
247
+ help='Sample points: "name:x,y"')
248
+ args = parser.parse_args()
249
+
250
+ img = Image.open(_resolve_macos_path(args.mock)).convert('RGB')
251
+ print(f'Image: {img.size[0]}x{img.size[1]}')
252
+
253
+ if args.auto_thumbnails:
254
+ print('\n--- Auto-detected thumbnails ---')
255
+ thumbs = auto_detect_thumbnails(img)
256
+ for name, x, y, tw, th in thumbs:
257
+ color = extract_region(img, x, y, tw, th)
258
+ print(f" {name:25s} {color} ({x},{y},{tw}x{th})")
259
+
260
+ if args.auto_colors:
261
+ print('\n--- Auto-detected colored regions ---')
262
+ regions = auto_detect_colored_regions(img)
263
+ for name, x, y, rw, rh in regions:
264
+ color = extract_region(img, x, y, rw, rh)
265
+ print(f" {name:25s} {color} ({x},{y},{rw}x{rh})")
266
+
267
+ for region_spec in args.regions:
268
+ name, coords = region_spec.split(':')
269
+ x, y, rw, rh = map(int, coords.split(','))
270
+ color = extract_region(img, x, y, rw, rh)
271
+ print(f" {name:25s} {color} ({x},{y},{rw}x{rh})")
272
+
273
+ for sample_spec in args.sample:
274
+ name, coords = sample_spec.split(':')
275
+ x, y = map(int, coords.split(','))
276
+ color = sample_point(img, x, y)
277
+ print(f" {name:25s} {color} ({x},{y})")
@@ -0,0 +1,303 @@
1
+ #!/usr/bin/env python3
2
+ """Fuzzy icon finder for Valdi's SIGIcon library.
3
+
4
+ Parses icon names from SIGIcons.tsx and performs fuzzy matching against
5
+ a search query. Uses word overlap, substring matching, and a synonym
6
+ map to find relevant icons.
7
+
8
+ Usage:
9
+ python3 find_icon.py "chat bubble" --icons-file /path/to/SIGIcons.tsx
10
+ python3 find_icon.py "settings"
11
+ python3 find_icon.py "arrow right share"
12
+ """
13
+
14
+ import argparse
15
+ import glob
16
+ import re
17
+ import sys
18
+ from typing import List, Tuple
19
+
20
+ # Synonym map: common search terms -> actual icon name words
21
+ # Values are the camelCase-split lowercase words that appear in icon names.
22
+ SYNONYMS = {
23
+ "settings": ["gear"],
24
+ "search": ["magnifying", "glass"],
25
+ "home": ["house"],
26
+ "profile": ["person"],
27
+ "audio": ["waveform"],
28
+ "music": ["waveform"],
29
+ "send": ["arrow", "paper", "plane"],
30
+ "delete": ["trash", "can"],
31
+ "edit": ["pencil"],
32
+ "close": ["x", "sign"],
33
+ "dismiss": ["x", "sign"],
34
+ "back": ["arrow", "left"],
35
+ "forward": ["arrow", "right"],
36
+ "menu": ["three", "dot", "horizontal"],
37
+ "more": ["three", "dot", "horizontal"],
38
+ "camera": ["camera"],
39
+ "photo": ["camera"],
40
+ "video": ["video", "camera"],
41
+ "location": ["map", "pin"],
42
+ "pin": ["map", "pin"],
43
+ "notification": ["bell"],
44
+ "alert": ["bell"],
45
+ }
46
+
47
+
48
+ def parse_icons(filepath: str) -> List[str]:
49
+ """Parse icon getter names from SIGIcons.tsx."""
50
+ pattern = re.compile(r"static get (\w+)\(\): Asset")
51
+ icons = []
52
+ with open(filepath, "r") as f:
53
+ for line in f:
54
+ m = pattern.search(line)
55
+ if m:
56
+ icons.append(m.group(1))
57
+ return icons
58
+
59
+
60
+ def split_camel_case(name: str) -> List[str]:
61
+ """Split a camelCase name into lowercase words.
62
+
63
+ Examples:
64
+ chatBubbleFill -> ['chat', 'bubble', 'fill']
65
+ arrowRightShareFill -> ['arrow', 'right', 'share', 'fill']
66
+ xmarkFill -> ['xmark', 'fill']
67
+ threeDotHorizontalFill -> ['three', 'dot', 'horizontal', 'fill']
68
+ """
69
+ # Insert a split before each uppercase letter that follows a lowercase letter
70
+ # or before an uppercase letter followed by a lowercase letter (for runs of caps)
71
+ parts = re.sub(r"([a-z])([A-Z])", r"\1 \2", name)
72
+ parts = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", parts)
73
+ return [w.lower() for w in parts.split()]
74
+
75
+
76
+ def expand_query(query_words: List[str]) -> List[str]:
77
+ """Expand query words using the synonym map.
78
+
79
+ Returns the original words plus any synonym expansions.
80
+ """
81
+ expanded = list(query_words)
82
+ for word in query_words:
83
+ key = word.lower()
84
+ if key in SYNONYMS:
85
+ for syn in SYNONYMS[key]:
86
+ if syn.lower() not in expanded:
87
+ expanded.append(syn.lower())
88
+ return expanded
89
+
90
+
91
+ def score_icon(icon_words: List[str], query_words: List[str], expanded_words: List[str]) -> float:
92
+ """Score an icon against the query.
93
+
94
+ Scoring factors:
95
+ - Exact word matches (highest weight)
96
+ - Prefix/substring matches on icon words
97
+ - Synonym-expanded matches
98
+ - Fill variant boost
99
+ - Penalty for icons with many extra unmatched words
100
+ """
101
+ # Words without fill/stroke for matching purposes
102
+ icon_content = [w for w in icon_words if w not in ("fill", "stroke")]
103
+ query_content = [w for w in expanded_words if w not in ("fill", "stroke")]
104
+
105
+ if not query_content:
106
+ return 0.0
107
+
108
+ score = 0.0
109
+ matched_icon_words = set()
110
+
111
+ # Exact word matches from original query (highest value)
112
+ for qw in query_words:
113
+ qw_lower = qw.lower()
114
+ if qw_lower in ("fill", "stroke"):
115
+ continue
116
+ for i, iw in enumerate(icon_content):
117
+ if iw == qw_lower:
118
+ score += 10.0
119
+ matched_icon_words.add(i)
120
+ break
121
+
122
+ # Exact word matches from expanded synonyms (slightly less value)
123
+ for qw in expanded_words:
124
+ qw_lower = qw.lower()
125
+ if qw_lower in query_words or qw_lower in ("fill", "stroke"):
126
+ continue
127
+ for i, iw in enumerate(icon_content):
128
+ if iw == qw_lower and i not in matched_icon_words:
129
+ score += 8.0
130
+ matched_icon_words.add(i)
131
+ break
132
+
133
+ # Prefix matches: query word is a prefix of an icon word
134
+ for qw in expanded_words:
135
+ qw_lower = qw.lower()
136
+ if qw_lower in ("fill", "stroke"):
137
+ continue
138
+ for i, iw in enumerate(icon_content):
139
+ if i not in matched_icon_words and iw.startswith(qw_lower) and len(qw_lower) >= 3:
140
+ score += 5.0
141
+ matched_icon_words.add(i)
142
+ break
143
+
144
+ # Substring matches: query word is contained in an icon word
145
+ for qw in expanded_words:
146
+ qw_lower = qw.lower()
147
+ if qw_lower in ("fill", "stroke"):
148
+ continue
149
+ for i, iw in enumerate(icon_content):
150
+ if i not in matched_icon_words and qw_lower in iw and len(qw_lower) >= 3:
151
+ score += 3.0
152
+ matched_icon_words.add(i)
153
+ break
154
+
155
+ # Reverse substring: icon word is contained in a query word
156
+ # Require the icon word to be at least 4 chars and at least 40% of the query word
157
+ # to avoid spurious matches like "one" in "nonexistenticon"
158
+ for i, iw in enumerate(icon_content):
159
+ if i not in matched_icon_words:
160
+ for qw in expanded_words:
161
+ qw_lower = qw.lower()
162
+ if qw_lower in ("fill", "stroke"):
163
+ continue
164
+ if iw in qw_lower and len(iw) >= 4 and len(iw) / len(qw_lower) >= 0.4:
165
+ score += 2.0
166
+ matched_icon_words.add(i)
167
+ break
168
+
169
+ if score == 0:
170
+ return 0.0
171
+
172
+ # Coverage bonus: reward icons where more of the icon's content words matched
173
+ if icon_content:
174
+ coverage = len(matched_icon_words) / len(icon_content)
175
+ score *= (0.5 + 0.5 * coverage)
176
+
177
+ # Query coverage bonus: reward matching more query words
178
+ query_match_count = 0
179
+ for qw in query_content:
180
+ for iw in icon_content:
181
+ if iw == qw or iw.startswith(qw) or qw in iw:
182
+ query_match_count += 1
183
+ break
184
+ if query_content:
185
+ query_coverage = query_match_count / len(query_content)
186
+ score *= (0.5 + 0.5 * query_coverage)
187
+
188
+ # Fill variant boost (fill icons are more commonly used)
189
+ is_fill = "fill" in icon_words
190
+ is_stroke = "stroke" in icon_words
191
+ if is_fill:
192
+ score *= 1.05
193
+
194
+ # Small penalty for extra unmatched words (prefer shorter, more precise icons)
195
+ unmatched = len(icon_content) - len(matched_icon_words)
196
+ if unmatched > 0:
197
+ score *= (1.0 / (1.0 + 0.1 * unmatched))
198
+
199
+ return score
200
+
201
+
202
+ def find_icons(query: str, icons_file: str, top_n: int = 5) -> List[Tuple[str, float, List[str]]]:
203
+ """Find the top N matching icons for a query.
204
+
205
+ Returns list of (icon_name, score, icon_words) tuples.
206
+ """
207
+ icons = parse_icons(icons_file)
208
+ query_words = query.lower().split()
209
+ expanded_words = expand_query(query_words)
210
+
211
+ scored = []
212
+ for icon in icons:
213
+ icon_words = split_camel_case(icon)
214
+ s = score_icon(icon_words, query_words, expanded_words)
215
+ if s > 0:
216
+ scored.append((icon, s, icon_words))
217
+
218
+ scored.sort(key=lambda x: -x[1])
219
+ return scored[:top_n]
220
+
221
+
222
+ def find_default_icons_file() -> str:
223
+ """Try to find SIGIcons.tsx in common locations."""
224
+ patterns = [
225
+ # Common icon library locations
226
+ "**/src/components/icon/*Icons.tsx",
227
+ "**/widgets/src/components/icon/*Icons.tsx",
228
+ ]
229
+ for pattern in patterns:
230
+ matches = glob.glob(pattern, recursive=True)
231
+ if matches:
232
+ return matches[0]
233
+ return ""
234
+
235
+
236
+ def main():
237
+ parser = argparse.ArgumentParser(
238
+ description="Fuzzy icon finder for Valdi SIGIcon library"
239
+ )
240
+ parser.add_argument("query", help="Search query (e.g. 'chat bubble', 'settings', 'arrow right')")
241
+ parser.add_argument(
242
+ "--icons-file",
243
+ default="",
244
+ help="Path to SIGIcons.tsx (auto-detected if not provided)",
245
+ )
246
+ parser.add_argument(
247
+ "--top",
248
+ type=int,
249
+ default=5,
250
+ help="Number of results to show (default: 5)",
251
+ )
252
+ parser.add_argument(
253
+ "--json",
254
+ action="store_true",
255
+ help="Output results as JSON",
256
+ )
257
+ args = parser.parse_args()
258
+
259
+ icons_file = args.icons_file
260
+ if not icons_file:
261
+ icons_file = find_default_icons_file()
262
+ if not icons_file:
263
+ print("Error: Could not find SIGIcons.tsx. Please provide --icons-file.", file=sys.stderr)
264
+ sys.exit(1)
265
+
266
+ results = find_icons(args.query, icons_file, args.top)
267
+
268
+ if args.json:
269
+ import json
270
+
271
+ output = []
272
+ for icon_name, score, icon_words in results:
273
+ is_fill = "fill" in icon_words
274
+ is_stroke = "stroke" in icon_words
275
+ variant = "Fill" if is_fill else ("Stroke" if is_stroke else "Other")
276
+ content_words = [w for w in icon_words if w not in ("fill", "stroke")]
277
+ output.append({
278
+ "name": icon_name,
279
+ "variant": variant,
280
+ "words": content_words,
281
+ "score": round(score, 2),
282
+ })
283
+ print(json.dumps(output, indent=2))
284
+ else:
285
+ print(f'Query: "{args.query}"')
286
+ if not results:
287
+ print(" No matching icons found.")
288
+ else:
289
+ # Calculate alignment width from longest icon name
290
+ max_name_len = max(len(r[0]) for r in results)
291
+ for i, (icon_name, score, icon_words) in enumerate(results, 1):
292
+ is_fill = "fill" in icon_words
293
+ is_stroke = "stroke" in icon_words
294
+ variant = "Fill" if is_fill else ("Stroke" if is_stroke else "Other")
295
+ content_words = [w for w in icon_words if w not in ("fill", "stroke")]
296
+ words_str = ", ".join(content_words)
297
+ padding = " " * (max_name_len - len(icon_name))
298
+ variant_padded = f"({variant})" + (" " if variant == "Fill" else "")
299
+ print(f" {i}. {icon_name}{padding} {variant_padded} — {words_str}")
300
+
301
+
302
+ if __name__ == "__main__":
303
+ main()
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env bash
2
+ # Capture a Valdi snapshot and generate a pixel diff against a mock.
3
+ #
4
+ # Usage:
5
+ # snapshot-and-diff.sh <mock_path> [--key <element_key>] [--port <port>] [--context <device_idx> <context_idx>]
6
+ #
7
+ # Outputs:
8
+ # - Snapshot PNG (path printed to stdout)
9
+ # - Diff PNG at /tmp/mock-vs-render-diff.png
10
+ # - Match percentage printed to stdout
11
+
12
+ set -euo pipefail
13
+
14
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
15
+ MOCK_PATH="${1:?Usage: snapshot-and-diff.sh <mock_path> [--key KEY] [--port PORT]}"
16
+ shift
17
+
18
+ KEY="ProfileStoriesPage"
19
+ PORT="13591"
20
+ CONTEXT_ARGS=""
21
+
22
+ while [[ $# -gt 0 ]]; do
23
+ case "$1" in
24
+ --key) KEY="$2"; shift 2 ;;
25
+ --port) PORT="$2"; shift 2 ;;
26
+ --context) CONTEXT_ARGS="$2 $3"; shift 3 ;;
27
+ *) echo "Unknown arg: $1" >&2; exit 1 ;;
28
+ esac
29
+ done
30
+
31
+ echo "Capturing snapshot (key=$KEY, port=$PORT, context=$CONTEXT_ARGS)..."
32
+ # Parse the JSON output to get the actual snapshot path
33
+ SNAPSHOT_CMD="valdi"
34
+ command -v valdi-sc &>/dev/null && SNAPSHOT_CMD="valdi-sc"
35
+ # shellcheck disable=SC2086
36
+ SNAPSHOT_OUTPUT=$($SNAPSHOT_CMD inspect snapshot $CONTEXT_ARGS --key "$KEY" --port "$PORT" 2>&1) || true
37
+ SNAPSHOT_PATH=$(echo "$SNAPSHOT_OUTPUT" | grep -o '"path":"[^"]*"' | head -1 | sed 's/"path":"//;s/"//')
38
+
39
+ if [[ -z "$SNAPSHOT_PATH" || ! -f "$SNAPSHOT_PATH" ]]; then
40
+ echo "ERROR: Could not capture snapshot. Output was:" >&2
41
+ echo "$SNAPSHOT_OUTPUT" >&2
42
+ exit 1
43
+ fi
44
+
45
+ echo "Snapshot: $SNAPSHOT_PATH"
46
+ echo "Generating diff..."
47
+ python3 "$SCRIPT_DIR/diff.py" "$MOCK_PATH" "$SNAPSHOT_PATH"
48
+
49
+ echo ""
50
+ echo "Diff: /tmp/mock-vs-render-diff.png"
51
+
52
+ # Open the diff image in a window for visual inspection
53
+ open /tmp/mock-vs-render-diff.png