//go:build browser // Arranging the presenter window, its ⋯ menu, and pairing a phone from // it (Task 13, spec §5.4, §5.6 and §6 "Who may drive"). The panels move // and resize on the 12×12 grid by pointer and by keyboard, never leave // the window, never overlap, and are remembered in the cookie the // server draws the first paint from. package slidestest import ( "context" "fmt" "math" "net/http" "net/url" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/accessibility" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/cdproto/input" "github.com/chromedp/cdproto/network" "github.com/chromedp/cdproto/target" "github.com/chromedp/chromedp" "github.com/chromedp/chromedp/kb" ) // arrangeRig is a talk on stepsDeck, with the browser signed in as its // presenter: the window is theirs by the cookie, no token in it. type arrangeRig struct { rig *harness.Rig app *testApp cookies []*http.Cookie session, token string window string } func newArrangeRig(t *testing.T) *arrangeRig { t.Helper() rig, app := newRigApp(t, nil) cookies := signedIn(t, app, allowedAddress) var set []chromedp.Action[chromedp.Void] for _, c := range cookies { set = append(set, cdpStep(network.SetCookie, network.SetCookieParams{Name: c.Name, Value: c.Value, URL: rig.Origin + "/", HTTPOnly: new(c.HttpOnly), Secure: new(c.Secure), SameSite: network.CookieSameSiteLax})) } set = append(set, cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1280, Height: 720, DeviceScaleFactor: 1, Mobile: false})) rig.Run(set...) session, token := startPresenting(t, app, stepsDeck(t, app, cookies), cookies) return &arrangeRig{rig: rig, app: app, cookies: cookies, session: session, token: token, window: rig.Origin + "/p/" + session + "/notes"} } // prefs sets the window's cookie as its script writes it. func (ar *arrangeRig) prefs(value string) { ar.rig.Run(cdpStep(network.SetCookie, network.SetCookieParams{Name: "slides-presenter", Value: url.QueryEscape(value), URL: ar.rig.Origin + "/p/", Path: "/p", SameSite: network.CookieSameSiteLax})) } // open loads the window and waits for its script to have the talk. func (ar *arrangeRig) open(t *testing.T) { t.Helper() ar.rig.Run(chromedp.Navigate(ar.window), waitFor(`document.querySelector('[presenter]')?.getAttribute('data-loaded') === 'all'`)) } // arrange opens the ⋯ menu and chooses Arrange this window. func (ar *arrangeRig) arrange(t *testing.T) { t.Helper() ar.rig.Run( chromedp.Click(chromedp.CSS(`[presenter-more]`)), waitFor(`document.querySelector('[presenter-more-menu]').open`), chromedp.Click(chromedp.CSS(`[presenter-arrange]`)), waitFor(`document.querySelector('[presenter]').hasAttribute('data-arranging') && !document.querySelector('[presenter-arrange-bar]').hidden`)) } // keys presses key n times, with Shift when shift is true. func keys(key string, n int, shift bool) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { for range n { var opts []chromedp.KeyOption if shift { opts = append(opts, chromedp.KeyModifiers(chromedp.ModifierShift)) } if _, err := chromedp.KeyEvent(key, opts...)(ctx, t); err != nil { return err } } return nil }) } // focus puts the keyboard on a panel. func focusPanel(name string) chromedp.Action[chromedp.Void] { return chromedp.Evaluate[chromedp.Void](`document.querySelector('[presenter-panel="` + name + `"]').focus()`) } // cookieValue is the window's cookie, decoded, or "". const cookieValueJS = `(() => { const m = document.cookie.split('; ').find(c => c.startsWith('slides-presenter=')); return m ? decodeURIComponent(m.slice('slides-presenter='.length)) : '' })()` type panelRect struct{ L, T, R, B float64 } func (r panelRect) String() string { return fmt.Sprintf("(%.1f,%.1f)-(%.1f,%.1f)", r.L, r.T, r.R, r.B) } func near(a, b panelRect) bool { return math.Abs(a.L-b.L) <= 0.5 && math.Abs(a.T-b.T) <= 0.5 && math.Abs(a.R-b.R) <= 0.5 && math.Abs(a.B-b.B) <= 0.5 } // panelRects is each panel and each frame, by name. const panelRectsJS = `(() => { const out = {}; for (const n of ['now', 'next', 'notes']) { const r = document.querySelector('[presenter-panel="' + n + '"]').getBoundingClientRect(); out[n] = { L: r.left, T: r.top, R: r.right, B: r.bottom }; const f = document.querySelector('[presenter-panel="' + n + '"] [presenter-frame]'); if (f) { const q = f.getBoundingClientRect(); out[n + '-frame'] = { L: q.left, T: q.top, R: q.right, B: q.bottom } } const fit = document.querySelector('[presenter-panel="' + n + '"] [presenter-fit]'); if (fit) { const q = fit.getBoundingClientRect(); out[n + '-fit'] = { L: q.left, T: q.top, R: q.right, B: q.bottom } } } return out })()` func (ar *arrangeRig) rects(t *testing.T) map[string]panelRect { t.Helper() var out map[string]panelRect ar.rig.Run(evalInto(&out, panelRectsJS)) return out } // inside fails for a document that scrolls or a box outside the window, // or one with no size. arranging is the one exception, and only while // arranging: a slide's frame may shrink to nothing in a 2×2 panel while // the arranging bar takes its height. Done, a reload, any window not // being arranged: every preview has a size. func inside(t *testing.T, ar *arrangeRig, what string, arranging bool) { t.Helper() var g presenterGeometry ar.rig.Run(evalInto(&g, presenterGeometryJS)) // The arranging bar and the selected panel's buttons, while shown. var extra []presenterBox ar.rig.Run(evalInto(&extra, `[['bar', '[presenter-arrange-bar]'], ['tools', '[presenter-arrange-tools]'], ...[...document.querySelectorAll('[presenter-arrange-tools] button')].map((b, i) => ['tool ' + i, b])].flatMap(([name, sel]) => { const b = typeof sel === 'string' ? document.querySelector(sel) : sel; if (!b || b.closest('[hidden]')) return []; const r = b.getBoundingClientRect(); return [{ name, l: r.left, t: r.top, r: r.right, b: r.bottom }] })`)) g.Boxes = append(g.Boxes, extra...) if g.SH != g.VH || g.SW != g.VW || g.BSH > g.VH || g.BSW > g.VW || g.ScrollY != 0 { t.Errorf("%s: the document is %.0f×%.0f (body %.0f×%.0f, scrolled %.0f) in a %.0f×%.0f window", what, g.SW, g.SH, g.BSW, g.BSH, g.ScrollY, g.VW, g.VH) } if len(g.Boxes) < 6 { t.Fatalf("%s: %d boxes measured, want the header, three panels and two frames", what, len(g.Boxes)) } for _, b := range g.Boxes { empty := b.R <= b.L || b.B <= b.T if arranging && b.Name == "frame" { empty = b.R < b.L || b.B < b.T } if b.L < 0 || b.T < 0 || b.R > g.VW || b.B > g.VH || empty { t.Errorf("%s: %s at (%.0f,%.0f)-(%.0f,%.0f) is not inside the %.0f×%.0f window", what, b.Name, b.L, b.T, b.R, b.B, g.VW, g.VH) } } } // overlapping is two panels sharing any area, beyond a rounding. func overlapping(a, b panelRect) bool { return a.L < b.R-1 && b.L < a.R-1 && a.T < b.B-1 && b.T < a.B-1 } // TestArrangedPanelsStayInsideTheWindow: however the panels are // arranged, at each of the ten window sizes nothing leaves the window // and the document never scrolls; the panels never overlap; Next fills // its own panel. Below 720×560 the arrangement is ignored and the // panels stack, and Arrange is not offered there. While arranging, // with the bar showing, the window still holds. func TestArrangedPanelsStayInsideTheWindow(t *testing.T) { ar := newArrangeRig(t) arrangements := []string{ "fit.24.0,0,4,4;0,4,4,4;8,0,4,12", "fit.24.10,10,2,2;0,0,2,2;5,5,2,2", "scroll.48.0,0,12,6;0,6,6,6;6,6,6,6", } for _, size := range presenterSizes { stacked := size.w < 720 || size.h < 560 t.Run(fmt.Sprintf("%dx%d", size.w, size.h), func(t *testing.T) { ar.rig.Run(cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: size.w, Height: size.h, DeviceScaleFactor: 1, Mobile: false})) for _, prefs := range arrangements { ar.prefs(prefs) ar.open(t) inside(t, ar, prefs, false) r := ar.rects(t) if stacked { if !(r["now"].B <= r["next"].T+1 && r["next"].B <= r["notes"].T+1) { t.Errorf("%s: stacked panels are not now, next, notes: %v %v %v", prefs, r["now"], r["next"], r["notes"]) } continue } for _, pair := range [][2]string{{"now", "next"}, {"now", "notes"}, {"next", "notes"}} { if overlapping(r[pair[0]], r[pair[1]]) { t.Errorf("%s: %s %v and %s %v overlap", prefs, pair[0], r[pair[0]], pair[1], r[pair[1]]) } } fit, frame := r["next-fit"], r["next-frame"] want := math.Min(fit.R-fit.L, (fit.B-fit.T)*16/9) if got := frame.R - frame.L; math.Abs(got-want) > 1 { t.Errorf("%s: Next is %.1fpx wide in a panel with room for %.1fpx: an arranged Next fills its panel", prefs, got, want) } } // Arranging, with the bar over the panels. ar.prefs(arrangements[0]) ar.open(t) var shown bool ar.rig.Run(evalInto(&shown, `getComputedStyle(document.querySelector('[presenter-arrange]')).display !== 'none'`)) if stacked { if shown { t.Errorf("Arrange is offered where the panels stack and the arrangement is ignored") } return } if !shown { t.Fatalf("Arrange is not offered at %dx%d", size.w, size.h) } ar.rig.Run(keys(kb.Escape, 1, false)) for _, prefs := range arrangements { ar.prefs(prefs) ar.open(t) ar.arrange(t) ar.toolsReachable(t, prefs) ar.rig.Run(keys(kb.Escape, 1, false), waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`)) } }) } } // unreachableToolsJS is each of the selected panel's buttons that a // pointer cannot reach at its centre: off the window, or under // something else. const unreachableToolsJS = `[...document.querySelectorAll('[presenter-arrange-tools] button')].filter(b => { const r = b.getBoundingClientRect(); const e = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); return !(e && b.contains(e)) }).map(b => b.getAttribute('aria-label'))` // toolsReachable selects each panel in turn and insists its eight // buttons are all inside the window and each can be pressed. func (ar *arrangeRig) toolsReachable(t *testing.T, what string) { t.Helper() for _, name := range []string{"now", "next", "notes"} { var tools int var lost []string ar.rig.Run(focusPanel(name), waitFor(`document.querySelector('[presenter-panel="`+name+`"]').hasAttribute('data-selected')`), evalInto(&tools, `document.querySelectorAll('[presenter-arrange-tools]:not([hidden]) button').length`), evalInto(&lost, unreachableToolsJS)) if tools != 8 { t.Errorf("%s, %s selected: %d buttons shown, want 8", what, name, tools) } if len(lost) > 0 { t.Errorf("%s, %s selected: %v cannot be reached", what, name, lost) } inside(t, ar, what+", arranging "+name, true) } } // TestArrangeToolsStayInsideTheWindow: a 2×2 panel in each corner of // the grid, selected, keeps all eight of its buttons inside the window // and within reach, from the smallest window that arranges (720×560) // up, the panel's buttons turning towards the middle as they must. func TestArrangeToolsStayInsideTheWindow(t *testing.T) { ar := newArrangeRig(t) sizes := []struct{ w, h int64 }{{720, 560}, {1280, 720}} for _, s := range presenterSizes { if s.w >= 720 && s.h >= 560 { sizes = append(sizes, s) } } corners := []string{ "fit.24.0,0,2,2;10,0,2,2;0,10,2,2", "fit.24.10,10,2,2;4,4,2,2;6,6,2,2", } for _, size := range sizes { t.Run(fmt.Sprintf("%dx%d", size.w, size.h), func(t *testing.T) { ar.rig.Run(cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: size.w, Height: size.h, DeviceScaleFactor: 1, Mobile: false})) for _, prefs := range corners { ar.prefs(prefs) ar.open(t) ar.arrange(t) ar.toolsReachable(t, prefs) ar.rig.Run(keys(kb.Escape, 1, false), waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`)) } }) } } // TestArrangeButtonsKeepTheirMeaningRightToLeft: in a right-to-left // window the grid runs the other way, so Move left and Move right are // mirrored to go where they say; Narrower and Wider still narrow and // widen. func TestArrangeButtonsKeepTheirMeaningRightToLeft(t *testing.T) { ar := newArrangeRig(t) ar.open(t) ar.rig.Run(chromedp.Evaluate[chromedp.Void](`document.documentElement.dir = 'rtl'`)) ar.arrange(t) disabled := func(label string) bool { var d string ar.rig.Run(evalInto(&d, `document.querySelector('[presenter-arrange-tools] button[aria-label="`+label+`"]').getAttribute('aria-disabled') || ''`)) return d == "true" } if disabled("Narrower") || !disabled("Wider") { t.Errorf("right to left, Now in the default window: Narrower disabled %v, Wider disabled %v; want Narrower only", disabled("Narrower"), disabled("Wider")) } ar.rig.Run(arrangeTool("Narrower")) if got, want := ar.arrangeStatus(t), "On screen now: 6 by 8, column 1, row 1"; got != want { t.Errorf("Narrower right to left says %q, want %q", got, want) } // Column 1 is on the right: Move right cannot go, Move left can, // and goes to column 2. if !disabled("Move right") || disabled("Move left") { t.Errorf("right to left, Now at column 1: Move right disabled %v, Move left disabled %v", disabled("Move right"), disabled("Move left")) } var before, after panelRect ar.rig.Run(evalInto(&before, `(() => { const r = document.querySelector('[presenter-panel="now"]').getBoundingClientRect(); return { L: r.left, T: r.top, R: r.right, B: r.bottom } })()`)) ar.rig.Run(arrangeTool("Move left")) ar.rig.Run(evalInto(&after, `(() => { const r = document.querySelector('[presenter-panel="now"]').getBoundingClientRect(); return { L: r.left, T: r.top, R: r.right, B: r.bottom } })()`)) if got, want := ar.arrangeStatus(t), "On screen now: 6 by 8, column 2, row 1"; got != want { t.Errorf("Move left right to left says %q, want %q", got, want) } if after.L >= before.L { t.Errorf("Move left moved Now from %v to %v, not to the left", before, after) } } // TestArrangeByKeyboardAndPointer: a focused panel moves a cell with an // arrow key and resizes with Shift and an arrow, so arranging is not // mouse-only; dragging a panel moves it and dragging its corner resizes // it, snapped to the grid. Done writes the cookie, keeping the notes' // part. While arranging, only the clicker's keys move the talk. func TestArrangeByKeyboardAndPointer(t *testing.T) { ar := newArrangeRig(t) ar.prefs("scroll.30.0,0,7,8;0,8,7,4;7,0,5,12") ar.open(t) ar.arrange(t) var focused string ar.rig.Run(evalInto(&focused, `document.activeElement.getAttribute('presenter-panel') || ''`)) if focused != "now" { t.Errorf("arranging puts the focus on %q, want the first panel, now", focused) } // Now 7×8 to 5×5; Next up three cells into the room that leaves. ar.rig.Run(focusPanel("now"), keys(kb.ArrowLeft, 2, true), keys(kb.ArrowUp, 3, true), focusPanel("next"), keys(kb.ArrowUp, 3, false)) // While arranging, B blacks nothing and the arrows move no slide; // the clicker's PageDown still presses. _, step, _ := rowPosition(t, ar.app, ar.session) ar.rig.Run(keys("b", 1, false), keys(kb.ArrowRight, 1, false), keys(kb.ArrowLeft, 1, false)) time.Sleep(300 * time.Millisecond) if _, now, _ := rowPosition(t, ar.app, ar.session); now != step { t.Errorf("a key while arranging moved the talk from step %d to %d", step, now) } var black string ar.rig.Run(evalInto(&black, `document.querySelector('[presenter]').getAttribute('data-blackout')`)) if black != "false" { t.Errorf("B while arranging blacked the screen") } ar.rig.Run(keys(kb.PageDown, 1, false), waitFor(`document.querySelector('[presenter]').getAttribute('data-step') === '`+fmt.Sprint(step+1)+`'`)) // The pointer: the notes' corner dragged two cells left narrows // them, and Now dragged a little over a cell right snaps to one. var cell struct{ W, H float64 } ar.rig.Run(evalInto(&cell, `(() => { const r = document.querySelector('[presenter-panels]').getBoundingClientRect(); return { W: r.width / 12, H: r.height / 12 } })()`)) drag := func(sel string, dx, dy float64) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { var at struct{ X, Y float64 } if _, err := evalInto(&at, `(() => { const r = document.querySelector('`+sel+`').getBoundingClientRect(); return { X: r.left + r.width / 2, Y: r.top + r.height / 2 } })()`)(ctx, t); err != nil { return err } if _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, input.DispatchMouseEventParams{Type: chromedp.MousePressed, X: at.X, Y: at.Y, Button: input.MouseButtonLeft, Buttons: 1, ClickCount: 1}); err != nil { return err } for i := 1; i <= 8; i++ { f := float64(i) / 8 if _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, input.DispatchMouseEventParams{Type: chromedp.MouseMoved, X: at.X + dx*f, Y: at.Y + dy*f, Button: input.MouseButtonLeft, Buttons: 1}); err != nil { return err } } _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, input.DispatchMouseEventParams{Type: chromedp.MouseReleased, X: at.X + dx, Y: at.Y + dy, Button: input.MouseButtonLeft, Buttons: 0, ClickCount: 1}) return err }) } ar.rig.Run(drag(`[presenter-panel="notes"] [presenter-arrange-handle]`, -2*cell.W, 0)) ar.rig.Run(drag(`[presenter-panel="now"]`, 1.2*cell.W, 0)) ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-arrange-done]`)), waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`)) var saved string ar.rig.Run(evalInto(&saved, cookieValueJS)) if want := "scroll.30.1,0,5,5;0,5,7,4;7,0,3,12"; saved != want { t.Errorf("Done saved %q, want %q", saved, want) } } // TestArrangeEscapeLeavesWithoutSaving: Esc puts the panels back where // arranging found them and writes nothing. func TestArrangeEscapeLeavesWithoutSaving(t *testing.T) { ar := newArrangeRig(t) ar.open(t) before := ar.rects(t) ar.arrange(t) ar.rig.Run(focusPanel("now"), keys(kb.ArrowLeft, 3, true)) if near(ar.rects(t)["now"], before["now"]) { t.Fatalf("Shift+ArrowLeft did not narrow Now") } ar.rig.Run(keys(kb.Escape, 1, false), waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`)) after := ar.rects(t) for _, n := range []string{"now", "next", "notes"} { if !near(before[n], after[n]) { t.Errorf("after Esc %s is at %v, was %v", n, after[n], before[n]) } } var saved string ar.rig.Run(evalInto(&saved, cookieValueJS)) if saved != "" { t.Errorf("Esc wrote the cookie: %q", saved) } } // TestArrangeResetReturnsTheDefault: Reset puts the panels where a // window with no cookie has them, Next half of Now again, and writes it, // keeping the notes' choice. func TestArrangeResetReturnsTheDefault(t *testing.T) { ar := newArrangeRig(t) ar.open(t) def := ar.rects(t) ar.prefs("scroll.30.0,0,4,4;0,4,4,4;8,0,4,12") ar.open(t) if near(ar.rects(t)["now"], def["now"]) { t.Fatalf("the arranged window looks like the default") } ar.arrange(t) ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-arrange-reset]`))) var saved string ar.rig.Run(evalInto(&saved, cookieValueJS)) if want := "scroll.30.0,0,7,8;0,8,7,4;7,0,5,12"; saved != want { t.Errorf("Reset saved %q, want %q", saved, want) } ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-arrange-done]`)), waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`)) check := func(when string) { got := ar.rects(t) for _, n := range []string{"now", "next", "notes", "now-frame", "next-frame"} { if !near(got[n], def[n]) { t.Errorf("%s: %s is at %v, the default window has it at %v", when, n, got[n], def[n]) } } } check("after Reset") ar.open(t) check("reloaded after Reset") } // TestArrangementIsFinalAtFirstPaint: the window the server draws from // the cookie, before any script, is the window the arranging left on // screen, frames and all. func TestArrangementIsFinalAtFirstPaint(t *testing.T) { ar := newArrangeRig(t) ar.open(t) ar.arrange(t) ar.rig.Run(focusPanel("now"), keys(kb.ArrowLeft, 2, true), keys(kb.ArrowUp, 3, true), focusPanel("next"), keys(kb.ArrowUp, 3, false), keys(kb.ArrowDown, 1, true), chromedp.Click(chromedp.CSS(`[presenter-arrange-done]`)), waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`)) live := ar.rects(t) ar.rig.Run(cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}), chromedp.Navigate(ar.window), chromedp.WaitReady(chromedp.CSS(`[presenter-panel="notes"]`))) painted := ar.rects(t) ar.rig.Run(cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: false})) for _, n := range []string{"now", "next", "notes", "now-frame", "next-frame"} { if !near(live[n], painted[n]) { t.Errorf("%s is at %v as arranged and at %v as first painted", n, live[n], painted[n]) } } } // TestTheMenuHasItsSixRows: the ⋯ menu's rows, in the spec's order, // each doing what it says: Pair posts to /pair in a window of its own, // the slide window opens in its own, Arrange shows the bar in the // approved words. func TestTheMenuHasItsSixRows(t *testing.T) { ar := newArrangeRig(t) ar.rig.Run(cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1440, Height: 900, DeviceScaleFactor: 1, Mobile: false})) ar.open(t) var rows []struct { Label, Tag, Href, Action, Target, Method, Op string Shown bool } ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-more]`)), waitFor(`document.querySelector('[presenter-more-menu]').open`), evalInto(&rows, `[...document.querySelectorAll('[presenter-menu] button, [presenter-menu] a')].map(e => { const f = e.closest('form'); const r = e.getBoundingClientRect(); return { Label: e.textContent.trim(), Tag: e.tagName.toLowerCase(), Href: e.getAttribute('href') || '', Action: f ? f.getAttribute('action') : '', Target: (f || e).getAttribute('target') || '', Method: f ? f.getAttribute('method') : '', Op: f && f.elements.op ? f.elements.op.value : '', Shown: r.width > 0 && r.height > 0 } })`)) want := []string{"Pair a phone as a remote…", "Open the slide window", "Switch to the full version", "Arrange this window…", "Back to the deck", "End presenting"} if len(rows) != len(want) { t.Fatalf("the menu has %d rows, want %d: %+v", len(rows), len(want), rows) } for i, w := range want { if rows[i].Label != w || !rows[i].Shown { t.Errorf("row %d is %q (shown %v), want %q", i+1, rows[i].Label, rows[i].Shown, w) } } session := "/p/" + ar.session if r := rows[0]; r.Action != session+"/pair" || r.Method != "post" || r.Target != "slides-pair" { t.Errorf("Pair is %+v, want a POST to %s/pair in the window slides-pair", r, session) } if r := rows[1]; r.Href != session || r.Target != "slides-window" { t.Errorf("the slide window row is %+v, want %s in the window slides-window", r, session) } if r := rows[2]; r.Action != session+"/command" || r.Op != "mode" { t.Errorf("the mode row is %+v, want the mode press", r) } if r := rows[3]; r.Tag != "button" { t.Errorf("Arrange is a %s, want a button", r.Tag) } if r := rows[4]; !strings.HasSuffix(r.Href, "/edit") { t.Errorf("Back to the deck goes to %q, want the editor", r.Href) } if r := rows[5]; r.Action != session+"/command" || r.Op != "end" { t.Errorf("End presenting is %+v, want the end press", r) } ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-arrange]`)), waitFor(`document.querySelector('[presenter]').hasAttribute('data-arranging')`)) var bar struct { Text, Reset, Done string MenuOpen bool } ar.rig.Run(evalInto(&bar, `(() => { const b = document.querySelector('[presenter-arrange-bar]'); return { Text: b.querySelector('span').textContent, Reset: b.querySelector('[presenter-arrange-reset]').textContent, Done: b.querySelector('[presenter-arrange-done]').textContent, MenuOpen: document.querySelector('[presenter-more-menu]').open } })()`)) if bar.Text != "Drag a panel to move it; drag its corner to resize it." || bar.Reset != "Reset to the default" || bar.Done != "Done" { t.Errorf("the arranging bar says %+v", bar) } if bar.MenuOpen { t.Errorf("the menu stays open while arranging") } } // TestPairingLeavesTheWindowItsTalk: Pair opens the pairing page in a // window of its own, with the code, the address and the QR; the // presenter window stays where it was and keeps driving, the old phone // is retired, and the new one moves the window. func TestPairingLeavesTheWindowItsTalk(t *testing.T) { ar := newArrangeRig(t) ar.open(t) ar.rig.Run(keys(kb.ArrowRight, 1, false), waitFor(`document.querySelector('[presenter]').getAttribute('data-step') === '1'`)) opened := chromedp.WaitNewTarget(ar.rig.Context(), func(info *target.Info) bool { return strings.HasSuffix(info.URL, "/p/"+ar.session+"/pair") }) ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-more]`)), waitFor(`document.querySelector('[presenter-more-menu]').open`), chromedp.Click(chromedp.CSS(`[presenter-menu] form[action$="/pair"] button`))) var id target.ID select { case id = <-opened: case <-time.After(20 * time.Second): t.Fatal("Pair opened no window of its own") } pairCtx, cancel := chromedp.NewContext(ar.rig.Context(), chromedp.WithTargetID(id)) defer cancel() var page, code string if err := chromedp.Do(pairCtx, waitFor(`document.querySelector('[slides-qr]')`), evalInto(&page, `document.documentElement.outerHTML`), evalInto(&code, `document.querySelector('[slides-code]').textContent`)); err != nil { t.Fatalf("read the pairing window: %v", err) } fresh := tokenOn(t, page) if code != sessionCode(t, ar.app, ar.session) { t.Errorf("the pairing window shows code %q, not the session's", code) } var where struct { Path, Name string Step string MenuOpen bool } ar.rig.Run(evalInto(&where, `({ Path: location.pathname, Name: window.name, Step: document.querySelector('[presenter]').getAttribute('data-step'), MenuOpen: document.querySelector('[presenter-more-menu]').open })`)) if where.Path != "/p/"+ar.session+"/notes" || where.Step != "1" { t.Errorf("pairing moved the window: %+v", where) } if where.MenuOpen { t.Errorf("the menu stays open after pairing") } if rec := pressRequest(t, ar.app, ar.session, ar.token, op(t, "next"), nil); rec.Code != http.StatusNotFound { t.Errorf("the retired phone still presses: status %d", rec.Code) } // The window still drives, by its presenter being signed in. ar.rig.Run(keys(kb.ArrowRight, 1, false)) deadline := time.Now().Add(10 * time.Second) for { if _, step, _ := rowPosition(t, ar.app, ar.session); step == 2 { break } if time.Now().After(deadline) { t.Fatal("the window's press after pairing never reached the talk") } time.Sleep(50 * time.Millisecond) } // And the new phone moves the window. press(t, ar.app, ar.session, fresh, op(t, "next"), nil) ar.rig.Run(waitFor(`document.querySelector('[presenter]').getAttribute('data-step') === '3'`)) } // arrangeTool is one of the selected panel's eight buttons, by its name. func arrangeTool(label string) chromedp.Action[chromedp.Void] { return chromedp.Click(chromedp.CSS(`[presenter-arrange-tools] button[aria-label="` + label + `"]`)) } // arrangeStatus is what the arranging's live region last said. func (ar *arrangeRig) arrangeStatus(t *testing.T) string { t.Helper() var s string ar.rig.Run(evalInto(&s, `document.querySelector('[presenter-arrange-status]').textContent`)) return s } // TestArrangeWithoutDragging: arranging needs neither a drag nor a // keyboard. A tap selects a panel, which shows its eight buttons; each // press moves or resizes it one cell, a move that cannot be made is // disabled, and each change is said aloud. func TestArrangeWithoutDragging(t *testing.T) { ar := newArrangeRig(t) ar.open(t) ar.arrange(t) disabled := func(label string) bool { var d string ar.rig.Run(evalInto(&d, `document.querySelector('[presenter-arrange-tools] button[aria-label="`+label+`"]').getAttribute('aria-disabled') || ''`)) return d == "true" } ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-panel="now"]`)), waitFor(`document.querySelector('[presenter-panel="now"]').hasAttribute('data-selected')`)) for label, want := range map[string]bool{"Move left": true, "Move up": true, "Move right": true, "Move down": true, "Wider": true, "Taller": true, "Narrower": false, "Shorter": false} { if got := disabled(label); got != want { t.Errorf("Now in the default window: %s disabled %v, want %v", label, got, want) } } ar.rig.Run(arrangeTool("Narrower"), arrangeTool("Narrower"), arrangeTool("Shorter"), arrangeTool("Shorter"), arrangeTool("Shorter")) if got, want := ar.arrangeStatus(t), "On screen now: 5 by 5, column 1, row 1"; got != want { t.Errorf("after resizing Now the live region says %q, want %q", got, want) } // Pressing a disabled one does nothing. ar.rig.Run(arrangeTool("Move left")) ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-panel="next"]`)), waitFor(`document.querySelector('[presenter-panel="next"]').hasAttribute('data-selected')`), arrangeTool("Move up"), arrangeTool("Move up"), arrangeTool("Move up")) if got, want := ar.arrangeStatus(t), "Coming next: 7 by 4, column 1, row 6"; got != want { t.Errorf("after moving Next the live region says %q, want %q", got, want) } if !disabled("Move up") { t.Errorf("Next against Now can still move up") } ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-arrange-done]`)), waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`)) var saved string ar.rig.Run(evalInto(&saved, cookieValueJS)) if want := "fit.24.0,0,5,5;0,5,7,4;7,0,5,12"; saved != want { t.Errorf("Done saved %q, want %q", saved, want) } } // axNode is one node of the accessibility tree, flattened. type axNode struct { Role, Name, Description string Props map[string]string } // axValue is a value in the accessibility tree, read loosely: the // protocol's own types refuse property names newer than they are. type axValue struct { Value any `json:"value"` } func (v *axValue) text() string { if v == nil || v.Value == nil { return "" } return fmt.Sprint(v.Value) } // axTree is the page's accessibility tree, as a screen reader is given it. func (ar *arrangeRig) axTree(t *testing.T) []axNode { t.Helper() var res struct { Nodes []struct { Ignored bool `json:"ignored"` Role *axValue `json:"role"` Name *axValue `json:"name"` Description *axValue `json:"description"` Properties []struct { Name string `json:"name"` Value *axValue `json:"value"` } `json:"properties"` } `json:"nodes"` } ar.rig.Run(chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { return t.Call(ctx, accessibility.CommandGetFullAXTree, nil, &res) })) var out []axNode for _, n := range res.Nodes { if n.Ignored { continue } a := axNode{Role: n.Role.text(), Name: n.Name.text(), Description: n.Description.text(), Props: map[string]string{}} for _, p := range n.Properties { a.Props[p.Name] = p.Value.text() } out = append(out, a) } return out } func findAX(nodes []axNode, role, name string) *axNode { for i := range nodes { if nodes[i].Role == role && nodes[i].Name == name { return &nodes[i] } } return nil } // TestArrangePanelsAreNamedControls: while arranging, each panel is a // focusable group with its name and the keys described; the selected // panel's buttons are named and say when they are disabled; every move // or resize, by keyboard as by button, is said in a polite live region // with the panel's size and place. func TestArrangePanelsAreNamedControls(t *testing.T) { ar := newArrangeRig(t) ar.open(t) ar.arrange(t) help := "Arrow keys move this panel. Shift and an arrow key resize it." tree := ar.axTree(t) for _, name := range []string{"On screen now", "Coming next", "Speaker notes"} { n := findAX(tree, "group", name) if n == nil { t.Errorf("no group named %q while arranging", name) continue } if n.Description != help || n.Props["focusable"] != "true" { t.Errorf("the %q panel is described %q (focusable %q), want %q and focusable", name, n.Description, n.Props["focusable"], help) } } for _, label := range []string{"Move left", "Move right", "Move up", "Move down", "Narrower", "Wider", "Shorter", "Taller"} { b := findAX(tree, "button", label) if b == nil { t.Errorf("no button named %q on the selected panel", label) continue } want := label == "Narrower" || label == "Shorter" if got := b.Props["disabled"] != "true"; got != want { t.Errorf("%q enabled %v, want %v", label, got, want) } } var bar string ar.rig.Run(evalInto(&bar, `document.querySelector('[presenter-arrange-bar]').innerText`)) if !strings.Contains(bar, help) { t.Errorf("the arranging bar does not show the keys: %q", bar) } // The keyboard, with the focus where arranging put it, on Now. ar.rig.Run(keys(kb.ArrowLeft, 1, true)) if got, want := ar.arrangeStatus(t), "On screen now: 6 by 8, column 1, row 1"; got != want { t.Errorf("after Shift+ArrowLeft the live region says %q, want %q", got, want) } tree = ar.axTree(t) var live *axNode for i := range tree { if tree[i].Role == "status" && tree[i].Props["live"] == "polite" { live = &tree[i] } } if live == nil { t.Fatalf("no polite live region while arranging") } if b := findAX(tree, "button", "Wider"); b == nil || b.Props["disabled"] == "true" { t.Errorf("Now narrowed by a cell cannot be widened again: %+v", b) } ar.rig.Run(focusPanel("notes"), keys(kb.ArrowDown, 1, true)) if got, want := ar.arrangeStatus(t), "Speaker notes: 5 by 12, column 8, row 1"; got != want { t.Errorf("a resize that cannot be made says %q, want the notes' place %q", got, want) } } // TestArrangedPreviewsAreNeverEmpty: at the smallest window that // arranges, 720×560, the smallest panels the grid allows still show // their slide: every preview has a size when the window opens on that // arrangement, after arranging to it and pressing Done, and after a // reload. func TestArrangedPreviewsAreNeverEmpty(t *testing.T) { ar := newArrangeRig(t) ar.rig.Run(cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 720, Height: 560, DeviceScaleFactor: 1, Mobile: false})) smallest := []string{ "fit.24.10,10,2,2;0,0,2,2;5,5,2,2", "fit.24.0,0,2,2;10,0,2,2;0,10,2,2", } for _, prefs := range smallest { ar.prefs(prefs) ar.open(t) inside(t, ar, prefs+", opened", false) } // Arranged down to the smallest by keyboard, then Done. ar.prefs("fit.24.0,0,7,8;0,8,7,4;7,0,5,12") ar.open(t) ar.arrange(t) ar.rig.Run(focusPanel("now"), keys(kb.ArrowLeft, 10, true), keys(kb.ArrowUp, 10, true), focusPanel("next"), keys(kb.ArrowLeft, 10, true), keys(kb.ArrowUp, 10, true)) ar.rig.Run(chromedp.Click(chromedp.CSS(`[presenter-arrange-done]`)), waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`)) var saved string ar.rig.Run(evalInto(&saved, cookieValueJS)) inside(t, ar, "after Done ("+saved+")", false) ar.open(t) inside(t, ar, "reloaded ("+saved+")", false) }