//go:build browser // The presenter window and the slide window move at once (Task 10, // spec ยง6): a press redraws the window from the talk it holds in // memory, then goes to the server; a press is never lost or repeated, // never unanswered, and needs no network. package slidestest import ( "context" "fmt" "net/http" "net/url" "strconv" "strings" "sync" "sync/atomic" "testing" "time" "amadan.net/rastrillo/rastrillo/blobs" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/input" "github.com/chromedp/chromedp" "github.com/chromedp/chromedp/kb" ) // movesTalk is a session on a deck of four slides in the talk: "steps" // (four presses), "plain", "picture" (an image) and "last". type movesTalk struct { fr *fontRig sqid string session, token string // hold, when set, sees each request first and may hold it. hold atomic.Pointer[func(r *http.Request)] // Chromium's offline emulation stops new requests but leaves a // stream already open delivering, so a cut network also ends every // open stream here, and refuses new ones until it is healed. mu sync.Mutex off bool streams map[*http.Request]context.CancelFunc } func newMovesTalk(t *testing.T) *movesTalk { t.Helper() store, err := blobs.Dir(t.TempDir()) if err != nil { t.Fatalf("blobs.Dir: %v", err) } fr := newFontRigWith(t, store) mt := &movesTalk{fr: fr, streams: map[*http.Request]context.CancelFunc{}} wrap := func(w http.ResponseWriter, r *http.Request, next http.Handler) { if hold := mt.hold.Load(); hold != nil { (*hold)(r) } if !strings.HasSuffix(r.URL.Path, "/stream") { next.ServeHTTP(w, r) return } mt.mu.Lock() if mt.off { mt.mu.Unlock() http.Error(w, "cut", http.StatusServiceUnavailable) return } ctx, cancel := context.WithCancel(r.Context()) mt.streams[r] = cancel mt.mu.Unlock() defer func() { mt.mu.Lock() delete(mt.streams, r) mt.mu.Unlock() cancel() }() next.ServeHTTP(w, r.WithContext(ctx)) } fr.wrap.Store(&wrap) mt.sqid = fr.deck(t, "Moves", `[]`) record := upload(t, fr.app, "/d/"+mt.sqid, fr.cookies, "chart.png", "image/png", onePixelPNG, "A chart") registerInDeck(t, fr.app, fr.token, mt.sqid, record) ops := []string{ `{"op":"add_slide","id":"steps","layout":"flow","template":"title-body"}`, `{"op":"add_block","slide":"steps","id":"stepshead","type":"heading","region":"heading","props":{"level":1},"markdown":"Steps"}`, } for i, word := range []string{"one", "two", "three", "four"} { id := quote("b" + strconv.Itoa(i+1)) ops = append(ops, `{"op":"add_block","slide":"steps","id":`+id+`,"type":"text","region":"body","markdown":`+quote(word)+`}`, `{"op":"set_block","slide":"steps","id":`+id+`,"step":`+strconv.Itoa(i+1)+`}`) } ops = append(ops, `{"op":"add_slide","id":"plain","layout":"flow","template":"title-body"}`, `{"op":"add_block","slide":"plain","id":"plainhead","type":"heading","region":"heading","props":{"level":1},"markdown":"Plain"}`, `{"op":"add_slide","id":"picture","layout":"flow","template":"image-full"}`, fmt.Sprintf(`{"op":"add_block","slide":"picture","id":"pictureimg","type":"image","region":"media","props":{"asset":%q}}`, record["id"]), `{"op":"add_slide","id":"last","layout":"flow","template":"title-body"}`, `{"op":"add_block","slide":"last","id":"lasthead","type":"heading","region":"heading","props":{"level":1},"markdown":"Last"}`) fr.ops(t, mt.sqid, "["+strings.Join(ops, ",")+"]") mt.session, mt.token = startPresenting(t, fr.app, "/d/"+mt.sqid, fr.cookies) return mt } func (mt *movesTalk) presenter() string { return "/p/" + mt.session + "/notes?t=" + url.QueryEscape(mt.token) } func (mt *movesTalk) slideWindow() string { return "/p/" + mt.session + "?t=" + url.QueryEscape(mt.token) } // phone presses as the paired phone does. func (mt *movesTalk) phone(t *testing.T, name string) pressAnswer { t.Helper() return press(t, mt.fr.app, mt.session, mt.token, op(t, name), nil) } func (mt *movesTalk) gotoSlide(t *testing.T, n int) { t.Helper() press(t, mt.fr.app, mt.session, mt.token, url.Values{"op": {"goto"}, "slide": {strconv.Itoa(n)}, "press": {newPressID(t)}}, nil) } // row is where the server says the talk is. func (mt *movesTalk) row(t *testing.T) (string, int, int64) { t.Helper() return rowPosition(t, mt.fr.app, mt.session) } // waitRow waits until the server's position is slide at step. func (mt *movesTalk) waitRow(t *testing.T, slide string, step int) { t.Helper() deadline := time.Now().Add(15 * time.Second) for { id, k, _ := mt.row(t) if id == slide && k == step { return } if time.Now().After(deadline) { t.Fatalf("the server is at %s step %d, want %s step %d", id, k, slide, step) } time.Sleep(50 * time.Millisecond) } } // root is the window's root on either page. const rootJS = `(document.querySelector('[presenter]') || document.querySelector('[slides-surface]'))` // open loads path in ctx and waits until the window holds the whole talk. func open(t *testing.T, ctx context.Context, origin, path string) { t.Helper() run(t, ctx, chromedp.Navigate(origin+path), waitFor(rootJS+`?.getAttribute('data-loaded') === 'all'`)) } func run(t *testing.T, ctx context.Context, actions ...chromedp.Action[chromedp.Void]) { t.Helper() if err := chromedp.Do(ctx, actions...); err != nil { t.Fatalf("drive: %v", err) } } // windowState is what a window's root says it shows. type windowState struct { Slide, Step, Mode, Black string Steps, Pos, Flash, Pulse string Now string } const windowStateJS = `(() => { const r = ` + rootJS + `; const sc = document.querySelector('[presenter-stepcount]'); const pos = document.querySelector('[presenter-pos]'); const now = document.querySelector('[presenter-panel="now"] [slides-slide]') || document.querySelector('[slides-stage] [slides-slide]'); return { Slide: r.dataset.slide, Step: r.dataset.step, Mode: r.dataset.mode, Black: r.dataset.blackout, Steps: sc && sc.checkVisibility() ? sc.innerText : '', Pos: pos ? pos.innerText : '', Flash: sc ? sc.getAttribute('data-flash') || '' : '', Pulse: pos ? pos.getAttribute('data-pulse') || '' : '', Now: now ? now.innerText : '' }; })()` func state(t *testing.T, ctx context.Context) windowState { t.Helper() var s windowState run(t, ctx, evalInto(&s, windowStateJS)) return s } func key(k string) chromedp.Action[chromedp.Void] { return chromedp.KeyEvent(k) } // mounted waits for the presenter window's script, which names its // window: a key pressed before any script ran is the browser's. var mounted = waitFor(`window.name === 'slides-presenter'`) // TestPresenterStepCountChangesOnEveryPress: through a slide with steps // the step count's words change on every press, at once; on slides // without steps it is not drawn and the position changes instead. func TestPresenterStepCountChangesOnEveryPress(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() open(t, ctx, mt.fr.rig.Origin, mt.presenter()) before := state(t, ctx) if before.Steps == "" { t.Fatalf("the step count is not drawn on a slide with steps: %+v", before) } for k := 1; k <= 4; k++ { run(t, ctx, key(kb.ArrowRight)) got := state(t, ctx) if got.Step != strconv.Itoa(k) || got.Steps == before.Steps || got.Steps == "" { t.Fatalf("press %d: step %q, step count %q (was %q); want step %d and new words, at once", k, got.Step, got.Steps, before.Steps, k) } if got.Flash == before.Flash { t.Errorf("press %d: the step count's flash did not restart", k) } before = got } for _, want := range []string{"2", "3", "4"} { run(t, ctx, key(kb.ArrowRight)) got := state(t, ctx) if got.Slide != want || got.Pos == before.Pos || got.Steps != "" { t.Fatalf("onto slide %s: data-slide %q, position %q (was %q), step count %q; want the position to change and no step count", want, got.Slide, got.Pos, before.Pos, got.Steps) } before = got } mt.waitRow(t, "last", 0) } // TestTheLastPressOfTheTalkStillAnswers: next on the last step of the // last slide moves nothing, and still answers: the position pulses // again, the step count's flash restarts, and the server hears it. func TestTheLastPressOfTheTalkStillAnswers(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() open(t, ctx, mt.fr.rig.Origin, mt.presenter()) run(t, ctx, key(kb.End)) mt.waitRow(t, "last", 0) before := state(t, ctx) _, _, seq := mt.row(t) for range 2 { var running bool run(t, ctx, key(kb.ArrowRight), evalInto(&running, `document.querySelector('[presenter-pos]').getAnimations().some(a => a.playState === 'running')`)) got := state(t, ctx) if got.Slide != before.Slide || got.Step != before.Step { t.Fatalf("next at the end moved the window: %+v, was %+v", got, before) } if got.Pulse == before.Pulse || got.Flash == before.Flash || !running { t.Errorf("next at the end did not answer: pulse %q (was %q), flash %q (was %q), animating %v", got.Pulse, before.Pulse, got.Flash, before.Flash, running) } before = got } deadline := time.Now().Add(10 * time.Second) for { _, _, now := mt.row(t) if now >= seq+2 { break } if time.Now().After(deadline) { t.Fatalf("the server heard %d of the two presses at the end", now-seq) } time.Sleep(50 * time.Millisecond) } } // TestPresenterFastPressesNeverJumpBack: with every press's answer // slow, three quick presses move the window three steps at once, it // never shows an earlier step on any frame while the answers come in, // and the server counts three. func TestPresenterFastPressesNeverJumpBack(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() open(t, ctx, mt.fr.rig.Origin, mt.presenter()) slow := func(r *http.Request) { if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/command") { time.Sleep(600 * time.Millisecond) } } mt.hold.Store(&slow) run(t, ctx, chromedp.Evaluate[chromedp.Void](`(() => { window.__steps = []; const r = `+rootJS+`; const sample = () => { window.__steps.push(Number(r.dataset.step)); requestAnimationFrame(sample) }; sample(); return true })()`)) run(t, ctx, key(kb.ArrowRight), key(kb.ArrowRight), key(kb.ArrowRight)) if got := state(t, ctx); got.Step != "3" { t.Fatalf("three quick presses: the window is at step %s, want 3 at once", got.Step) } mt.waitRow(t, "steps", 3) run(t, ctx, chromedp.Sleep(1500*time.Millisecond)) var steps []int run(t, ctx, evalInto(&steps, `window.__steps`)) for i := 1; i < len(steps); i++ { if steps[i] < steps[i-1] { t.Fatalf("the step went back from %d to %d on frame %d of %d: %v", steps[i-1], steps[i], i, len(steps), steps) } } if len(steps) == 0 || steps[len(steps)-1] != 3 { t.Errorf("the window ended at %v, want step 3", steps) } if _, step, _ := mt.row(t); step != 3 { t.Errorf("the server counted %d presses, want 3", step) } } // TestPresenterIgnoresKeyRepeat: a key held down is one press. func TestPresenterIgnoresKeyRepeat(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() open(t, ctx, mt.fr.rig.Origin, mt.presenter()) down := func(repeat bool) chromedp.Action[chromedp.Void] { return cdpStep(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: input.DispatchKeyEventTypeKeyDown, Key: "ArrowRight", Code: "ArrowRight", WindowsVirtualKeyCode: 39, NativeVirtualKeyCode: 39, AutoRepeat: new(repeat)}) } run(t, ctx, down(false), down(true), down(true), down(true), cdpStep(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: input.DispatchKeyEventTypeKeyUp, Key: "ArrowRight", Code: "ArrowRight", WindowsVirtualKeyCode: 39, NativeVirtualKeyCode: 39})) if got := state(t, ctx); got.Step != "1" { t.Fatalf("a held key moved the window to step %s, want 1", got.Step) } mt.waitRow(t, "steps", 1) run(t, ctx, chromedp.Sleep(time.Second)) if _, step, _ := mt.row(t); step != 1 { t.Errorf("a held key moved the talk to step %d, want 1", step) } } // TestPresenterClickerWorksFromAField: with a field focused, the // clicker's PageDown and PageUp still move the talk, and every other // key is typed into the field. func TestPresenterClickerWorksFromAField(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() open(t, ctx, mt.fr.rig.Origin, mt.presenter()) run(t, ctx, chromedp.Evaluate[chromedp.Void](`(() => { const f = document.createElement('input'); f.id = 'field'; document.querySelector('[presenter-head]').append(f); return true })()`), chromedp.Focus(chromedp.CSS(`#field`)), key(kb.PageDown)) if got := state(t, ctx); got.Step != "1" { t.Fatalf("PageDown from a field: step %s, want 1", got.Step) } var value string run(t, ctx, key("b"), key(kb.ArrowRight), harness.Into(&value, chromedp.Value(chromedp.CSS(`#field`)))) if got := state(t, ctx); got.Step != "1" || got.Black != "false" || value != "b" { t.Errorf("typing in a field moved the talk: step %s, black %s, the field holds %q", got.Step, got.Black, value) } run(t, ctx, key(kb.PageUp)) if got := state(t, ctx); got.Step != "0" { t.Errorf("PageUp from a field: step %s, want 0", got.Step) } mt.waitRow(t, "steps", 0) } // TestTwoWindowsAndAPhoneStayTogether: a press in either window or on // the phone moves all three; the laptop and the phone pressing at once // both count. func TestTwoWindowsAndAPhoneStayTogether(t *testing.T) { mt := newMovesTalk(t) presenter := mt.fr.rig.Context() slides, cancel := chromedp.NewContext(presenter) defer cancel() open(t, presenter, mt.fr.rig.Origin, mt.presenter()) open(t, slides, mt.fr.rig.Origin, mt.slideWindow()) both := func(slide, step string) { t.Helper() want := rootJS + `.dataset.slide === '` + slide + `' && ` + rootJS + `.dataset.step === '` + step + `'` run(t, presenter, waitFor(want)) run(t, slides, waitFor(want)) } run(t, presenter, key(kb.ArrowRight)) both("1", "1") run(t, slides, key(kb.ArrowRight)) both("1", "2") mt.phone(t, "next") both("1", "3") var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() rec := pressRequest(t, mt.fr.app, mt.session, mt.token, op(t, "next"), nil) if rec.Code != http.StatusOK { t.Errorf("the phone's press: %d", rec.Code) } }() run(t, presenter, key(kb.ArrowRight)) wg.Wait() mt.waitRow(t, "plain", 0) both("2", "0") } // emulateNetworkConditions is Network.emulateNetworkConditions as // chromedp v0.14's cdproto sent it. cdproto v0.158 dropped it for // overrideNetworkState, but under that one // TestADroppedNetworkKeepsThePressingWindowMoving's server never reached // the window's offline position after the network came back, so the cut // keeps the command it was written against. var emulateNetworkConditions = cdp.Command[emulateNetworkConditionsParams, cdp.Empty]{Method: "Network.emulateNetworkConditions"} type emulateNetworkConditionsParams struct { Offline bool `json:"offline"` Latency float64 `json:"latency"` DownloadThroughput float64 `json:"downloadThroughput"` UploadThroughput float64 `json:"uploadThroughput"` } // cut takes the pages in ctxs off the network, or puts them back. func (mt *movesTalk) cut(t *testing.T, off bool, ctxs ...context.Context) { t.Helper() for _, ctx := range ctxs { run(t, ctx, cdpStep(emulateNetworkConditions, emulateNetworkConditionsParams{Offline: off, Latency: 0, DownloadThroughput: -1, UploadThroughput: -1})) } mt.mu.Lock() mt.off = off if off { for _, cancel := range mt.streams { cancel() } } mt.mu.Unlock() } // TestADroppedNetworkKeepsThePressingWindowMoving: with the network cut // the presenter window still moves across slides, a picture included, // and says so; the slide window holds still and says it is waiting; when // the network returns the server takes the presenter window's position // over a phone press made meanwhile, and the slide window follows. func TestADroppedNetworkKeepsThePressingWindowMoving(t *testing.T) { mt := newMovesTalk(t) mt.gotoSlide(t, 2) presenter := mt.fr.rig.Context() slides, cancel := chromedp.NewContext(presenter) defer cancel() open(t, presenter, mt.fr.rig.Origin, mt.presenter()) open(t, slides, mt.fr.rig.Origin, mt.slideWindow()) run(t, presenter, waitFor(rootJS+`.dataset.slide === '2'`)) run(t, slides, waitFor(rootJS+`.dataset.slide === '2'`)) mt.cut(t, true, presenter, slides) // The cut is real: a phone press made now reaches neither window. mt.phone(t, "prev") run(t, presenter, chromedp.Sleep(2*time.Second)) for name, ctx := range map[string]context.Context{"presenter window": presenter, "slide window": slides} { if got := state(t, ctx); got.Slide != "2" { t.Fatalf("the %s heard the phone through a cut network: on slide %s step %s", name, got.Slide, got.Step) } } picture := `(() => { const img = document.querySelector('[presenter-panel="now"] img'); return !!img && img.complete && img.naturalWidth > 0 })()` var drawn bool run(t, presenter, key(kb.ArrowRight), evalInto(&drawn, picture)) if got := state(t, presenter); got.Slide != "3" || !drawn { t.Fatalf("offline, next onto the picture: slide %s, picture drawn %v", got.Slide, drawn) } run(t, presenter, key(kb.ArrowRight)) if got := state(t, presenter); got.Slide != "4" || !strings.Contains(got.Now, "Last") { t.Fatalf("offline, next onto the last slide: slide %s, Now %q", got.Slide, got.Now) } run(t, presenter, waitFor(`document.querySelector('[presenter-status]').innerText === 'Offline. This window still moves.'`)) run(t, slides, waitFor(`document.querySelector('[slides-waiting]')?.checkVisibility() && document.querySelector('[slides-waiting]').innerText === 'Waiting for the network'`)) if got := state(t, slides); got.Slide != "2" { t.Errorf("the slide window moved while cut off: slide %s", got.Slide) } mt.cut(t, false, presenter, slides) mt.waitRow(t, "last", 0) run(t, slides, waitFor(rootJS+`.dataset.slide === '4'`), waitFor(`!document.querySelector('[slides-waiting]').checkVisibility()`)) run(t, presenter, waitFor(`document.querySelector('[presenter-status]').innerText === ''`)) if got := state(t, presenter); got.Slide != "4" { t.Errorf("the presenter window left its own position on reconnecting: slide %s", got.Slide) } } // TestAWindowThatPressedNothingTakesTheServersPosition: a window cut off // that pressed nothing takes where the phone took the talk meanwhile, // and tells the server nothing. func TestAWindowThatPressedNothingTakesTheServersPosition(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() open(t, ctx, mt.fr.rig.Origin, mt.presenter()) mt.cut(t, true, ctx) mt.phone(t, "next") mt.phone(t, "next") run(t, ctx, chromedp.Sleep(2*time.Second)) if got := state(t, ctx); got.Step != "0" { t.Fatalf("the window heard the phone through a cut network: step %s", got.Step) } run(t, ctx, waitFor(`document.querySelector('[presenter-status]').innerText === 'Offline. This window still moves.'`)) _, _, seq := mt.row(t) mt.cut(t, false, ctx) run(t, ctx, waitFor(rootJS+`.dataset.step === '2'`), waitFor(`document.querySelector('[presenter-status]').innerText === ''`)) run(t, ctx, chromedp.Sleep(time.Second)) if id, step, now := mt.row(t); id != "steps" || step != 2 || now != seq { t.Errorf("the server is at %s step %d (seq %d, was %d); the window that pressed nothing changed it", id, step, now, seq) } } // TestPresenterTakesAnEditAtTheNextSlide: a deck changed during the // talk is loaded quietly and taken at the window's next change of // slide, landing where the server lands: the current slide deleted, // parked, or left with fewer steps. func TestPresenterTakesAnEditAtTheNextSlide(t *testing.T) { for _, c := range []struct { name string start func(mt *movesTalk, t *testing.T) edit string key string slide string // where the window and the server land step int shows string }{ {name: "the current slide deleted", start: func(mt *movesTalk, t *testing.T) { mt.gotoSlide(t, 2) }, edit: `[{"op":"remove_slide","id":"plain"}]`, key: kb.ArrowLeft, slide: "steps", step: 4, shows: "four"}, {name: "the current slide parked", start: func(mt *movesTalk, t *testing.T) { mt.gotoSlide(t, 2) }, edit: `[{"op":"set_slide","id":"plain","talk":"parked"}]`, key: kb.ArrowLeft, slide: "steps", step: 4, shows: "four"}, {name: "the current slide losing steps", start: func(mt *movesTalk, t *testing.T) { mt.phone(t, "next") mt.phone(t, "next") mt.phone(t, "next") }, edit: `[{"op":"set_block","slide":"steps","id":"b4","step":null}]`, key: kb.ArrowRight, slide: "plain", step: 0, shows: "Plain"}, } { t.Run(c.name, func(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() c.start(mt, t) open(t, ctx, mt.fr.rig.Origin, mt.presenter()) before := state(t, ctx) mt.fr.ops(t, mt.sqid, c.edit) // The speaker comes back from the editor. run(t, ctx, chromedp.Evaluate[chromedp.Void](`window.dispatchEvent(new Event('focus'))`), waitFor(rootJS+`.hasAttribute('data-deck-pending')`)) if got := state(t, ctx); got.Now != before.Now || got.Slide != before.Slide { t.Fatalf("the window took the edit before the slide changed: Now %q (was %q)", got.Now, before.Now) } run(t, ctx, key(c.key)) got := state(t, ctx) mt.waitRow(t, c.slide, c.step) if got.Step != strconv.Itoa(c.step) || !strings.Contains(got.Now, c.shows) { t.Errorf("after the press the window is at step %s showing %q; the server is at %s step %d (%s)", got.Step, got.Now, c.slide, c.step, c.shows) } var pending bool run(t, ctx, evalInto(&pending, rootJS+`.hasAttribute('data-deck-pending')`)) if pending { t.Error("the newer version is still waiting after a change of slide") } }) } } // frameLogJS records, on every frame, the slide on the presenter's Now: // its heading, and whether its picture is drawn. const frameLogJS = `(() => { window.__frames = []; const log = () => { const now = document.querySelectorAll('[presenter-panel="now"] [slides-slide]'); const img = now[0] && now[0].querySelector('img'); window.__frames.push({ n: now.length, text: now[0] ? now[0].innerText : '', img: !!img, ok: !!img && img.complete && img.naturalWidth > 0 }); requestAnimationFrame(log) }; log(); return true })()` // TestPressBeforeTheTalkLoadsKeepsTheSlideOnScreen: a press made while // the talk and the next slide's picture are still on their way leaves // the slide on screen, never a blank, until the next is complete, which // arrives whole. func TestPressBeforeTheTalkLoadsKeepsTheSlideOnScreen(t *testing.T) { mt := newMovesTalk(t) mt.gotoSlide(t, 2) ctx := mt.fr.rig.Context() // The talk later than the window's first paint, which waits for // Next's picture up to 3.5 s (the font gate), so the press is made // while the talk is still on its way. hold := func(r *http.Request) { switch { case strings.HasSuffix(r.URL.Path, "/talk"): time.Sleep(5 * time.Second) case strings.Contains(r.URL.Path, "/assets/"): time.Sleep(3 * time.Second) } } mt.hold.Store(&hold) run(t, ctx, mt.fr.navigate(mt.presenter())) mt.fr.shown(t) run(t, ctx, mounted, chromedp.Evaluate[chromedp.Void](frameLogJS), key(kb.ArrowRight)) var loaded string run(t, ctx, evalInto(&loaded, rootJS+`.getAttribute('data-loaded') || ''`)) if loaded == "all" { t.Fatal("the talk was loaded before the press; the check needs it not to be") } run(t, ctx, waitFor(rootJS+`.dataset.slide === '3'`), chromedp.Sleep(300*time.Millisecond)) var frames []struct { N int Text string Img, OK bool } run(t, ctx, evalInto(&frames, `window.__frames`)) seenPicture := false for i, f := range frames { if f.N != 1 { t.Fatalf("frame %d of %d had %d slides on Now: never a blank", i, len(frames), f.N) } if f.Img && !f.OK { t.Fatalf("frame %d: the picture slide was up before its picture", i) } if f.Img { seenPicture = true } else if seenPicture { t.Fatalf("frame %d: back off the picture slide to %q", i, f.Text) } else if !strings.Contains(f.Text, "Plain") { t.Fatalf("frame %d: before the picture Now showed %q, want the slide it was on", i, f.Text) } } if !seenPicture { t.Errorf("the picture slide never came up in %d frames", len(frames)) } mt.waitRow(t, "picture", 0) } // TestPressBeforeTheTalkLoadsStillJumps: a slide number typed and // Entered while the talk is still on its way is not lost: the window // goes there once it holds the talk. func TestPressBeforeTheTalkLoadsStillJumps(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() hold := func(r *http.Request) { if strings.HasSuffix(r.URL.Path, "/talk") { time.Sleep(1500 * time.Millisecond) } } mt.hold.Store(&hold) run(t, ctx, mt.fr.navigate(mt.presenter())) mt.fr.shown(t) run(t, ctx, mounted, key("4"), key(kb.Enter)) var loaded string run(t, ctx, evalInto(&loaded, rootJS+`.getAttribute('data-loaded') || ''`)) if loaded != "" { t.Fatal("the talk had arrived before the jump; the check needs it not to have") } run(t, ctx, waitFor(rootJS+`.dataset.slide === '4'`)) mt.waitRow(t, "last", 0) } // nextLogJS records, on every frame, what Now and Next show: each // one's heading or text, and whether a picture on Next is drawn. const nextLogJS = `(() => { window.__next = []; const log = () => { const now = document.querySelector('[presenter-panel="now"] [slides-slide]'); const next = document.querySelector('[presenter-panel="next"] [slides-slide]'); const img = next && next.querySelector('img'); window.__next.push({ now: now ? now.innerText : '', next: next ? next.innerText : '', img: !!img, ok: !!img && img.complete && img.naturalWidth > 0 }); requestAnimationFrame(log) }; log(); return true })()` // TestPresenterNextWaitsForItsSlide: Next never shows a slide before it // is ready. With the picture slow, Next keeps the preview it had until // the picture is in, and then shows the picture slide whole. func TestPresenterNextWaitsForItsSlide(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() for range 3 { mt.phone(t, "next") } hold := func(r *http.Request) { if strings.Contains(r.URL.Path, "/assets/") { time.Sleep(4 * time.Second) } } mt.hold.Store(&hold) run(t, ctx, mt.fr.navigate(mt.presenter())) mt.fr.shown(t) run(t, ctx, waitFor(rootJS+`.hasAttribute('data-loaded')`), chromedp.Sleep(300*time.Millisecond), chromedp.Evaluate[chromedp.Void](nextLogJS), key(kb.ArrowRight), // step 4: Next is the plain slide chromedp.Sleep(300*time.Millisecond), key(kb.ArrowRight), // the plain slide: Next is the picture, still on its way waitFor(`window.__next.some(f => f.img && f.ok)`), chromedp.Sleep(200*time.Millisecond)) var frames []struct { Now, Next string Img, OK bool } run(t, ctx, evalInto(&frames, `window.__next`)) waited := false for i, f := range frames { if f.Img && !f.OK { t.Fatalf("frame %d of %d: Next showed the picture slide before its picture", i, len(frames)) } if strings.Contains(f.Now, "Plain") && strings.Contains(f.Next, "Plain") { waited = true } } if !waited { t.Error("Next never had to wait for the picture; the check needs it to") } } // TestADroppedNetworkKeepsBlackAsPressed: the black screen is part of // where the pressing window went while cut off: blacked offline, the // server blacks; lifted offline by a press, the server lifts it. func TestADroppedNetworkKeepsBlackAsPressed(t *testing.T) { mt := newMovesTalk(t) ctx := mt.fr.rig.Context() open(t, ctx, mt.fr.rig.Origin, mt.presenter()) black := func() bool { var b bool if err := mt.fr.app.db.G.Raw("SELECT blackout FROM presentations WHERE sqid = ?", mt.session).Row().Scan(&b); err != nil { t.Fatalf("read the blackout: %v", err) } return b } until := func(want bool, step int) { t.Helper() deadline := time.Now().Add(15 * time.Second) for { _, k, _ := mt.row(t) if black() == want && k == step { return } if time.Now().After(deadline) { t.Fatalf("the server is at step %d, black %v; want step %d, black %v", k, black(), step, want) } time.Sleep(50 * time.Millisecond) } } mt.cut(t, true, ctx) run(t, ctx, key("b")) if got := state(t, ctx); got.Black != "true" { t.Fatalf("B offline: the window is black %s", got.Black) } run(t, ctx, waitFor(`document.querySelector('[presenter-status]').innerText !== ''`)) mt.cut(t, false, ctx) until(true, 0) mt.cut(t, true, ctx) run(t, ctx, key(kb.ArrowRight)) if got := state(t, ctx); got.Black != "false" || got.Step != "1" { t.Fatalf("next offline: black %s step %s, want the black lifted at step 1", got.Black, got.Step) } run(t, ctx, waitFor(`document.querySelector('[presenter-status]').innerText !== ''`)) mt.cut(t, false, ctx) until(false, 1) }