@snap/valdi 1.0.8 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/.bootstrap/apps/cli_application/BUILD.bazel.template +7 -0
  2. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +11 -0
  3. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +1 -0
  4. package/.bootstrap/apps/ui_application/.eslint.rc +27 -0
  5. package/.bootstrap/apps/ui_application/BUILD.bazel.template +19 -0
  6. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +21 -0
  7. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  8. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +133 -0
  9. package/.bootstrap/apps/ui_application/package.json +24 -0
  10. package/.bootstrap/modules/polyglot_bridge_module/BUILD.bazel.template +54 -0
  11. package/.bootstrap/modules/polyglot_bridge_module/android/CalculatorModuleFactory.kt.template +18 -0
  12. package/.bootstrap/modules/polyglot_bridge_module/ios/SCCCalculatorModuleFactory.m.template +31 -0
  13. package/.bootstrap/modules/polyglot_bridge_module/src/Calculator.d.ts +4 -0
  14. package/.bootstrap/modules/polyglot_bridge_module/web/Calculator.ts +11 -0
  15. package/.bootstrap/modules/polyglot_bridge_module/web/tsconfig.json +16 -0
  16. package/.bootstrap/modules/polyglot_view_module/BUILD.bazel.template +75 -0
  17. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeView.kt.template +41 -0
  18. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeViewAttributesBinder.kt.template +17 -0
  19. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.h +8 -0
  20. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.m +23 -0
  21. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.h +8 -0
  22. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.m +23 -0
  23. package/.bootstrap/modules/polyglot_view_module/src/PolyglotCustomView.tsx.template +23 -0
  24. package/.bootstrap/modules/polyglot_view_module/web/PolyglotWeb.ts.template +30 -0
  25. package/.bootstrap/modules/polyglot_view_module/web/tsconfig.json +16 -0
  26. package/.bootstrap/modules/ui_component/BUILD.bazel.template +34 -0
  27. package/.bootstrap/modules/ui_component/src/NewModuleComponent.tsx +45 -0
  28. package/.metadata/.bazelrc.template +92 -0
  29. package/.metadata/.bazelversion.template +1 -0
  30. package/.metadata/.editorconfig.template +37 -0
  31. package/.metadata/.eslintrc.js.template +27 -0
  32. package/.metadata/.gitignore.template +4 -0
  33. package/.metadata/.prettierrc.json.template +7 -0
  34. package/.metadata/.watchmanconfig.template +8 -0
  35. package/.metadata/AGENTS.md.template +16 -0
  36. package/.metadata/MODULE.bazel.template +62 -0
  37. package/.metadata/README.md.template +31 -0
  38. package/.metadata/config.yaml.template +1 -0
  39. package/.metadata/package.json.template +23 -0
  40. package/.metadata/skill-reference.tsx.template +8 -0
  41. package/.metadata/skill-tests-BUILD.bazel.template +21 -0
  42. package/.metadata/skill-tests-README.md.template +17 -0
  43. package/.metadata/skill.md.template +27 -0
  44. package/bundled-skills/registry.json +14 -2
  45. package/bundled-skills/skills/valdi-animations/skill.md +197 -0
  46. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +1 -1
  47. package/bundled-skills/skills/valdi-bazel/skill.md +21 -2
  48. package/bundled-skills/skills/valdi-component-dedup/skill.md +263 -0
  49. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
  50. package/bundled-skills/skills/valdi-custom-view/skill.md +49 -5
  51. package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
  52. package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
  53. package/bundled-skills/skills/valdi-inspect/skill.md +217 -0
  54. package/bundled-skills/skills/valdi-localization/skill.md +142 -0
  55. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
  56. package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
  57. package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
  58. package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
  59. package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
  60. package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
  61. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
  62. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
  63. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
  64. package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
  65. package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
  66. package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
  67. package/bundled-skills/skills/valdi-overview/skill.md +7 -4
  68. package/bundled-skills/skills/valdi-perf/skill.md +223 -0
  69. package/bundled-skills/skills/valdi-polyglot-module/skill.md +131 -12
  70. package/bundled-skills/skills/valdi-preview/skill.md +303 -0
  71. package/bundled-skills/skills/valdi-profile/skill.md +126 -0
  72. package/bundled-skills/skills/valdi-setup/skill.md +55 -5
  73. package/bundled-skills/skills/valdi-testing/skill.md +23 -7
  74. package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
  75. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
  76. package/dist/commands/agentCheck.js +184 -0
  77. package/dist/commands/analyze.js +16 -0
  78. package/dist/commands/analyze_commands/duplicates.js +134 -0
  79. package/dist/commands/bootstrap.js +57 -73
  80. package/dist/commands/doctor.js +40 -203
  81. package/dist/commands/hotreload.js +15 -0
  82. package/dist/commands/inspect.js +16 -0
  83. package/dist/commands/inspect_commands/contexts.js +55 -0
  84. package/dist/commands/inspect_commands/devices.js +53 -0
  85. package/dist/commands/inspect_commands/heap.js +59 -0
  86. package/dist/commands/inspect_commands/select.js +43 -0
  87. package/dist/commands/inspect_commands/snapshot.js +129 -0
  88. package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
  89. package/dist/commands/inspect_commands/status.js +68 -0
  90. package/dist/commands/inspect_commands/tree.js +86 -0
  91. package/dist/commands/preview.js +81 -0
  92. package/dist/commands/profile.js +16 -0
  93. package/dist/commands/profile_commands/capture.js +106 -0
  94. package/dist/commands/projectsync.js +9 -7
  95. package/dist/commands/skills_commands/install.js +6 -1
  96. package/dist/commands/skills_commands/update.js +2 -1
  97. package/dist/core/analyze/clusterer.js +150 -0
  98. package/dist/core/analyze/fingerprint.js +2 -0
  99. package/dist/core/analyze/knownPatterns.js +76 -0
  100. package/dist/core/analyze/parser.js +177 -0
  101. package/dist/core/analyze/reporter.js +83 -0
  102. package/dist/core/analyze/scanner.js +172 -0
  103. package/dist/core/analyze/similarity.js +56 -0
  104. package/dist/core/constants.js +1 -1
  105. package/dist/core/packageFiles.spec.js +29 -0
  106. package/dist/preview/previewGenerator.js +240 -0
  107. package/dist/preview/previewGenerator.spec.js +203 -0
  108. package/dist/preview/viewModelParser.js +86 -0
  109. package/dist/preview/viewModelParser.spec.js +171 -0
  110. package/dist/setup/DevSetupHelper.js +0 -51
  111. package/dist/setup/linuxSetup.js +0 -2
  112. package/dist/setup/macOSSetup.js +1 -4
  113. package/dist/utils/BazelClient.js +15 -0
  114. package/dist/utils/daemonClient.js +344 -0
  115. package/dist/utils/hermesClient.js +252 -0
  116. package/dist/utils/skillsAdapters.js +86 -5
  117. package/dist/utils/skillsAdapters.spec.js +60 -0
  118. package/dist/utils/skillsRegistry.js +8 -0
  119. package/dist/utils/stringUtils.spec.js +1 -1
  120. package/package.json +30 -12
  121. package/dist/setup/versions.js +0 -8
@@ -0,0 +1,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
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env python3
2
+ """Tests for diff.py — pixel diff and shadow detection logic."""
3
+
4
+ import os
5
+ import sys
6
+ import tempfile
7
+ import unittest
8
+
9
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
10
+ from diff import (
11
+ _crop_to_phone_frame,
12
+ _auto_detect_masks,
13
+ _apply_masks,
14
+ _segment_match,
15
+ _parse_mask_region,
16
+ detect_missing_shadows,
17
+ generate_diff,
18
+ )
19
+
20
+ try:
21
+ from PIL import Image, ImageChops
22
+ except ImportError:
23
+ print("Pillow required for tests: pip3 install Pillow", file=sys.stderr)
24
+ sys.exit(1)
25
+
26
+
27
+ class TestCropToPhoneFrame(unittest.TestCase):
28
+ def test_crops_centered_white_frame(self):
29
+ # Simulate a desktop window with dark bg and white phone frame
30
+ img = Image.new('RGB', (800, 600), (51, 51, 51)) # #333 background
31
+ # White phone frame 390px wide, centered
32
+ left = (800 - 390) // 2
33
+ for y in range(600):
34
+ for x in range(left, left + 390):
35
+ img.putpixel((x, y), (255, 255, 255))
36
+ cropped = _crop_to_phone_frame(img)
37
+ # Should be approximately 390px wide (with small padding)
38
+ self.assertGreater(cropped.width, 380)
39
+ self.assertLess(cropped.width, 410)
40
+
41
+ def test_returns_full_image_when_no_frame(self):
42
+ # All-dark image — no phone frame to detect
43
+ img = Image.new('RGB', (400, 600), (51, 51, 51))
44
+ cropped = _crop_to_phone_frame(img)
45
+ self.assertEqual(cropped.size, img.size)
46
+
47
+ def test_returns_full_image_when_all_white(self):
48
+ img = Image.new('RGB', (400, 600), (255, 255, 255))
49
+ cropped = _crop_to_phone_frame(img)
50
+ # Entire image is "bright", so it returns the whole thing
51
+ self.assertEqual(cropped.width, 400)
52
+
53
+
54
+ class TestAutoDetectMasks(unittest.TestCase):
55
+ def test_detects_dark_blocks(self):
56
+ img = Image.new('RGB', (200, 200), (255, 255, 255))
57
+ # Dark block in left column
58
+ for y in range(40, 80):
59
+ for x in range(15, 35):
60
+ img.putpixel((x, y), (50, 50, 50))
61
+ masks = _auto_detect_masks(img)
62
+ self.assertGreater(len(masks), 0)
63
+
64
+ def test_no_masks_on_white(self):
65
+ img = Image.new('RGB', (200, 200), (255, 255, 255))
66
+ masks = _auto_detect_masks(img)
67
+ self.assertEqual(len(masks), 0)
68
+
69
+
70
+ class TestApplyMasks(unittest.TestCase):
71
+ def test_fills_mask_regions(self):
72
+ img = Image.new('RGB', (100, 100), (255, 0, 0))
73
+ masked = _apply_masks(img, [(10, 10, 20, 20)], fill=(128, 128, 128))
74
+ # Center of masked region should be gray
75
+ self.assertEqual(masked.getpixel((20, 20)), (128, 128, 128))
76
+ # Outside mask should still be red
77
+ self.assertEqual(masked.getpixel((0, 0)), (255, 0, 0))
78
+
79
+ def test_clamps_to_image_bounds(self):
80
+ img = Image.new('RGB', (50, 50), (0, 255, 0))
81
+ # Mask extends beyond image — should not crash
82
+ masked = _apply_masks(img, [(40, 40, 20, 20)])
83
+ self.assertEqual(masked.size, (50, 50))
84
+
85
+ def test_empty_masks_returns_copy(self):
86
+ img = Image.new('RGB', (50, 50), (100, 100, 100))
87
+ masked = _apply_masks(img, [])
88
+ self.assertEqual(masked.getpixel((25, 25)), (100, 100, 100))
89
+
90
+
91
+ class TestSegmentMatch(unittest.TestCase):
92
+ def test_identical_images_100_percent(self):
93
+ # All-black diff = perfect match
94
+ diff = Image.new('RGB', (100, 100), (0, 0, 0))
95
+ segments = _segment_match(diff, num_segments=4, threshold=30)
96
+ self.assertEqual(len(segments), 4)
97
+ for label, pct in segments:
98
+ self.assertEqual(pct, 100.0)
99
+
100
+ def test_all_different_0_percent(self):
101
+ # All-white diff = no match
102
+ diff = Image.new('RGB', (100, 100), (255, 255, 255))
103
+ segments = _segment_match(diff, num_segments=2, threshold=30)
104
+ self.assertEqual(len(segments), 2)
105
+ for label, pct in segments:
106
+ self.assertEqual(pct, 0.0)
107
+
108
+ def test_mixed_segments(self):
109
+ # Top half black (match), bottom half white (no match)
110
+ diff = Image.new('RGB', (100, 100), (0, 0, 0))
111
+ for y in range(50, 100):
112
+ for x in range(100):
113
+ diff.putpixel((x, y), (255, 255, 255))
114
+ segments = _segment_match(diff, num_segments=2, threshold=30)
115
+ self.assertEqual(len(segments), 2)
116
+ self.assertEqual(segments[0][1], 100.0) # top = match
117
+ self.assertEqual(segments[1][1], 0.0) # bottom = no match
118
+
119
+ def test_label_format(self):
120
+ diff = Image.new('RGB', (100, 100), (0, 0, 0))
121
+ segments = _segment_match(diff, num_segments=4)
122
+ labels = [s[0] for s in segments]
123
+ self.assertIn('rows 0-25%', labels)
124
+ self.assertIn('rows 75-100%', labels)
125
+
126
+
127
+ class TestParseMaskRegion(unittest.TestCase):
128
+ def test_valid_region(self):
129
+ self.assertEqual(_parse_mask_region('10,20,30,40'), (10, 20, 30, 40))
130
+
131
+ def test_invalid_region(self):
132
+ with self.assertRaises(ValueError):
133
+ _parse_mask_region('10,20,30')
134
+ with self.assertRaises(ValueError):
135
+ _parse_mask_region('10,20,30,40,50')
136
+
137
+
138
+ class TestDetectMissingShadows(unittest.TestCase):
139
+ def test_identical_images_no_shadows(self):
140
+ img = Image.new('RGB', (100, 100), (200, 200, 200))
141
+ overlay, count, pct = detect_missing_shadows(img, img)
142
+ self.assertEqual(count, 0)
143
+ self.assertEqual(pct, 0)
144
+
145
+ def test_returns_image_of_correct_size(self):
146
+ mock = Image.new('RGB', (100, 100), (180, 180, 180))
147
+ render = Image.new('RGB', (100, 100), (220, 220, 220))
148
+ overlay, count, pct = detect_missing_shadows(mock, render)
149
+ self.assertEqual(overlay.size, (100, 100))
150
+
151
+
152
+ class TestGenerateDiff(unittest.TestCase):
153
+ def setUp(self):
154
+ self.tmpdir = tempfile.mkdtemp()
155
+
156
+ def tearDown(self):
157
+ import shutil
158
+ shutil.rmtree(self.tmpdir)
159
+
160
+ def test_identical_images_high_match(self):
161
+ img = Image.new('RGB', (400, 800), (255, 255, 255))
162
+ mock_path = os.path.join(self.tmpdir, 'mock.png')
163
+ render_path = os.path.join(self.tmpdir, 'render.png')
164
+ output_path = os.path.join(self.tmpdir, 'diff.png')
165
+ img.save(mock_path)
166
+ img.save(render_path)
167
+ match_pct = generate_diff(mock_path, render_path, output_path)
168
+ self.assertGreater(match_pct, 90.0)
169
+ self.assertTrue(os.path.exists(output_path))
170
+
171
+ def test_output_is_4_panels_wide(self):
172
+ img = Image.new('RGB', (400, 800), (200, 200, 200))
173
+ mock_path = os.path.join(self.tmpdir, 'mock.png')
174
+ render_path = os.path.join(self.tmpdir, 'render.png')
175
+ output_path = os.path.join(self.tmpdir, 'diff.png')
176
+ img.save(mock_path)
177
+ img.save(render_path)
178
+ generate_diff(mock_path, render_path, output_path, width=200)
179
+ result = Image.open(output_path)
180
+ # 4 panels of 200px + 3 gaps of 6px = 818
181
+ self.assertEqual(result.width, 200 * 4 + 6 * 3)
182
+
183
+ def test_with_segments(self):
184
+ img = Image.new('RGB', (400, 800), (255, 255, 255))
185
+ mock_path = os.path.join(self.tmpdir, 'mock.png')
186
+ render_path = os.path.join(self.tmpdir, 'render.png')
187
+ output_path = os.path.join(self.tmpdir, 'diff.png')
188
+ img.save(mock_path)
189
+ img.save(render_path)
190
+ # Should not crash with segments enabled
191
+ match_pct = generate_diff(mock_path, render_path, output_path, num_segments=4)
192
+ self.assertGreater(match_pct, 90.0)
193
+
194
+ def test_with_mask_regions(self):
195
+ img = Image.new('RGB', (400, 800), (255, 255, 255))
196
+ mock_path = os.path.join(self.tmpdir, 'mock.png')
197
+ render_path = os.path.join(self.tmpdir, 'render.png')
198
+ output_path = os.path.join(self.tmpdir, 'diff.png')
199
+ img.save(mock_path)
200
+ img.save(render_path)
201
+ match_pct = generate_diff(mock_path, render_path, output_path,
202
+ mask_regions=[(10, 10, 50, 50)])
203
+ self.assertGreater(match_pct, 90.0)
204
+
205
+
206
+ if __name__ == '__main__':
207
+ unittest.main()