//go:build browser package slidestest // Clips in a real browser (scenes and clips spec §2; plan call R3; // Review Focus 5; fixtures/clip.mjs): a press plays one, back pauses and // rewinds it, a loop starts with its slide, every video is muted, and a // video that won't play leaves its poster while the talk moves on. // // The video is made in the test: the browser draws a second and a half // of coloured frames on a canvas and records them with MediaRecorder as // a VP8 WebM (no encoder in the repo or node_modules makes one, and // Chromium plays what it records). It is recorded once per run. import ( "context" "encoding/base64" "encoding/json" "fmt" "net/url" "os" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/rastrillo/rastrillo/blobs" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/chromedp" "github.com/chromedp/chromedp/kb" ) // recordJS records the clip: 320 by 180, a colour that changes each // frame and a square that moves, for 1.6 seconds, as base64. const recordJS = `(async () => { const c = document.createElement('canvas'); c.width = 320; c.height = 180; document.body.append(c); const g = c.getContext('2d'); let i = 0; const draw = () => { g.fillStyle = 'hsl(' + ((i * 29) % 360) + ' 70% 45%)'; g.fillRect(0, 0, 320, 180); g.fillStyle = '#fff'; g.fillRect((i * 12) % 280, 70, 40, 40); i++; }; draw(); const rec = new MediaRecorder(c.captureStream(15), {mimeType: 'video/webm;codecs=vp8'}); const parts = []; rec.ondataavailable = (e) => { if (e.data.size) parts.push(e.data); }; const tick = setInterval(draw, 66); rec.start(); await new Promise((r) => setTimeout(r, 1600)); const stopped = new Promise((r) => { rec.onstop = r; }); rec.stop(); await stopped; clearInterval(tick); c.remove(); const bytes = new Uint8Array(await new Blob(parts, {type: 'video/webm'}).arrayBuffer()); let s = ''; for (let k = 0; k < bytes.length; k += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(k, k + 0x8000)); return btoa(s); })()` var recorded struct { sync.Mutex webm []byte } // recordedWebM is the test's clip, recorded in ctx's browser on origin // the first time it is asked for. func recordedWebM(t *testing.T, ctx context.Context, origin string) []byte { t.Helper() recorded.Lock() defer recorded.Unlock() if recorded.webm != nil { return recorded.webm } var b64 string run(t, ctx, chromedp.Navigate(origin+"/"), evalInto(&b64, recordJS, awaitPromise)) raw, err := base64.StdEncoding.DecodeString(b64) if err != nil || len(raw) < 200 { t.Fatalf("recording a clip gave %d bytes: %v", len(raw), err) } recorded.webm = raw return raw } // clipTalk is a session on clipDeck's deck, its clip video (recorded, or // what the test gives). type clipTalk struct { fr *fontRig f clipFixture session, token string } func newClipTalk(t *testing.T, video []byte) *clipTalk { t.Helper() store, err := blobs.Dir(t.TempDir()) if err != nil { t.Fatalf("blobs.Dir: %v", err) } fr := newFontRigWith(t, store) if video == nil { video = recordedWebM(t, fr.rig.Context(), fr.rig.Origin) } ct := &clipTalk{fr: fr} ct.f = clipDeck(t, fr.app, fr.cookies, fr.token, video) ct.session, ct.token = startPresenting(t, fr.app, "/d/"+ct.f.sqid, fr.cookies) return ct } func (ct *clipTalk) slideWindow() string { return "/p/" + ct.session + "?t=" + url.QueryEscape(ct.token) } func (ct *clipTalk) gotoSlide(t *testing.T, n int) { t.Helper() press(t, ct.fr.app, ct.session, ct.token, url.Values{"op": {"goto"}, "slide": {fmt.Sprint(n)}, "press": {newPressID(t)}}, nil) } // clipState is one clip block as the reader meets it. type clipState struct { Found, Video, Paused, Ended, Muted, Loop, Live bool Time float64 VideoShown, PosterShown bool } func clipJS(within, id string) string { return `(() => { const scope = ` + within + `; const b = scope && scope.querySelector('[slides-block][data-id="` + id + `"]'); if (!b) return {Found: false}; const v = b.querySelector('video'); const img = b.querySelector('img'); const shown = (e) => !!e && getComputedStyle(e).visibility === 'visible' && getComputedStyle(e).opacity === '1'; return {Found: true, Video: !!v, Paused: v ? v.paused : true, Ended: v ? v.ended : false, Muted: v ? v.muted : false, Loop: v ? v.loop : false, Live: b.hasAttribute('data-clip-live'), Time: v ? v.currentTime : 0, VideoShown: shown(v), PosterShown: shown(img) && img.complete && img.naturalWidth > 0 && shown(b)}; })()` } func readClip(t *testing.T, ctx context.Context, within, id string) clipState { t.Helper() var out clipState run(t, ctx, evalInto(&out, clipJS(within, id))) return out } func waitClip(t *testing.T, ctx context.Context, within, id, what string, ok func(clipState) bool) clipState { t.Helper() deadline := time.Now().Add(10 * time.Second) for { got := readClip(t, ctx, within, id) if ok(got) { return got } if time.Now().After(deadline) { raw, _ := json.Marshal(got) t.Fatalf("waiting for %s; the clip is %s", what, raw) } time.Sleep(60 * time.Millisecond) } } const pageScope = `document` func playing(c clipState) bool { return c.Video && !c.Paused && c.Time > 0.1 && c.Live && c.VideoShown } // TestAClipPlaysOnItsPress: a clip on a press shows its poster when its // slide arrives and plays on the press; back pauses it, rewinds it and // gives the poster back; pressed again it plays from the start. func TestAClipPlaysOnItsPress(t *testing.T) { ct := newClipTalk(t, nil) ctx := ct.fr.rig.Context() open(t, ctx, ct.fr.rig.Origin, ct.slideWindow()) at := waitClip(t, ctx, pageScope, "clippress", "the clip waiting with its poster", func(c clipState) bool { return c.Video && c.PosterShown }) time.Sleep(700 * time.Millisecond) if at = readClip(t, ctx, pageScope, "clippress"); !at.Paused || at.Time != 0 || at.Live || at.VideoShown || !at.PosterShown { t.Errorf("before its press the clip is %+v, want paused at the start under its poster", at) } run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`)) waitClip(t, ctx, pageScope, "clippress", "the clip playing on its press", playing) run(t, ctx, key(kb.ArrowLeft), waitFor(rootJS+`.dataset.step === '0'`)) back := waitClip(t, ctx, pageScope, "clippress", "the clip paused and rewound", func(c clipState) bool { return c.Paused && !c.Live }) if back.Time != 0 || back.VideoShown || !back.PosterShown { t.Errorf("after back the clip is %+v, want it at the start under its poster", back) } run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`)) waitClip(t, ctx, pageScope, "clippress", "the clip playing again", playing) // The next press is the next slide's: the clip took exactly one. run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.slide === '2'`)) } // TestALoopingClipStartsWithTheSlide: a looping clip plays as its slide // arrives, with no press of its own, and goes round again; a clip played // once plays to its end and stays on its last frame. func TestALoopingClipStartsWithTheSlide(t *testing.T) { ct := newClipTalk(t, nil) ctx := ct.fr.rig.Context() open(t, ctx, ct.fr.rig.Origin, ct.slideWindow()) ct.gotoSlide(t, 2) run(t, ctx, waitFor(rootJS+`.dataset.slide === '2'`)) c := waitClip(t, ctx, pageScope, "cliploop", "the loop playing", playing) if !c.Loop { t.Errorf("the looping clip is %+v, want loop on", c) } // Round again: its time comes back towards the start while it plays. var wrapped bool run(t, ctx, evalInto(&wrapped, `new Promise((resolve) => { const v = document.querySelector('[data-id="cliploop"] video'); let last = v.currentTime; const until = Date.now() + 6000; const look = () => { if (v.currentTime < last - 0.2 && !v.paused) return resolve(true); last = v.currentTime; if (Date.now() > until) return resolve(false); setTimeout(look, 50); }; look(); })`, awaitPromise)) if !wrapped { t.Errorf("the looping clip never went round again: %+v", readClip(t, ctx, pageScope, "cliploop")) } ct.gotoSlide(t, 3) run(t, ctx, waitFor(rootJS+`.dataset.slide === '3'`)) waitClip(t, ctx, pageScope, "cliponce", "the once clip playing", playing) end := waitClip(t, ctx, pageScope, "cliponce", "the once clip at its end", func(c clipState) bool { return c.Ended }) if !end.Live || !end.VideoShown || end.Loop { t.Errorf("at its end the once clip is %+v, want its last frame shown", end) } time.Sleep(500 * time.Millisecond) if again := readClip(t, ctx, pageScope, "cliponce"); !again.Ended || !again.Paused { t.Errorf("the once clip started again: %+v", again) } } // mutedJS is every video in the page: muted by attribute and property, // with no controls, so nothing on any surface can make a sound. const mutedJS = `[...document.querySelectorAll('video')].map((v) => ({Muted: v.muted && v.defaultMuted && v.hasAttribute('muted'), Controls: v.controls, Inline: v.hasAttribute('playsinline'), Preload: v.getAttribute('preload')}))` type videoFacts struct { Muted, Controls, Inline bool Preload string } // TestClipsAreMuted: on every surface that plays clips (the slide // window, the presenter's Now, the viewer and the follow link) every // video is muted, inline and offered no controls; the presenter's Next // shows the poster, and the remote plays nothing. func TestClipsAreMuted(t *testing.T) { ct := newClipTalk(t, nil) ctx := ct.fr.rig.Context() ct.gotoSlide(t, 2) check := func(where string, want int) { t.Helper() deadline := time.Now().Add(10 * time.Second) var vs []videoFacts for { run(t, ctx, evalInto(&vs, mutedJS)) if len(vs) >= want || time.Now().After(deadline) { break } time.Sleep(60 * time.Millisecond) } if len(vs) < want { t.Errorf("%s: %d videos, want %d", where, len(vs), want) } for _, v := range vs { if !v.Muted || v.Controls || !v.Inline || v.Preload != "auto" { t.Errorf("%s: a video is %+v, want muted, inline, preloaded and without controls", where, v) } } } open(t, ctx, ct.fr.rig.Origin, ct.slideWindow()) run(t, ctx, waitFor(rootJS+`.dataset.slide === '2'`)) waitClip(t, ctx, pageScope, "cliploop", "the loop playing in the slide window", playing) check("the slide window", 1) ct.gotoSlide(t, 1) open(t, ctx, ct.fr.rig.Origin, "/p/"+ct.session+"/notes?t="+url.QueryEscape(ct.token)) run(t, ctx, waitFor(rootJS+`.dataset.slide === '1'`)) waitClip(t, ctx, `document.querySelector('[presenter-panel="now"]')`, "clippress", "the clip in Now", func(c clipState) bool { return c.Video && c.PosterShown }) check("the presenter window", 1) run(t, ctx, waitFor(`!!document.querySelector('[presenter-panel="next"] [data-block="clip"] img')`)) if n := readClip(t, ctx, `document.querySelector('[presenter-panel="next"]')`, "clippress"); n.Video || !n.PosterShown { t.Errorf("Next shows the clip as %+v, want its poster", n) } run(t, ctx, key(kb.ArrowRight)) waitClip(t, ctx, `document.querySelector('[presenter-panel="now"]')`, "clippress", "the clip playing in Now", playing) check("the presenter window, playing", 1) ct.gotoSlide(t, 2) run(t, ctx, chromedp.Navigate(ct.fr.rig.Origin+"/d/"+ct.f.sqid+"?slide=2")) waitClip(t, ctx, pageScope, "cliploop", "the loop in the viewer", playing) check("the viewer", 1) share := "/s/" + mintShareLink(t, ct.fr.app, "/d/"+ct.f.sqid, ct.fr.cookies) run(t, ctx, chromedp.Navigate(ct.fr.rig.Origin+share+"?follow=1")) waitClip(t, ctx, pageScope, "cliploop", "the loop on the follow link", playing) check("the follow link", 1) // The remote shows each slide as its picture, the clip's poster in it. run(t, ctx, chromedp.Navigate(ct.fr.rig.Origin+"/p/"+ct.session+"/remote?t="+url.QueryEscape(ct.token)), waitFor(`!!document.querySelector('img[slides-thumb-img]')`)) time.Sleep(800 * time.Millisecond) check("the remote", 0) var remote int run(t, ctx, evalInto(&remote, `document.querySelectorAll('video').length`)) if remote != 0 { t.Errorf("the remote plays %d videos, want the poster only", remote) } } // TestAClipThatWontPlayKeepsItsPoster (Review Focus 5): a video the // browser cannot play leaves its poster, never a blank or a broken // player, and its press still counts: the talk moves on. func TestAClipThatWontPlayKeepsItsPoster(t *testing.T) { ct := newClipTalk(t, fakeWebM()) ctx := ct.fr.rig.Context() open(t, ctx, ct.fr.rig.Origin, ct.slideWindow()) waitClip(t, ctx, pageScope, "clippress", "the poster, and no video", func(c clipState) bool { return !c.Video && c.PosterShown && !c.Live }) run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`)) time.Sleep(500 * time.Millisecond) if c := readClip(t, ctx, pageScope, "clippress"); c.Video || c.Live || !c.PosterShown { t.Errorf("pressed, the clip that won't play is %+v, want its poster", c) } run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.slide === '2'`)) waitClip(t, ctx, pageScope, "cliploop", "the looping clip's poster", func(c clipState) bool { return !c.Video && c.PosterShown && !c.Live }) run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.slide === '3'`)) } // TestReducedMotionKeepsAClipsPoster: a reader who asked for less // motion gets a loop's poster; a clip on a press still plays on it, // because the person asked for it. func TestReducedMotionKeepsAClipsPoster(t *testing.T) { ct := newClipTalk(t, nil) ctx := ct.fr.rig.Context() run(t, ctx, cdpStep(emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{ {Name: "prefers-reduced-motion", Value: "reduce"}, }})) ct.gotoSlide(t, 2) open(t, ctx, ct.fr.rig.Origin, ct.slideWindow()) run(t, ctx, waitFor(rootJS+`.dataset.slide === '2'`)) waitClip(t, ctx, pageScope, "cliploop", "the loop's poster", func(c clipState) bool { return c.Video && c.PosterShown }) time.Sleep(800 * time.Millisecond) if c := readClip(t, ctx, pageScope, "cliploop"); !c.Paused || c.Live || !c.PosterShown { t.Errorf("with reduced motion the loop is %+v, want its poster", c) } ct.gotoSlide(t, 1) run(t, ctx, waitFor(rootJS+`.dataset.slide === '1'`), key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`)) waitClip(t, ctx, pageScope, "clippress", "the pressed clip playing", playing) } // TestBrowserUploadsAClip: Insert → Clip in the editor takes a video // off disk, draws its first frame as the poster, uploads both and puts // the clip on the slide; a file that is not a video is refused in the // approved words, with its name; the card's Play is a segmented choice. func TestBrowserUploadsAClip(t *testing.T) { store, err := blobs.Dir(t.TempDir()) if err != nil { t.Fatal(err) } fr := newFontRigWith(t, store) ctx := fr.rig.Context() webm := recordedWebM(t, ctx, fr.rig.Origin) dir := t.TempDir() clipPath := filepath.Join(dir, "demo.webm") pngPath := filepath.Join(dir, "dot.png") if err := os.WriteFile(clipPath, webm, 0o600); err != nil { t.Fatal(err) } if err := os.WriteFile(pngPath, onePixelPNG, 0o600); err != nil { t.Fatal(err) } sqid := apiDeck(t, fr.app, fr.token, "A clip") const saved = `document.querySelector('[estilo-save-status]').dataset.state === 'saved'` run(t, ctx, chromedp.Navigate(fr.rig.Origin+"/d/"+sqid+"/edit"), chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)), waitFor(`document.querySelector('[slides-stage] [slides-slide]') !== null`), evalValue(nil, `(() => { document.querySelector('[slides-menu="insert"]').open = true; document.querySelector('[slides-menu="insert"] [data-insert-clip]').click(); return true })()`), waitFor(`document.querySelector('[slides-stage] [data-block="clip"]') !== null`), waitFor(saved), chromedp.SetUploadFiles(chromedp.CSS(`[slides-clip-input]`), []string{pngPath}), waitFor(`document.querySelector('[slides-clip-status]').dataset.state === 'error'`), ) var refused string run(t, ctx, harness.Into(&refused, chromedp.Text(chromedp.CSS(`[slides-clip-status]`)))) if refused != "dot.png isn't an MP4 or WebM video." { t.Errorf("the refusal reads %q", refused) } run(t, ctx, chromedp.SetUploadFiles(chromedp.CSS(`[slides-clip-input]`), []string{clipPath}), waitFor(`['done', 'error'].includes(document.querySelector('[slides-clip-status]').dataset.state)`), ) var said struct{ State, Text string } run(t, ctx, evalInto(&said, `(() => { const s = document.querySelector('[slides-clip-status]'); return {State: s.dataset.state, Text: s.textContent}; })()`)) if said.State != "done" || said.Text != "Uploaded." { t.Fatalf("the clip's upload says %+v", said) } run(t, ctx, waitFor(`document.querySelector('[slides-stage] [data-block="clip"] img') !== null`), waitFor(saved), ) view := apiJSON(t, fr.app, "GET", "/api/v1/decks/"+sqid, fr.token, "", 200) var video, poster map[string]any for _, a := range view["assets"].(map[string]any) { if m := a.(map[string]any); m["poster"] != nil { video = m } } if video == nil { t.Fatalf("the deck holds no video: %v", view["assets"]) } for _, a := range view["assets"].(map[string]any) { if m := a.(map[string]any); m["ref"] == video["poster"] { poster = m } } if poster == nil || video["width"] != float64(320) || video["height"] != float64(180) || video["ref"] != hashOf(webm) { t.Errorf("the clip is %v and its poster %v", video, poster) } var src string run(t, ctx, attributeInto(chromedp.CSS(`[slides-stage] [data-block="clip"] img`), "src", &src, nil)) if !strings.HasSuffix(src, "/assets/"+poster["ref"].(string)) { t.Errorf("the stage draws %q, want the poster", src) } // Its description is the image's own control, and the poster's text. run(t, ctx, waitFor(`document.querySelector('#rst-block-alt').checkVisibility() === true`), setValue(`#rst-block-alt`, "Paul opens a deck"), waitFor(saved), waitFor(`document.querySelector('[slides-stage] [data-block="clip"] img')?.getAttribute('alt') === 'Paul opens a deck'`), ) // Play: On a press, Loop, Once, one radio each; Loop is one set_block. var words string 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('|')`)) if words != "On a press*|Loop|Once" { t.Errorf("the Play choice reads %q", words) } run(t, ctx, chromedp.Click(chromedp.CSS(`input[name="rst-block-play"][value="loop"]`)), waitFor(saved)) view = apiJSON(t, fr.app, "GET", "/api/v1/decks/"+sqid, fr.token, "", 200) var play any for _, s := range view["slides"].([]any) { for _, b := range s.(map[string]any)["blocks"].([]any) { if m := b.(map[string]any); m["type"] == "clip" { play = m["props"].(map[string]any)["play"] } } } if play != "loop" { t.Errorf("after Loop the clip plays %v", play) } }