//go:build browser // The editor, tidied (docs/superpowers/specs/2026-11-16-editor-tidy-design.md), // held in a real Chromium: what only geometry can show — the page that // never scrolls. (New slide's place in the strip is the quieter editor's // now: TestQuieterStrip, browser_quieter_test.go.) package slidestest import ( "encoding/json" "fmt" "math" "net/http" "os" "regexp" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/blobs" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/network" "github.com/chromedp/cdproto/runtime" "github.com/chromedp/chromedp" "github.com/chromedp/chromedp/kb" ) // tidyEditor is a signed-in browser with the editor open on a deck. type tidyEditor struct { rig *harness.Rig app *testApp cookies []*http.Cookie path string // the deck's editor path, /d/{sqid}/edit } // openTidyEditor signs a browser in, makes a deck of n slides // (deckWithSlides: the first with 400 words of notes), and opens its // editor at width×height, bound. func openTidyEditor(t *testing.T, n int, width, height int64) *tidyEditor { t.Helper() return openTidyEditorOn(t, width, height, func(a *testApp, cookies []*http.Cookie) string { return deckWithSlides(t, a, cookies, n) }) } // openTidyEditorOn is openTidyEditor on the deck deck makes, given the // app and the signed-in person's cookies; deck returns its editor path. func openTidyEditorOn(t *testing.T, width, height int64, deck func(a *testApp, cookies []*http.Cookie) string) *tidyEditor { t.Helper() te := newTidyEditor(t, width, height, deck) te.rig.Run( chromedp.Navigate(te.rig.Origin+te.path), chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)), waitFor(editorBound), ) return te } // newTidyEditor is openTidyEditorOn up to the navigation: a signed-in // browser at width×height and the deck made, the editor not yet open // (for a deck whose editor has nothing to bind, an empty one). func newTidyEditor(t *testing.T, width, height int64, deck func(a *testApp, cookies []*http.Cookie) string) *tidyEditor { t.Helper() return newTidyEditorWith(t, nil, width, height, deck) } // newTidyEditorWith is newTidyEditor with an object store bound (nil: none). func newTidyEditorWith(t *testing.T, store blobs.Store, width, height int64, deck func(a *testApp, cookies []*http.Cookie) string) *tidyEditor { t.Helper() rig, app := newRigApp(t, store) 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, })) } rig.Run(set...) te := &tidyEditor{rig: rig, app: app, cookies: cookies, path: deck(app, cookies)} te.size(width, height) return te } // size sets the viewport, and waits until the page has laid out at it. func (te *tidyEditor) size(width, height int64) { te.rig.Run( chromedp.EmulateViewport(width, height), waitFor(fmt.Sprintf(`innerWidth === %d && innerHeight === %d`, width, height)), ) } // scrolls reports how far the document is bigger than the window, in // each direction; "" is the pass. func (te *tidyEditor) scrolls(t *testing.T) string { t.Helper() var got string te.rig.Run(evalInto(&got, `(() => { const d = document.documentElement, out = [] if (d.scrollHeight !== innerHeight) out.push('scrollHeight ' + d.scrollHeight + ' != innerHeight ' + innerHeight) if (d.scrollWidth !== innerWidth) out.push('scrollWidth ' + d.scrollWidth + ' != innerWidth ' + innerWidth) return out.join('; ') })()`)) return got } // TestTidyPageNeverScrolls (spec §2, §8): with forty slides and long // notes, the page is exactly the window, at a laptop's size and a // desktop's. The strip, the stage, the inspector and the notes scroll // inside themselves. func TestTidyPageNeverScrolls(t *testing.T) { te := openTidyEditor(t, 40, 1280, 720) // The first slide, the one with 400 words of notes, with the notes // open: they scroll inside their card, the page does not. te.rig.Run( waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.index === '0'`), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open' && !document.querySelector('[slides-notes-pane]').hidden`), waitFor(`document.querySelector('[slides-notes]').innerText.split(/\s+/).length >= 400`), ) for _, vp := range [][2]int64{{1280, 720}, {1920, 1080}} { te.size(vp[0], vp[1]) if got := te.scrolls(t); got != "" { t.Errorf("at %dx%d the page scrolls: %s", vp[0], vp[1], got) } var body string te.rig.Run(evalInto(&body, `(b => b.scrollHeight > b.clientHeight && getComputedStyle(b).overflowY === 'auto' ? '' : 'the notes body ' + b.clientHeight + 'px tall holds ' + b.scrollHeight + 'px and does not scroll')(document.querySelector('[slides-notes-body]'))`)) if body != "" { t.Errorf("at %dx%d: %s", vp[0], vp[1], body) } } te.rig.Screen(`[slides-editor]`, "the editor, forty slides") // A canvas shape selected: the card is the shape's options, the // longest a box has, and still only the card scrolls. canvas := te.addCanvasShape(t) te.size(1280, 720) te.openOn(canvas) te.selectBox("shape") for _, vp := range [][2]int64{{1280, 720}, {1920, 1080}} { te.size(vp[0], vp[1]) if got := te.scrolls(t); got != "" { t.Errorf("at %dx%d with a canvas shape selected the page scrolls: %s", vp[0], vp[1], got) } } te.rig.Screen(`[slides-editor]`, "a canvas shape selected") } // notesJS is the notes card's state: open or closed, its height and // top, the tab's box and text (the quieter editor's, spec §6.2: it was // an icon with a dot and a name), the View menu row's check, where // focus is, and the bottom of whatever the stage draws (the editable // stage, or its phone frame in phone view). const notesJS = `(() => { const pane = document.querySelector('[slides-notes-pane]'), icon = document.querySelector('[slides-notes-open]') const edge = document.querySelector('[slides-notes-resize]') const shown = e => !e.hidden && getComputedStyle(e).display !== 'none' && e.getBoundingClientRect().height > 0 const r = pane.getBoundingClientRect(), i = icon.getBoundingClientRect() const view = document.querySelector('[slides-stage-pane]').dataset.view const stage = document.querySelector(view === 'phone' ? '[slides-stage-frame]' : '[slides-stage]').getBoundingClientRect() const a = document.activeElement return { State: pane.dataset.state, CardShown: shown(pane), Height: r.height, Top: r.top, IconShown: shown(icon), IconW: i.width, IconH: i.height, Label: icon.textContent, Pressed: document.querySelector('[data-view-toggle="notes"]').getAttribute('aria-pressed'), Focus: a === icon ? 'icon' : a && a.closest('[slides-notes]') ? 'notes' : a ? a.tagName : '', Min: Number(edge.getAttribute('aria-valuemin')), Max: Number(edge.getAttribute('aria-valuemax')), Now: Number(edge.getAttribute('aria-valuenow')), StageBottom: stage.bottom } })()` type notesState struct { State string CardShown, IconShown bool Height, Top float64 IconW, IconH float64 Label, Pressed, Focus string Min, Max, Now float64 StageBottom float64 } func (te *tidyEditor) notes() notesState { var s notesState te.rig.Run(evalInto(&s, notesJS)) return s } // TestTidyNotes (spec §5): the notes are a card at the foot of the // desk. The × closes it to a tab (an icon until the quieter editor, // §6.2), and the tab and View → Speaker notes open it again; the tab's // text says whether the slide has notes, and how many words, across a // slide change and after the notes are emptied; // the top edge drags within its limits and the height survives a // reload; and the stage, a phone frame included, ends above the card. func TestTidyNotes(t *testing.T) { te := openTidyEditor(t, 3, 1280, 720) ids, _ := te.slideIDs() const saved = `document.querySelector('[estilo-save-status]').dataset.state === 'saved'` s := te.notes() if s.State != "open" || !s.CardShown || s.IconShown { t.Fatalf("at first the notes are %+v; want the card open and the tab hidden", s) } if s.Pressed != "true" { t.Errorf("View → Speaker notes is aria-pressed=%q with the notes open", s.Pressed) } for _, v := range []string{"desktop", "phone", "both"} { te.view(v) if v == "phone" { te.rig.Run(waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.vp === 'phone'`)) } if s := te.notes(); s.StageBottom > s.Top+0.5 { t.Errorf("%s view: the stage ends at %.1f, under the notes card's top %.1f", v, s.StageBottom, s.Top) } // The top edge is a 24px target that lies over neither the // stages (and so no frame's edge) nor the × or the notes' first // line: a point at the centre of the ×, and at the middle of the // first line's height, finds them. var edge string te.rig.Run(evalInto(&edge, `(() => { const q = s => document.querySelector(s), out = [] const e = q('[slides-notes-resize]').getBoundingClientRect() if (e.height < 24 || e.width < 24) out.push('the top edge is ' + e.width + 'x' + e.height + ', under 24x24') const stages = q('[slides-stages]').getBoundingClientRect() if (e.top < stages.bottom - 0.5) out.push('the top edge (top ' + e.top + ') is over the stages (bottom ' + stages.bottom + ')') const notes = q('[slides-notes]'), line = parseFloat(getComputedStyle(notes).lineHeight) const x = q('[slides-notes-close]').getBoundingClientRect(), n = notes.getBoundingClientRect() for (const [name, sel, px, py] of [['the ×', '[slides-notes-close]', x.left + x.width / 2, x.top + x.height / 2], ['the first line', '[slides-notes]', n.left + 20, n.top + line / 2]]) { const hit = document.elementFromPoint(px, py) if (!hit || !hit.closest(sel)) out.push('at the centre of ' + name + ' is ' + (hit ? hit.outerHTML.slice(0, 80) : 'nothing')) } return out.join('; ') })()`)) if edge != "" { t.Errorf("%s view: %s", v, edge) } te.rig.Screen(`[slides-stage-pane]`, v+" view with the notes open") } te.view("desktop") // The × closes; focus goes to the tab, which shows and counts the // first slide's 400 words. te.rig.Run(chromedp.Click(chromedp.CSS(`[slides-notes-close]`)), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'closed'`)) s = te.notes() if s.CardShown || !s.IconShown || s.Focus != "icon" { t.Errorf("after ×: %+v; want the card gone, the tab shown and focused", s) } if s.IconW < 24 || s.IconH < 24 { t.Errorf("the tab is %gx%g, under 24x24", s.IconW, s.IconH) } if s.Label != "Notes · 400 words" || s.Pressed != "false" { t.Errorf("closed on the slide with notes: the tab says %q, View row pressed %q", s.Label, s.Pressed) } te.rig.Screen(`[slides-stage-pane]`, "notes closed: the tab, with its count") // The second slide has no notes; back on the first, the count again. te.rig.Run( chromedp.Evaluate[chromedp.Void](`location.hash = '`+ids[1]+`'`), waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+ids[1]+`'`), ) if s := te.notes(); s.Label != "Notes" { t.Errorf("on a slide without notes: the tab says %q", s.Label) } te.rig.Run( chromedp.Evaluate[chromedp.Void](`location.hash = '`+ids[0]+`'`), waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+ids[0]+`'`), ) if s := te.notes(); s.Label != "Notes · 400 words" { t.Errorf("back on the slide with notes: the tab says %q", s.Label) } // The tab opens, into the notes. te.rig.Run(chromedp.Click(chromedp.CSS(`[slides-notes-open]`)), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open'`)) if s := te.notes(); !s.CardShown || s.IconShown || s.Focus != "notes" || s.Pressed != "true" { t.Errorf("after the tab: %+v; want the card shown, focus in the notes, the View row pressed", s) } // View → Speaker notes closes and opens it too. te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[data-view-toggle="notes"]').click()`), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'closed'`)) if s := te.notes(); s.CardShown || !s.IconShown || s.Pressed != "false" { t.Errorf("after View → Speaker notes: %+v; want closed, the row unpressed", s) } te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[data-view-toggle="notes"]').click()`), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open'`)) if s := te.notes(); !s.CardShown || s.Pressed != "true" || s.Focus != "notes" { t.Errorf("after View → Speaker notes again: %+v; want open, the row pressed, focus in the notes", s) } // Emptied, the slide has no notes: the count goes. te.rig.Run( // Select all the way a person does (ProseMirror's Mod-a, in the // notes), then delete: a DOM selection set by script reached // ProseMirror only after the key, now and then. chromedp.Focus(chromedp.CSS(`[slides-notes]`)), waitFor(`document.activeElement === document.querySelector('[slides-notes]')`), modKey("a", chromedp.ModifierCtrl), chromedp.KeyEvent(kb.Backspace), waitFor(`document.querySelector('[slides-notes]').textContent.trim() === ''`), waitFor(saved), ) if s := te.notes(); s.Label != "Notes" { t.Errorf("after deleting the notes' text: the tab says %q", s.Label) } // The top edge: dragged far up it stops at its maximum, far down at // its minimum, and a short drag up grows it by the drag. drag := func(dy float64) notesState { t.Helper() var pt struct{ X, Y float64 } te.rig.Run(evalInto(&pt, `(() => { const r = document.querySelector('[slides-notes-resize]').getBoundingClientRect(); return {X: r.left + r.width / 3, Y: r.top + r.height / 2} })()`)) te.rig.Run(dragBy(pt.X, pt.Y, 0, dy)) return te.notes() } s = drag(-600) if s.Max <= s.Min || math.Abs(s.Height-s.Max) > 1 { t.Errorf("dragged far up, the card is %.1fpx; want its maximum %g (minimum %g)", s.Height, s.Max, s.Min) } s = drag(600) if math.Abs(s.Height-s.Min) > 1 { t.Errorf("dragged far down, the card is %.1fpx; want its minimum %g", s.Height, s.Min) } s = drag(-40) want := s.Min + 40 if math.Abs(s.Height-want) > 1 || math.Abs(s.Now-s.Height) > 1 { t.Errorf("a 40px drag up from %g made the card %.1fpx (aria-valuenow %g); want %g", s.Min, s.Height, s.Now, want) } if got := te.scrolls(t); got != "" { t.Errorf("after resizing the notes the page scrolls: %s", got) } // The height survives a reload. te.rig.Run( chromedp.Reload(), chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)), waitFor(editorBound), ) if s := te.notes(); s.State != "open" || math.Abs(s.Height-want) > 1 { t.Errorf("after a reload the notes are %s and %.1fpx tall; want open and %g", s.State, s.Height, want) } } // TestTidyViewSwitch (spec §3): the three icons and the View menu's // three rows each light exactly one view and show the frames it names; // ArrowRight from the first icon moves to the next. func TestTidyViewSwitch(t *testing.T) { te := openTidyEditor(t, 3, 1280, 720) // state: which radios are checked, how the one editable stage is // drawn (full width; inside a phone, its frame a phone's 390:844 // (TestTidyPhoneFrame holds the rest of that); or sharing the row // with the preview — it is not the read-only [slides-stage-phone], // which only "both" shows), and whether the read-only phone preview // is showing. const state = `(() => { const shown = el => !!el && !el.hidden && getComputedStyle(el).display !== 'none' const checked = [...document.querySelectorAll('input[name="slides-view"]')].filter(i => i.checked).map(i => i.value) const stage = document.querySelector('[data-vp="desktop"]') const w = shown(stage) ? stage.getBoundingClientRect().width : 0 const f = document.querySelector('[slides-stage-frame]').getBoundingClientRect() const phone = getComputedStyle(document.querySelector('[slides-stage-frame]')).display !== 'contents' && f.height > 0 && Math.abs(f.width / f.height - 390 / 844) < 0.01 const kind = !w ? '' : phone ? 'phone-frame' : w > 600 ? 'wide' : 'shared' return checked.join(',') + '|' + kind + '|' + (shown(document.querySelector('[slides-stage-phone]')) ? 'preview' : '') })()` want := map[string]string{"desktop": "desktop|wide|", "phone": "phone|phone-frame|", "both": "both|shared|preview"} check := func(how, view string) { t.Helper() var got string te.rig.Run(evalInto(&got, state)) if got != want[view] { t.Errorf("%s: state is %q, want %q", how, got, want[view]) } } center := func(sel string) { var pt struct{ X, Y float64 } te.rig.Run(evalInto(&pt, `(() => { const r = document.querySelector('`+sel+`').getBoundingClientRect(); return {X: r.x + r.width / 2, Y: r.y + r.height / 2} })()`)) te.rig.Run(chromedp.MouseClickXY(pt.X, pt.Y)) } for _, v := range []string{"phone", "both", "desktop"} { center(`[slides-switcher] label:has(input[value="` + v + `"])`) te.rig.Run(waitFor(fmt.Sprintf(`document.querySelector('[slides-stage-pane]').dataset.view === %q`, v))) check("clicking the "+v+" icon", v) } // ArrowRight from the first (focused) moves to the second. te.rig.Run(chromedp.Focus(chromedp.CSS(`input[name="slides-view"][value="desktop"]`)), chromedp.KeyEvent(kb.ArrowRight)) te.rig.Run(waitFor(`document.querySelector('[slides-stage-pane]').dataset.view === 'phone'`)) check("ArrowRight from the first icon", "phone") // The View menu's rows do the same, chosen as a person would: the // menu opened with a click on its title, the row clicked where it // is drawn. for _, v := range []string{"both", "desktop", "phone"} { var open bool te.rig.Run(evalInto(&open, `document.querySelector('[slides-menu="view"]').open`)) if !open { center(`[slides-menu="view"] > summary`) te.rig.Run(waitFor(`document.querySelector('[slides-menu="view"]').open`)) } center(`[data-view-choice="` + v + `"]`) te.rig.Run(waitFor(fmt.Sprintf(`document.querySelector('[slides-stage-pane]').dataset.view === %q`, v))) check("the View menu's "+v+" row", v) } // One pill: each segment is at least 24x24, the pill's ends are // rounded and its two inner joins square. var pill string te.rig.Run(evalInto(&pill, `(() => { const items = [...document.querySelectorAll('[slides-switcher] > label')], out = [] items.forEach((l, i) => { const r = l.getBoundingClientRect(), s = getComputedStyle(l) if (r.width < 24 || r.height < 24) out.push(i + ' is ' + r.width + 'x' + r.height) const left = parseFloat(s.borderStartStartRadius) > 0, right = parseFloat(s.borderStartEndRadius) > 0 if (left !== (i === 0) || right !== (i === items.length - 1)) out.push(i + ' corners: left ' + left + ', right ' + right) }) return out.join('; ') })()`)) if pill != "" { t.Errorf("the view switch is not one pill of 24px targets: %s", pill) } te.rig.Screen(`[slides-stage-bar]`, "the view switch") } // The phone frame (spec §6.1): in phone view the editable stage, and in // Both the read-only [slides-stage-phone], is a phone — a 390×844 screen // scaled by --slides-phone-scale to the height the stages have, which // scrolls inside itself. // phoneStageHTML is the golden file of what the two phone renderings // hold, captured from the commit before the frame (task B4): the frame // changes, the content does not. const phoneStageHTML = "testdata/phone-stage-html.json" // tallSlide is the id of the slide phoneFrameDeck adds, taller than a // phone at phone width. const tallSlide = "tallslide222" // phoneFrameDeck is the sample deck (eight fixed slides, a canvas one // among them) with one more slide of forty paragraphs at its end. func phoneFrameDeck(t *testing.T) func(a *testApp, cookies []*http.Cookie) string { return func(a *testApp, cookies []*http.Cookie) string { path := sampleDeck(t, a, cookies) token := mintAgent(t, a, cookies, "phone-frame") paras := make([]string, 40) for i := range paras { paras[i] = fmt.Sprintf("Paragraph %d of a slide far longer than a phone is tall.", i+1) } ops := `{"ops":[{"op":"add_slide","id":"` + tallSlide + `","layout":"flow","template":"title-body"},` + `{"op":"add_block","slide":"` + tallSlide + `","type":"text","region":"body","markdown":` + quote(strings.Join(paras, "\n\n")) + `}]}` apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+strings.TrimPrefix(path, "/d/")+"/ops", token, ops, http.StatusOK) return path + "/edit" } } // slideIDs is the deck's slide ids in strip order, with each one's label. func (te *tidyEditor) slideIDs() (ids, labels []string) { var pairs [][2]string te.rig.Run(evalInto(&pairs, `[...document.querySelectorAll('[slides-strip-item][data-slide-id]')].map(li => [li.dataset.slideId, li.querySelector('[slides-strip-label]')?.textContent ?? ''])`)) for _, p := range pairs { ids, labels = append(ids, p[0]), append(labels, p[1]) } return ids, labels } // view picks a view by its radio, and waits for the pane to say so. func (te *tidyEditor) view(v string) { te.rig.Run( chromedp.Evaluate[chromedp.Void](`document.querySelector('input[name="slides-view"][value="`+v+`"]').click()`), waitFor(fmt.Sprintf(`document.querySelector('[slides-stage-pane]').dataset.view === %q`, v)), ) } // showIn shows slide id in view v and waits until the stage that view // edits or previews holds it in the phone rendering, bound when it is // the editable one. func (te *tidyEditor) showIn(id, v string) { // The slide first, then the view: a view switched while a slide is // still loading re-fetches the slide it started from. te.rig.Run( chromedp.Evaluate[chromedp.Void](`location.hash = '`+id+`'`), waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+id+`'`), ) te.view(v) te.rig.Run(waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '` + id + `'`)) switch v { case "phone": te.rig.Run( waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.vp === 'phone'`), waitFor(`document.querySelector('[slides-stage] [contenteditable="true"]')`), ) case "both": te.rig.Run(waitFor(`document.querySelector('[slides-phone-screen] [slides-slide]')?.dataset.id === '` + id + `'`)) } } // stableIDs replaces every id the server minted (twelve base32 // characters, as an attribute's whole value) with its order of first // appearance, so two decks seeded alike compare alike. func stableIDs(html string) string { seen := map[string]string{} return regexp.MustCompile(`="[a-z2-7]{12}"`).ReplaceAllStringFunc(html, func(m string) string { id := m[2 : len(m)-1] if _, ok := seen[id]; !ok { seen[id] = fmt.Sprintf("id-%d", len(seen)+1) } return `="` + seen[id] + `"` }) } // phoneFrameJS measures the frame view v shows (the editable stage's // frame in phone view, [slides-stage-phone] in Both): its rect, the // stages' rect, its scale, its screen (the element that scrolls), the // slide's top in the screen's own CSS px, and the desktop stage's rect. const phoneFrameJS = `((v) => { const frame = document.querySelector(v === 'phone' ? '[slides-stage-frame]' : '[slides-stage-phone]') const screen = document.querySelector(v === 'phone' ? '[slides-stage-frame]' : '[slides-phone-screen]') const slide = screen.querySelector('[slides-slide]') const scale = parseFloat(getComputedStyle(frame).getPropertyValue('--slides-phone-scale')) const r = e => { const b = e.getBoundingClientRect(); return {L: b.left, T: b.top, R: b.right, B: b.bottom, W: b.width, H: b.height} } screen.scrollTop = 0 return { Frame: r(frame), Stages: r(document.querySelector('[slides-stages]')), Desktop: r(document.querySelector('[slides-stage]')), Scale: scale, SlideTop: (slide.getBoundingClientRect().top - screen.getBoundingClientRect().top) / scale, Radius: getComputedStyle(frame).borderTopLeftRadius } })` type edges struct{ L, T, R, B, W, H float64 } type phoneFrame struct { Frame, Stages, Desktop edges Scale, SlideTop float64 Radius string } func (te *tidyEditor) phoneFrame(v string) phoneFrame { var f phoneFrame te.rig.Run(evalInto(&f, phoneFrameJS+`('`+v+`')`)) return f } // TestTidyPhoneFrame (spec §6.1, §8): at 1280×720, in phone view and in // Both, the phone is a phone's proportions and no taller than the // stages; it holds the same HTML each view held before it was a frame; // a slide taller than a phone scrolls inside the screen and not the // page; and the slide sits as far down the screen as the viewer puts it // on a 390×844 phone. func TestTidyPhoneFrame(t *testing.T) { te := openTidyEditorOn(t, 1280, 720, phoneFrameDeck(t)) ids, labels := te.slideIDs() canvas := -1 for i, l := range labels { if strings.HasPrefix(l, "Canvas:") { canvas = i } } if len(ids) != 9 || canvas < 0 { t.Fatalf("the deck's strip is %q; want the sample deck's eight, a canvas one among them, and the tall one", labels) } // The same bytes, for the first slide and the canvas one. raw, err := os.ReadFile(phoneStageHTML) if err != nil { t.Fatal(err) } var want map[string]string if err := json.Unmarshal(raw, &want); err != nil { t.Fatalf("%s: %v", phoneStageHTML, err) } for _, n := range []int{0, canvas} { var phone, both string te.showIn(ids[n], "phone") te.rig.Run(evalInto(&phone, `document.querySelector('[slides-stage]').innerHTML`)) te.showIn(ids[n], "both") te.rig.Run(evalInto(&both, `document.querySelector('[slides-phone-screen]').innerHTML`)) for key, got := range map[string]string{fmt.Sprintf("phone/%d", n+1): phone, fmt.Sprintf("both/%d", n+1): both} { if stableIDs(got) != want[key] { t.Errorf("%s: the stage holds other HTML than it did before the frame\n got: %s\nwant: %s", key, stableIDs(got), want[key]) } } } // Where the viewer puts the first slide on a 390×844 phone. Read // after the editor's checks, from the same browser. viewerTop := map[string]float64{} defer func() { te.size(390, 844) var top float64 te.rig.Run( chromedp.Navigate(te.rig.Origin+strings.TrimSuffix(te.path, "/edit")+"?slide=1"), chromedp.WaitVisible(chromedp.CSS(`[slides-viewer] [slides-slide]`)), evalInto(&top, `document.querySelector('[slides-viewer] [slides-slide]').getBoundingClientRect().top + scrollY`), ) for _, v := range []string{"phone", "both"} { if got := viewerTop[v]; got < top-1 || got > top+1 { t.Errorf("%s: the slide is %.1fpx down the phone's screen; the viewer puts it %.1fpx down a 390×844 page", v, got, top) } } }() const ratio = 390.0 / 844.0 for _, v := range []string{"phone", "both"} { te.showIn(ids[0], v) f := te.phoneFrame(v) t.Logf("%s: frame %.1f×%.1f at scale %g, stages %.1f×%.1f", v, f.Frame.W, f.Frame.H, f.Scale, f.Stages.W, f.Stages.H) if f.Frame.H == 0 || math.Abs(f.Frame.W/f.Frame.H-ratio)/ratio > 0.01 { t.Errorf("%s: the frame is %.1f×%.1f, not a phone's 390:844 within 1%%", v, f.Frame.W, f.Frame.H) } if f.Frame.B > f.Stages.B+0.5 { t.Errorf("%s: the frame's bottom %.1f is below the stages' bottom %.1f", v, f.Frame.B, f.Stages.B) } if !(f.Scale > 0 && f.Scale < 1) { t.Errorf("%s: --slides-phone-scale is %g at 1280×720; want it between 0 and 1", v, f.Scale) } if f.Radius != "28px" { t.Errorf("%s: the frame's corner radius is %s, want 28px", v, f.Radius) } if v == "both" && f.Desktop.R > f.Frame.L { t.Errorf("both: the desktop stage (right %.1f) overlaps the phone frame (left %.1f)", f.Desktop.R, f.Frame.L) } viewerTop[v] = f.SlideTop te.rig.Screen("[slides-stage-pane]", v+" view, the phone frame") } // The tall slide scrolls inside the screen, never the page. for _, v := range []string{"phone", "both"} { te.showIn(tallSlide, v) screen := map[string]string{"phone": "[slides-stage-frame]", "both": "[slides-phone-screen]"}[v] var scrolled float64 te.rig.Run(evalInto(&scrolled, `(s => { s.scrollTop = 300; return s.scrollHeight > s.clientHeight ? s.scrollTop : -1 })(document.querySelector('`+screen+`'))`)) if scrolled <= 0 { t.Errorf("%s: the tall slide does not scroll inside %s (scrollTop %g)", v, screen, scrolled) } if got := te.scrolls(t); got != "" { t.Errorf("%s: with the tall slide the page scrolls: %s", v, got) } te.rig.Screen("[slides-stage-pane]", v+" view, a tall slide scrolled") } } // TestTidyPhoneFrameStillEdits: in phone view at 1280×720, where the // phone is scaled below 1, the stage still edits. A click in a text box // puts the caret where it was clicked and typing changes that box; on a // canvas slide a selected box has its outline over it, and a drag moves // it by the pointer's distance in the slide's own fractions. func TestTidyPhoneFrameStillEdits(t *testing.T) { te := openTidyEditorOn(t, 1280, 720, phoneFrameDeck(t)) ids, labels := te.slideIDs() canvas := "" for i, l := range labels { if strings.HasPrefix(l, "Canvas:") { canvas = ids[i] } } if canvas == "" { t.Fatalf("the sample deck has no canvas slide: %q", labels) } const saved = `document.querySelector('[estilo-save-status]').dataset.state === 'saved'` te.showIn(ids[0], "phone") if f := te.phoneFrame("phone"); !(f.Scale > 0 && f.Scale < 1) { t.Fatalf("--slides-phone-scale is %g at 1280×720; this test needs the phone scaled below 1", f.Scale) } // A click just inside the end of the body text's first word: the // caret lands within a character of that point, in that box. const body = `[slides-stage] [data-block="text"]` var at struct{ X, Y float64 } te.rig.Run(evalInto(&at, `(() => { const p = document.querySelector('`+body+` p'), r = document.createRange() r.setStart(p.firstChild, 0); r.setEnd(p.firstChild, 5) const b = r.getBoundingClientRect() return {X: b.right - 1, Y: b.top + b.height / 2} })()`)) var before string te.rig.Run( evalInto(&before, `document.querySelector('`+body+`').textContent`), chromedp.MouseClickXY(at.X, at.Y), waitFor(`document.querySelector('`+body+`').contains(getSelection().anchorNode)`), ) var caret struct{ X, Y, Char float64 } te.rig.Run(evalInto(&caret, `(() => { const s = getSelection(), r = s.getRangeAt(0).cloneRange() const b = r.getBoundingClientRect(), c = document.createRange() c.setStart(s.anchorNode, 0); c.setEnd(s.anchorNode, 1) return {X: b.left, Y: b.top + b.height / 2, Char: c.getBoundingClientRect().width} })()`)) if math.Abs(caret.X-at.X) > caret.Char+1 || math.Abs(caret.Y-at.Y) > 4 { t.Errorf("clicked at (%.1f, %.1f); the caret is at (%.1f, %.1f), more than a character (%.1fpx) away", at.X, at.Y, caret.X, caret.Y, caret.Char) } te.rig.Run( chromedp.KeyEvent("XQ"), waitFor(`document.querySelector('`+body+`').textContent.includes('XQ')`), waitFor(saved), ) var after string te.rig.Run(evalInto(&after, `document.querySelector('`+body+`').textContent`)) if len(after) != len(before)+2 { t.Errorf("typing XQ made the box %q from %q", after, before) } // The canvas slide: select the rectangle a little in from its left // edge — clear of the ellipse over its middle, of the heading, whose // words run down over its top at a phone's width, and of the 24px // handles, which cover much of a box this small. te.showIn(canvas, "phone") const rectSel = `[slides-stage] [data-block="shape"][data-kind="rect"]` type geom struct{ Box, Overlay, Frame edges } measure := func() geom { var g geom te.rig.Run(evalInto(&g, `(() => { const r = e => { const b = e.getBoundingClientRect(); return {L: b.left, T: b.top, R: b.right, B: b.bottom, W: b.width, H: b.height} } return {Box: r(document.querySelector('`+rectSel+`')), Overlay: r(document.querySelector('[slides-canvas-overlay]')), Frame: r(document.querySelector('[slides-stage] [slides-slide]'))} })()`)) return g } overOutline := func(when string, g geom) { t.Helper() for _, d := range [][3]any{{"left", g.Box.L, g.Overlay.L}, {"top", g.Box.T, g.Overlay.T}, {"right", g.Box.R, g.Overlay.R}, {"bottom", g.Box.B, g.Overlay.B}} { if math.Abs(d[1].(float64)-d[2].(float64)) > 2 { t.Errorf("%s: the selection outline's %s is %.1f, the box's %.1f", when, d[0], d[2], d[1]) } } } g := measure() x, y := g.Box.L+g.Box.W*0.27, g.Box.T+g.Box.H*0.6 te.rig.Run( chromedp.MouseClickXY(x, y), waitFor(`document.querySelector('`+rectSel+`').getAttribute('aria-selected') === 'true'`), waitFor(`!document.querySelector('[slides-canvas-overlay]').hidden`), ) g = measure() overOutline("selected", g) te.rig.Screen("[slides-stage-pane]", "phone view, the rectangle selected") // The box's left edge as a fraction of the slide, measured on // screen; the drag is written as the phone override (set_phone), // which the phone rendering carries as --slides-phone-left. from := (g.Box.L - g.Frame.L) / g.Frame.W const dx = 30.0 te.rig.Run( dragBy(x, y, dx, 0), waitFor(saved), waitFor(`document.querySelector('`+rectSel+`')?.style.getPropertyValue('--slides-phone-left') !== ''`), waitFor(`document.querySelector('`+rectSel+`')?.getAttribute('aria-selected') === 'true'`), ) var phoneLeft float64 te.rig.Run(evalInto(&phoneLeft, `parseFloat(document.querySelector('`+rectSel+`').style.getPropertyValue('--slides-phone-left')) / 100`)) // The pointer moved dx screen px over a slide g.Frame.W screen px // wide; snapping may pull the edge up to one per cent further. want := dx / g.Frame.W if got := phoneLeft - from; math.Abs(got-want) > 0.0105 { t.Errorf("a %gpx drag over a %.1fpx-wide slide moved the box %.4f of the slide, want %.4f (±0.01 snap)", dx, g.Frame.W, got, want) } overOutline("after the drag", measure()) te.rig.Screen("[slides-stage-pane]", "phone view, the rectangle dragged") } // TestTidyPhoneFrameFitsANarrowWindow (spec §8's 320px reflow): in a // 320×700 window, in phone view and in Both, the phone is scaled to the // width it has — its frame lies inside the stages — and the page does // not scroll sideways. func TestTidyPhoneFrameFitsANarrowWindow(t *testing.T) { te := openTidyEditorOn(t, 1280, 720, phoneFrameDeck(t)) ids, _ := te.slideIDs() te.size(320, 700) for _, v := range []string{"phone", "both"} { te.showIn(ids[0], v) var got string te.rig.Run(evalInto(&got, `((v) => { const frame = document.querySelector(v === 'phone' ? '[slides-stage-frame]' : '[slides-stage-phone]').getBoundingClientRect() const stages = document.querySelector('[slides-stages]').getBoundingClientRect() const out = [] if (frame.width === 0) out.push('the frame has no box') if (frame.left < stages.left - 0.5 || frame.right > stages.right + 0.5) out.push('the frame [' + frame.left.toFixed(1) + ', ' + frame.right.toFixed(1) + '] is outside the stages [' + stages.left.toFixed(1) + ', ' + stages.right.toFixed(1) + ']') // Nothing wider than the window. Not scrollWidth === innerWidth: // at 320px the editor is 305px wide in every view (a scrollbar's // 15px short of the window, desktop view included), and // scrollWidth reports that rather than the window. const d = document.documentElement if (d.scrollWidth > innerWidth || d.scrollWidth > d.clientWidth) out.push('scrollWidth ' + d.scrollWidth + ' > clientWidth ' + d.clientWidth + ' / innerWidth ' + innerWidth) return out.join('; ') })('`+v+`')`)) if got != "" { t.Errorf("%s view at 320×700: %s", v, got) } te.rig.Screen("[slides-stage-pane]", v+" view at 320px") } } // cardJS is the inspector card's geometry against the desk, the stages // and the window: its state, whether it is drawn, its box, how it // scrolls, and the desktop frame's box (the slide on the stage). const cardJS = `(() => { const q = s => document.querySelector(s), box = e => { const r = e.getBoundingClientRect(); return {L: r.left, T: r.top, R: r.right, B: r.bottom, W: r.width, H: r.height} } const card = q('[slides-inspector]'), cs = getComputedStyle(card) const fmt = q('[data-view-toggle="inspector"][aria-expanded]') const slide = q('[slides-stage] > [slides-slide]') const d = document.documentElement return { State: card.dataset.state, Display: cs.display, Position: cs.position, Shadow: cs.boxShadow, OverflowY: cs.overflowY, Expanded: fmt.getAttribute('aria-expanded'), Pressed: q('[estilo-menu-item][data-view-toggle="inspector"]').getAttribute('aria-pressed'), Card: box(card), Desk: box(q('[slides-desk]')), Strip: box(q('[slides-strip-nav]')), Pane: box(q('[slides-stage-pane]')), Notes: box(q('[slides-notes-pane]')), Slide: slide ? box(slide) : null, Format: box(fmt), ScrollH: card.scrollHeight, ClientH: card.clientHeight, DocW: d.scrollWidth, DocH: d.scrollHeight, ClientW: d.clientWidth, WinW: innerWidth, WinH: innerHeight, Cookie: document.cookie } })()` type cardState struct { State, Display, Position, Shadow, OverflowY, Expanded, Pressed, Cookie string Card, Desk, Strip, Pane, Notes, Format edges4 Slide *edges4 ScrollH, ClientH, DocW, DocH, ClientW, WinW, WinH float64 } type edges4 struct{ L, T, R, B, W, H float64 } func (te *tidyEditor) card() cardState { var c cardState te.rig.Run(evalInto(&c, cardJS)) return c } // pressFormat clicks the bar's Format button and waits for the card to // be in state. func (te *tidyEditor) pressFormat(state string) { te.rig.Run( chromedp.Click(chromedp.CSS(`[estilo-bar-control] > [data-view-toggle="inspector"]`)), waitFor(`document.querySelector('[slides-inspector]').dataset.state === '`+state+`'`), ) } // TestTidyCardFloats (spec §2, §4): at 1280×720 the inspector is Docs' // card over the desk's top end corner, 12px in from the desk's top and // end edges, 248px wide, stopping 12px or more short of its foot and // scrolling inside itself when what it holds is taller; the slide is // never under it, and re-centres in the desk when Format hides it. The // state is a cookie the server reads, so the first paint is already // final: with the bundle blocked, a closed card is not drawn and an // open one is where it will stay. func TestTidyCardFloats(t *testing.T) { te := openTidyEditor(t, 3, 1280, 720) near := func(a, b float64) bool { return math.Abs(a-b) <= 1 } c := te.card() if c.State != "open" || c.Display == "none" || c.Expanded != "true" || c.Pressed != "true" { t.Fatalf("at first the card is %s (display %s), Format aria-expanded=%s, View row aria-pressed=%s; want it open and shown", c.State, c.Display, c.Expanded, c.Pressed) } if c.Position != "absolute" { t.Errorf("the card's position is %s, want absolute", c.Position) } if !near(c.Card.T-c.Desk.T, 12) || !near(c.Desk.R-c.Card.R, 12) || !near(c.Card.W, 248) { t.Errorf("the card is %+v in the desk %+v; want 12px from its top and end, 248px wide", c.Card, c.Desk) } if c.Card.L < c.Desk.L || c.Card.B > c.Desk.B-12+0.5 { t.Errorf("the card %+v is not inside the desk %+v, 12px short of its foot", c.Card, c.Desk) } if c.Slide == nil || c.Slide.R > c.Card.L-0.5 { t.Errorf("the desktop frame %+v runs under the card (left %.1f)", c.Slide, c.Card.L) } if c.Notes.R > c.Card.L-0.5 { t.Errorf("the notes card (right %.1f) runs under the inspector card (left %.1f)", c.Notes.R, c.Card.L) } te.rig.Screen(`[slides-editor]`, "the card over the desk") // The slide's options (nothing selected: the card's longest on this // deck, since it shows one thing at a time), in a window short enough // that they are taller than the card, which scrolls inside itself; // the page does not. Since the deck's options (Q2) and the list of // boxes (Q5) left the card, and its layout became a row of pictures // with two quiet rows (Q3), only a 252px window makes them overflow. te.rig.Run(waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`)) c = te.card() if c.ScrollH <= c.ClientH { te.size(1280, 252) c = te.card() } if c.ScrollH <= c.ClientH || (c.OverflowY != "auto" && c.OverflowY != "scroll") { t.Errorf("on the slide's options the card holds %.0fpx in %.0fpx and overflow-y is %s; want it to scroll inside itself", c.ScrollH, c.ClientH, c.OverflowY) } if c.Card.B > c.Desk.B-12+0.5 { t.Errorf("on the slide's options the card's bottom %.1f is less than 12px above the desk's %.1f", c.Card.B, c.Desk.B) } var scrolled float64 te.rig.Run(evalInto(&scrolled, `(c => { c.scrollTop = 200; return c.scrollTop })(document.querySelector('[slides-inspector]'))`)) if scrolled <= 0 { t.Errorf("the card does not scroll (scrollTop %g)", scrolled) } if got := te.scrolls(t); got != "" { t.Errorf("on the slide's options the page scrolls: %s", got) } te.rig.Screen(`[slides-editor]`, "the slide's options, the card scrolled") te.size(1280, 720) te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-inspector]').scrollTop = 0`)) // A selected box whose options are taller than the card (a canvas // shape's, the longest a box has) in a short window: the card // scrolls inside itself, and the page does not. canvas := te.addCanvasShape(t) // Its On a phone group is part of what makes it tall, and only the // phone views draw it (Q6): the test is in Both view. te.openOn(canvas) te.view("both") te.selectBox("shape") te.size(1280, 480) c = te.card() if c.ScrollH <= c.ClientH || (c.OverflowY != "auto" && c.OverflowY != "scroll") { t.Errorf("1280x480, a shape selected: the card holds %.0fpx in %.0fpx and overflow-y is %s; want it to scroll inside itself", c.ScrollH, c.ClientH, c.OverflowY) } var moved struct{ Top, Shift float64 } te.rig.Run(evalInto(&moved, `(c => { const f = c.querySelector('form[data-section="block"]'), before = f.getBoundingClientRect().top; c.scrollTop = 200; return {Top: c.scrollTop, Shift: before - f.getBoundingClientRect().top} })(document.querySelector('[slides-inspector]'))`)) if moved.Top <= 0 || moved.Shift <= 0 { t.Errorf("1280x480, a shape selected: scrolling the card gives scrollTop %g and moves its content %gpx; want both above 0", moved.Top, moved.Shift) } if got := te.scrolls(t); got != "" { t.Errorf("1280x480, a shape selected: the page scrolls: %s", got) } te.rig.Screen(`[slides-editor]`, "1280x480, a shape selected, the card scrolled") te.size(1280, 720) te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-inspector]').scrollTop = 0`)) te.view("desktop") // the one stage that re-centres alone // Format hides it: the frame re-centres in the desk (the strip's // edge to the desk's end), and the cookie says closed. te.pressFormat("closed") te.rig.Run(waitFor(`(() => { const s = document.querySelector('[slides-stage] > [slides-slide]').getBoundingClientRect(), d = document.querySelector('[slides-desk]').getBoundingClientRect(), n = document.querySelector('[slides-strip-nav]').getBoundingClientRect(); return Math.abs((s.left + s.right) / 2 - (n.right + d.right) / 2) <= 1 })()`)) c = te.card() if c.Display != "none" || c.Expanded != "false" || c.Pressed != "false" { t.Errorf("after Format: display %s, aria-expanded %s, View row aria-pressed %s", c.Display, c.Expanded, c.Pressed) } if !strings.Contains(c.Cookie, "slides-inspector=closed") { t.Errorf("after Format the cookies are %q; want slides-inspector=closed", c.Cookie) } te.rig.Screen(`[slides-editor]`, "the card hidden, the slide re-centred") // No flash: the server paints the remembered state before any // script. The bundle is blocked, so what is measured is the server's // HTML and CSS alone. te.rig.Run( cdpStep(network.Enable, network.EnableParams{}), blockURLs("*/static/editor.*.js"), chromedp.Navigate(te.rig.Origin+te.path), chromedp.WaitReady(chromedp.CSS(`[slides-inspector]`)), ) var bound bool te.rig.Run(evalInto(&bound, editorBound)) if bound { t.Fatal("the editor bound with its bundle blocked; this check would not be of the first paint") } if c := te.card(); c.Display != "none" || c.Expanded != "false" || c.Pressed != "false" { t.Errorf("first paint with the closed cookie: display %s, aria-expanded %s, View row aria-pressed %s; want none, false, false", c.Display, c.Expanded, c.Pressed) } te.rig.Run( cdpStep(network.DeleteCookies, network.DeleteCookiesParams{Name: "slides-inspector", URL: te.rig.Origin + "/"}), chromedp.Navigate(te.rig.Origin+te.path), chromedp.WaitReady(chromedp.CSS(`[slides-inspector]`)), ) c = te.card() if c.Display == "none" || c.Expanded != "true" || c.Position != "absolute" || !near(c.Card.T-c.Desk.T, 12) || !near(c.Desk.R-c.Card.R, 12) || !near(c.Card.W, 248) { t.Errorf("first paint with no cookie: display %s, aria-expanded %s, position %s, card %+v in desk %+v; want it shown where it stays", c.Display, c.Expanded, c.Position, c.Card, c.Desk) } te.rig.Run(blockURLs()) } // TestTidyNarrowAndShortWindows (Review Focus 1): under 1100px, down to // 320px, the card is in the flow under the stage with no shadow, Format // still shows and hides it, and nothing scrolls sideways; at 1280×600 // the card and the notes scroll inside themselves and the page does not. func TestTidyNarrowAndShortWindows(t *testing.T) { te := openTidyEditor(t, 3, 1280, 720) for _, vp := range [][2]int64{{1000, 800}, {320, 700}} { te.size(vp[0], vp[1]) name := fmt.Sprintf("%dx%d", vp[0], vp[1]) c := te.card() if c.Display == "none" || c.Position == "absolute" || c.Shadow != "none" { t.Errorf("%s: the card is display %s, position %s, shadow %s; want it in the flow with no shadow", name, c.Display, c.Position, c.Shadow) } if c.Card.T < c.Pane.B-0.5 { t.Errorf("%s: the card (top %.1f) is not under the stage pane (bottom %.1f)", name, c.Card.T, c.Pane.B) } if c.DocW > c.ClientW || c.Card.R > c.WinW+0.5 { t.Errorf("%s: something is wider than the window: scrollWidth %.0f, clientWidth %.0f, card right %.1f", name, c.DocW, c.ClientW, c.Card.R) } if c.Format.W < 24 || c.Format.H < 24 || c.Format.L < 0 || c.Format.R > c.WinW { t.Errorf("%s: the Format button is %+v; want it on screen and at least 24×24", name, c.Format) } te.rig.Screen(`[slides-editor]`, name+", the card in the flow") te.pressFormat("closed") if c := te.card(); c.Display != "none" || c.Expanded != "false" || c.DocW > c.ClientW { t.Errorf("%s: after Format the card is display %s, aria-expanded %s, scrollWidth %.0f", name, c.Display, c.Expanded, c.DocW) } te.pressFormat("open") if c := te.card(); c.Display == "none" || c.Expanded != "true" { t.Errorf("%s: after Format again the card is display %s, aria-expanded %s", name, c.Display, c.Expanded) } } // Short enough that the slide's options overflow the card (252px: // since Q2, Q5 and Q3 took the deck's options, the list of boxes and // the layout's fields out of the card, 380px is not). te.size(1280, 252) // From 320px the stacked bar's height is still published on the // root (estilo chrome.js's --estilo-bar-block-size) until the media // query's change event lands, a frame after the resize: until then // the bar is as tall as it was at 320px and the desk under it is // short. The card is measured once that is gone. te.rig.Run(waitFor(`document.documentElement.style.getPropertyValue('--estilo-bar-block-size') === ''`)) c := te.card() if c.ScrollH <= c.ClientH || c.Card.B > c.Desk.B-12+0.5 { t.Errorf("1280x252: the card holds %.0fpx in %.0fpx and ends at %.1f (desk %.1f); want it to scroll inside itself, 12px short of the foot", c.ScrollH, c.ClientH, c.Card.B, c.Desk.B) } var notes string te.rig.Run(evalInto(¬es, `(b => b.scrollHeight > b.clientHeight && getComputedStyle(b).overflowY === 'auto' ? '' : 'the notes body ' + b.clientHeight + 'px tall holds ' + b.scrollHeight + 'px and does not scroll')(document.querySelector('[slides-notes-body]'))`)) if notes != "" { t.Errorf("1280x252: %s", notes) } if got := te.scrolls(t); got != "" { t.Errorf("1280x252: the page scrolls: %s", got) } te.rig.Screen(`[slides-editor]`, "1280x252") } // focusJS says where focus is: the element's description, whether it is // drawn (a box, and not inside a closed
other than as its // summary), and whether it is in the card. const focusJS = `(() => { const a = document.activeElement if (!a || a === document.body) return {Where: 'body', Drawn: false, InCard: false} const r = a.getBoundingClientRect() const closed = a.closest('details:not([open])') const hidden = closed && !(a.matches('summary') && a.parentElement === closed) return { Where: a.matches('[slides-menu="view"] > summary') ? 'view menu' : a.matches('[estilo-bar-control] > [data-view-toggle="inspector"]') ? 'format' : a.outerHTML.slice(0, 80), Drawn: r.width > 0 && r.height > 0 && !hidden && a.checkVisibility(), InCard: !!a.closest('[slides-inspector]') } })()` type focusState struct { Where string Drawn, InCard bool } func (te *tidyEditor) focus() focusState { var f focusState te.rig.Run(evalInto(&f, focusJS)) return f } // tabTo presses Tab until the element sel has focus, at most n times. func (te *tidyEditor) tabTo(t *testing.T, sel string, n int) { t.Helper() for range n { var on bool te.rig.Run(evalInto(&on, `document.activeElement === document.querySelector('`+sel+`')`)) if on { return } te.rig.Run(chromedp.KeyEvent(kb.Tab)) } t.Fatalf("Tab never reached %s; focus is %+v", sel, te.focus()) } // TestTidyCardFocusReturns (spec §4.4): opened from the keyboard, the // card takes focus; dismissed, it gives focus back to where the action // came from, and that is somewhere a person can see. From the View // menu, that is the menu's own button (its summary): the Inspector row // is hidden once the menu closes. func TestTidyCardFocusReturns(t *testing.T) { te := openTidyEditor(t, 3, 1280, 720) te.pressFormat("closed") const viewMenu = `[slides-menu="view"] > summary` const row = `[estilo-menu-item][data-view-toggle="inspector"]` openFromView := func() { te.rig.Run( chromedp.Evaluate[chromedp.Void](`document.querySelector('`+viewMenu+`').focus()`), chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelector('[slides-menu="view"]').open`), ) te.tabTo(t, row, 12) te.rig.Run(chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelector('[slides-inspector]').dataset.state === 'open'`)) if f := te.focus(); !f.InCard || !f.Drawn { t.Fatalf("opened from View → Inspector by keyboard, focus is %+v; want it on a control in the card", f) } } // Dismissed with Format, from the keyboard. openFromView() te.rig.Run( chromedp.Evaluate[chromedp.Void](`document.querySelector('[estilo-bar-control] > [data-view-toggle="inspector"]').focus()`), chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelector('[slides-inspector]').dataset.state === 'closed'`), ) if f := te.focus(); f.Where != "view menu" || !f.Drawn { t.Errorf("dismissed with Format, focus is %+v; want the View menu's button, drawn", f) } // Dismissed with the View row again, from the keyboard. openFromView() te.rig.Run( chromedp.Evaluate[chromedp.Void](`document.querySelector('`+viewMenu+`').focus()`), chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelector('[slides-menu="view"]').open`), ) te.tabTo(t, row, 12) te.rig.Run(chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelector('[slides-inspector]').dataset.state === 'closed'`)) if f := te.focus(); f.Where != "view menu" || !f.Drawn { t.Errorf("dismissed with View → Inspector, focus is %+v; want the View menu's button, drawn", f) } } // inspectJS is what the card shows: data-inspect, which of the three // sections are drawn, the selected box's kind, and the card's named controls, drawn (Got) // and owed to that kind on this slide's layout by the Block form's own // data-types and data-layout marks (Want). const inspectJS = `(() => { const root = document.querySelector('[slides-editor]'), card = document.querySelector('[slides-inspector]') const form = s => card.querySelector('form[data-section="' + s + '"]') const drawn = el => !!el && el.checkVisibility() && el.getBoundingClientRect().height > 0 const sel = document.querySelector('[slides-stage] [slides-block][aria-selected="true"]') const kind = sel ? sel.dataset.block : '' const layout = document.querySelector('[slides-stage] [slides-slide]')?.dataset.layout || '' const got = [], want = [] for (const el of card.querySelectorAll('[name]')) if (el.checkVisibility()) got.push(el.name) for (const el of form('block').querySelectorAll('[name]')) { let ok = true for (let p = el; p && p !== form('block'); p = p.parentElement) { if (p.hasAttribute('data-types') && !p.getAttribute('data-types').split(' ').includes(kind)) ok = false if (p.hasAttribute('data-layout') && p.getAttribute('data-layout') !== layout) ok = false // A shape's field for some kinds alone (corner radius), and // Position and size, a group closed until it is opened (Q4). if (p.hasAttribute('data-kinds') && kind === 'shape' && !p.getAttribute('data-kinds').split(' ').includes(sel.dataset.kind || 'rect')) ok = false if (p.matches('details:not([open])') && el.parentElement !== p) ok = false } if (ok) want.push(el.name) } return { Inspect: root.dataset.inspect, Kind: kind, Box: drawn(form('block')), Slide: drawn(form('slide')), Deck: drawn(form('deck')), Got: got.sort(), Want: want.sort() } })()` type inspectState struct { Inspect, Kind string Box, Slide, Deck bool Got, Want []string } func (te *tidyEditor) inspect() inspectState { var s inspectState te.rig.Run(evalInto(&s, inspectJS)) return s } // onSlideOptions fails the test unless the card shows the slide's // options: the Slide section, and no box's. The deck's are not in the // card (the Deck settings dialog, Q2), nor the slide's boxes (View → // Outline, Q5). func (s inspectState) onSlideOptions(t *testing.T, after string) { t.Helper() if s.Inspect != "slide" || !s.Slide || s.Deck || s.Box { t.Errorf("after %s the card is %+v; want data-inspect=slide, the Slide section, and no box's or deck's", after, s) } } // selectBox clicks the box of this kind on the stage and waits until it // is the selection. func (te *tidyEditor) selectBox(kind string) { sel := `[slides-stage] [slides-block][data-block="` + kind + `"]` te.rig.Run( chromedp.Click(chromedp.CSS(sel)), waitFor(`document.querySelector('`+sel+`')?.getAttribute('aria-selected') === 'true'`), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`), ) } // openOn opens this editor afresh on a canvas slide (the hash; the // reload, because a new hash alone is not a new page), mounted: the // canvas overlay is on the stage. func (te *tidyEditor) openOn(slide string) { te.rig.Run( chromedp.Navigate(te.rig.Origin+te.path+"#"+slide), chromedp.Reload(), waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+slide+`'`), waitFor(`document.querySelector('[slides-stage] [slides-canvas-overlay]')`), ) } // editorShown is true once a newly opened editor is settled in the view // it will stay in: the remembered view (localStorage, shared by every // tab of the origin) is applied, and the font gate has lifted its hold // on the slide (html[data-slides-fonts="shown"]). Until then the slide // is drawn with visibility: hidden, which nothing can click: a click on // a box lands on the stage behind it. Both view holds longer than // Desktop, because the phone preview is fetched before the hold lifts. const editorShown = `document.documentElement.getAttribute('data-slides-fonts') === 'shown' && document.querySelector('[slides-stage-pane]').dataset.view === (localStorage.getItem('slides.editor.view') || 'desktop')` // addCanvasShape adds a canvas slide holding one shape to this editor's // deck, over the API, and returns the slide's id. func (te *tidyEditor) addCanvasShape(t *testing.T) string { t.Helper() sqid := strings.TrimSuffix(strings.TrimPrefix(te.path, "/d/"), "/edit") token := mintAgent(t, te.app, te.cookies, "canvas-shape") apiJSON(t, te.app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[{"op":"add_slide","layout":"canvas","template":"blank"}]}`, http.StatusOK) view := apiJSON(t, te.app, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK) slides, _ := view["slides"].([]any) canvas, _ := slides[len(slides)-1].(map[string]any)["id"].(string) apiJSON(t, te.app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[{"op":"add_block","slide":`+quote(canvas)+`,"type":"shape","props":{},"box":{"x":0.1,"y":0.1,"w":0.4,"h":0.3},"z":0,"markdown":"Shape"}]}`, http.StatusOK) return canvas } // clickNotes puts the caret in the notes, near the top of their card // (the notes can be longer than it), and waits for the card to say so. func (te *tidyEditor) clickNotes() { var at []float64 te.rig.Run( waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open'`), evalInto(&at, `(r => [r.left + 40, r.top + 12])(document.querySelector('[slides-notes]').getBoundingClientRect())`), ) te.rig.Run( chromedp.MouseClickXY(at[0], at[1]), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'notes'`), ) } // TestTidyCardFollowsSelection (spec §4.1, §4.2): the card shows one // thing, and this person's selection decides it. A box of each of the // twelve kinds shows exactly the named controls its kind has (read off // the form's own data-types); the caret in the notes shows none of the // slide's or the deck's options and no field of a box's; the desk, // a slide in the strip and Esc each bring back the slide's options. A // colleague selecting a box changes nothing here. func TestTidyCardFollowsSelection(t *testing.T) { var slide string te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string { var path string path, slide = deckWithEveryKind(t, a, cookies) return path }) te.inspect().onSlideOptions(t, "opening the editor") te.openOn(slide) te.inspect().onSlideOptions(t, "opening the canvas slide") // The On a phone group is in the card in the phone views alone (Q6), // and each kind's want list holds it: the test is in Both view. te.view("both") var kinds []string te.rig.Run(evalInto(&kinds, `[...document.querySelectorAll('[slides-menu="insert"] [data-insert-block]')].map(b => b.dataset.insertBlock)`)) if len(kinds) != 12 { t.Fatalf("the Insert menu lists %d kinds, want twelve: %v", len(kinds), kinds) } for _, kind := range kinds { te.selectBox(kind) s := te.inspect() if s.Kind != kind || !s.Box || s.Slide || s.Deck { t.Errorf("%s selected: the card is %+v; want the box's options alone", kind, s) } if strings.Join(s.Got, " ") != strings.Join(s.Want, " ") { t.Errorf("%s selected: the card's named controls are\n %v\nwant\n %v", kind, s.Got, s.Want) } if kind == "shape" { te.rig.Screen(`[slides-editor]`, "a shape selected, its options") } } // Corner radius is Style's, for an image and a shape alike (ruling // R16): a shape shows no Image group; an image's Image group holds // its file and fit. groupsJS := `(() => { const out = {} for (const g of document.querySelectorAll('[slides-inspector] form[data-section="block"] [data-group]')) { if (!g.checkVisibility()) continue // A group's label, or its disclosure's summary (Position and size, Q4). out[(g.querySelector('[estilo-inspector-label]') || g.querySelector('summary')).textContent.trim()] = [...g.querySelectorAll('[name]')].filter(el => el.checkVisibility()).map(el => el.name) } return out })()` for _, c := range []struct { kind string image []string // nil: no Image group drawn }{ {"shape", nil}, {"image", []string{"rst-block-image", "rst-block-fit", "rst-block-fit"}}, } { te.selectBox(c.kind) var groups map[string][]string te.rig.Run(evalInto(&groups, groupsJS)) image, shown := groups["Image"] if c.image == nil && shown { t.Errorf("%s selected: an Image group is drawn, holding %v; want none", c.kind, image) } if c.image != nil && strings.Join(image, " ") != strings.Join(c.image, " ") { t.Errorf("%s selected: the Image group holds %v, want %v", c.kind, image, c.image) } if !slicesHas(groups["Style"], "rst-block-radius") { t.Errorf("%s selected: Corner radius is not drawn in Style; the groups are %v", c.kind, groups) } } // Back to the same box from the notes: its options again, though // the selection itself never changed. te.selectBox("shape") te.clickNotes() te.selectBox("shape") if s := te.inspect(); s.Kind != "shape" || !s.Box || s.Slide || s.Deck { t.Errorf("the shape, the notes, the shape again: the card is %+v; want the shape's options", s) } // Esc in a box: one press, on a box with no caret and on one with // the caret in its text. te.selectBox("shape") te.rig.Run( chromedp.KeyEvent(kb.Escape), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), ) te.inspect().onSlideOptions(t, "Esc on a shape") te.selectBox("heading") te.rig.Run(waitFor(`document.activeElement.closest('[slides-block][data-block="heading"]')`)) te.rig.Run( chromedp.KeyEvent(kb.Escape), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), waitFor(`!document.querySelector('[slides-stage] [aria-selected="true"]')`), ) te.inspect().onSlideOptions(t, "one Esc with the caret in a heading") // Something transient takes the first Esc: the link prompt (Ctrl+K) // closes, and the box is still selected; the next Esc deselects it. te.selectBox("heading") te.rig.Run( waitFor(`document.activeElement.closest('[slides-block][data-block="heading"]')`), chromedp.KeyEvent("k", chromedp.KeyModifiers(chromedp.ModifierCtrl)), waitFor(`document.querySelector('dialog[open]')`), chromedp.KeyEvent(kb.Escape), waitFor(`!document.querySelector('dialog[open]')`), waitFor(`document.activeElement.closest('[slides-block][data-block="heading"]')`), // The dialog's close event is a task of its own, and the prompt // gives the caret back to the heading when it runs: a person's // next Esc comes after it, and so does this one. chromedp.Sleep(100*time.Millisecond), ) if s := te.inspect(); s.Inspect != "box" || s.Kind != "heading" { t.Errorf("Esc closing the link prompt left the card %+v; want the heading's options still", s) } te.rig.Run( chromedp.KeyEvent(kb.Escape), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), ) te.inspect().onSlideOptions(t, "Esc after the link prompt closed") // The desk: the slide's own ground (under the grid's last row, which // every one of the twelve kinds fills now), and the pane beside the // slide. for _, where := range []struct{ name, js string }{ {"a click on the slide's ground", `(r => [r.left + r.width * 0.88, r.top + r.height * 0.98])(document.querySelector('[slides-stage] [slides-slide]').getBoundingClientRect())`}, {"a click on the desk beside the slide", `((p, s) => [(p.left + s.left) / 2, (s.top + s.bottom) / 2])(document.querySelector('[slides-stage-pane]').getBoundingClientRect(), document.querySelector('[slides-stage] [slides-slide]').getBoundingClientRect())`}, } { te.selectBox("shape") var xy []float64 te.rig.Run(evalInto(&xy, where.js)) te.rig.Run( chromedp.MouseClickXY(xy[0], xy[1]), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), waitFor(`!document.querySelector('[slides-stage] [aria-selected="true"]')`), ) te.inspect().onSlideOptions(t, where.name) } // A slide in the strip, and back. te.selectBox("list") te.rig.Run( chromedp.Click(chromedp.CSS(`[slides-strip-item]:first-child [slides-strip-link]`)), waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.index === '0'`), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), ) te.inspect().onSlideOptions(t, "a slide picked in the strip") // View → Outline, from the keyboard: the box's options, and focus on // the box it chose (Q5; the card's list of boxes is gone). var focus struct { OnBox, Shown bool } te.rig.Run( openOutline(), chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`), evalInto(&focus, `(a => ({OnBox: !!a.closest('[slides-stage] [slides-block][aria-selected="true"]'), Shown: a.checkVisibility()}))(document.activeElement)`), ) if !focus.OnBox || !focus.Shown { t.Errorf("a box chosen from the Outline by keyboard leaves focus %+v; want it on that box", focus) } // The caret in the notes (a box still selected, from the Outline): // neither the slide's options nor the deck's, and none of the box's // fields (the Text group alone, TestTidyMarksInCard). te.clickNotes() if s := te.inspect(); s.Slide || s.Deck || len(s.Got) != 0 { t.Errorf("with the caret in the notes the card is %+v; want no slide or deck options and no named control", s) } te.rig.Screen(`[slides-editor]`, "the caret in the notes") // A colleague's change to this slide re-fetches the stage and // re-marks the selected box; that is not this person choosing it, // and the card stays on the notes. var first string te.rig.Run(evalInto(&first, `document.querySelector('[slides-stage] [slides-slide]').dataset.id`)) sqid := strings.TrimSuffix(strings.TrimPrefix(te.path, "/d/"), "/edit") token := mintAgent(t, te.app, te.cookies, "colleague") apiJSON(t, te.app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[{"op":"add_block","slide":`+quote(first)+`,"type":"text","region":"body","markdown":"From a colleague"}]}`, http.StatusOK) te.rig.Run(waitFor(`[...document.querySelectorAll('[slides-stage] [data-block="text"]')].some(b => b.textContent.includes('From a colleague'))`)) if s := te.inspect(); s.Inspect != "notes" { t.Errorf("after a colleague's change re-fetched the stage, the card is %+v; want it still on the notes", s) } // Escape on the notes: the slide's options. Once with the caret // gone (the refresh rebinds the notes and takes the caret with it), // once with it in the notes. te.rig.Run( chromedp.KeyEvent(kb.Escape), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), ) te.inspect().onSlideOptions(t, "Esc on the notes, the caret taken by a refresh") te.clickNotes() te.rig.Run( chromedp.KeyEvent(kb.Escape), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), ) te.inspect().onSlideOptions(t, "Esc in the notes") // A colleague's selection is theirs: a second tab on the canvas // slide selects a box; once it is drawn here, this card is as it was. te.openOn(slide) tab2, cancel := chromedp.NewContext(te.rig.Context()) defer cancel() runOn(t, tab2, chromedp.EmulateViewport(1280, 720), chromedp.Navigate(te.rig.Origin+te.path+"#"+slide), waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+slide+`'`), waitFor(editorShown), chromedp.Click(chromedp.CSS(`[slides-stage] [data-block="shape"]`)), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`), ) te.rig.Run(waitFor(`document.querySelector('[slides-presence-mark]')`)) te.inspect().onSlideOptions(t, "a colleague selected a box") } // TestTidyCardSurvivesBoxRemoval (Review Focus 2): the box this person // has selected is deleted by a colleague; within a second the card is // back on the slide's options, and never shows an empty box. func TestTidyCardSurvivesBoxRemoval(t *testing.T) { var slide string te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string { var path string path, slide = deckWithEveryKind(t, a, cookies) return path }) te.openOn(slide) te.selectBox("shape") tab2, cancel := chromedp.NewContext(te.rig.Context()) defer cancel() runOn(t, tab2, chromedp.EmulateViewport(1280, 720), chromedp.Navigate(te.rig.Origin+te.path+"#"+slide), waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+slide+`'`), waitFor(editorShown), chromedp.Click(chromedp.CSS(`[slides-stage] [data-block="shape"]`)), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`), ) // The clock starts at the press on Delete, in the box's menu (Q4), // over there. runOn(t, tab2, openBoxMenu()) start := time.Now() runOn(t, tab2, chromedp.Click(chromedp.CSS(`[slides-box-menu] [data-row="block-delete"]`))) te.rig.Run(waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide' && !document.querySelector('[slides-stage] [data-block="shape"]')`)) if took := time.Since(start); took > time.Second { t.Errorf("the card took %v to leave the deleted box, want under a second", took) } te.inspect().onSlideOptions(t, "a colleague deleted the selected box") te.rig.Screen(`[slides-editor]`, "the selected box deleted elsewhere") } // TestTidyEmptyDeck (Review Focus 4): a deck with no slides. The card // shows no section (the deck's options are the Deck settings dialog's // since Q2); the notes tab is disabled and the notes // card cannot open; New slide is pinned in view and adds a slide. func TestTidyEmptyDeck(t *testing.T) { 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, })) } rig.Run(set...) te := &tidyEditor{rig: rig, app: app, cookies: cookies, path: emptyDeck(t, app, cookies)} te.size(1280, 720) rig.Run( chromedp.Navigate(rig.Origin+te.path), chromedp.WaitVisible(chromedp.CSS(`[slides-stage-empty]`)), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), ) s := te.inspect() if s.Deck || s.Slide || s.Box { t.Errorf("with no slides the card is %+v; want no section (the deck's are the Deck settings dialog's)", s) } var notes struct { Disabled, PaneShown bool } rig.Run(evalInto(¬es, `({Disabled: document.querySelector('[slides-notes-open]').disabled, PaneShown: document.querySelector('[slides-notes-pane]').checkVisibility()})`)) if !notes.Disabled || notes.PaneShown { t.Errorf("with no slides the notes tab is disabled=%v and the notes card shown=%v; want disabled, not shown", notes.Disabled, notes.PaneShown) } // The View menu's Speaker notes row cannot bring the card up either. rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[data-view-toggle="notes"]').click()`)) rig.Run(evalInto(¬es.PaneShown, `document.querySelector('[slides-notes-pane]').checkVisibility()`)) if notes.PaneShown { t.Error("with no slides the View menu's Speaker notes row shows the notes card") } rig.Screen(`[slides-editor]`, "an empty deck") const pill = `[slides-strip-add] > button:first-child` var inView bool rig.Run(evalInto(&inView, `(r => r.width > 0 && r.top >= 0 && r.bottom <= innerHeight)(document.querySelector('`+pill+`').getBoundingClientRect())`)) if !inView { t.Error("with no slides New slide is not in view") } rig.Run( chromedp.Click(chromedp.CSS(pill)), waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 1`), waitFor(`document.querySelector('[slides-stage] [slides-slide]')`), waitFor(`!document.querySelector('[slides-notes-open]').disabled`), ) te.inspect().onSlideOptions(t, "New slide in an empty deck") } // marksJS is the card's Text group as a person meets it: each mark's // pressed and disabled state and whether it is drawn, the groups and // named controls drawn, whether the slide's and the deck's options // show, and whether the stage bar still has marks. const marksJS = `(() => { const card = document.querySelector('[slides-inspector]') const drawn = el => !!el && el.checkVisibility() && el.getBoundingClientRect().height > 0 const marks = {} for (const b of card.querySelectorAll('[data-mark]')) marks[b.dataset.mark] = {Pressed: b.getAttribute('aria-pressed') === 'true', Disabled: b.disabled, Drawn: drawn(b)} return { Inspect: document.querySelector('[slides-editor]').dataset.inspect, Marks: marks, Groups: [...card.querySelectorAll('[data-group]')].filter(drawn).map(g => g.dataset.group), Named: [...card.querySelectorAll('[name]')].filter(el => el.checkVisibility()).map(el => el.name), Slide: drawn(card.querySelector('form[data-section="slide"]')), Deck: drawn(card.querySelector('form[data-section="deck"]')), Bar: !!document.querySelector('[slides-stage-bar] [data-mark]') } })()` type markState struct{ Pressed, Disabled, Drawn bool } type marksState struct { Inspect string Marks map[string]markState Groups []string Named []string Slide, Deck bool Bar bool } func (te *tidyEditor) marks() marksState { var s marksState te.rig.Run(evalInto(&s, marksJS)) return s } // TestTidyMarksInCard (spec E3, §4.2): the five marks are the card's // Text group. With the caret in a box's text and in the notes, each // toggles its mark, shows it pressed, and leaves the caret in the text; // the shortcuts still work; before any text has had the caret they are // disabled, as the pill's were; a box with no text has no Text group; // and the caret in the notes shows the Text group and nothing else. func TestTidyMarksInCard(t *testing.T) { var slide string te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string { var path string path, slide = deckWithEveryKind(t, a, cookies) return path }) te.openOn(slide) if s := te.marks(); s.Bar || len(s.Marks) != 5 { t.Fatalf("the card holds marks %v and the stage bar has marks: %v; want five in the card and none on the bar", s.Marks, s.Bar) } // No text has had the caret yet: the heading selected by its address // (#slide/box, which selects without the caret; the Outline puts the // caret in a heading) shows the Text group, its marks disabled. var heading string te.rig.Run(evalInto(&heading, `document.querySelector('[slides-stage] [data-block="heading"]').dataset.id`)) te.rig.Run( chromedp.Evaluate[chromedp.Void](`location.hash = '`+slide+`/`+heading+`'`), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`), ) s := te.marks() for m, st := range s.Marks { if !st.Drawn || !st.Disabled { t.Errorf("a heading selected before any text had the caret: mark %s is %+v; want drawn and disabled", m, st) } } // A box with no text has no Text group. te.selectBox("image") if s := te.marks(); slicesHas(s.Groups, "text") { t.Errorf("an image selected: the card's groups are %v; want no Text group", s.Groups) } const inHeading = `document.activeElement.closest('[slides-stage] [data-block="heading"]')` const headingEl = `document.querySelector('[slides-stage] [data-block="heading"]')` tags := map[string]string{"b": "strong", "i": "em", "c": "code", "h": "mark"} keys := map[string]chromedp.Action[chromedp.Void]{ "b": modKey("b", chromedp.ModifierCtrl), "i": modKey("i", chromedp.ModifierCtrl), "c": modKey("e", chromedp.ModifierCtrl), "h": modKey("H", chromedp.ModifierCtrl|chromedp.ModifierShift), } pressed := func(m string) string { return `document.querySelector('[slides-inspector] [data-mark="` + m + `"]').getAttribute('aria-pressed') === 'true'` } // In a box: the heading, its words selected. te.selectBox("heading") te.rig.Run(waitFor(inHeading), modKey("a", chromedp.ModifierCtrl)) s = te.marks() if s.Inspect != "box" || !slicesHas(s.Groups, "text") { t.Fatalf("the caret in the heading: the card is %+v; want the heading's options with its Text group", s) } for _, m := range []string{"b", "i", "c", "h"} { te.rig.Run( chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="`+m+`"]`)), waitFor(headingEl+`.querySelector('`+tags[m]+`')`), waitFor(pressed(m)), ) var in bool te.rig.Run(evalInto(&in, `!!`+inHeading)) if !in { t.Errorf("clicking the %s mark in the card took the caret out of the heading", m) } } te.rig.Screen(`[slides-editor]`, "the heading's marks, pressed in the card") // The link: the button opens the link prompt, as Mod+K does. te.rig.Run( chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="href"]`)), waitFor(`document.querySelector('[slides-link-dialog]').open`), chromedp.SendKeys(chromedp.CSS(`#slides-link-url`), "https://example.test/"), chromedp.KeyEvent(kb.Enter), waitFor(`!document.querySelector('[slides-link-dialog]').open`), waitFor(headingEl+`.querySelector('a[href="https://example.test/"]')`), waitFor(pressed("href")), ) // The shortcuts take each off again. te.rig.Run(chromedp.Focus(chromedp.CSS(`[slides-stage] [data-block="heading"] [contenteditable="true"], [slides-stage] [data-block="heading"][contenteditable="true"]`)), waitFor(inHeading), modKey("a", chromedp.ModifierCtrl)) for _, m := range []string{"b", "i", "c", "h"} { te.rig.Run( keys[m], waitFor(`!`+headingEl+`.querySelector('`+tags[m]+`')`), waitFor(`!(`+pressed(m)+`)`), ) } te.rig.Run( modKey("k", chromedp.ModifierCtrl), waitFor(`document.querySelector('[slides-link-dialog]').open`), chromedp.Click(chromedp.CSS(`[slides-link-dialog] button[value="remove"]`)), waitFor(`!`+headingEl+`.querySelector('a')`), waitFor(`!(`+pressed("href")+`)`), ) // The code block: the marks act there as the pill's did. te.rig.Run( chromedp.Click(chromedp.CSS(`[slides-stage] [data-block="code"] code`)), waitFor(`document.activeElement.closest('[slides-stage] [data-block="code"]')`), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`), modKey("a", chromedp.ModifierCtrl), chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="b"]`)), waitFor(`document.querySelector('[slides-stage] [data-block="code"] strong')`), waitFor(pressed("b")), modKey("b", chromedp.ModifierCtrl), waitFor(`!document.querySelector('[slides-stage] [data-block="code"] strong')`), ) // In the notes: the Text group and nothing else. te.clickNotes() s = te.marks() if strings.Join(s.Groups, " ") != "text" || len(s.Named) != 0 || s.Slide || s.Deck { t.Errorf("the caret in the notes: the card is %+v; want the Text group alone", s) } for m, st := range s.Marks { if !st.Drawn || st.Disabled { t.Errorf("the caret in the notes: mark %s is %+v; want drawn and enabled", m, st) } } te.rig.Screen(`[slides-editor]`, "the caret in the notes, the Text group alone") const inNotes = `document.activeElement.closest('[slides-notes]')` te.rig.Run( chromedp.KeyEvent("Spoken words"), waitFor(`document.querySelector('[slides-notes]').textContent.includes('Spoken words')`), modKey("a", chromedp.ModifierCtrl), ) for _, m := range []string{"b", "i", "c", "h"} { te.rig.Run( chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="`+m+`"]`)), waitFor(`document.querySelector('[slides-notes]').querySelector('`+tags[m]+`')`), waitFor(pressed(m)), ) var in bool te.rig.Run(evalInto(&in, `!!`+inNotes)) if !in { t.Errorf("clicking the %s mark in the card took the caret out of the notes", m) } te.rig.Run( keys[m], waitFor(`!document.querySelector('[slides-notes]').querySelector('`+tags[m]+`')`), ) } // The link in the notes: put on with the card's button and taken off // with Mod+K, then put on with Mod+K and taken off with the button. const notesLink = `document.querySelector('[slides-notes] a[href="https://example.test/notes"]')` link := func(open chromedp.Action[chromedp.Void], how string) { t.Helper() te.rig.Run( open, waitFor(`document.querySelector('[slides-link-dialog]').open`), chromedp.SendKeys(chromedp.CSS(`#slides-link-url`), "https://example.test/notes"), chromedp.KeyEvent(kb.Enter), waitFor(`!document.querySelector('[slides-link-dialog]').open`), waitFor(notesLink), waitFor(pressed("href")), ) var in bool te.rig.Run(evalInto(&in, `!!`+inNotes)) if !in { t.Errorf("a link put on the notes with %s left the caret out of the notes", how) } } unlink := func(open chromedp.Action[chromedp.Void]) { t.Helper() te.rig.Run( open, waitFor(`document.querySelector('[slides-link-dialog]').open`), chromedp.Click(chromedp.CSS(`[slides-link-dialog] button[value="remove"]`)), waitFor(`!document.querySelector('[slides-notes] a')`), waitFor(`!(`+pressed("href")+`)`), ) } button := chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="href"]`)) modK := modKey("k", chromedp.ModifierCtrl) link(button, "the card's button") unlink(modK) link(modK, "Mod+K") unlink(button) if s := te.marks(); s.Inspect != "notes" { t.Errorf("after the marks in the notes the card is on %q, want notes", s.Inspect) } } func slicesHas(s []string, v string) bool { for _, x := range s { if x == v { return true } } return false } // TestTidyKeyboardOnlyBox is TestQuieterKeyboardOnlyShape now // (browser_quieter_box_test.go): the shape is changed and deleted from // its menu and its keys, Delete block having left the card (Q4). // TestTidyDeleteSlideConfirmsInCard (spec E10, §4.3, §4.4): with the // card hidden, Delete slide from the Slide menu and from a slide's own // menu in the strip each show the card on the slide's options with // focus on the confirmation. Cancel leaves the card showing, deletes // nothing and gives focus back to the menu it came from; Delete deletes. func TestTidyDeleteSlideConfirmsInCard(t *testing.T) { te := openTidyEditor(t, 3, 1280, 720) count := func() int { var n int te.rig.Run(evalInto(&n, `document.querySelectorAll('[slides-strip-item][data-slide-id]').length`)) return n } const confirmDelete = `[slides-inspector] [slides-confirm] [data-command="slide-delete"]` asked := func(from string) { t.Helper() te.rig.Run( waitFor(`document.querySelector('[slides-inspector]').dataset.state === 'open'`), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), waitFor(`!document.querySelector('[slides-inspector] [slides-confirm]').hidden`), ) var on bool te.rig.Run(evalInto(&on, `document.activeElement === document.querySelector('`+confirmDelete+`') && document.activeElement.checkVisibility()`)) if !on { t.Errorf("%s: focus is %+v; want the confirmation's Delete", from, te.focus()) } } cancel := func(from, back string) { t.Helper() te.rig.Run( chromedp.KeyEvent(kb.Tab), waitFor(`document.activeElement.matches('[slides-confirm] [data-command="slide-delete-cancel"]')`), chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelector('[slides-inspector] [slides-confirm]').hidden`), ) if c := te.card(); c.State != "open" { t.Errorf("%s, Cancel: the card is %s; want it still showing", from, c.State) } if n := count(); n != 3 { t.Errorf("%s, Cancel: the deck has %d slides, want 3", from, n) } var on bool te.rig.Run(evalInto(&on, `document.activeElement === document.querySelector('`+back+`') && document.activeElement.checkVisibility()`)) if !on { t.Errorf("%s, Cancel: focus is %+v; want %s", from, te.focus(), back) } } // The Slide menu. te.pressFormat("closed") const slideMenu = `[slides-menu="slide"] > summary` te.rig.Run( chromedp.Click(chromedp.CSS(slideMenu)), waitFor(`document.querySelector('[slides-menu="slide"]').open`), chromedp.Click(chromedp.CSS(`[slides-menu="slide"] [data-command="slide-delete-ask"]`)), ) asked("Slide → Delete slide") te.rig.Screen(`[slides-editor]`, "Delete slide asks in the card") cancel("Slide → Delete slide", slideMenu) // A slide's own menu in the strip: the second slide's. te.pressFormat("closed") const stripMenu = `[slides-strip-item][data-slide-id]:nth-child(2) [slides-strip-menu] > summary` te.rig.Run( chromedp.Click(chromedp.CSS(stripMenu)), chromedp.Click(chromedp.CSS(`[slides-strip-item][data-slide-id]:nth-child(2) [data-slide-command="delete"]`)), waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.index === '1'`), ) asked("the strip's Delete") cancel("the strip's Delete", stripMenu) // Delete deletes. te.pressFormat("closed") te.rig.Run( chromedp.Click(chromedp.CSS(stripMenu)), chromedp.Click(chromedp.CSS(`[slides-strip-item][data-slide-id]:nth-child(2) [data-slide-command="delete"]`)), ) asked("the strip's Delete, again") te.rig.Run( chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 2`), ) } // headingOnlyTitleDeck is a deck of one slide, a `title` slide with a // heading and nothing under it; it returns the deck's editor path. func headingOnlyTitleDeck(t *testing.T) func(a *testApp, cookies []*http.Cookie) string { return func(a *testApp, cookies []*http.Cookie) string { token := mintAgent(t, a, cookies, "cover") sqid := apiDeck(t, a, token, "Cover") view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK) slides, _ := view["slides"].([]any) ops := []string{ `{"op":"add_slide","id":"slidecover01","layout":"flow","template":"title"}`, `{"op":"add_block","slide":"slidecover01","type":"heading","region":"heading","markdown":"A heading alone"}`, } for _, s := range slides { id, _ := s.(map[string]any)["id"].(string) ops = append(ops, `{"op":"remove_slide","id":`+quote(id)+`}`) } apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) return "/d/" + sqid + "/edit" } } // coverState is a deck tile's cover on the deck list: the picture's // box in its cover's, and where the slide's text falls in the picture. type coverState struct { Err string Img, Cover edges Text edges // the union of the SVG's boxes, in its viewBox units FrameW, FrameH float64 Texts int } // TestTidyCoverIsCentred (spec §3): a deck's cover shows its first // slide centred. For a `title` slide with a heading alone, the // heading in the cover's picture (the thumbnail SVG, inlined so its // text can be measured) is where the slide's own page puts it — the // editor's stage, the truth the picture is of — within 0.5% each way; // that is the middle across, and half the frame's row gap above the // middle down (slides.css keeps the empty body row and the gap beside // it, so `align-content: center` centres the heading and that gap, // 2% of the frame). And the picture is centred in the cover within a // pixel. func TestTidyCoverIsCentred(t *testing.T) { te := openTidyEditorOn(t, 1280, 800, headingOnlyTitleDeck(t)) // The slide's own page: the heading's box in the frame, and the // frame's row gap, in the 1920×1080 the picture is drawn at. var stage struct{ L, T, R, B, Gap float64 } te.rig.Run(evalInto(&stage, `(() => { const s = document.querySelector('[slides-stage] [slides-slide]') const sr = s.getBoundingClientRect(), k = 1920 / sr.width const h = s.querySelector('[data-region="heading"] [slides-block]').getBoundingClientRect() return {L: (h.left - sr.left) * k, T: (h.top - sr.top) * k, R: (h.right - sr.left) * k, B: (h.bottom - sr.top) * k, Gap: parseFloat(getComputedStyle(s.querySelector('[slides-frame]')).rowGap) * k} })()`)) if want := 540 - stage.Gap/2; math.Abs((stage.T+stage.B)/2-want) > 0.005*1080 { t.Fatalf("on the stage the heading's centre is %.1f, want %.1f (the middle less half the %.1f gap): the stylesheet has changed under this test", (stage.T+stage.B)/2, want, stage.Gap) } te.rig.Run( chromedp.Navigate(te.rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`[slides-tile][href="`+te.path+`"] [slides-cover] img`)), waitFor(`document.querySelector('[slides-tile][href="`+te.path+`"] [slides-cover] img').complete`), ) var c coverState te.rig.Run(evalInto(&c, `(async () => { const img = document.querySelector('[slides-tile][href="`+te.path+`"] [slides-cover] img') const box = e => { const r = e.getBoundingClientRect(); return {L: r.left, T: r.top, R: r.right, B: r.bottom, W: r.width, H: r.height} } const res = await fetch(img.src) if (!res.ok) return {Err: 'GET ' + img.src + ': ' + res.status} const doc = new DOMParser().parseFromString(await res.text(), 'image/svg+xml') const svg = document.importNode(doc.documentElement, true) const holder = document.createElement('div') holder.style.cssText = 'position:fixed;left:0;top:0;width:480px;height:270px' svg.setAttribute('width', '480'); svg.setAttribute('height', '270') holder.append(svg); document.body.append(holder) const vb = svg.viewBox.baseVal let L = Infinity, T = Infinity, R = -Infinity, B = -Infinity const texts = svg.querySelectorAll('text') for (const el of texts) { const b = el.getBBox() if (!b.width) continue L = Math.min(L, b.x); T = Math.min(T, b.y); R = Math.max(R, b.x + b.width); B = Math.max(B, b.y + b.height) } holder.remove() return {Img: box(img), Cover: box(img.parentElement), Text: {L, T, R, B, W: R - L, H: B - T}, FrameW: vb.width, FrameH: vb.height, Texts: texts.length} })()`, func(p *runtime.EvaluateParams) { p.AwaitPromise = new(true) })) if c.Err != "" { t.Fatal(c.Err) } if c.Texts == 0 || c.FrameW != 1920 || c.FrameH != 1080 { t.Fatalf("the cover's picture has %d in a %.0f×%.0f frame; want text in 1920×1080", c.Texts, c.FrameW, c.FrameH) } te.rig.Screen(`[slides-tile][href="`+te.path+`"]`, "the cover of a title slide with a heading alone") cx, cy := (c.Text.L+c.Text.R)/2, (c.Text.T+c.Text.B)/2 if dx := math.Abs(cx - 960); dx > 0.005*1920 { t.Errorf("in the cover's picture the heading's centre is %.1f across, %.1f off the middle; want within 0.5%%: text %+v", cx, dx, c.Text) } // Compared with the stage, not the frame's midpoint: a lone heading sits half a gap above the middle on the slide itself, and moving it would change how slides render, which this slice does not do (ruling R18; an open question for Paul). if want, dy := (stage.T+stage.B)/2, math.Abs(cy-(stage.T+stage.B)/2); dy > 0.005*1080 { t.Errorf("in the cover's picture the heading's centre is %.1f down; the slide's own page puts it at %.1f (%.1f off, %.1f%%; want within 0.5%%): text %+v, stage %+v", cy, want, dy, 100*dy/1080, c.Text, stage) } if d := math.Abs((c.Img.L + c.Img.R - c.Cover.L - c.Cover.R) / 2); d > 1 { t.Errorf("the picture is %.1fpx off the cover's middle across: img %+v, cover %+v", d, c.Img, c.Cover) } if d := math.Abs((c.Img.T + c.Img.B - c.Cover.T - c.Cover.B) / 2); d > 1 { t.Errorf("the picture is %.1fpx off the cover's middle down: img %+v, cover %+v", d, c.Img, c.Cover) } } // barState is the bar's buttons as drawn: each one's box, fill and // border, and the history pill's. type barState struct { Undo, Redo, History, Format, Share, Present edges FormatBg, ShareBg, PresentBg, PageBg string ShareBorder, PresentRadius string HistoryOutline string WinW float64 } const barJS = `(() => { const q = s => document.querySelector(s) const box = e => { const r = e.getBoundingClientRect(); return {L: r.left, T: r.top, R: r.right, B: r.bottom, W: r.width, H: r.height} } const cs = e => getComputedStyle(e) const undo = q('[slides-history] [data-command="undo"]'), redo = q('[slides-history] [data-command="redo"]') const format = q('[slides-head-end] [data-view-toggle="inspector"]'), share = q('[slides-head-share]'), present = q('[slides-present-form] button') return {Undo: box(undo), Redo: box(redo), History: box(q('[slides-history]')), Format: box(format), Share: box(share), Present: box(present), FormatBg: cs(format).backgroundColor, ShareBg: cs(share).backgroundColor, PresentBg: cs(present).backgroundColor, PageBg: cs(q('[slides-head]')).backgroundColor, ShareBorder: [cs(share).borderTopWidth, cs(share).borderRightWidth, cs(share).borderBottomWidth, cs(share).borderLeftWidth].join(' '), PresentRadius: cs(present).borderTopLeftRadius, HistoryOutline: cs(q('[slides-history]')).outlineWidth + ' ' + cs(q('[slides-history]')).outlineStyle, WinW: innerWidth} })()` // TestTidyBarPills (spec §2): from 800px the bar's buttons are estilo's // 28px pills — Format tinted while its card shows, Share… estilo's // plain pill (no border, as in Docs), // Present filled — and undo and redo are one pill: two buttons side by // side with no gap, one outline round the pair, each at least 24×24. // Narrower, every one of them is still there and at least 24×24. func TestTidyBarPills(t *testing.T) { te := openTidyEditor(t, 2, 1280, 800) var b barState te.rig.Run(evalInto(&b, barJS)) te.rig.Screen(`[slides-head]`, "1280, the bar") for name, e := range map[string]edges{"Format": b.Format, "Share": b.Share, "Present": b.Present} { if math.Abs(e.H-28) > 0.5 { t.Errorf("1280: %s is %.1fpx tall; want estilo's 28px pill", name, e.H) } } if b.FormatBg == "rgba(0, 0, 0, 0)" { t.Errorf("1280: Format, its card shown, has no tint") } if b.ShareBorder != "0px 0px 0px 0px" || b.ShareBg != "rgba(0, 0, 0, 0)" { t.Errorf("1280: Share's border is %q and its fill %s; want estilo's plain pill as in Docs: no border, transparent at rest", b.ShareBorder, b.ShareBg) } if b.PresentBg == "rgba(0, 0, 0, 0)" || b.PresentBg == b.PageBg { t.Errorf("1280: Present's fill is %s on a %s bar; want it filled", b.PresentBg, b.PageBg) } if b.PresentRadius != "999px" { t.Errorf("1280: Present's radius is %s; want estilo's pill", b.PresentRadius) } if gap := b.Redo.L - b.Undo.R; math.Abs(gap) > 0.5 || b.Undo.T != b.Redo.T || b.Undo.H != b.Redo.H { t.Errorf("1280: undo %+v and redo %+v are not one pill (gap %.1f)", b.Undo, b.Redo, gap) } if !strings.HasSuffix(b.HistoryOutline, " none") || math.Abs(b.History.H-28) > 0.5 { t.Errorf("1280: the history pill is %.1fpx tall with outline %q; want 28px and Docs' soft pill, no outline", b.History.H, b.HistoryOutline) } for _, w := range []int64{1280, 700, 320} { te.size(w, 800) te.rig.Run(evalInto(&b, barJS)) for name, e := range map[string]edges{"undo": b.Undo, "redo": b.Redo, "Format": b.Format, "Share": b.Share, "Present": b.Present} { if e.W < 24 || e.H < 24 || e.L < 0 || e.R > b.WinW+0.5 { t.Errorf("%d: %s is %+v; want it on screen and at least 24×24", w, name, e) } } te.rig.Screen(`[slides-head]`, fmt.Sprintf("%d, the bar", w)) } } // TestTidyDeleteAnotherSlideWithABoxSelected (final review, finding 1): // a box is selected on slide A, and Delete is chosen from slide B's own // menu in the strip. Slide B is on the stage, the hash names B, the // confirmation asks about B, and confirming deletes B and keeps A. func TestTidyDeleteAnotherSlideWithABoxSelected(t *testing.T) { te := openTidyEditor(t, 3, 1280, 720) ids, _ := te.slideIDs() if len(ids) != 3 { t.Fatalf("the deck has slides %v, want 3", ids) } a, b := ids[0], ids[1] te.selectBox("heading") const stripMenu = `[slides-strip-item][data-slide-id]:nth-child(2) [slides-strip-menu] > summary` te.rig.Run( chromedp.Click(chromedp.CSS(stripMenu)), chromedp.Click(chromedp.CSS(`[slides-strip-item][data-slide-id]:nth-child(2) [data-slide-command="delete"]`)), waitFor(`!document.querySelector('[slides-inspector] [slides-confirm]').hidden`), ) var got struct { Shown, Hash, Inspect string Selected bool } // Give a late hash write and its hashchange the time they would take. te.rig.Run( chromedp.Sleep(300*time.Millisecond), evalInto(&got, `({Shown: document.querySelector('[slides-stage] [slides-slide]')?.dataset.id || '', Hash: location.hash, Inspect: document.querySelector('[slides-editor]').dataset.inspect, Selected: !!document.querySelector('[slides-stage] [aria-selected="true"]')})`), ) if got.Shown != b || got.Hash != "#"+b || got.Inspect != "slide" || got.Selected { t.Errorf("a box selected on slide A (%s), Delete from slide B's (%s) strip menu: the stage shows %s, the hash is %q, the card is %q, a box selected=%v; want B shown and named, the slide's options, nothing selected", a, b, got.Shown, got.Hash, got.Inspect, got.Selected) } te.rig.Run( chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 2`), ) left, _ := te.slideIDs() if slicesHas(left, b) || !slicesHas(left, a) { t.Errorf("confirming deleted the wrong slide: %v are left; want B (%s) gone and A (%s) kept", left, b, a) } } // editorOf is a selector for the text editor of the box of this kind on // the stage: the box itself, or the element inside it the view mounts on. func editorOf(kind string) string { return `[slides-stage] [data-block="` + kind + `"][contenteditable="true"], [slides-stage] [data-block="` + kind + `"] [contenteditable="true"]` } // TestTidyMarksActOnTheCardsBox (final review, finding 2): the marks act // on the box the card shows and on no other. Text typed in box A, then // heading B selected by its address: the card shows B, and its marks // are disabled (they would have acted on A). A press on Bold changes // nothing. The caret put in B, Bold makes B's words bold and leaves A's. func TestTidyMarksActOnTheCardsBox(t *testing.T) { var slide string te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string { var path string path, slide = deckWithEveryKind(t, a, cookies) return path }) te.openOn(slide) const textEl = `document.querySelector('[slides-stage] [data-block="text"]')` const headingEl = `document.querySelector('[slides-stage] [data-block="heading"]')` var heading string te.rig.Run(evalInto(&heading, headingEl+`.dataset.id`)) // A: the text box, typed in and its words selected. te.selectBox("text") te.rig.Run( waitFor(`document.activeElement.closest('[slides-stage] [data-block="text"]')`), chromedp.KeyEvent(" more"), waitFor(textEl+`.textContent.includes('more')`), modKey("a", chromedp.ModifierCtrl), ) // Back to the slide's options, and B, the heading, by its address // (#slide/box), which selects it without the caret. te.rig.Run( chromedp.KeyEvent(kb.Escape), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`), chromedp.Evaluate[chromedp.Void](`location.hash = '`+slide+`/`+heading+`'`), waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`), waitFor(headingEl+`.getAttribute('aria-selected') === 'true'`), ) s := te.marks() for m, st := range s.Marks { if !st.Drawn || !st.Disabled { t.Errorf("text typed in a text box, then the heading selected: mark %s is %+v; want drawn and disabled", m, st) } } // A press anyway (a click on a disabled button does nothing; this is // the button's own click, as a stale target would have heard it). te.rig.Run( chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-inspector] [data-mark="b"]').click()`), chromedp.Sleep(200*time.Millisecond), ) var bold struct{ A, B bool } read := `({A: !!` + textEl + `.querySelector('strong'), B: !!` + headingEl + `.querySelector('strong')})` te.rig.Run(evalInto(&bold, read)) if bold.A || bold.B { t.Errorf("Bold pressed with the heading's options shown and no caret in it: text bold=%v, heading bold=%v; want neither changed", bold.A, bold.B) } // The caret in B: Bold is B's. te.rig.Run( chromedp.Focus(chromedp.CSS(editorOf("heading"))), waitFor(`document.activeElement.closest('[slides-stage] [data-block="heading"]')`), modKey("a", chromedp.ModifierCtrl), waitFor(`!document.querySelector('[slides-inspector] [data-mark="b"]').disabled`), chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="b"]`)), waitFor(headingEl+`.querySelector('strong')`), ) te.rig.Run(evalInto(&bold, read)) if bold.A || !bold.B { t.Errorf("the caret in the heading, Bold: text bold=%v, heading bold=%v; want the heading bold and the text not", bold.A, bold.B) } } // TestTidyFocusSelectsTheBox (final review, finding 3): a box's text // taking focus by any means makes that box the selection. Tab into the // heading's text with no click, then on to the next text box, then // on to a table's cell: the card shows each box's options in turn (the // table's for its cell), with the marks enabled for it. func TestTidyFocusSelectsTheBox(t *testing.T) { var slide string te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string { var path string path, slide = deckWithEveryKind(t, a, cookies) return path }) te.openOn(slide) te.inspect().onSlideOptions(t, "opening the canvas slide") check := func(kind, how string) { t.Helper() te.rig.Run(chromedp.Sleep(100 * time.Millisecond)) s := te.inspect() if s.Inspect != "box" || s.Kind != kind || !s.Box { t.Errorf("%s: the card is %+v; want the %s's options", how, s, kind) } for m, st := range te.marks().Marks { if !st.Drawn || st.Disabled { t.Errorf("%s: mark %s is %+v; want drawn and enabled", how, m, st) } } } te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.activeElement.blur()`)) te.tabTo(t, editorOf("heading"), 80) check("heading", "Tab into the heading's text") te.tabTo(t, `[slides-stage] [data-block="text"]`, 6) check("text", "Tab on to the text box") // With a box already selected, Tab on to a table's cell. te.tabTo(t, `[slides-stage] [data-block="table"] td, [slides-stage] [data-block="table"] th`, 40) check("table", "Tab on to a table's cell") } // TestTidyLastSlideRemovedFromTheNotes (final review, finding 4): this // person has the caret in the notes of a deck's only slide when a // colleague, in another tab, deletes that slide. The card goes to the // slide's options, which an empty deck does not draw (and the deck's // are the Deck settings dialog's since Q2): data-inspect is slide, no // section shows, and no mark is drawn. func TestTidyLastSlideRemovedFromTheNotes(t *testing.T) { te := openTidyEditor(t, 1, 1280, 720) te.clickNotes() tab2, cancel := chromedp.NewContext(te.rig.Context()) defer cancel() runOn(t, tab2, chromedp.EmulateViewport(1280, 720), chromedp.Navigate(te.rig.Origin+te.path), waitFor(editorBound), chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-menu="slide"] [data-command="slide-delete-ask"]').click()`), waitFor(`!document.querySelector('[slides-inspector] [slides-confirm]').hidden`), chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-inspector] [slides-confirm] [data-command="slide-delete"]').click()`), waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 0`), ) te.rig.Run( waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 0`), waitFor(`!document.querySelector('[slides-stage] [slides-slide]')`), chromedp.Sleep(200*time.Millisecond), ) s := te.inspect() m := te.marks() drawn := 0 for _, st := range m.Marks { if st.Drawn { drawn++ } } if s.Inspect != "slide" || s.Deck || s.Slide || s.Box || drawn != 0 { t.Errorf("the last slide removed by a colleague while the caret was in its notes: the card is %+v with %d marks drawn; want data-inspect=slide, no section, no marks", s, drawn) } } // fitJS is the desktop slide against the room it has: the slide's own // rect, the stage's (the visible stage area), the notes card's top (or // null when it is not drawn) and the inspector card's left (null when // hidden), the stage's scroll and client heights, and its width over // its height. const fitJS = `(() => { const q = s => document.querySelector(s) const drawn = el => !!el && el.checkVisibility() && el.getBoundingClientRect().height > 0 const box = el => { const r = el.getBoundingClientRect(); return {L: r.left, T: r.top, R: r.right, B: r.bottom, W: r.width, H: r.height} } const stage = q('[slides-stage]'), slide = q('[slides-stage] > [slides-slide]') const notes = q('[slides-notes-pane]'), card = q('[slides-inspector]') return { Slide: box(slide), Stage: box(stage), NotesTop: drawn(notes) ? notes.getBoundingClientRect().top : -1, CardLeft: drawn(card) ? card.getBoundingClientRect().left : -1, ScrollH: stage.scrollHeight, ClientH: stage.clientHeight, ScrollW: stage.scrollWidth, ClientW: stage.clientWidth } })()` type fitState struct { Slide, Stage edges4 NotesTop, CardLeft float64 ScrollH, ClientH, ScrollW, ClientW float64 } // fits says how the slide fails to fit its room; "" is the pass. func (f fitState) fits() string { var out []string const e = 0.5 if f.Slide.L < f.Stage.L-e || f.Slide.T < f.Stage.T-e || f.Slide.R > f.Stage.R+e || f.Slide.B > f.Stage.B+e { out = append(out, fmt.Sprintf("the slide %+v is not inside the stage %+v", f.Slide, f.Stage)) } if f.NotesTop >= 0 && f.Slide.B > f.NotesTop+e { out = append(out, fmt.Sprintf("the slide ends at %.1f, under the notes card's top %.1f", f.Slide.B, f.NotesTop)) } if f.CardLeft >= 0 && f.Slide.R > f.CardLeft+e { out = append(out, fmt.Sprintf("the slide ends at %.1f, under the inspector card's left %.1f", f.Slide.R, f.CardLeft)) } if f.Slide.H <= 0 || math.Abs(f.Slide.W/f.Slide.H-16.0/9)/(16.0/9) > 0.01 { out = append(out, fmt.Sprintf("the slide is %.1f×%.1f, not 16:9 within 1%%", f.Slide.W, f.Slide.H)) } if f.ScrollH != f.ClientH { out = append(out, fmt.Sprintf("the stage scrolls: scrollHeight %g, clientHeight %g", f.ScrollH, f.ClientH)) } return strings.Join(out, "; ") } // TestTidyDesktopSlideFits (final review, finding 5, V1): the desktop // slide fits the room above the notes, both ways, at 16:9. At 1280×720 // and 1920×1080, in desktop view and in Both, with the notes open at // their default height, at their maximum and closed, and with the card // shown and hidden: the slide's own rect is inside the stage, above the // notes card, left of the inspector card, 16:9 within 1%, and the stage // does not scroll. func TestTidyDesktopSlideFits(t *testing.T) { te := openTidyEditor(t, 2, 1280, 720) notes := map[string]func(){ "the notes at their default height": func() { te.rig.Run( chromedp.Evaluate[chromedp.Void](`(p => { if (p.dataset.state !== 'open') document.querySelector('[data-view-toggle="notes"]').click() })(document.querySelector('[slides-notes-pane]'))`), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open'`), chromedp.Focus(chromedp.CSS(`[slides-notes-resize]`)), chromedp.KeyEvent(kb.Home), ) // From the minimum up to the default, 144px, by script: the // default is not a multiple of the arrow's step. te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-notes-pane]').style.setProperty('--slides-notes-block-size', '144px')`)) }, "the notes at their maximum": func() { te.rig.Run( chromedp.Focus(chromedp.CSS(`[slides-notes-resize]`)), chromedp.KeyEvent(kb.End), ) }, "the notes closed": func() { te.rig.Run( chromedp.Evaluate[chromedp.Void](`document.querySelector('[data-view-toggle="notes"]').click()`), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'closed'`), ) }, } for _, vp := range [][2]int64{{1280, 720}, {1920, 1080}} { te.size(vp[0], vp[1]) for _, v := range []string{"desktop", "both"} { te.view(v) for _, card := range []string{"open", "closed"} { var now string te.rig.Run(evalInto(&now, `document.querySelector('[slides-inspector]').dataset.state`)) if now != card { te.pressFormat(card) } for _, n := range []string{"the notes at their default height", "the notes at their maximum", "the notes closed"} { notes[n]() te.rig.Run(chromedp.Sleep(100 * time.Millisecond)) var f fitState te.rig.Run(evalInto(&f, fitJS)) if got := f.fits(); got != "" { t.Errorf("%dx%d, %s view, the card %s, %s: %s", vp[0], vp[1], v, card, n, got) } } } } } te.view("desktop") } // statusJS is the strip's top against the bar's bottom, and where the // stage and the view switch are. const statusJS = `(() => { const r = s => document.querySelector(s).getBoundingClientRect() const stage = r('[slides-stage]'), sw = r('[slides-switcher]') return {StripTop: r('[slides-strip-nav]').top, BarBottom: r('[slides-head]').bottom, Stage: [stage.left, stage.top, stage.width, stage.height], Switch: [sw.left, sw.top, sw.width, sw.height]} })()` type statusState struct { StripTop, BarBottom float64 Stage, Switch []float64 } // TestTidyStripMeetsTheBar (final review, finding 7, V2): the strip's // surface starts directly under the bar, with no band of desk between // them, and the font status keeps its room in the stage's column, so a // note appearing and clearing moves neither the stage nor the view // switch. func TestTidyStripMeetsTheBar(t *testing.T) { te := openTidyEditor(t, 2, 1280, 720) read := func() statusState { var s statusState te.rig.Run(evalInto(&s, statusJS)) return s } before := read() if math.Abs(before.StripTop-before.BarBottom) > 1 { t.Errorf("the strip's top is at %.1f and the bar's bottom at %.1f; want the strip directly under the bar", before.StripTop, before.BarBottom) } // A note, said as font-status.mjs says one (the longest the catalog // has, which stays a while), then cleared. te.rig.Run(chromedp.Evaluate[chromedp.Void](`(s => { s.setAttribute('data-state', 'unavailable'); s.querySelector('[slides-fonts-status-text]').textContent = s.getAttribute('data-unavailable') })(document.querySelector('[slides-fonts-status]'))`)) said := read() te.rig.Run(chromedp.Evaluate[chromedp.Void](`(s => { s.removeAttribute('data-state'); s.querySelector('[slides-fonts-status-text]').textContent = '' })(document.querySelector('[slides-fonts-status]'))`)) cleared := read() for _, c := range []struct { when string s statusState }{{"with a font note shown", said}, {"with the note cleared", cleared}} { if fmt.Sprint(c.s.Stage) != fmt.Sprint(before.Stage) || fmt.Sprint(c.s.Switch) != fmt.Sprint(before.Switch) { t.Errorf("%s the stage is %v and the switch %v; before, %v and %v: want nothing moved", c.when, c.s.Stage, c.s.Switch, before.Stage, before.Switch) } } } // TestTidyNotesFirstPaint (final review, finding 6; ruling R21): the // notes card's remembered state and height are cookies the server // renders, so with the bundle blocked — before any script — the card // is already closed, or open at the remembered height; and once the // bundle has bound, it is exactly as it was. func TestTidyNotesFirstPaint(t *testing.T) { te := openTidyEditor(t, 2, 1280, 720) const paneJS = `(() => { const p = document.querySelector('[slides-notes-pane]'), i = document.querySelector('[slides-notes-open]') return {State: p.dataset.state, Shown: p.checkVisibility(), Height: p.getBoundingClientRect().height, Icon: i.checkVisibility(), Pressed: document.querySelector('[data-view-toggle="notes"]').getAttribute('aria-pressed')} })()` type pane struct { State string Shown, Icon bool Height float64 Pressed string } set := func(kv ...string) chromedp.Action[chromedp.Void] { var acts []chromedp.Action[chromedp.Void] for i := 0; i < len(kv); i += 2 { acts = append(acts, cdpStep(network.SetCookie, network.SetCookieParams{Name: kv[i], Value: kv[i+1], URL: te.rig.Origin + "/", SameSite: network.CookieSameSiteLax})) } return chromedp.Steps(acts...) } blocked := func(what string) pane { t.Helper() te.rig.Run( cdpStep(network.Enable, network.EnableParams{}), blockURLs("*/static/editor.*.js"), chromedp.Navigate(te.rig.Origin+te.path), chromedp.WaitReady(chromedp.CSS(`[slides-notes-pane]`)), ) var bound bool te.rig.Run(evalInto(&bound, editorBound)) if bound { t.Fatalf("%s: the editor bound with its bundle blocked; this check would not be of the first paint", what) } var p pane te.rig.Run(evalInto(&p, paneJS)) return p } te.rig.Run(set("slides-notes", "closed")) if p := blocked("closed"); p.State != "closed" || p.Shown || !p.Icon || p.Pressed != "false" { t.Errorf("first paint with slides-notes=closed: %+v; want closed, the card not drawn, the tab drawn, the View row unpressed", p) } te.rig.Run(set("slides-notes", "open", "slides-notes-height", "220")) if p := blocked("open at 220"); p.State != "open" || !p.Shown || p.Icon || math.Abs(p.Height-220) > 0.5 || p.Pressed != "true" { t.Errorf("first paint with slides-notes=open and slides-notes-height=220: %+v; want open, drawn 220px tall", p) } // The bundle let through: once bound, nothing has moved. te.rig.Run( blockURLs(), chromedp.Navigate(te.rig.Origin+te.path), waitFor(editorBound), chromedp.Sleep(200*time.Millisecond), ) var p pane te.rig.Run(evalInto(&p, paneJS)) if p.State != "open" || math.Abs(p.Height-220) > 0.5 { t.Errorf("once the editor bound, the notes are %+v; want them as the server painted them, open and 220px", p) } }