100+ copy-paste UI components in plain HTML and CSS: no dependencies, no build step.

0 downloads

dbbasic-web-native/test_spatial.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-web-native.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-web-native.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-web-native.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add canonical.html v1.0 - The single source of truth for usability standards fb6e650 1 year ago History
test_spatial.py · 17.7 KB · 451 lines
1#!/usr/bin/env python3
2"""
3Spatial context tests for AR/VR environments.
4Tests component behavior in 3D space, distance scaling, and spatial interactions.
5Cost: FREE (Simulated spatial contexts)
6Run: On schedule (future capability)
7"""
8
9from playwright.sync_api import sync_playwright
10from pathlib import Path
11import json
12import math
13
14class SpatialTester:
15 def __init__(self):
16 self.results = []
17
18 # Spatial contexts based on viewing distance
19 SPATIAL_CONTEXTS = [
20 {'name': 'handheld', 'distance_cm': 30, 'viewport': {'width': 375, 'height': 667}, 'dpi_scale': 1.0},
21 {'name': 'desktop', 'distance_cm': 60, 'viewport': {'width': 1400, 'height': 1200}, 'dpi_scale': 1.0},
22 {'name': 'ar_near', 'distance_cm': 100, 'viewport': {'width': 1920, 'height': 1080}, 'dpi_scale': 1.5},
23 {'name': 'ar_mid', 'distance_cm': 200, 'viewport': {'width': 1920, 'height': 1080}, 'dpi_scale': 2.0},
24 {'name': 'ar_far', 'distance_cm': 400, 'viewport': {'width': 1920, 'height': 1080}, 'dpi_scale': 3.0},
25 ]
26
27 def calculate_visual_angle(self, size_px, distance_cm, dpi=96):
28 """Calculate visual angle in degrees for element at given distance"""
29 # Convert pixels to cm (assuming standard DPI)
30 size_cm = (size_px / dpi) * 2.54
31
32 # Calculate visual angle using small angle approximation
33 # tan(θ) ≈ θ (in radians) for small angles
34 visual_angle_rad = size_cm / distance_cm
35 visual_angle_deg = math.degrees(visual_angle_rad)
36
37 return visual_angle_deg
38
39 def test_distance_readability(self, page, component_name, context):
40 """Test if text is readable at specified viewing distance"""
41 issues = []
42
43 file_path = Path(__file__).parent / 'docs' / component_name
44 page.goto(f'file://{file_path}')
45 page.wait_for_load_state('networkidle')
46
47 # Get all text elements
48 text_elements = page.evaluate("""() => {
49 const elements = document.querySelectorAll('*');
50 const textSizes = [];
51
52 elements.forEach(el => {
53 const text = el.textContent.trim();
54 if (text && el.children.length === 0) { // Leaf text nodes
55 const style = window.getComputedStyle(el);
56 const fontSize = parseFloat(style.fontSize);
57 textSizes.push({ fontSize, text: text.substring(0, 30) });
58 }
59 });
60
61 return textSizes;
62 }""")
63
64 # Check visual angle for each text element
65 for text_info in text_elements:
66 font_size_px = text_info['fontSize']
67 visual_angle = self.calculate_visual_angle(
68 font_size_px,
69 context['distance_cm']
70 )
71
72 # Minimum visual angle for comfortable reading: 0.3 degrees
73 # Optimal: 0.5-1.0 degrees
74 if visual_angle < 0.2:
75 issues.append({
76 'type': 'text_too_small_for_distance',
77 'font_size_px': font_size_px,
78 'distance_cm': context['distance_cm'],
79 'visual_angle_deg': round(visual_angle, 3),
80 'min_angle_deg': 0.3,
81 'severity': 'error',
82 'message': f"Text {font_size_px}px at {context['distance_cm']}cm = {visual_angle:.3f}° (min 0.3°)"
83 })
84 elif visual_angle < 0.3:
85 issues.append({
86 'type': 'text_marginally_readable',
87 'font_size_px': font_size_px,
88 'distance_cm': context['distance_cm'],
89 'visual_angle_deg': round(visual_angle, 3),
90 'severity': 'warning',
91 'message': f"Text barely readable: {visual_angle:.3f}° visual angle"
92 })
93
94 return {
95 'component': component_name,
96 'context': context['name'],
97 'passed': len([i for i in issues if i['severity'] == 'error']) == 0,
98 'issues': issues
99 }
100
101 def test_touch_target_at_distance(self, page, component_name, context):
102 """Test if touch targets are appropriately sized for viewing distance"""
103 issues = []
104
105 file_path = Path(__file__).parent / 'docs' / component_name
106 page.goto(f'file://{file_path}')
107 page.wait_for_load_state('networkidle')
108
109 # Get interactive elements
110 buttons = page.locator('button, a[href], [role="button"]').all()
111
112 for button in buttons:
113 box = button.bounding_box()
114 if box:
115 # Calculate visual angle
116 visual_angle = self.calculate_visual_angle(
117 min(box['width'], box['height']),
118 context['distance_cm']
119 )
120
121 # Touch targets should subtend at least 1.0 degree visual angle
122 # At closer distances (handheld), physical size matters more
123 if context['name'] in ['handheld', 'desktop']:
124 # Use physical size threshold (44px)
125 if box['width'] < 44 or box['height'] < 44:
126 issues.append({
127 'type': 'small_touch_target',
128 'size': f"{box['width']}x{box['height']}",
129 'context': context['name'],
130 'severity': 'error'
131 })
132 else:
133 # AR contexts: use visual angle
134 if visual_angle < 1.0:
135 issues.append({
136 'type': 'touch_target_too_small_for_distance',
137 'visual_angle_deg': round(visual_angle, 2),
138 'min_angle_deg': 1.0,
139 'distance_cm': context['distance_cm'],
140 'severity': 'error',
141 'message': f"Touch target {visual_angle:.2f}° at {context['distance_cm']}cm (min 1.0°)"
142 })
143
144 return {
145 'component': component_name,
146 'context': context['name'],
147 'passed': len([i for i in issues if i['severity'] == 'error']) == 0,
148 'issues': issues
149 }
150
151 def test_depth_perception(self, page, component_name):
152 """Test that component provides depth cues (shadows, layering)"""
153 issues = []
154
155 file_path = Path(__file__).parent / 'docs' / component_name
156 page.goto(f'file://{file_path}')
157 page.wait_for_load_state('networkidle')
158
159 # Check for depth cues
160 depth_info = page.evaluate("""() => {
161 const elements = document.querySelectorAll('*');
162 let hasShadows = 0;
163 let hasTransforms = 0;
164 let hasZIndex = 0;
165
166 elements.forEach(el => {
167 const style = window.getComputedStyle(el);
168
169 if (style.boxShadow && style.boxShadow !== 'none') {
170 hasShadows++;
171 }
172
173 if (style.transform && style.transform !== 'none') {
174 hasTransforms++;
175 }
176
177 if (style.zIndex && style.zIndex !== 'auto') {
178 hasZIndex++;
179 }
180 });
181
182 return { hasShadows, hasTransforms, hasZIndex };
183 }""")
184
185 # Components should use at least one depth cue
186 total_depth_cues = depth_info['hasShadows'] + depth_info['hasTransforms'] + depth_info['hasZIndex']
187
188 if total_depth_cues == 0:
189 issues.append({
190 'type': 'no_depth_cues',
191 'severity': 'warning',
192 'message': 'No depth cues detected (shadows, transforms, z-index)'
193 })
194
195 return {
196 'component': component_name,
197 'passed': len([i for i in issues if i['severity'] == 'error']) == 0,
198 'depth_info': depth_info,
199 'issues': issues
200 }
201
202 def test_spatial_attention(self, page, component_name):
203 """Test that component doesn't overwhelm spatial field of view"""
204 issues = []
205
206 file_path = Path(__file__).parent / 'docs' / component_name
207 page.goto(f'file://{file_path}')
208 page.wait_for_load_state('networkidle')
209
210 # Calculate total component coverage
211 coverage = page.evaluate("""() => {
212 const body = document.body;
213 const bodyBox = body.getBoundingClientRect();
214 const viewport = { width: window.innerWidth, height: window.innerHeight };
215
216 // Calculate what percentage of viewport is covered
217 const coveragePercent = (bodyBox.width * bodyBox.height) / (viewport.width * viewport.height) * 100;
218
219 return {
220 coveragePercent: coveragePercent,
221 bodyWidth: bodyBox.width,
222 bodyHeight: bodyBox.height,
223 viewportWidth: viewport.width,
224 viewportHeight: viewport.height
225 };
226 }""")
227
228 # Components shouldn't dominate entire field of view in AR contexts
229 # Threshold: < 60% coverage for comfortable spatial experience
230 if coverage['coveragePercent'] > 80:
231 issues.append({
232 'type': 'overwhelming_spatial_presence',
233 'coverage_percent': round(coverage['coveragePercent'], 1),
234 'threshold': '80%',
235 'severity': 'warning',
236 'message': f"Component covers {coverage['coveragePercent']:.1f}% of viewport (>80%)"
237 })
238
239 return {
240 'component': component_name,
241 'passed': len([i for i in issues if i['severity'] == 'error']) == 0,
242 'coverage': coverage,
243 'issues': issues
244 }
245
246 def test_spatial_positioning(self, page, component_name):
247 """Test that component uses relative positioning suitable for AR"""
248 issues = []
249
250 file_path = Path(__file__).parent / 'docs' / component_name
251 page.goto(f'file://{file_path}')
252 page.wait_for_load_state('networkidle')
253
254 # Check positioning styles
255 positioning = page.evaluate("""() => {
256 const elements = document.querySelectorAll('*');
257 let fixed = 0;
258 let absolute = 0;
259 let relative = 0;
260 let sticky = 0;
261
262 elements.forEach(el => {
263 const style = window.getComputedStyle(el);
264 const pos = style.position;
265
266 if (pos === 'fixed') fixed++;
267 else if (pos === 'absolute') absolute++;
268 else if (pos === 'relative') relative++;
269 else if (pos === 'sticky') sticky++;
270 });
271
272 return { fixed, absolute, relative, sticky };
273 }""")
274
275 # Fixed positioning is problematic in AR/VR (no "fixed" in 3D space)
276 if positioning['fixed'] > 0:
277 issues.append({
278 'type': 'fixed_positioning_in_spatial',
279 'count': positioning['fixed'],
280 'severity': 'warning',
281 'message': f"{positioning['fixed']} fixed elements incompatible with spatial contexts"
282 })
283
284 return {
285 'component': component_name,
286 'passed': len([i for i in issues if i['severity'] == 'error']) == 0,
287 'positioning': positioning,
288 'issues': issues
289 }
290
291 def test_spatial_focus_indicator(self, page, component_name):
292 """Test that focus indicators work at various distances"""
293 issues = []
294
295 file_path = Path(__file__).parent / 'docs' / component_name
296 page.goto(f'file://{file_path}')
297 page.wait_for_load_state('networkidle')
298
299 # Check focus outline visibility
300 buttons = page.locator('button, a[href]').all()
301
302 for button in buttons[:3]: # Test first 3
303 # Focus element
304 button.focus()
305
306 # Check outline thickness
307 outline = button.evaluate("""el => {
308 const style = window.getComputedStyle(el);
309 return {
310 outlineWidth: style.outlineWidth,
311 outlineStyle: style.outlineStyle,
312 outlineColor: style.outlineColor
313 };
314 }""")
315
316 # Outline should be at least 2px for spatial visibility
317 outline_width = float(outline['outlineWidth'].replace('px', '')) if 'px' in outline['outlineWidth'] else 0
318
319 if outline['outlineStyle'] != 'none' and outline_width < 2:
320 issues.append({
321 'type': 'thin_focus_outline_spatial',
322 'outline_width': outline['outlineWidth'],
323 'min_width': '2px',
324 'severity': 'warning',
325 'message': f"Focus outline {outline['outlineWidth']} too thin for spatial contexts (min 2px)"
326 })
327
328 return {
329 'component': component_name,
330 'passed': len([i for i in issues if i['severity'] == 'error']) == 0,
331 'issues': issues
332 }
333
334 def run_all_tests(self):
335 """Run all spatial context tests"""
336 print("\n🥽 Running spatial context tests (AR/VR simulation)...\n")
337
338 components = [
339 'semantic-action.html',
340 'semantic-card.html',
341 'semantic-input.html',
342 'semantic-modal.html',
343 'semantic-navigator.html',
344 'semantic-list.html',
345 'semantic-menu.html',
346 'semantic-feedback.html',
347 'semantic-adjuster.html'
348 ]
349
350 with sync_playwright() as p:
351 browser = p.chromium.launch(headless=True)
352
353 for component in components:
354 print(f"\n📋 Testing {component}:")
355
356 # Test across different spatial contexts
357 for context in self.SPATIAL_CONTEXTS:
358 print(f"\n 📍 Context: {context['name']} ({context['distance_cm']}cm)")
359
360 page = browser.new_page(viewport=context['viewport'])
361
362 tests = [
363 ('Distance Readability', lambda: self.test_distance_readability(page, component, context)),
364 ('Touch Targets at Distance', lambda: self.test_touch_target_at_distance(page, component, context)),
365 ]
366
367 for test_name, test_func in tests:
368 print(f" 🔍 {test_name}...", end='')
369 result = test_func()
370 self.results.append({
371 'test': test_name,
372 'component': component,
373 'context': context['name'],
374 'passed': result['passed'],
375 'issues': result.get('issues', [])
376 })
377
378 error_count = len([i for i in result.get('issues', []) if i['severity'] == 'error'])
379 warning_count = len([i for i in result.get('issues', []) if i['severity'] == 'warning'])
380
381 if result['passed']:
382 if warning_count > 0:
383 print(f" ⚠️ ({warning_count} warnings)")
384 else:
385 print(" ✅")
386 else:
387 print(f" ❌ ({error_count} errors)")
388
389 page.close()
390
391 # Test spatial-specific properties (once per component)
392 page = browser.new_page(viewport={'width': 1920, 'height': 1080})
393
394 spatial_tests = [
395 ('Depth Perception', lambda: self.test_depth_perception(page, component)),
396 ('Spatial Attention', lambda: self.test_spatial_attention(page, component)),
397 ('Spatial Positioning', lambda: self.test_spatial_positioning(page, component)),
398 ('Spatial Focus', lambda: self.test_spatial_focus_indicator(page, component))
399 ]
400
401 print(f"\n 🌐 Spatial properties:")
402 for test_name, test_func in spatial_tests:
403 print(f" 🔍 {test_name}...", end='')
404 result = test_func()
405 self.results.append({
406 'test': test_name,
407 'component': component,
408 'passed': result['passed'],
409 'issues': result.get('issues', [])
410 })
411
412 error_count = len([i for i in result.get('issues', []) if i['severity'] == 'error'])
413 warning_count = len([i for i in result.get('issues', []) if i['severity'] == 'warning'])
414
415 if result['passed']:
416 if warning_count > 0:
417 print(f" ⚠️ ({warning_count} warnings)")
418 else:
419 print(" ✅")
420 else:
421 print(f" ❌ ({error_count} errors)")
422
423 page.close()
424
425 browser.close()
426
427 self.generate_report()
428
429 def generate_report(self):
430 """Generate test report"""
431 passed = sum(1 for r in self.results if r['passed'])
432 total = len(self.results)
433
434 # Save JSON
435 results_path = Path(__file__).parent / 'test-results' / 'results-spatial.json'
436 results_path.parent.mkdir(exist_ok=True)
437 with open(results_path, 'w') as f:
438 json.dump(self.results, f, indent=2)
439
440 print(f"\n📊 Spatial context tests complete!")
441 print(f" Passed: {passed}/{total}")
442 print(f" Results: {results_path}")
443 print(f"\n💡 Note: Spatial tests simulate AR/VR contexts for future compatibility")
444
445 # Exit with error if any tests failed
446 if passed < total:
447 exit(1)
448
449if __name__ == '__main__':
450 tester = SpatialTester()
451 tester.run_all_tests()