interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / test-hive-cosmic.py

329 lines · 16952 bytes Raw Blame History
1"""Static presentation checks. Does not substitute for a Rust build or browser QA.
2
3The scene behind the /hive/ masthead is Allen's two black holes: om/hive-page/hive.om
4computes the inspiral (native/kernel/ui/night.c orbit_angle and ck_night_at) and
5writes the samples into om/hive-page/main.html as CSS keyframes. These checks
6recompute that law here, independently, and compare every stop with it, and they
7pin the two contracts the artifact cannot state about itself: only transform and
8opacity are animated, and nothing animates under prefers-reduced-motion.
9"""
10from pathlib import Path
11import hashlib, math, re, unittest, xml.etree.ElementTree as ET
12
13ROOT = Path(__file__).resolve().parents[1]
14PAGE = ROOT / 'om/hive-page/main.html'
15CSS = ROOT / 'public/assets/hive.css'
16GUIDE = ROOT / 'AGENTS.md'
17
18CYCLE = 19000 # ms, one pass of the sequence plus the hold in the sky
19APPEAR = 2600 # CK_NIGHT_HOLES_MS
20SHADOW = 4000 # the shadow starts to grow (APPEAR + 1400)
21SPIRAL = 6000 # CK_NIGHT_SPIRAL_MS
22MERGE = 12000 # CK_NIGHT_MERGE_MS
23FADE = 12900 # MERGE + 900, the last hole starts to dissolve
24GONE = 15200 # CK_NIGHT_GONE_MS
25RIPPLE = 15600 # MERGE + CK_NIGHT_RIPPLE_MS
26A0 = 270.0 # separation of the wide orbit, Allen units
27ORBIT = 5200.0 # ms per turn of the wide orbit
28SF = (SPIRAL - APPEAR) * 65536 // ORBIT # 42850, 1/65536 turns
29TURNS = 65536 * 8 * (MERGE - SPIRAL) // (5 * ORBIT) # 120989, 1/65536 turns
30STEP = 40 # ms between position samples
31
32
33def phase(page):
34 m = re.search(r'<style>(.*?)</style>', page, re.S)
35 assert m, 'the artifact no longer carries the emitted style block'
36 return m.group(1)
37
38
39def rules(css):
40 """Top level rules of a stylesheet, comments stripped, as (header, body)."""
41 css = re.sub(r'/\*.*?\*/', '', css, flags=re.S)
42 out, i, n = [], 0, len(css)
43 while i < n:
44 open_at = css.find('{', i)
45 if open_at < 0:
46 break
47 depth, k = 1, open_at + 1
48 while k < n and depth:
49 depth += {'{': 1, '}': -1}.get(css[k], 0)
50 k += 1
51 out.append((css[i:open_at].strip(), css[open_at + 1:k - 1]))
52 i = k
53 return out
54
55
56def keyframes(css):
57 return {h.split(None, 1)[1]: b for h, b in rules(css) if h.startswith('@keyframes')}
58
59
60def stops(body):
61 """[(ms, declarations)] of one @keyframes body."""
62 body = re.sub(r'/\*.*?\*/', '', body, flags=re.S)
63 return [(round(float(m.group(1)) * CYCLE / 100), m.group(2).strip())
64 for m in re.finditer(r'([\d.]+)%\s*\{([^}]*)\}', body)]
65
66
67def at(table, ms):
68 """The declaration of the stop at ms, or of the nearest stop to it."""
69 t, decl = min(table, key=lambda row: abs(row[0] - ms))
70 return decl
71
72
73def smooth(u):
74 u = max(0, min(256, u))
75 return u * u * (768 - 2 * u) >> 16
76
77
78def prog(t, a, b):
79 if t <= a:
80 return 0
81 if t >= b:
82 return 256
83 return (t - a) * 256 // (b - a)
84
85
86def law(t):
87 """Separation (Allen units) and angle (turns) at t ms, from night.c."""
88 t = max(t, APPEAR)
89 if t < SPIRAL:
90 return A0, (t - APPEAR) / ORBIT
91 left = max(0.0, (MERGE - t) / (MERGE - SPIRAL))
92 r8 = left ** 0.125
93 return A0 * r8 * r8, SF / 65536 + (TURNS / 65536) * (1.0 - r8 ** 5)
94
95
96def place(t, sign):
97 sep, turn = law(t)
98 a = 2 * math.pi * turn
99 return sign * 0.5 * sep * math.cos(a), sign * 0.25 * sep * math.sin(a)
100
101
102def translate(decl):
103 return [float(v) for v in re.findall(r'(-?[\d.]+)em', decl)]
104
105
106class CosmicChecks(unittest.TestCase):
107
108 def test_omega_bytes_untouched(self):
109 self.assertEqual(hashlib.sha256(PAGE.read_bytes()).hexdigest(),
110 (ROOT / 'om/hive-page/main.html.sha256').read_text().split()[0])
111
112 def test_residual_sky_asset(self):
113 p = ROOT / 'public/assets/hive-universe.svg'
114 self.assertEqual(ET.parse(p).getroot().attrib['viewBox'], '0 0 1600 900')
115 self.assertNotRegex(p.read_text(), r'<script|<foreignObject|href=')
116
117 def test_scene_is_allens_pair(self):
118 page = PAGE.read_text()
119 scene = re.search(r'<div class="hive-scene".*?</div></div>', page, re.S)
120 self.assertTrue(scene, 'the artifact lost the scene markup')
121 box = scene.group(0)
122 self.assertIn('aria-hidden="true"', box)
123 self.assertIn('data-scene="allen"', box)
124 for name, ms in [('cycle', CYCLE), ('appear', APPEAR), ('spiral', SPIRAL),
125 ('merge', MERGE), ('gone', GONE), ('ripple', RIPPLE)]:
126 self.assertIn(f'data-{name}="{ms}"', box, f'the scene must state {name} = {ms} ms')
127 self.assertIn(f'--hive-cycle:{CYCLE}ms', box)
128 self.assertEqual(box.count('class="hive-hole '), 2, 'two black holes, not one and not three')
129 for part in ['hive-hole-a', 'hive-hole-b', 'hive-bend', 'hive-plate',
130 'hive-merge', 'hive-mglow', 'hive-mplate', 'hive-ring', 'hive-ripple']:
131 self.assertIn(part, box, f'the scene must carry {part}')
132 # The static frame: each hole has its place in the cycle written inline,
133 # so with motion off the reader still sees the pair, at a separation.
134 for cls, sign in [('hive-hole-a', 1), ('hive-hole-b', -1)]:
135 m = re.search(r'class="hive-hole ' + cls + r'" style="([^"]+)"', box)
136 self.assertTrue(m, f'{cls} must carry the static frame inline')
137 x, y = translate(m.group(1))
138 wx, wy = place(7000, sign)
139 self.assertAlmostEqual(x, wx, delta=0.05)
140 self.assertAlmostEqual(y, wy, delta=0.05)
141 self.assertGreater(x * sign, 0.0, 'the two holes sit on opposite sides of the stage')
142 self.assertGreater(math.hypot(x, y), 40.0, 'the static frame must show a visible separation')
143
144 def test_keyframes_animate_transform_and_opacity_only(self):
145 css = phase(PAGE.read_text())
146 animated = keyframes(css)
147 self.assertEqual(sorted(animated), ['hive-bend', 'hive-mkeep', 'hive-mring', 'hive-msiz',
148 'hive-posa', 'hive-posb', 'hive-ripp', 'hive-size'])
149 for name, body in animated.items():
150 for block in re.findall(r'\{([^{}]*)\}', body):
151 for decl in block.split(';'):
152 if not decl.strip():
153 continue
154 prop = decl.split(':')[0].strip()
155 self.assertIn(prop, ('transform', 'opacity'),
156 f'{name} animates {prop}: the scene must stay on the compositor')
157 # The other half of the same rule: nothing that would cost layout or a
158 # repaint of the disc, and no shorthand that could hide one.
159 for word in ['filter', 'box-shadow', 'background-position', 'background-size',
160 'width', 'height', 'left', 'top', 'font-size', 'animation-name']:
161 for name, body in animated.items():
162 self.assertNotIn(word, re.sub(r'scale\(|translate3d\(|opacity:', '', body),
163 f'{name} must not touch {word}')
164
165 def test_keyframes_follow_allens_law(self):
166 animated = keyframes(phase(PAGE.read_text()))
167 for name, sign in [('hive-posa', 1), ('hive-posb', -1)]:
168 table = stops(animated[name])
169 times = [t for t, _ in table]
170 self.assertEqual(len(table), 1 + (MERGE - APPEAR) // STEP + 2,
171 f'{name} samples APPEAR to MERGE every {STEP} ms, and holds at both ends')
172 self.assertEqual(times[0], 0)
173 self.assertEqual(times[1], APPEAR)
174 self.assertEqual(times[-2], MERGE)
175 self.assertEqual(times[-1], CYCLE)
176 self.assertEqual(times[2] - times[1], STEP)
177 worst, where = 0.0, None
178 for t, decl in table:
179 x, y = translate(decl)
180 wx, wy = place(t, sign)
181 err = max(abs(x - wx), abs(y - wy))
182 if err > worst:
183 worst, where = err, (t, x, y, wx, wy)
184 self.assertLess(worst, 0.05,
185 f'{name} leaves the law at {where}: the samples are not night.c')
186 # The pair starts wide, is still wide when the wide orbit ends, and
187 # has collapsed to the merge point.
188 for t in (0, APPEAR):
189 x, y = translate(at(table, t))
190 self.assertAlmostEqual(2 * abs(x), A0, delta=0.05, msg='the wide orbit is 270 units')
191 self.assertAlmostEqual(y, 0.0, delta=0.05)
192 self.assertAlmostEqual(law(SPIRAL)[0], A0, delta=0.05)
193 x, y = translate(at(table, MERGE))
194 self.assertEqual((x, y), (0.0, 0.0), 'the pair must collapse to the centre at the merger')
195 x, y = translate(at(table, CYCLE))
196 self.assertEqual((x, y), (0.0, 0.0))
197
198 def test_merge_and_shadow_sizes(self):
199 animated = keyframes(phase(PAGE.read_text()))
200 size = stops(animated['hive-size'])
201 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(size, APPEAR)).group(1)), 0.0,
202 msg='no shadow exists before it grows in')
203 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(size, SHADOW)).group(1)), 0.0)
204 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(size, SPIRAL)).group(1)), 1.0)
205 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(size, MERGE - STEP)).group(1)), 1.0)
206 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(size, MERGE)).group(1)), 0.0)
207 merged = stops(animated['hive-msiz'])
208 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(merged, MERGE)).group(1)), 1.26171875,
209 places=2, msg='the merged shadow starts at 323/256 of a single one')
210 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(merged, MERGE + 180)).group(1)), 2.0,
211 places=2, msg='and reaches twice a single one after 180 ms')
212 # The shadow keeps its merged size to the end; the group's opacity is what
213 # dissolves it, so the shadow does not shrink as well (night.c shrinks it by
214 # the square of the fade and the page folds that into the fade).
215 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(merged, GONE)).group(1)), 2.0)
216 # The ring wobbles at 95 ms and dies with a 260 ms time constant.
217 ring = stops(animated['hive-mring'])
218 peak = max(float(re.search(r'([\d.]+)', d).group(1)) for _, d in ring)
219 self.assertLess(peak, 1.075, 'the ring stays inside 7 percent of the shadow radius')
220 self.assertGreater(peak, 1.03, 'and it does move')
221 late = float(re.search(r'([\d.]+)', at(ring, MERGE + 1500)).group(1))
222 self.assertLess(abs(late - 1.0), 0.004, 'by 1.5 s the wobble is gone')
223 keep = stops(animated['hive-mkeep'])
224 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(keep, MERGE)).group(1)), 1.0)
225 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(keep, FADE)).group(1)), 1.0)
226 self.assertAlmostEqual(float(re.search(r'([\d.]+)', at(keep, GONE)).group(1)), 0.0)
227
228 def test_ripple_runs_and_fades(self):
229 ripp = stops(keyframes(phase(PAGE.read_text()))['hive-ripp'])
230 first = at(ripp, MERGE)
231 self.assertIn('scale(0.00', first)
232 self.assertIn('opacity:0.00', first)
233 peak = max(float(re.search(r'opacity:([\d.]+)', d).group(1)) for _, d in ripp)
234 self.assertGreater(peak, 0.1, 'the ripple must be visible')
235 self.assertLess(peak, 0.5, 'and it is a faint wave, not a flash')
236 end = at(ripp, RIPPLE)
237 self.assertIn('scale(1000.00', end)
238 self.assertIn('opacity:0.00', end, 'the ripple has died by 15600 ms')
239
240 def test_timeline_is_in_the_artifact(self):
241 css = phase(PAGE.read_text())
242 for ms in (APPEAR, SHADOW, SPIRAL, MERGE, FADE, GONE, RIPPLE, CYCLE):
243 self.assertIn(f'{ms}ms', css, f'the artifact must name {ms} ms where the eye can read it')
244
245 def test_nothing_animates_under_reduced_motion(self):
246 page = PAGE.read_text()
247 flat = re.sub(r'/\*.*?\*/', '', phase(page), flags=re.S)
248 top = dict(rules(flat))
249 gate = [h for h in top if h.startswith('@media') and 'prefers-reduced-motion:no-preference' in h]
250 self.assertEqual(len(gate), 1, 'exactly one motion gate, so there is one place to look')
251 inside = top[gate[0]]
252 for name in ['hive-posa', 'hive-posb', 'hive-bend', 'hive-size', 'hive-msiz',
253 'hive-mring', 'hive-mkeep', 'hive-ripp']:
254 self.assertIn(f'animation:{name} var(--hive-cycle) linear infinite', inside,
255 f'{name} must be attached inside the motion gate')
256 self.assertEqual(inside.count('animation:'), 8)
257 # The native checkbox, not browser code, owns the second motion key.
258 self.assertEqual(inside.count('.hive:has(#hive-motion:checked)'), 8)
259 # Every animation in the artifact is inside the gate: one place to look.
260 self.assertEqual(flat.count('animation:'), inside.count('animation:'),
261 'an animation escaped the prefers-reduced-motion gate')
262 outside = flat.replace(inside, '')
263 self.assertNotIn('animation:', outside)
264 sheet = CSS.read_text()
265 self.assertNotIn('@keyframes', sheet)
266 for value in re.findall(r'animation:([^;}]+)', sheet):
267 self.assertTrue(value.strip().startswith('none'),
268 f'only the motion off rules may name an animation: {value!r}')
269
270 def test_stylesheet_places_and_paints_only(self):
271 sheet = CSS.read_text()
272 self.assertIn("url('/assets/hive-universe.svg')", sheet)
273 self.assertIn('pointer-events:none', sheet)
274 self.assertIn('prefers-reduced-motion', sheet)
275 self.assertIn('.hive:not(:has(#hive-motion:checked))', sheet)
276 self.assertNotRegex(sheet, r'#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?\b')
277 self.assertIn(':focus-visible', sheet)
278 for part in ['.hive-masthead > .hive-scene', '.hive-stage', '.hive-bend', '.hive-plate',
279 '.hive-mglow', '.hive-mplate', '.hive-ring', '.hive-ripple',
280 'font-size:var(--hive-u,1px)', '--hive-u:.86px']:
281 self.assertIn(part, sheet, f'the stylesheet must still place {part}')
282 # No negative z-index, no isolation: see the flicker note in the sheet.
283 self.assertNotRegex(sheet, r'z-index\s*:\s*-')
284 self.assertNotIn('isolation:isolate', sheet)
285 self.assertIn('will-change:transform', sheet)
286 self.assertIn('transform:translateZ(0)', sheet)
287 self.assertIn('/ cover no-repeat', sheet)
288 # The sky is one fixed, viewport-sized layer behind the whole page, not a band.
289 sky = re.search(r'\.hive::before \{([^}]*)\}', sheet)
290 self.assertIsNotNone(sky, 'the sky lives on .hive::before')
291 for decl in ['position:fixed', 'inset:0', 'z-index:0', "url('/assets/hive-universe.svg')", 'transform:translateZ(0)']:
292 self.assertIn(decl, sky.group(1))
293 self.assertNotIn('.hive-masthead::before', sheet)
294 self.assertIn('.hive > * { position:relative; z-index:1; }', sheet)
295 self.assertIn('.aien-footer { position:relative; z-index:1; }', sheet)
296 self.assertNotIn('auto 120%', sheet)
297 # The scene's own layer sits at 0, the scrim at 1, the prose at 2.
298 self.assertIn('.hive-masthead > * { position:relative; z-index:2; }', sheet)
299 self.assertIn('z-index:1; pointer-events:none', sheet)
300
301 def test_scrim_and_provenance_stay(self):
302 sheet = CSS.read_text()
303 for stop in ['92%, transparent) 0%', '90%, transparent) 68%',
304 '55%, transparent) 86%',
305 '94%, transparent) 0%', '90%, transparent) 55%',
306 '60%, transparent) 80%']:
307 self.assertIn(stop, sheet, f'the scrim stop {stop} is a contrast contract')
308 page = PAGE.read_text()
309 self.assertIn('hive-omega', page)
310 self.assertIn('This page is written in Omega.', page)
311 self.assertIn('bear with the glitches while I iron it out', page)
312 self.assertIn('Read the Omega source', page)
313 self.assertIn('.hive-omega {', sheet)
314
315 def test_the_guide_says_what_the_scene_is(self):
316 guide = GUIDE.read_text()
317 self.assertIn("Allen's law", guide)
318 guide_low = guide.lower()
319 self.assertIn('illustration', guide_low)
320 for word in ['ripple', 'ring']:
321 self.assertIn(word, guide_low)
322 self.assertIn('om/hive-page/hive.om', guide)
323 for text in [PAGE.read_text(), CSS.read_text(), guide]:
324 self.assertNotIn('\u2014', text, 'no em dash')
325 self.assertNotIn('\u2013', text, 'no en dash')
326
327
328if __name__ == '__main__':
329 unittest.main()