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// Clips in a real browser (scenes and clips spec §2; plan call R3;
6// Review Focus 5; fixtures/clip.mjs): a press plays one, back pauses and
7// rewinds it, a loop starts with its slide, every video is muted, and a
8// video that won't play leaves its poster while the talk moves on.
9//
10// The video is made in the test: the browser draws a second and a half
11// of coloured frames on a canvas and records them with MediaRecorder as
12// a VP8 WebM (no encoder in the repo or node_modules makes one, and
13// Chromium plays what it records). It is recorded once per run.
14
15import (
16 "context"
17 "encoding/base64"
18 "encoding/json"
19 "fmt"
20 "net/url"
21 "os"
22 "path/filepath"
23 "strings"
24 "sync"
25 "testing"
26 "time"
27
28 "amadan.net/rastrillo/rastrillo/blobs"
29 "amadan.net/rastrillo/rastrillo/harness"
30 "github.com/chromedp/cdproto/emulation"
31 "github.com/chromedp/chromedp"
32 "github.com/chromedp/chromedp/kb"
33)
34
35// recordJS records the clip: 320 by 180, a colour that changes each
36// frame and a square that moves, for 1.6 seconds, as base64.
37const recordJS = `(async () => {
38 const c = document.createElement('canvas');
39 c.width = 320; c.height = 180;
40 document.body.append(c);
41 const g = c.getContext('2d');
42 let i = 0;
43 const draw = () => { g.fillStyle = 'hsl(' + ((i * 29) % 360) + ' 70% 45%)'; g.fillRect(0, 0, 320, 180);
44 g.fillStyle = '#fff'; g.fillRect((i * 12) % 280, 70, 40, 40); i++; };
45 draw();
46 const rec = new MediaRecorder(c.captureStream(15), {mimeType: 'video/webm;codecs=vp8'});
47 const parts = [];
48 rec.ondataavailable = (e) => { if (e.data.size) parts.push(e.data); };
49 const tick = setInterval(draw, 66);
50 rec.start();
51 await new Promise((r) => setTimeout(r, 1600));
52 const stopped = new Promise((r) => { rec.onstop = r; });
53 rec.stop();
54 await stopped;
55 clearInterval(tick);
56 c.remove();
57 const bytes = new Uint8Array(await new Blob(parts, {type: 'video/webm'}).arrayBuffer());
58 let s = '';
59 for (let k = 0; k < bytes.length; k += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(k, k + 0x8000));
60 return btoa(s);
61})()`
62
63var recorded struct {
64 sync.Mutex
65 webm []byte
66}
67
68// recordedWebM is the test's clip, recorded in ctx's browser on origin
69// the first time it is asked for.
70func recordedWebM(t *testing.T, ctx context.Context, origin string) []byte {
71 t.Helper()
72 recorded.Lock()
73 defer recorded.Unlock()
74 if recorded.webm != nil {
75 return recorded.webm
76 }
77 var b64 string
78 run(t, ctx, chromedp.Navigate(origin+"/"), evalInto(&b64, recordJS, awaitPromise))
79 raw, err := base64.StdEncoding.DecodeString(b64)
80 if err != nil || len(raw) < 200 {
81 t.Fatalf("recording a clip gave %d bytes: %v", len(raw), err)
82 }
83 recorded.webm = raw
84 return raw
85}
86
87// clipTalk is a session on clipDeck's deck, its clip video (recorded, or
88// what the test gives).
89type clipTalk struct {
90 fr *fontRig
91 f clipFixture
92 session, token string
93}
94
95func newClipTalk(t *testing.T, video []byte) *clipTalk {
96 t.Helper()
97 store, err := blobs.Dir(t.TempDir())
98 if err != nil {
99 t.Fatalf("blobs.Dir: %v", err)
100 }
101 fr := newFontRigWith(t, store)
102 if video == nil {
103 video = recordedWebM(t, fr.rig.Context(), fr.rig.Origin)
104 }
105 ct := &clipTalk{fr: fr}
106 ct.f = clipDeck(t, fr.app, fr.cookies, fr.token, video)
107 ct.session, ct.token = startPresenting(t, fr.app, "/d/"+ct.f.sqid, fr.cookies)
108 return ct
109}
110
111func (ct *clipTalk) slideWindow() string {
112 return "/p/" + ct.session + "?t=" + url.QueryEscape(ct.token)
113}
114
115func (ct *clipTalk) gotoSlide(t *testing.T, n int) {
116 t.Helper()
117 press(t, ct.fr.app, ct.session, ct.token, url.Values{"op": {"goto"}, "slide": {fmt.Sprint(n)}, "press": {newPressID(t)}}, nil)
118}
119
120// clipState is one clip block as the reader meets it.
121type clipState struct {
122 Found, Video, Paused, Ended, Muted, Loop, Live bool
123 Time float64
124 VideoShown, PosterShown bool
125}
126
127func clipJS(within, id string) string {
128 return `(() => {
129 const scope = ` + within + `;
130 const b = scope && scope.querySelector('[slides-block][data-id="` + id + `"]');
131 if (!b) return {Found: false};
132 const v = b.querySelector('video');
133 const img = b.querySelector('img');
134 const shown = (e) => !!e && getComputedStyle(e).visibility === 'visible' && getComputedStyle(e).opacity === '1';
135 return {Found: true, Video: !!v, Paused: v ? v.paused : true, Ended: v ? v.ended : false, Muted: v ? v.muted : false,
136 Loop: v ? v.loop : false, Live: b.hasAttribute('data-clip-live'), Time: v ? v.currentTime : 0,
137 VideoShown: shown(v), PosterShown: shown(img) && img.complete && img.naturalWidth > 0 && shown(b)};
138})()`
139}
140
141func readClip(t *testing.T, ctx context.Context, within, id string) clipState {
142 t.Helper()
143 var out clipState
144 run(t, ctx, evalInto(&out, clipJS(within, id)))
145 return out
146}
147
148func waitClip(t *testing.T, ctx context.Context, within, id, what string, ok func(clipState) bool) clipState {
149 t.Helper()
150 deadline := time.Now().Add(10 * time.Second)
151 for {
152 got := readClip(t, ctx, within, id)
153 if ok(got) {
154 return got
155 }
156 if time.Now().After(deadline) {
157 raw, _ := json.Marshal(got)
158 t.Fatalf("waiting for %s; the clip is %s", what, raw)
159 }
160 time.Sleep(60 * time.Millisecond)
161 }
162}
163
164const pageScope = `document`
165
166func playing(c clipState) bool { return c.Video && !c.Paused && c.Time > 0.1 && c.Live && c.VideoShown }
167
168// TestAClipPlaysOnItsPress: a clip on a press shows its poster when its
169// slide arrives and plays on the press; back pauses it, rewinds it and
170// gives the poster back; pressed again it plays from the start.
171func TestAClipPlaysOnItsPress(t *testing.T) {
172 ct := newClipTalk(t, nil)
173 ctx := ct.fr.rig.Context()
174 open(t, ctx, ct.fr.rig.Origin, ct.slideWindow())
175
176 at := waitClip(t, ctx, pageScope, "clippress", "the clip waiting with its poster", func(c clipState) bool { return c.Video && c.PosterShown })
177 time.Sleep(700 * time.Millisecond)
178 if at = readClip(t, ctx, pageScope, "clippress"); !at.Paused || at.Time != 0 || at.Live || at.VideoShown || !at.PosterShown {
179 t.Errorf("before its press the clip is %+v, want paused at the start under its poster", at)
180 }
181 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`))
182 waitClip(t, ctx, pageScope, "clippress", "the clip playing on its press", playing)
183
184 run(t, ctx, key(kb.ArrowLeft), waitFor(rootJS+`.dataset.step === '0'`))
185 back := waitClip(t, ctx, pageScope, "clippress", "the clip paused and rewound", func(c clipState) bool { return c.Paused && !c.Live })
186 if back.Time != 0 || back.VideoShown || !back.PosterShown {
187 t.Errorf("after back the clip is %+v, want it at the start under its poster", back)
188 }
189 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`))
190 waitClip(t, ctx, pageScope, "clippress", "the clip playing again", playing)
191 // The next press is the next slide's: the clip took exactly one.
192 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.slide === '2'`))
193}
194
195// TestALoopingClipStartsWithTheSlide: a looping clip plays as its slide
196// arrives, with no press of its own, and goes round again; a clip played
197// once plays to its end and stays on its last frame.
198func TestALoopingClipStartsWithTheSlide(t *testing.T) {
199 ct := newClipTalk(t, nil)
200 ctx := ct.fr.rig.Context()
201 open(t, ctx, ct.fr.rig.Origin, ct.slideWindow())
202 ct.gotoSlide(t, 2)
203 run(t, ctx, waitFor(rootJS+`.dataset.slide === '2'`))
204 c := waitClip(t, ctx, pageScope, "cliploop", "the loop playing", playing)
205 if !c.Loop {
206 t.Errorf("the looping clip is %+v, want loop on", c)
207 }
208 // Round again: its time comes back towards the start while it plays.
209 var wrapped bool
210 run(t, ctx, evalInto(&wrapped, `new Promise((resolve) => {
211 const v = document.querySelector('[data-id="cliploop"] video');
212 let last = v.currentTime;
213 const until = Date.now() + 6000;
214 const look = () => {
215 if (v.currentTime < last - 0.2 && !v.paused) return resolve(true);
216 last = v.currentTime;
217 if (Date.now() > until) return resolve(false);
218 setTimeout(look, 50);
219 };
220 look();
221 })`, awaitPromise))
222 if !wrapped {
223 t.Errorf("the looping clip never went round again: %+v", readClip(t, ctx, pageScope, "cliploop"))
224 }
225
226 ct.gotoSlide(t, 3)
227 run(t, ctx, waitFor(rootJS+`.dataset.slide === '3'`))
228 waitClip(t, ctx, pageScope, "cliponce", "the once clip playing", playing)
229 end := waitClip(t, ctx, pageScope, "cliponce", "the once clip at its end", func(c clipState) bool { return c.Ended })
230 if !end.Live || !end.VideoShown || end.Loop {
231 t.Errorf("at its end the once clip is %+v, want its last frame shown", end)
232 }
233 time.Sleep(500 * time.Millisecond)
234 if again := readClip(t, ctx, pageScope, "cliponce"); !again.Ended || !again.Paused {
235 t.Errorf("the once clip started again: %+v", again)
236 }
237}
238
239// mutedJS is every video in the page: muted by attribute and property,
240// with no controls, so nothing on any surface can make a sound.
241const mutedJS = `[...document.querySelectorAll('video')].map((v) => ({Muted: v.muted && v.defaultMuted && v.hasAttribute('muted'),
242 Controls: v.controls, Inline: v.hasAttribute('playsinline'), Preload: v.getAttribute('preload')}))`
243
244type videoFacts struct {
245 Muted, Controls, Inline bool
246 Preload string
247}
248
249// TestClipsAreMuted: on every surface that plays clips (the slide
250// window, the presenter's Now, the viewer and the follow link) every
251// video is muted, inline and offered no controls; the presenter's Next
252// shows the poster, and the remote plays nothing.
253func TestClipsAreMuted(t *testing.T) {
254 ct := newClipTalk(t, nil)
255 ctx := ct.fr.rig.Context()
256 ct.gotoSlide(t, 2)
257 check := func(where string, want int) {
258 t.Helper()
259 deadline := time.Now().Add(10 * time.Second)
260 var vs []videoFacts
261 for {
262 run(t, ctx, evalInto(&vs, mutedJS))
263 if len(vs) >= want || time.Now().After(deadline) {
264 break
265 }
266 time.Sleep(60 * time.Millisecond)
267 }
268 if len(vs) < want {
269 t.Errorf("%s: %d videos, want %d", where, len(vs), want)
270 }
271 for _, v := range vs {
272 if !v.Muted || v.Controls || !v.Inline || v.Preload != "auto" {
273 t.Errorf("%s: a video is %+v, want muted, inline, preloaded and without controls", where, v)
274 }
275 }
276 }
277 open(t, ctx, ct.fr.rig.Origin, ct.slideWindow())
278 run(t, ctx, waitFor(rootJS+`.dataset.slide === '2'`))
279 waitClip(t, ctx, pageScope, "cliploop", "the loop playing in the slide window", playing)
280 check("the slide window", 1)
281
282 ct.gotoSlide(t, 1)
283 open(t, ctx, ct.fr.rig.Origin, "/p/"+ct.session+"/notes?t="+url.QueryEscape(ct.token))
284 run(t, ctx, waitFor(rootJS+`.dataset.slide === '1'`))
285 waitClip(t, ctx, `document.querySelector('[presenter-panel="now"]')`, "clippress", "the clip in Now", func(c clipState) bool { return c.Video && c.PosterShown })
286 check("the presenter window", 1)
287 run(t, ctx, waitFor(`!!document.querySelector('[presenter-panel="next"] [data-block="clip"] img')`))
288 if n := readClip(t, ctx, `document.querySelector('[presenter-panel="next"]')`, "clippress"); n.Video || !n.PosterShown {
289 t.Errorf("Next shows the clip as %+v, want its poster", n)
290 }
291 run(t, ctx, key(kb.ArrowRight))
292 waitClip(t, ctx, `document.querySelector('[presenter-panel="now"]')`, "clippress", "the clip playing in Now", playing)
293 check("the presenter window, playing", 1)
294
295 ct.gotoSlide(t, 2)
296 run(t, ctx, chromedp.Navigate(ct.fr.rig.Origin+"/d/"+ct.f.sqid+"?slide=2"))
297 waitClip(t, ctx, pageScope, "cliploop", "the loop in the viewer", playing)
298 check("the viewer", 1)
299
300 share := "/s/" + mintShareLink(t, ct.fr.app, "/d/"+ct.f.sqid, ct.fr.cookies)
301 run(t, ctx, chromedp.Navigate(ct.fr.rig.Origin+share+"?follow=1"))
302 waitClip(t, ctx, pageScope, "cliploop", "the loop on the follow link", playing)
303 check("the follow link", 1)
304
305 // The remote shows each slide as its picture, the clip's poster in it.
306 run(t, ctx, chromedp.Navigate(ct.fr.rig.Origin+"/p/"+ct.session+"/remote?t="+url.QueryEscape(ct.token)),
307 waitFor(`!!document.querySelector('img[slides-thumb-img]')`))
308 time.Sleep(800 * time.Millisecond)
309 check("the remote", 0)
310 var remote int
311 run(t, ctx, evalInto(&remote, `document.querySelectorAll('video').length`))
312 if remote != 0 {
313 t.Errorf("the remote plays %d videos, want the poster only", remote)
314 }
315}
316
317// TestAClipThatWontPlayKeepsItsPoster (Review Focus 5): a video the
318// browser cannot play leaves its poster, never a blank or a broken
319// player, and its press still counts: the talk moves on.
320func TestAClipThatWontPlayKeepsItsPoster(t *testing.T) {
321 ct := newClipTalk(t, fakeWebM())
322 ctx := ct.fr.rig.Context()
323 open(t, ctx, ct.fr.rig.Origin, ct.slideWindow())
324 waitClip(t, ctx, pageScope, "clippress", "the poster, and no video", func(c clipState) bool { return !c.Video && c.PosterShown && !c.Live })
325 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`))
326 time.Sleep(500 * time.Millisecond)
327 if c := readClip(t, ctx, pageScope, "clippress"); c.Video || c.Live || !c.PosterShown {
328 t.Errorf("pressed, the clip that won't play is %+v, want its poster", c)
329 }
330 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.slide === '2'`))
331 waitClip(t, ctx, pageScope, "cliploop", "the looping clip's poster", func(c clipState) bool { return !c.Video && c.PosterShown && !c.Live })
332 run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.slide === '3'`))
333}
334
335// TestReducedMotionKeepsAClipsPoster: a reader who asked for less
336// motion gets a loop's poster; a clip on a press still plays on it,
337// because the person asked for it.
338func TestReducedMotionKeepsAClipsPoster(t *testing.T) {
339 ct := newClipTalk(t, nil)
340 ctx := ct.fr.rig.Context()
341 run(t, ctx, cdpStep(emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{
342 {Name: "prefers-reduced-motion", Value: "reduce"},
343 }}))
344 ct.gotoSlide(t, 2)
345 open(t, ctx, ct.fr.rig.Origin, ct.slideWindow())
346 run(t, ctx, waitFor(rootJS+`.dataset.slide === '2'`))
347 waitClip(t, ctx, pageScope, "cliploop", "the loop's poster", func(c clipState) bool { return c.Video && c.PosterShown })
348 time.Sleep(800 * time.Millisecond)
349 if c := readClip(t, ctx, pageScope, "cliploop"); !c.Paused || c.Live || !c.PosterShown {
350 t.Errorf("with reduced motion the loop is %+v, want its poster", c)
351 }
352 ct.gotoSlide(t, 1)
353 run(t, ctx, waitFor(rootJS+`.dataset.slide === '1'`), key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`))
354 waitClip(t, ctx, pageScope, "clippress", "the pressed clip playing", playing)
355}
356
357// TestBrowserUploadsAClip: Insert → Clip in the editor takes a video
358// off disk, draws its first frame as the poster, uploads both and puts
359// the clip on the slide; a file that is not a video is refused in the
360// approved words, with its name; the card's Play is a segmented choice.
361func TestBrowserUploadsAClip(t *testing.T) {
362 store, err := blobs.Dir(t.TempDir())
363 if err != nil {
364 t.Fatal(err)
365 }
366 fr := newFontRigWith(t, store)
367 ctx := fr.rig.Context()
368 webm := recordedWebM(t, ctx, fr.rig.Origin)
369 dir := t.TempDir()
370 clipPath := filepath.Join(dir, "demo.webm")
371 pngPath := filepath.Join(dir, "dot.png")
372 if err := os.WriteFile(clipPath, webm, 0o600); err != nil {
373 t.Fatal(err)
374 }
375 if err := os.WriteFile(pngPath, onePixelPNG, 0o600); err != nil {
376 t.Fatal(err)
377 }
378 sqid := apiDeck(t, fr.app, fr.token, "A clip")
379 const saved = `document.querySelector('[estilo-save-status]').dataset.state === 'saved'`
380 run(t, ctx,
381 chromedp.Navigate(fr.rig.Origin+"/d/"+sqid+"/edit"),
382 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
383 waitFor(`document.querySelector('[slides-stage] [slides-slide]') !== null`),
384 evalValue(nil, `(() => { document.querySelector('[slides-menu="insert"]').open = true;
385 document.querySelector('[slides-menu="insert"] [data-insert-clip]').click(); return true })()`),
386 waitFor(`document.querySelector('[slides-stage] [data-block="clip"]') !== null`),
387 waitFor(saved),
388 chromedp.SetUploadFiles(chromedp.CSS(`[slides-clip-input]`), []string{pngPath}),
389 waitFor(`document.querySelector('[slides-clip-status]').dataset.state === 'error'`),
390 )
391 var refused string
392 run(t, ctx, harness.Into(&refused, chromedp.Text(chromedp.CSS(`[slides-clip-status]`))))
393 if refused != "dot.png isn't an MP4 or WebM video." {
394 t.Errorf("the refusal reads %q", refused)
395 }
396
397 run(t, ctx,
398 chromedp.SetUploadFiles(chromedp.CSS(`[slides-clip-input]`), []string{clipPath}),
399 waitFor(`['done', 'error'].includes(document.querySelector('[slides-clip-status]').dataset.state)`),
400 )
401 var said struct{ State, Text string }
402 run(t, ctx, evalInto(&said, `(() => { const s = document.querySelector('[slides-clip-status]'); return {State: s.dataset.state, Text: s.textContent}; })()`))
403 if said.State != "done" || said.Text != "Uploaded." {
404 t.Fatalf("the clip's upload says %+v", said)
405 }
406 run(t, ctx,
407 waitFor(`document.querySelector('[slides-stage] [data-block="clip"] img') !== null`),
408 waitFor(saved),
409 )
410 view := apiJSON(t, fr.app, "GET", "/api/v1/decks/"+sqid, fr.token, "", 200)
411 var video, poster map[string]any
412 for _, a := range view["assets"].(map[string]any) {
413 if m := a.(map[string]any); m["poster"] != nil {
414 video = m
415 }
416 }
417 if video == nil {
418 t.Fatalf("the deck holds no video: %v", view["assets"])
419 }
420 for _, a := range view["assets"].(map[string]any) {
421 if m := a.(map[string]any); m["ref"] == video["poster"] {
422 poster = m
423 }
424 }
425 if poster == nil || video["width"] != float64(320) || video["height"] != float64(180) || video["ref"] != hashOf(webm) {
426 t.Errorf("the clip is %v and its poster %v", video, poster)
427 }
428 var src string
429 run(t, ctx, attributeInto(chromedp.CSS(`[slides-stage] [data-block="clip"] img`), "src", &src, nil))
430 if !strings.HasSuffix(src, "/assets/"+poster["ref"].(string)) {
431 t.Errorf("the stage draws %q, want the poster", src)
432 }
433
434 // Its description is the image's own control, and the poster's text.
435 run(t, ctx,
436 waitFor(`document.querySelector('#rst-block-alt').checkVisibility() === true`),
437 setValue(`#rst-block-alt`, "Paul opens a deck"),
438 waitFor(saved),
439 waitFor(`document.querySelector('[slides-stage] [data-block="clip"] img')?.getAttribute('alt') === 'Paul opens a deck'`),
440 )
441
442 // Play: On a press, Loop, Once, one radio each; Loop is one set_block.
443 var words string
444 run(t, ctx, evalInto(&words, `[...document.querySelectorAll('[slides-inspector-form] input[name="rst-block-play"]')].map((r) => r.closest('label').textContent.trim() + (r.checked ? '*' : '')).join('|')`))
445 if words != "On a press*|Loop|Once" {
446 t.Errorf("the Play choice reads %q", words)
447 }
448 run(t, ctx, chromedp.Click(chromedp.CSS(`input[name="rst-block-play"][value="loop"]`)), waitFor(saved))
449 view = apiJSON(t, fr.app, "GET", "/api/v1/decks/"+sqid, fr.token, "", 200)
450 var play any
451 for _, s := range view["slides"].([]any) {
452 for _, b := range s.(map[string]any)["blocks"].([]any) {
453 if m := b.(map[string]any); m["type"] == "clip" {
454 play = m["props"].(map[string]any)["play"]
455 }
456 }
457 }
458 if play != "loop" {
459 t.Errorf("after Loop the clip plays %v", play)
460 }
461}
462