oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package slidestest
4
5// Scenes running on every surface, carried on between slides, and
6// stills wherever code doesn't run (scenes and clips spec §3, §8.7;
7// Review Focus 1; fixtures/scene-layer.mjs, scene-frame.mjs).
8
9import (
10 "bytes"
11 "context"
12 "encoding/json"
13 "fmt"
14 "image/color"
15 "image/png"
16 "net/url"
17 "strings"
18 "testing"
19 "time"
20
21 "amadan.net/rastrillo/rastrillo/blobs"
22 "github.com/chromedp/cdproto/emulation"
23 "github.com/chromedp/chromedp"
24 "github.com/chromedp/chromedp/kb"
25)
26
27// recorderScene draws a box and answers ready after its first init. It
28// tells the page everything it has been sent, again and again, under a
29// name of its own (doc), so the test can tell one frame's document from
30// another's and read what each was told whenever it looks.
31const recorderScene = `<!doctype html>
32<html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#2471a3}</style></head>
33<body><script>
34const doc = Math.random().toString(36).slice(2);
35const log = [];
36const tell = () => parent.postMessage({type: 'seen', doc, log}, '*');
37addEventListener('message', (e) => {
38 if (e.source !== parent || !e.data) return;
39 const m = e.data;
40 log.push({type: m.type, state: m.state, animate: m.animate, reducedMotion: m.reducedMotion,
41 w: m.size ? m.size.w : 0, word: m.words ? m.words.two : ''});
42 if (m.type === 'init' && log.filter((x) => x.type === 'init').length === 1) parent.postMessage({type: 'ready'}, '*');
43 tell();
44});
45setInterval(tell, 150);
46</script></body></html>
47`
48
49// silentScene never answers.
50const silentScene = `<!doctype html>
51<html><body><script>addEventListener('message', () => {});</script></body></html>
52`
53
54// wanderingScene answers ready, then takes its frame somewhere else.
55const wanderingScene = `<!doctype html>
56<html><body style="background:#c0392b"><script>
57addEventListener('message', (e) => {
58 if (e.source !== parent || !e.data || e.data.type !== 'init') return;
59 parent.postMessage({type: 'ready'}, '*');
60 setTimeout(() => { location.href = 'about:blank'; }, 400);
61});
62</script></body></html>
63`
64
65// sceneWatch is installed in a page: every frame's document is learned
66// from what it says (window.__scenes, doc to log), and each iframe is
67// marked with its document's name (__doc).
68const sceneWatch = `(() => {
69 if (window.__sceneWatch) return true;
70 window.__sceneWatch = true;
71 window.__scenes = {};
72 addEventListener('message', (e) => {
73 if (!e.data || e.data.type !== 'seen') return;
74 window.__scenes[e.data.doc] = e.data.log;
75 for (const f of document.querySelectorAll('iframe')) if (f.contentWindow === e.source) f.__doc = e.data.doc;
76 });
77 return true;
78})()`
79
80type sceneMsg struct {
81 Type, State, Word string
82 Animate *bool
83 ReducedMotion *bool
84 W float64
85}
86
87type sceneFrameState struct {
88 Doc string
89 Visible bool
90 Mark bool
91 Log []sceneMsg
92 Left, Top float64
93 Width, Height float64
94 BlockLeft float64
95 BlockTop float64
96 BlockWidth float64
97 BlockHeight float64
98 Live bool
99 StillShown string
100 StillOpacities []string
101}
102
103// framesJS is every scene frame in the page part sel holds (the whole
104// page by default), with what its document has been told and where it
105// sits beside the block it is over.
106func framesJS(sel string) string {
107 return `(() => {
108 const within = ` + sel + `;
109 if (!within) return [];
110 return [...within.querySelectorAll('[slides-scene-layer] iframe')].map((f) => {
111 const r = f.getBoundingClientRect();
112 const block = within.querySelector('[slides-block][data-id="' + f.getAttribute('data-for') + '"]');
113 const b = block ? block.getBoundingClientRect() : {left: 0, top: 0, width: 0, height: 0};
114 const shown = block ? [...block.querySelectorAll('[data-scene-state]')].filter((s) => getComputedStyle(s).visibility === 'visible') : [];
115 return {Doc: f.__doc || '', Visible: getComputedStyle(f).visibility === 'visible' && getComputedStyle(f).opacity === '1', Mark: !!f.__mark,
116 Log: (window.__scenes || {})[f.__doc] || [],
117 Left: r.left, Top: r.top, Width: r.width, Height: r.height,
118 BlockLeft: b.left, BlockTop: b.top, BlockWidth: b.width, BlockHeight: b.height,
119 Live: !!block && block.hasAttribute('data-scene-live'),
120 StillShown: shown.map((s) => s.getAttribute('data-scene-state')).join(' '),
121 StillOpacities: block ? [...block.querySelectorAll('[data-scene-state]')].map((s) => getComputedStyle(s).opacity) : []};
122 });
123})()`
124}
125
126func readFrames(t *testing.T, ctx context.Context, sel string) []sceneFrameState {
127 t.Helper()
128 var out []sceneFrameState
129 run(t, ctx, evalInto(&out, framesJS(sel)))
130 return out
131}
132
133// waitFrames waits until the frames in sel satisfy ok, failing with
134// what they were at the end.
135func waitFrames(t *testing.T, ctx context.Context, sel, what string, ok func([]sceneFrameState) bool) []sceneFrameState {
136 t.Helper()
137 deadline := time.Now().Add(10 * time.Second)
138 for {
139 got := readFrames(t, ctx, sel)
140 if ok(got) {
141 return got
142 }
143 if time.Now().After(deadline) {
144 raw, _ := json.MarshalIndent(got, "", " ")
145 t.Fatalf("waiting for %s; the frames are:\n%s", what, raw)
146 }
147 time.Sleep(60 * time.Millisecond)
148 }
149}
150
151func lastMsg(f sceneFrameState) sceneMsg {
152 if len(f.Log) == 0 {
153 return sceneMsg{}
154 }
155 return f.Log[len(f.Log)-1]
156}
157
158func said(f sceneFrameState, typ, state string, animate bool) bool {
159 m := lastMsg(f)
160 return m.Type == typ && m.State == state && (typ == "init" || (m.Animate != nil && *m.Animate == animate))
161}
162
163const pageJS = `document`
164
165// sceneTalk is a session on sceneDeckOver's deck with recorderScene
166// as Boxes, and other as Silent.
167type sceneTalk struct {
168 fr *fontRig
169 f sceneFixture
170 session, token string
171}
172
173func newSceneTalk(t *testing.T, other string) *sceneTalk {
174 t.Helper()
175 store, err := blobs.Dir(t.TempDir())
176 if err != nil {
177 t.Fatalf("blobs.Dir: %v", err)
178 }
179 fr := newFontRigWith(t, store)
180 st := &sceneTalk{fr: fr}
181 st.f = sceneDeckOver(t, fr.app, fr.cookies, fr.token, []byte(recorderScene), []byte(other))
182 st.session, st.token = startPresenting(t, fr.app, "/d/"+st.f.sqid, fr.cookies)
183 return st
184}
185
186func (st *sceneTalk) slideWindow() string {
187 return "/p/" + st.session + "?t=" + url.QueryEscape(st.token)
188}
189
190func (st *sceneTalk) gotoSlide(t *testing.T, n int) {
191 t.Helper()
192 press(t, st.fr.app, st.session, st.token, url.Values{"op": {"goto"}, "slide": {fmt.Sprint(n)}, "press": {newPressID(t)}}, nil)
193}
194
195// openWatched opens path and waits for the talk to be held (a presenting
196// window) or a slide to be shown (any other page), with the watch on.
197func (st *sceneTalk) openWatched(t *testing.T, ctx context.Context, path string, talk bool) {
198 t.Helper()
199 if talk {
200 open(t, ctx, st.fr.rig.Origin, path)
201 } else {
202 run(t, ctx, chromedp.Navigate(st.fr.rig.Origin+path),
203 waitFor(`document.documentElement.getAttribute('data-slides-fonts') !== 'pending' && !!document.querySelector('[slides-slide]')`))
204 }
205 run(t, ctx, evalValue(nil, sceneWatch))
206}
207
208func readyOne(t *testing.T, ctx context.Context, sel, state string) sceneFrameState {
209 t.Helper()
210 got := waitFrames(t, ctx, sel, "one frame, ready, told "+state, func(fs []sceneFrameState) bool {
211 return len(fs) == 1 && fs[0].Visible && fs[0].Doc != "" && lastMsg(fs[0]).State == state
212 })
213 return got[0]
214}
215
216// mark marks the one frame there is, to tell it from any made later.
217func mark(t *testing.T, ctx context.Context) {
218 t.Helper()
219 run(t, ctx, evalValue(nil, `document.querySelectorAll('[slides-scene-layer] iframe').forEach((f) => { f.__mark = true; })`))
220}
221
222func nearPx(a, b float64) bool { return a-b < 1.5 && b-a < 1.5 }
223
224func TestASceneCarriesOnBetweenSlides(t *testing.T) {
225 st := newSceneTalk(t, silentScene)
226 ctx := st.fr.rig.Context()
227 st.openWatched(t, ctx, st.slideWindow(), true)
228
229 first := readyOne(t, ctx, pageJS, "one")
230 if m := first.Log[0]; m.Type != "init" || m.Word != "Second" || m.W < 100 || m.ReducedMotion == nil || *m.ReducedMotion {
231 t.Errorf("the scene was told %+v first, want init with its words, its size and no reduced motion", m)
232 }
233 if !nearPx(first.Left, first.BlockLeft) || !nearPx(first.Top, first.BlockTop) || !nearPx(first.Width, first.BlockWidth) || !nearPx(first.Height, first.BlockHeight) {
234 t.Errorf("the frame is at %v,%v %vx%v; the block at %v,%v %vx%v", first.Left, first.Top, first.Width, first.Height,
235 first.BlockLeft, first.BlockTop, first.BlockWidth, first.BlockHeight)
236 }
237 // While the scene shows, its still is under it, kept for assistive
238 // technology but not drawn.
239 if !first.Live || first.StillShown != "one" || first.StillOpacities[0] != "0" {
240 t.Errorf("under the live frame: live %v, still shown %q, opacities %v", first.Live, first.StillShown, first.StillOpacities)
241 }
242 mark(t, ctx)
243
244 steps := []struct{ slide, step, state string }{
245 {"1", "1", "two"}, // a press on the slide
246 {"2", "0", "two"}, // onto the next slide: the same scene in the same box
247 {"2", "1", "three"}, // and on
248 }
249 for _, s := range steps {
250 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.slide === '`+s.slide+`' && `+rootJS+`.dataset.step === '`+s.step+`'`))
251 got := waitFrames(t, ctx, pageJS, "the same frame told "+s.state, func(fs []sceneFrameState) bool {
252 return len(fs) == 1 && said(fs[0], "state", s.state, true)
253 })[0]
254 if !got.Mark || got.Doc != first.Doc || !got.Visible {
255 t.Fatalf("at slide %s step %s the frame is another (%+v), want the first carried on", s.slide, s.step, got)
256 }
257 if n := strings.Count(fmt.Sprint(got.Log), "init"); n != 1 {
258 t.Errorf("the scene was told init %d times", n)
259 }
260 }
261
262 // The viewer moving in place carries it on too: the same frame, told
263 // the next slide's state (its finished slide: three).
264 view := "/d/" + st.f.sqid + "?slide=1"
265 st.openWatched(t, ctx, view, false)
266 v := readyOne(t, ctx, pageJS, "two")
267 mark(t, ctx)
268 run(t, ctx, chromedp.Click(chromedp.CSS(`[slides-pager] a[rel="next"]`)),
269 waitFor(`location.search.includes('slide=2')`))
270 got := waitFrames(t, ctx, pageJS, "the viewer's frame told three", func(fs []sceneFrameState) bool {
271 return len(fs) == 1 && said(fs[0], "state", "three", true)
272 })[0]
273 if !got.Mark || got.Doc != v.Doc {
274 t.Errorf("the viewer made a new frame for the same scene in the same box")
275 }
276}
277
278func TestAJumpLandsOnTheState(t *testing.T) {
279 st := newSceneTalk(t, silentScene)
280 ctx := st.fr.rig.Context()
281 st.openWatched(t, ctx, st.slideWindow(), true)
282 first := readyOne(t, ctx, pageJS, "one")
283 mark(t, ctx)
284
285 // From the first slide's first step to the second slide is not one
286 // press: the frame is kept (the same box) and told to jump.
287 st.gotoSlide(t, 2)
288 run(t, ctx, waitFor(rootJS+`.dataset.slide === '2'`))
289 got := waitFrames(t, ctx, pageJS, "a jump to two", func(fs []sceneFrameState) bool {
290 return len(fs) == 1 && said(fs[0], "state", "two", false)
291 })[0]
292 if !got.Mark || got.Doc != first.Doc {
293 t.Errorf("a jump to the same box made a new frame")
294 }
295 // Back to the first slide from its next one's first step is one
296 // press (the first slide fully built), and moves.
297 run(t, ctx, key(kb.ArrowLeft), waitFor(rootJS+`.dataset.slide === '1' && `+rootJS+`.dataset.step === '1'`))
298 waitFrames(t, ctx, pageJS, "back to two, animated", func(fs []sceneFrameState) bool {
299 return len(fs) == 1 && said(fs[0], "state", "two", true)
300 })
301 // A jump to the plain slide and back lands where it is told: a new
302 // frame, started at the state its slide is at.
303 st.gotoSlide(t, 5)
304 run(t, ctx, waitFor(rootJS+`.dataset.slide === '5'`))
305 waitFrames(t, ctx, pageJS, "no frame on a slide with no scene", func(fs []sceneFrameState) bool { return len(fs) == 0 })
306 st.gotoSlide(t, 2)
307 run(t, ctx, waitFor(rootJS+`.dataset.slide === '2'`))
308 again := readyOne(t, ctx, pageJS, "two")
309 if again.Mark || again.Log[0].Type != "init" {
310 t.Errorf("after a slide with no scene, the scene was not started afresh: %+v", again)
311 }
312}
313
314func TestADifferentBoxStartsFresh(t *testing.T) {
315 st := newSceneTalk(t, silentScene)
316 ctx := st.fr.rig.Context()
317 st.openWatched(t, ctx, st.slideWindow(), true)
318 first := readyOne(t, ctx, pageJS, "one")
319 mark(t, ctx)
320 for _, s := range []string{"1.1", "2.0", "2.1", "3.0"} {
321 slide, step, _ := strings.Cut(s, ".")
322 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.slide === '`+slide+`' && `+rootJS+`.dataset.step === '`+step+`'`))
323 }
324 got := readyOne(t, ctx, pageJS, "one")
325 if got.Mark || got.Doc == first.Doc || len(got.Log) == 0 || got.Log[0].Type != "init" {
326 t.Errorf("in another box the scene carried on (%+v), want a new frame told init", got)
327 }
328 if !nearPx(got.Left, got.BlockLeft) || !nearPx(got.Width, got.BlockWidth) {
329 t.Errorf("the new frame is at %v (%v wide), its block at %v (%v)", got.Left, got.Width, got.BlockLeft, got.BlockWidth)
330 }
331}
332
333// TestASilentSceneShowsItsStill (Review Focus 1): a scene that never
334// says ready, or that navigates its frame away, shows its still; the
335// talk moves on regardless.
336func TestASilentSceneShowsItsStill(t *testing.T) {
337 for name, bundle := range map[string]string{"silent": silentScene, "wandering": wanderingScene} {
338 t.Run(name, func(t *testing.T) {
339 st := newSceneTalk(t, bundle)
340 ctx := st.fr.rig.Context()
341 st.openWatched(t, ctx, st.slideWindow(), true)
342 readyOne(t, ctx, pageJS, "one")
343 st.gotoSlide(t, 4)
344 run(t, ctx, waitFor(rootJS+`.dataset.slide === '4'`))
345 start := time.Now()
346 // Its still shows from the start, whatever the frame does.
347 var still string
348 run(t, ctx, evalInto(&still, `getComputedStyle(document.querySelector('[data-id="scened"] [data-scene-state]')).visibility`))
349 if still != "visible" {
350 t.Errorf("the still is %s while the scene starts", still)
351 }
352 waitFrames(t, ctx, pageJS, "the frame given up", func(fs []sceneFrameState) bool {
353 return len(fs) == 0
354 })
355 if name == "silent" && time.Since(start) < 2500*time.Millisecond {
356 t.Errorf("the silent scene was given up after %v, want 3 s", time.Since(start))
357 }
358 var shown struct{ Visibility, Opacity string }
359 run(t, ctx, evalInto(&shown, `(() => { const s = getComputedStyle(document.querySelector('[data-id="scened"] [data-scene-state]'));
360 return {Visibility: s.visibility, Opacity: s.opacity}; })()`))
361 if shown.Visibility != "visible" || shown.Opacity != "1" {
362 t.Errorf("after the scene was given up its still is %+v", shown)
363 }
364 // A press still answers at once.
365 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.slide === '5'`))
366 })
367 }
368}
369
370// TestReducedMotionGetsTheStill: a reader who asked for less motion is
371// shown each state's still, its settled end, and no scene runs at all.
372func TestReducedMotionGetsTheStill(t *testing.T) {
373 st := newSceneTalk(t, silentScene)
374 ctx := st.fr.rig.Context()
375 run(t, ctx, cdpStep(emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{
376 {Name: "prefers-reduced-motion", Value: "reduce"},
377 }}))
378 st.openWatched(t, ctx, st.slideWindow(), true)
379 still := func(want string) {
380 t.Helper()
381 var shown string
382 run(t, ctx, evalInto(&shown, `[...document.querySelectorAll('[data-id="scenea"] [data-scene-state]')]
383 .filter((s) => getComputedStyle(s).visibility === 'visible' && getComputedStyle(s).opacity === '1')
384 .map((s) => s.getAttribute('data-scene-state')).join(' ')`))
385 if shown != want {
386 t.Errorf("the still shown is %q, want %q", shown, want)
387 }
388 }
389 time.Sleep(time.Second)
390 if fs := readFrames(t, ctx, pageJS); len(fs) != 0 {
391 t.Errorf("with reduced motion %d scenes run", len(fs))
392 }
393 still("one")
394 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`))
395 still("two")
396 time.Sleep(500 * time.Millisecond)
397 if fs := readFrames(t, ctx, pageJS); len(fs) != 0 {
398 t.Errorf("after a press, with reduced motion, %d scenes run", len(fs))
399 }
400}
401
402// TestSceneStillsInNextAndOnAPhone (plan call R5): the presenter's Now
403// runs the scene and its Next shows stills; the viewer's phone view
404// shows stills; the editor runs a scene only while its block is chosen.
405func TestSceneStillsInNextAndOnAPhone(t *testing.T) {
406 st := newSceneTalk(t, silentScene)
407 ctx := st.fr.rig.Context()
408
409 presenter := "/p/" + st.session + "/notes?t=" + url.QueryEscape(st.token)
410 st.openWatched(t, ctx, presenter, true)
411 readyOne(t, ctx, `document.querySelector('[presenter-panel="now"]')`, "one")
412 run(t, ctx, key(kb.ArrowRight))
413 waitFrames(t, ctx, `document.querySelector('[presenter-panel="now"]')`, "Now told two", func(fs []sceneFrameState) bool {
414 return len(fs) == 1 && said(fs[0], "state", "two", true)
415 })
416 var next struct{ Frames, Stills int }
417 run(t, ctx, evalInto(&next, `(() => { const n = document.querySelector('[presenter-panel="next"]');
418 return {Frames: n.querySelectorAll('iframe').length, Stills: n.querySelectorAll('[data-scene-state]').length}; })()`))
419 if next.Frames != 0 || next.Stills == 0 {
420 t.Errorf("Next has %d frames and %d stills, want stills alone", next.Frames, next.Stills)
421 }
422
423 // The phone view.
424 st.openWatched(t, ctx, "/d/"+st.f.sqid+"?slide=1&vp=phone", false)
425 time.Sleep(time.Second)
426 if fs := readFrames(t, ctx, pageJS); len(fs) != 0 {
427 t.Errorf("the phone view runs %d scenes", len(fs))
428 }
429
430 // The editor: stills until the block is chosen.
431 run(t, ctx, chromedp.Navigate(st.fr.rig.Origin+"/d/"+st.f.sqid+"/edit#carry1"),
432 waitFor(`!!document.querySelector('[slides-stage] [data-id="scenea"]') && document.documentElement.getAttribute('data-slides-fonts') === 'shown'`),
433 evalValue(nil, sceneWatch))
434 time.Sleep(time.Second)
435 if fs := readFrames(t, ctx, pageJS); len(fs) != 0 {
436 t.Errorf("the editor runs a scene nobody chose: %d frames", len(fs))
437 }
438 run(t, ctx, chromedp.Click(chromedp.CSS(`[slides-stage] [data-id="scenea"]`)))
439 readyOne(t, ctx, pageJS, "two")
440}
441
442// TestAFollowerSeesTheSceneCarryOn: the follow link runs the scene and
443// carries it on as the talk moves.
444func TestAFollowerSeesTheSceneCarryOn(t *testing.T) {
445 st := newSceneTalk(t, silentScene)
446 ctx := st.fr.rig.Context()
447 share := "/s/" + mintShareLink(t, st.fr.app, "/d/"+st.f.sqid, st.fr.cookies)
448 st.openWatched(t, ctx, share+"?follow=1", false)
449 first := readyOne(t, ctx, pageJS, "one")
450 mark(t, ctx)
451 press(t, st.fr.app, st.session, st.token, op(t, "next"), nil)
452 waitFrames(t, ctx, pageJS, "the follower's frame told two", func(fs []sceneFrameState) bool {
453 return len(fs) == 1 && said(fs[0], "state", "two", true)
454 })
455 press(t, st.fr.app, st.session, st.token, op(t, "next"), nil)
456 got := waitFrames(t, ctx, pageJS, "the follower's frame carried onto slide 2", func(fs []sceneFrameState) bool {
457 return len(fs) == 1 && fs[0].Mark && said(fs[0], "state", "two", true) && len(fs[0].Log) >= 3
458 })[0]
459 if got.Doc != first.Doc {
460 t.Errorf("the follower made a new frame for the same scene in the same box")
461 }
462}
463
464// TestACaptionAboveASceneStaysAbove: a box drawn above a scene on a
465// canvas stays above it while the scene runs; the scene runs inside its
466// own block there, where the slide's stacking holds.
467func TestACaptionAboveASceneStaysAbove(t *testing.T) {
468 st := newSceneTalk(t, silentScene)
469 ctx := st.fr.rig.Context()
470 st.openWatched(t, ctx, st.slideWindow(), true)
471 readyOne(t, ctx, pageJS, "one")
472 st.gotoSlide(t, 6)
473 run(t, ctx, waitFor(rootJS+`.dataset.slide === '6'`))
474 var got struct{ Live, Inside bool }
475 deadline := time.Now().Add(10 * time.Second)
476 for {
477 run(t, ctx, evalInto(&got, `(() => {
478 const f = document.querySelector('[data-id="scenee"] iframe');
479 return {Live: !!f && getComputedStyle(f).opacity === '1', Inside: !!f};
480 })()`))
481 if got.Live || time.Now().After(deadline) {
482 break
483 }
484 time.Sleep(60 * time.Millisecond)
485 }
486 if !got.Live || !got.Inside {
487 t.Fatalf("the covered scene is not running inside its block: %+v", got)
488 }
489 if fs := readFrames(t, ctx, pageJS); len(fs) != 0 {
490 t.Errorf("the covered scene also has %d frames over the slide", len(fs))
491 }
492 // What is drawn: the caption's white over the scene's blue, and the
493 // scene's blue beside it.
494 pixel := func(sel string, fx, fy float64) color.RGBA {
495 t.Helper()
496 var shot []byte
497 run(t, ctx, inViewShot(sel, &shot))
498 img, err := png.Decode(bytes.NewReader(shot))
499 if err != nil {
500 t.Fatal(err)
501 }
502 b := img.Bounds()
503 r, g, bl, _ := img.At(b.Min.X+int(fx*float64(b.Dx())), b.Min.Y+int(fy*float64(b.Dy()))).RGBA()
504 return color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(bl >> 8), 255}
505 }
506 if c := pixel(`[data-id="caption"]`, 0.1, 0.5); c.R < 240 || c.G < 240 || c.B < 240 {
507 t.Errorf("inside the caption the page shows %v, want the caption's white over the scene", c)
508 }
509 if c := pixel(`[data-id="scenee"]`, 0.05, 0.05); c.B < 140 || c.R > 80 {
510 t.Errorf("beside the caption the page shows %v, want the running scene's blue", c)
511 }
512}
513
514// TestASceneInADelayedContainerWaits: a scene inside a box that arrives
515// on a later press runs only once that box has arrived.
516func TestASceneInADelayedContainerWaits(t *testing.T) {
517 st := newSceneTalk(t, silentScene)
518 ctx := st.fr.rig.Context()
519 st.openWatched(t, ctx, st.slideWindow(), true)
520 readyOne(t, ctx, pageJS, "one")
521 st.gotoSlide(t, 7)
522 run(t, ctx, waitFor(rootJS+`.dataset.slide === '7' && `+rootJS+`.dataset.step === '0'`))
523 time.Sleep(time.Second)
524 if fs := readFrames(t, ctx, pageJS); len(fs) != 0 {
525 t.Fatalf("a scene in a box still to come runs: %d frames", len(fs))
526 }
527 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`))
528 readyOne(t, ctx, pageJS, "one")
529}
530
531// TestAPhoneWidthGivesTheSceneStillBack: narrowing the window to a phone's
532// width stops the scene and shows its still; widening starts it again.
533func TestAPhoneWidthGivesTheSceneStillBack(t *testing.T) {
534 st := newSceneTalk(t, silentScene)
535 ctx := st.fr.rig.Context()
536 size := func(w int64) chromedp.Action[chromedp.Void] {
537 return cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: w, Height: 900, DeviceScaleFactor: 1})
538 }
539 st.openWatched(t, ctx, "/d/"+st.f.sqid+"?slide=1", false)
540 readyOne(t, ctx, pageJS, "two")
541 run(t, ctx, size(420))
542 waitFrames(t, ctx, pageJS, "no scene at a phone's width", func(fs []sceneFrameState) bool { return len(fs) == 0 })
543 var shown struct{ Opacity, Live string }
544 run(t, ctx, evalInto(&shown, `(() => { const b = document.querySelector('[data-id="scenea"]');
545 return {Opacity: getComputedStyle(b.querySelector('[data-scene-state="two"]')).opacity, Live: String(b.hasAttribute('data-scene-live'))}; })()`))
546 if shown.Opacity != "1" || shown.Live != "false" {
547 t.Errorf("at a phone's width the still is %+v, want it drawn", shown)
548 }
549 run(t, ctx, size(1280))
550 readyOne(t, ctx, pageJS, "two")
551}
552
553// TestAFollowerJumpDoesNotAnimate: on the follow view, the next slide
554// reached before the last step of this one is a jump.
555func TestAFollowerJumpDoesNotAnimate(t *testing.T) {
556 st := newSceneTalk(t, silentScene)
557 ctx := st.fr.rig.Context()
558 share := "/s/" + mintShareLink(t, st.fr.app, "/d/"+st.f.sqid, st.fr.cookies)
559 st.openWatched(t, ctx, share+"?follow=1", false)
560 first := readyOne(t, ctx, pageJS, "one")
561 mark(t, ctx)
562 st.gotoSlide(t, 2)
563 got := waitFrames(t, ctx, pageJS, "the follower's frame told two, not animated", func(fs []sceneFrameState) bool {
564 return len(fs) == 1 && said(fs[0], "state", "two", false)
565 })[0]
566 if !got.Mark || got.Doc != first.Doc {
567 t.Errorf("the follower made a new frame for the same scene in the same box")
568 }
569}
570
571// TestAFollowerKeepsTheSceneOverANewStage: the follow view's stage
572// drawn again for the same slide (an edit elsewhere on it) puts the
573// running scene over the new block, and tells it nothing new.
574func TestAFollowerKeepsTheSceneOverANewStage(t *testing.T) {
575 st := newSceneTalk(t, silentScene)
576 ctx := st.fr.rig.Context()
577 share := "/s/" + mintShareLink(t, st.fr.app, "/d/"+st.f.sqid, st.fr.cookies)
578 st.openWatched(t, ctx, share+"?follow=1", false)
579 first := readyOne(t, ctx, pageJS, "one")
580 run(t, ctx, evalValue(nil, `(() => { const s = document.querySelector('[slides-stage]');
581 s.innerHTML = s.innerHTML.replace(/ data-scene-live=""/g, ''); return true; })()`))
582 got := waitFrames(t, ctx, pageJS, "the frame over the new block", func(fs []sceneFrameState) bool {
583 return len(fs) == 1 && fs[0].Live && fs[0].Visible
584 })[0]
585 if got.Doc != first.Doc || len(got.Log) != len(first.Log) {
586 t.Errorf("drawing the same slide again told the scene %v (was %v)", got.Log, first.Log)
587 }
588 if !nearPx(got.Left, got.BlockLeft) || !nearPx(got.Width, got.BlockWidth) {
589 t.Errorf("the frame is at %v (%v wide), the new block at %v (%v)", got.Left, got.Width, got.BlockLeft, got.BlockWidth)
590 }
591}
592
593// TestASceneFitsAShortRegionOnThePage: in a flow region too short for a
594// 16:9 box at its width, the still and the scene are the largest 16:9
595// box that fits, centred (TestAShortFlowRegionFitsTheScene is the
596// picture's half).
597func TestASceneFitsAShortRegionOnThePage(t *testing.T) {
598 st := newSceneTalk(t, silentScene)
599 ctx := st.fr.rig.Context()
600 type fitted struct{ X, Y, W, H, BX, BY, BW, BH, FX, FY, FW, FH, FO float64 }
601 // measure is the still, its block and the scene's frame (over the
602 // slide, or inside the block) once the frame shows.
603 measure := func(block string) fitted {
604 t.Helper()
605 var g fitted
606 deadline := time.Now().Add(10 * time.Second)
607 for {
608 run(t, ctx, evalInto(&g, `(() => {
609 const b = document.querySelector('[data-id="`+block+`"]');
610 const f = b.querySelector('iframe') || document.querySelector('[slides-scene-layer] iframe[data-for="`+block+`"]');
611 const s = b.querySelector('[data-scene-state]').getBoundingClientRect();
612 const r = b.getBoundingClientRect();
613 const q = f ? f.getBoundingClientRect() : {left: 0, top: 0, width: 0, height: 0};
614 return {X: s.left, Y: s.top, W: s.width, H: s.height, BX: r.left, BY: r.top, BW: r.width, BH: r.height,
615 FX: q.left, FY: q.top, FW: q.width, FH: q.height, FO: f ? Number(getComputedStyle(f).opacity) : 0};
616 })()`))
617 if g.FO == 1 || time.Now().After(deadline) {
618 return g
619 }
620 time.Sleep(60 * time.Millisecond)
621 }
622 }
623 for _, c := range []struct{ slide, block string }{{"8", "sceneg"}, {"9", "sceneh"}} {
624 st.openWatched(t, ctx, "/d/"+st.f.sqid+"?slide="+c.slide, false)
625 g := measure(c.block)
626 if g.FO != 1 {
627 t.Fatalf("slide %s: the scene never showed: %+v", c.slide, g)
628 }
629 if r := g.H / g.W; r < 0.55 || r > 0.575 {
630 t.Errorf("slide %s: the still is %vx%v, want 16:9", c.slide, g.W, g.H)
631 }
632 if g.W > g.BW+1 || g.H > g.BH+1 || g.W >= g.BW-1 {
633 t.Errorf("slide %s: the still is %vx%v in a %vx%v block, want it fitted to the block's height", c.slide, g.W, g.H, g.BW, g.BH)
634 }
635 if mid, bc := g.X+g.W/2, g.BX+g.BW/2; mid < bc-1.5 || mid > bc+1.5 {
636 t.Errorf("slide %s: the still is centred at %v, its block at %v", c.slide, mid, bc)
637 }
638 if !nearPx(g.FX, g.X) || !nearPx(g.FY, g.Y) || !nearPx(g.FW, g.W) || !nearPx(g.FH, g.H) {
639 t.Errorf("slide %s: the scene is at %v,%v %vx%v, its still at %v,%v %vx%v", c.slide, g.FX, g.FY, g.FW, g.FH, g.X, g.Y, g.W, g.H)
640 }
641 }
642}
643