oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3// The editor, tidied (docs/superpowers/specs/2026-11-16-editor-tidy-design.md),
4// held in a real Chromium: what only geometry can show — the page that
5// never scrolls. (New slide's place in the strip is the quieter editor's
6// now: TestQuieterStrip, browser_quieter_test.go.)
7package slidestest
8
9import (
10 "encoding/json"
11 "fmt"
12 "math"
13 "net/http"
14 "os"
15 "regexp"
16 "strings"
17 "testing"
18 "time"
19
20 "amadan.net/rastrillo/rastrillo/blobs"
21 "amadan.net/rastrillo/rastrillo/harness"
22 "github.com/chromedp/cdproto/network"
23 "github.com/chromedp/cdproto/runtime"
24 "github.com/chromedp/chromedp"
25 "github.com/chromedp/chromedp/kb"
26)
27
28// tidyEditor is a signed-in browser with the editor open on a deck.
29type tidyEditor struct {
30 rig *harness.Rig
31 app *testApp
32 cookies []*http.Cookie
33 path string // the deck's editor path, /d/{sqid}/edit
34}
35
36// openTidyEditor signs a browser in, makes a deck of n slides
37// (deckWithSlides: the first with 400 words of notes), and opens its
38// editor at width×height, bound.
39func openTidyEditor(t *testing.T, n int, width, height int64) *tidyEditor {
40 t.Helper()
41 return openTidyEditorOn(t, width, height, func(a *testApp, cookies []*http.Cookie) string {
42 return deckWithSlides(t, a, cookies, n)
43 })
44}
45
46// openTidyEditorOn is openTidyEditor on the deck deck makes, given the
47// app and the signed-in person's cookies; deck returns its editor path.
48func openTidyEditorOn(t *testing.T, width, height int64, deck func(a *testApp, cookies []*http.Cookie) string) *tidyEditor {
49 t.Helper()
50 te := newTidyEditor(t, width, height, deck)
51 te.rig.Run(
52 chromedp.Navigate(te.rig.Origin+te.path),
53 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
54 waitFor(editorBound),
55 )
56 return te
57}
58
59// newTidyEditor is openTidyEditorOn up to the navigation: a signed-in
60// browser at width×height and the deck made, the editor not yet open
61// (for a deck whose editor has nothing to bind, an empty one).
62func newTidyEditor(t *testing.T, width, height int64, deck func(a *testApp, cookies []*http.Cookie) string) *tidyEditor {
63 t.Helper()
64 return newTidyEditorWith(t, nil, width, height, deck)
65}
66
67// newTidyEditorWith is newTidyEditor with an object store bound (nil: none).
68func newTidyEditorWith(t *testing.T, store blobs.Store, width, height int64, deck func(a *testApp, cookies []*http.Cookie) string) *tidyEditor {
69 t.Helper()
70 rig, app := newRigApp(t, store)
71 cookies := signedIn(t, app, allowedAddress)
72 var set []chromedp.Action[chromedp.Void]
73 for _, c := range cookies {
74 set = append(set, cdpStep(network.SetCookie, network.SetCookieParams{
75 Name: c.Name, Value: c.Value, URL: rig.Origin + "/",
76 HTTPOnly: new(c.HttpOnly), Secure: new(c.Secure), SameSite: network.CookieSameSiteLax,
77 }))
78 }
79 rig.Run(set...)
80 te := &tidyEditor{rig: rig, app: app, cookies: cookies, path: deck(app, cookies)}
81 te.size(width, height)
82 return te
83}
84
85// size sets the viewport, and waits until the page has laid out at it.
86func (te *tidyEditor) size(width, height int64) {
87 te.rig.Run(
88 chromedp.EmulateViewport(width, height),
89 waitFor(fmt.Sprintf(`innerWidth === %d && innerHeight === %d`, width, height)),
90 )
91}
92
93// scrolls reports how far the document is bigger than the window, in
94// each direction; "" is the pass.
95func (te *tidyEditor) scrolls(t *testing.T) string {
96 t.Helper()
97 var got string
98 te.rig.Run(evalInto(&got, `(() => {
99 const d = document.documentElement, out = []
100 if (d.scrollHeight !== innerHeight) out.push('scrollHeight ' + d.scrollHeight + ' != innerHeight ' + innerHeight)
101 if (d.scrollWidth !== innerWidth) out.push('scrollWidth ' + d.scrollWidth + ' != innerWidth ' + innerWidth)
102 return out.join('; ')
103 })()`))
104 return got
105}
106
107// TestTidyPageNeverScrolls (spec §2, §8): with forty slides and long
108// notes, the page is exactly the window, at a laptop's size and a
109// desktop's. The strip, the stage, the inspector and the notes scroll
110// inside themselves.
111func TestTidyPageNeverScrolls(t *testing.T) {
112 te := openTidyEditor(t, 40, 1280, 720)
113 // The first slide, the one with 400 words of notes, with the notes
114 // open: they scroll inside their card, the page does not.
115 te.rig.Run(
116 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.index === '0'`),
117 waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open' && !document.querySelector('[slides-notes-pane]').hidden`),
118 waitFor(`document.querySelector('[slides-notes]').innerText.split(/\s+/).length >= 400`),
119 )
120 for _, vp := range [][2]int64{{1280, 720}, {1920, 1080}} {
121 te.size(vp[0], vp[1])
122 if got := te.scrolls(t); got != "" {
123 t.Errorf("at %dx%d the page scrolls: %s", vp[0], vp[1], got)
124 }
125 var body string
126 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]'))`))
127 if body != "" {
128 t.Errorf("at %dx%d: %s", vp[0], vp[1], body)
129 }
130 }
131 te.rig.Screen(`[slides-editor]`, "the editor, forty slides")
132
133 // A canvas shape selected: the card is the shape's options, the
134 // longest a box has, and still only the card scrolls.
135 canvas := te.addCanvasShape(t)
136 te.size(1280, 720)
137 te.openOn(canvas)
138 te.selectBox("shape")
139 for _, vp := range [][2]int64{{1280, 720}, {1920, 1080}} {
140 te.size(vp[0], vp[1])
141 if got := te.scrolls(t); got != "" {
142 t.Errorf("at %dx%d with a canvas shape selected the page scrolls: %s", vp[0], vp[1], got)
143 }
144 }
145 te.rig.Screen(`[slides-editor]`, "a canvas shape selected")
146}
147
148// notesJS is the notes card's state: open or closed, its height and
149// top, the tab's box and text (the quieter editor's, spec §6.2: it was
150// an icon with a dot and a name), the View menu row's check, where
151// focus is, and the bottom of whatever the stage draws (the editable
152// stage, or its phone frame in phone view).
153const notesJS = `(() => {
154 const pane = document.querySelector('[slides-notes-pane]'), icon = document.querySelector('[slides-notes-open]')
155 const edge = document.querySelector('[slides-notes-resize]')
156 const shown = e => !e.hidden && getComputedStyle(e).display !== 'none' && e.getBoundingClientRect().height > 0
157 const r = pane.getBoundingClientRect(), i = icon.getBoundingClientRect()
158 const view = document.querySelector('[slides-stage-pane]').dataset.view
159 const stage = document.querySelector(view === 'phone' ? '[slides-stage-frame]' : '[slides-stage]').getBoundingClientRect()
160 const a = document.activeElement
161 return {
162 State: pane.dataset.state, CardShown: shown(pane), Height: r.height, Top: r.top,
163 IconShown: shown(icon), IconW: i.width, IconH: i.height, Label: icon.textContent,
164 Pressed: document.querySelector('[data-view-toggle="notes"]').getAttribute('aria-pressed'),
165 Focus: a === icon ? 'icon' : a && a.closest('[slides-notes]') ? 'notes' : a ? a.tagName : '',
166 Min: Number(edge.getAttribute('aria-valuemin')), Max: Number(edge.getAttribute('aria-valuemax')), Now: Number(edge.getAttribute('aria-valuenow')),
167 StageBottom: stage.bottom
168 }
169})()`
170
171type notesState struct {
172 State string
173 CardShown, IconShown bool
174 Height, Top float64
175 IconW, IconH float64
176 Label, Pressed, Focus string
177 Min, Max, Now float64
178 StageBottom float64
179}
180
181func (te *tidyEditor) notes() notesState {
182 var s notesState
183 te.rig.Run(evalInto(&s, notesJS))
184 return s
185}
186
187// TestTidyNotes (spec §5): the notes are a card at the foot of the
188// desk. The × closes it to a tab (an icon until the quieter editor,
189// §6.2), and the tab and View → Speaker notes open it again; the tab's
190// text says whether the slide has notes, and how many words, across a
191// slide change and after the notes are emptied;
192// the top edge drags within its limits and the height survives a
193// reload; and the stage, a phone frame included, ends above the card.
194func TestTidyNotes(t *testing.T) {
195 te := openTidyEditor(t, 3, 1280, 720)
196 ids, _ := te.slideIDs()
197 const saved = `document.querySelector('[estilo-save-status]').dataset.state === 'saved'`
198
199 s := te.notes()
200 if s.State != "open" || !s.CardShown || s.IconShown {
201 t.Fatalf("at first the notes are %+v; want the card open and the tab hidden", s)
202 }
203 if s.Pressed != "true" {
204 t.Errorf("View → Speaker notes is aria-pressed=%q with the notes open", s.Pressed)
205 }
206 for _, v := range []string{"desktop", "phone", "both"} {
207 te.view(v)
208 if v == "phone" {
209 te.rig.Run(waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.vp === 'phone'`))
210 }
211 if s := te.notes(); s.StageBottom > s.Top+0.5 {
212 t.Errorf("%s view: the stage ends at %.1f, under the notes card's top %.1f", v, s.StageBottom, s.Top)
213 }
214 // The top edge is a 24px target that lies over neither the
215 // stages (and so no frame's edge) nor the × or the notes' first
216 // line: a point at the centre of the ×, and at the middle of the
217 // first line's height, finds them.
218 var edge string
219 te.rig.Run(evalInto(&edge, `(() => {
220 const q = s => document.querySelector(s), out = []
221 const e = q('[slides-notes-resize]').getBoundingClientRect()
222 if (e.height < 24 || e.width < 24) out.push('the top edge is ' + e.width + 'x' + e.height + ', under 24x24')
223 const stages = q('[slides-stages]').getBoundingClientRect()
224 if (e.top < stages.bottom - 0.5) out.push('the top edge (top ' + e.top + ') is over the stages (bottom ' + stages.bottom + ')')
225 const notes = q('[slides-notes]'), line = parseFloat(getComputedStyle(notes).lineHeight)
226 const x = q('[slides-notes-close]').getBoundingClientRect(), n = notes.getBoundingClientRect()
227 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]]) {
228 const hit = document.elementFromPoint(px, py)
229 if (!hit || !hit.closest(sel)) out.push('at the centre of ' + name + ' is ' + (hit ? hit.outerHTML.slice(0, 80) : 'nothing'))
230 }
231 return out.join('; ')
232 })()`))
233 if edge != "" {
234 t.Errorf("%s view: %s", v, edge)
235 }
236 te.rig.Screen(`[slides-stage-pane]`, v+" view with the notes open")
237 }
238 te.view("desktop")
239
240 // The × closes; focus goes to the tab, which shows and counts the
241 // first slide's 400 words.
242 te.rig.Run(chromedp.Click(chromedp.CSS(`[slides-notes-close]`)), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'closed'`))
243 s = te.notes()
244 if s.CardShown || !s.IconShown || s.Focus != "icon" {
245 t.Errorf("after ×: %+v; want the card gone, the tab shown and focused", s)
246 }
247 if s.IconW < 24 || s.IconH < 24 {
248 t.Errorf("the tab is %gx%g, under 24x24", s.IconW, s.IconH)
249 }
250 if s.Label != "Notes · 400 words" || s.Pressed != "false" {
251 t.Errorf("closed on the slide with notes: the tab says %q, View row pressed %q", s.Label, s.Pressed)
252 }
253 te.rig.Screen(`[slides-stage-pane]`, "notes closed: the tab, with its count")
254
255 // The second slide has no notes; back on the first, the count again.
256 te.rig.Run(
257 chromedp.Evaluate[chromedp.Void](`location.hash = '`+ids[1]+`'`),
258 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+ids[1]+`'`),
259 )
260 if s := te.notes(); s.Label != "Notes" {
261 t.Errorf("on a slide without notes: the tab says %q", s.Label)
262 }
263 te.rig.Run(
264 chromedp.Evaluate[chromedp.Void](`location.hash = '`+ids[0]+`'`),
265 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+ids[0]+`'`),
266 )
267 if s := te.notes(); s.Label != "Notes · 400 words" {
268 t.Errorf("back on the slide with notes: the tab says %q", s.Label)
269 }
270
271 // The tab opens, into the notes.
272 te.rig.Run(chromedp.Click(chromedp.CSS(`[slides-notes-open]`)), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open'`))
273 if s := te.notes(); !s.CardShown || s.IconShown || s.Focus != "notes" || s.Pressed != "true" {
274 t.Errorf("after the tab: %+v; want the card shown, focus in the notes, the View row pressed", s)
275 }
276
277 // View → Speaker notes closes and opens it too.
278 te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[data-view-toggle="notes"]').click()`), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'closed'`))
279 if s := te.notes(); s.CardShown || !s.IconShown || s.Pressed != "false" {
280 t.Errorf("after View → Speaker notes: %+v; want closed, the row unpressed", s)
281 }
282 te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[data-view-toggle="notes"]').click()`), waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open'`))
283 if s := te.notes(); !s.CardShown || s.Pressed != "true" || s.Focus != "notes" {
284 t.Errorf("after View → Speaker notes again: %+v; want open, the row pressed, focus in the notes", s)
285 }
286
287 // Emptied, the slide has no notes: the count goes.
288 te.rig.Run(
289 // Select all the way a person does (ProseMirror's Mod-a, in the
290 // notes), then delete: a DOM selection set by script reached
291 // ProseMirror only after the key, now and then.
292 chromedp.Focus(chromedp.CSS(`[slides-notes]`)),
293 waitFor(`document.activeElement === document.querySelector('[slides-notes]')`),
294 modKey("a", chromedp.ModifierCtrl),
295 chromedp.KeyEvent(kb.Backspace),
296 waitFor(`document.querySelector('[slides-notes]').textContent.trim() === ''`),
297 waitFor(saved),
298 )
299 if s := te.notes(); s.Label != "Notes" {
300 t.Errorf("after deleting the notes' text: the tab says %q", s.Label)
301 }
302
303 // The top edge: dragged far up it stops at its maximum, far down at
304 // its minimum, and a short drag up grows it by the drag.
305 drag := func(dy float64) notesState {
306 t.Helper()
307 var pt struct{ X, Y float64 }
308 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} })()`))
309 te.rig.Run(dragBy(pt.X, pt.Y, 0, dy))
310 return te.notes()
311 }
312 s = drag(-600)
313 if s.Max <= s.Min || math.Abs(s.Height-s.Max) > 1 {
314 t.Errorf("dragged far up, the card is %.1fpx; want its maximum %g (minimum %g)", s.Height, s.Max, s.Min)
315 }
316 s = drag(600)
317 if math.Abs(s.Height-s.Min) > 1 {
318 t.Errorf("dragged far down, the card is %.1fpx; want its minimum %g", s.Height, s.Min)
319 }
320 s = drag(-40)
321 want := s.Min + 40
322 if math.Abs(s.Height-want) > 1 || math.Abs(s.Now-s.Height) > 1 {
323 t.Errorf("a 40px drag up from %g made the card %.1fpx (aria-valuenow %g); want %g", s.Min, s.Height, s.Now, want)
324 }
325 if got := te.scrolls(t); got != "" {
326 t.Errorf("after resizing the notes the page scrolls: %s", got)
327 }
328
329 // The height survives a reload.
330 te.rig.Run(
331 chromedp.Reload(),
332 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
333 waitFor(editorBound),
334 )
335 if s := te.notes(); s.State != "open" || math.Abs(s.Height-want) > 1 {
336 t.Errorf("after a reload the notes are %s and %.1fpx tall; want open and %g", s.State, s.Height, want)
337 }
338}
339
340// TestTidyViewSwitch (spec §3): the three icons and the View menu's
341// three rows each light exactly one view and show the frames it names;
342// ArrowRight from the first icon moves to the next.
343func TestTidyViewSwitch(t *testing.T) {
344 te := openTidyEditor(t, 3, 1280, 720)
345
346 // state: which radios are checked, how the one editable stage is
347 // drawn (full width; inside a phone, its frame a phone's 390:844
348 // (TestTidyPhoneFrame holds the rest of that); or sharing the row
349 // with the preview — it is not the read-only [slides-stage-phone],
350 // which only "both" shows), and whether the read-only phone preview
351 // is showing.
352 const state = `(() => {
353 const shown = el => !!el && !el.hidden && getComputedStyle(el).display !== 'none'
354 const checked = [...document.querySelectorAll('input[name="slides-view"]')].filter(i => i.checked).map(i => i.value)
355 const stage = document.querySelector('[data-vp="desktop"]')
356 const w = shown(stage) ? stage.getBoundingClientRect().width : 0
357 const f = document.querySelector('[slides-stage-frame]').getBoundingClientRect()
358 const phone = getComputedStyle(document.querySelector('[slides-stage-frame]')).display !== 'contents' && f.height > 0 && Math.abs(f.width / f.height - 390 / 844) < 0.01
359 const kind = !w ? '' : phone ? 'phone-frame' : w > 600 ? 'wide' : 'shared'
360 return checked.join(',') + '|' + kind + '|' + (shown(document.querySelector('[slides-stage-phone]')) ? 'preview' : '')
361 })()`
362 want := map[string]string{"desktop": "desktop|wide|", "phone": "phone|phone-frame|", "both": "both|shared|preview"}
363 check := func(how, view string) {
364 t.Helper()
365 var got string
366 te.rig.Run(evalInto(&got, state))
367 if got != want[view] {
368 t.Errorf("%s: state is %q, want %q", how, got, want[view])
369 }
370 }
371 center := func(sel string) {
372 var pt struct{ X, Y float64 }
373 te.rig.Run(evalInto(&pt, `(() => { const r = document.querySelector('`+sel+`').getBoundingClientRect(); return {X: r.x + r.width / 2, Y: r.y + r.height / 2} })()`))
374 te.rig.Run(chromedp.MouseClickXY(pt.X, pt.Y))
375 }
376
377 for _, v := range []string{"phone", "both", "desktop"} {
378 center(`[slides-switcher] label:has(input[value="` + v + `"])`)
379 te.rig.Run(waitFor(fmt.Sprintf(`document.querySelector('[slides-stage-pane]').dataset.view === %q`, v)))
380 check("clicking the "+v+" icon", v)
381 }
382
383 // ArrowRight from the first (focused) moves to the second.
384 te.rig.Run(chromedp.Focus(chromedp.CSS(`input[name="slides-view"][value="desktop"]`)), chromedp.KeyEvent(kb.ArrowRight))
385 te.rig.Run(waitFor(`document.querySelector('[slides-stage-pane]').dataset.view === 'phone'`))
386 check("ArrowRight from the first icon", "phone")
387
388 // The View menu's rows do the same, chosen as a person would: the
389 // menu opened with a click on its title, the row clicked where it
390 // is drawn.
391 for _, v := range []string{"both", "desktop", "phone"} {
392 var open bool
393 te.rig.Run(evalInto(&open, `document.querySelector('[slides-menu="view"]').open`))
394 if !open {
395 center(`[slides-menu="view"] > summary`)
396 te.rig.Run(waitFor(`document.querySelector('[slides-menu="view"]').open`))
397 }
398 center(`[data-view-choice="` + v + `"]`)
399 te.rig.Run(waitFor(fmt.Sprintf(`document.querySelector('[slides-stage-pane]').dataset.view === %q`, v)))
400 check("the View menu's "+v+" row", v)
401 }
402
403 // One pill: each segment is at least 24x24, the pill's ends are
404 // rounded and its two inner joins square.
405 var pill string
406 te.rig.Run(evalInto(&pill, `(() => {
407 const items = [...document.querySelectorAll('[slides-switcher] > label')], out = []
408 items.forEach((l, i) => {
409 const r = l.getBoundingClientRect(), s = getComputedStyle(l)
410 if (r.width < 24 || r.height < 24) out.push(i + ' is ' + r.width + 'x' + r.height)
411 const left = parseFloat(s.borderStartStartRadius) > 0, right = parseFloat(s.borderStartEndRadius) > 0
412 if (left !== (i === 0) || right !== (i === items.length - 1)) out.push(i + ' corners: left ' + left + ', right ' + right)
413 })
414 return out.join('; ')
415 })()`))
416 if pill != "" {
417 t.Errorf("the view switch is not one pill of 24px targets: %s", pill)
418 }
419 te.rig.Screen(`[slides-stage-bar]`, "the view switch")
420}
421
422// The phone frame (spec §6.1): in phone view the editable stage, and in
423// Both the read-only [slides-stage-phone], is a phone — a 390×844 screen
424// scaled by --slides-phone-scale to the height the stages have, which
425// scrolls inside itself.
426
427// phoneStageHTML is the golden file of what the two phone renderings
428// hold, captured from the commit before the frame (task B4): the frame
429// changes, the content does not.
430const phoneStageHTML = "testdata/phone-stage-html.json"
431
432// tallSlide is the id of the slide phoneFrameDeck adds, taller than a
433// phone at phone width.
434const tallSlide = "tallslide222"
435
436// phoneFrameDeck is the sample deck (eight fixed slides, a canvas one
437// among them) with one more slide of forty paragraphs at its end.
438func phoneFrameDeck(t *testing.T) func(a *testApp, cookies []*http.Cookie) string {
439 return func(a *testApp, cookies []*http.Cookie) string {
440 path := sampleDeck(t, a, cookies)
441 token := mintAgent(t, a, cookies, "phone-frame")
442 paras := make([]string, 40)
443 for i := range paras {
444 paras[i] = fmt.Sprintf("Paragraph %d of a slide far longer than a phone is tall.", i+1)
445 }
446 ops := `{"ops":[{"op":"add_slide","id":"` + tallSlide + `","layout":"flow","template":"title-body"},` +
447 `{"op":"add_block","slide":"` + tallSlide + `","type":"text","region":"body","markdown":` + quote(strings.Join(paras, "\n\n")) + `}]}`
448 apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+strings.TrimPrefix(path, "/d/")+"/ops", token, ops, http.StatusOK)
449 return path + "/edit"
450 }
451}
452
453// slideIDs is the deck's slide ids in strip order, with each one's label.
454func (te *tidyEditor) slideIDs() (ids, labels []string) {
455 var pairs [][2]string
456 te.rig.Run(evalInto(&pairs, `[...document.querySelectorAll('[slides-strip-item][data-slide-id]')].map(li => [li.dataset.slideId, li.querySelector('[slides-strip-label]')?.textContent ?? ''])`))
457 for _, p := range pairs {
458 ids, labels = append(ids, p[0]), append(labels, p[1])
459 }
460 return ids, labels
461}
462
463// view picks a view by its radio, and waits for the pane to say so.
464func (te *tidyEditor) view(v string) {
465 te.rig.Run(
466 chromedp.Evaluate[chromedp.Void](`document.querySelector('input[name="slides-view"][value="`+v+`"]').click()`),
467 waitFor(fmt.Sprintf(`document.querySelector('[slides-stage-pane]').dataset.view === %q`, v)),
468 )
469}
470
471// showIn shows slide id in view v and waits until the stage that view
472// edits or previews holds it in the phone rendering, bound when it is
473// the editable one.
474func (te *tidyEditor) showIn(id, v string) {
475 // The slide first, then the view: a view switched while a slide is
476 // still loading re-fetches the slide it started from.
477 te.rig.Run(
478 chromedp.Evaluate[chromedp.Void](`location.hash = '`+id+`'`),
479 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+id+`'`),
480 )
481 te.view(v)
482 te.rig.Run(waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '` + id + `'`))
483 switch v {
484 case "phone":
485 te.rig.Run(
486 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.vp === 'phone'`),
487 waitFor(`document.querySelector('[slides-stage] [contenteditable="true"]')`),
488 )
489 case "both":
490 te.rig.Run(waitFor(`document.querySelector('[slides-phone-screen] [slides-slide]')?.dataset.id === '` + id + `'`))
491 }
492}
493
494// stableIDs replaces every id the server minted (twelve base32
495// characters, as an attribute's whole value) with its order of first
496// appearance, so two decks seeded alike compare alike.
497func stableIDs(html string) string {
498 seen := map[string]string{}
499 return regexp.MustCompile(`="[a-z2-7]{12}"`).ReplaceAllStringFunc(html, func(m string) string {
500 id := m[2 : len(m)-1]
501 if _, ok := seen[id]; !ok {
502 seen[id] = fmt.Sprintf("id-%d", len(seen)+1)
503 }
504 return `="` + seen[id] + `"`
505 })
506}
507
508// phoneFrameJS measures the frame view v shows (the editable stage's
509// frame in phone view, [slides-stage-phone] in Both): its rect, the
510// stages' rect, its scale, its screen (the element that scrolls), the
511// slide's top in the screen's own CSS px, and the desktop stage's rect.
512const phoneFrameJS = `((v) => {
513 const frame = document.querySelector(v === 'phone' ? '[slides-stage-frame]' : '[slides-stage-phone]')
514 const screen = document.querySelector(v === 'phone' ? '[slides-stage-frame]' : '[slides-phone-screen]')
515 const slide = screen.querySelector('[slides-slide]')
516 const scale = parseFloat(getComputedStyle(frame).getPropertyValue('--slides-phone-scale'))
517 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} }
518 screen.scrollTop = 0
519 return {
520 Frame: r(frame), Stages: r(document.querySelector('[slides-stages]')),
521 Desktop: r(document.querySelector('[slides-stage]')),
522 Scale: scale,
523 SlideTop: (slide.getBoundingClientRect().top - screen.getBoundingClientRect().top) / scale,
524 Radius: getComputedStyle(frame).borderTopLeftRadius
525 }
526})`
527
528type edges struct{ L, T, R, B, W, H float64 }
529
530type phoneFrame struct {
531 Frame, Stages, Desktop edges
532 Scale, SlideTop float64
533 Radius string
534}
535
536func (te *tidyEditor) phoneFrame(v string) phoneFrame {
537 var f phoneFrame
538 te.rig.Run(evalInto(&f, phoneFrameJS+`('`+v+`')`))
539 return f
540}
541
542// TestTidyPhoneFrame (spec §6.1, §8): at 1280×720, in phone view and in
543// Both, the phone is a phone's proportions and no taller than the
544// stages; it holds the same HTML each view held before it was a frame;
545// a slide taller than a phone scrolls inside the screen and not the
546// page; and the slide sits as far down the screen as the viewer puts it
547// on a 390×844 phone.
548func TestTidyPhoneFrame(t *testing.T) {
549 te := openTidyEditorOn(t, 1280, 720, phoneFrameDeck(t))
550 ids, labels := te.slideIDs()
551 canvas := -1
552 for i, l := range labels {
553 if strings.HasPrefix(l, "Canvas:") {
554 canvas = i
555 }
556 }
557 if len(ids) != 9 || canvas < 0 {
558 t.Fatalf("the deck's strip is %q; want the sample deck's eight, a canvas one among them, and the tall one", labels)
559 }
560
561 // The same bytes, for the first slide and the canvas one.
562 raw, err := os.ReadFile(phoneStageHTML)
563 if err != nil {
564 t.Fatal(err)
565 }
566 var want map[string]string
567 if err := json.Unmarshal(raw, &want); err != nil {
568 t.Fatalf("%s: %v", phoneStageHTML, err)
569 }
570 for _, n := range []int{0, canvas} {
571 var phone, both string
572 te.showIn(ids[n], "phone")
573 te.rig.Run(evalInto(&phone, `document.querySelector('[slides-stage]').innerHTML`))
574 te.showIn(ids[n], "both")
575 te.rig.Run(evalInto(&both, `document.querySelector('[slides-phone-screen]').innerHTML`))
576 for key, got := range map[string]string{fmt.Sprintf("phone/%d", n+1): phone, fmt.Sprintf("both/%d", n+1): both} {
577 if stableIDs(got) != want[key] {
578 t.Errorf("%s: the stage holds other HTML than it did before the frame\n got: %s\nwant: %s", key, stableIDs(got), want[key])
579 }
580 }
581 }
582
583 // Where the viewer puts the first slide on a 390×844 phone. Read
584 // after the editor's checks, from the same browser.
585 viewerTop := map[string]float64{}
586 defer func() {
587 te.size(390, 844)
588 var top float64
589 te.rig.Run(
590 chromedp.Navigate(te.rig.Origin+strings.TrimSuffix(te.path, "/edit")+"?slide=1"),
591 chromedp.WaitVisible(chromedp.CSS(`[slides-viewer] [slides-slide]`)),
592 evalInto(&top, `document.querySelector('[slides-viewer] [slides-slide]').getBoundingClientRect().top + scrollY`),
593 )
594 for _, v := range []string{"phone", "both"} {
595 if got := viewerTop[v]; got < top-1 || got > top+1 {
596 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)
597 }
598 }
599 }()
600
601 const ratio = 390.0 / 844.0
602 for _, v := range []string{"phone", "both"} {
603 te.showIn(ids[0], v)
604 f := te.phoneFrame(v)
605 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)
606 if f.Frame.H == 0 || math.Abs(f.Frame.W/f.Frame.H-ratio)/ratio > 0.01 {
607 t.Errorf("%s: the frame is %.1f×%.1f, not a phone's 390:844 within 1%%", v, f.Frame.W, f.Frame.H)
608 }
609 if f.Frame.B > f.Stages.B+0.5 {
610 t.Errorf("%s: the frame's bottom %.1f is below the stages' bottom %.1f", v, f.Frame.B, f.Stages.B)
611 }
612 if !(f.Scale > 0 && f.Scale < 1) {
613 t.Errorf("%s: --slides-phone-scale is %g at 1280×720; want it between 0 and 1", v, f.Scale)
614 }
615 if f.Radius != "28px" {
616 t.Errorf("%s: the frame's corner radius is %s, want 28px", v, f.Radius)
617 }
618 if v == "both" && f.Desktop.R > f.Frame.L {
619 t.Errorf("both: the desktop stage (right %.1f) overlaps the phone frame (left %.1f)", f.Desktop.R, f.Frame.L)
620 }
621 viewerTop[v] = f.SlideTop
622 te.rig.Screen("[slides-stage-pane]", v+" view, the phone frame")
623 }
624
625 // The tall slide scrolls inside the screen, never the page.
626 for _, v := range []string{"phone", "both"} {
627 te.showIn(tallSlide, v)
628 screen := map[string]string{"phone": "[slides-stage-frame]", "both": "[slides-phone-screen]"}[v]
629 var scrolled float64
630 te.rig.Run(evalInto(&scrolled, `(s => { s.scrollTop = 300; return s.scrollHeight > s.clientHeight ? s.scrollTop : -1 })(document.querySelector('`+screen+`'))`))
631 if scrolled <= 0 {
632 t.Errorf("%s: the tall slide does not scroll inside %s (scrollTop %g)", v, screen, scrolled)
633 }
634 if got := te.scrolls(t); got != "" {
635 t.Errorf("%s: with the tall slide the page scrolls: %s", v, got)
636 }
637 te.rig.Screen("[slides-stage-pane]", v+" view, a tall slide scrolled")
638 }
639}
640
641// TestTidyPhoneFrameStillEdits: in phone view at 1280×720, where the
642// phone is scaled below 1, the stage still edits. A click in a text box
643// puts the caret where it was clicked and typing changes that box; on a
644// canvas slide a selected box has its outline over it, and a drag moves
645// it by the pointer's distance in the slide's own fractions.
646func TestTidyPhoneFrameStillEdits(t *testing.T) {
647 te := openTidyEditorOn(t, 1280, 720, phoneFrameDeck(t))
648 ids, labels := te.slideIDs()
649 canvas := ""
650 for i, l := range labels {
651 if strings.HasPrefix(l, "Canvas:") {
652 canvas = ids[i]
653 }
654 }
655 if canvas == "" {
656 t.Fatalf("the sample deck has no canvas slide: %q", labels)
657 }
658 const saved = `document.querySelector('[estilo-save-status]').dataset.state === 'saved'`
659
660 te.showIn(ids[0], "phone")
661 if f := te.phoneFrame("phone"); !(f.Scale > 0 && f.Scale < 1) {
662 t.Fatalf("--slides-phone-scale is %g at 1280×720; this test needs the phone scaled below 1", f.Scale)
663 }
664
665 // A click just inside the end of the body text's first word: the
666 // caret lands within a character of that point, in that box.
667 const body = `[slides-stage] [data-block="text"]`
668 var at struct{ X, Y float64 }
669 te.rig.Run(evalInto(&at, `(() => {
670 const p = document.querySelector('`+body+` p'), r = document.createRange()
671 r.setStart(p.firstChild, 0); r.setEnd(p.firstChild, 5)
672 const b = r.getBoundingClientRect()
673 return {X: b.right - 1, Y: b.top + b.height / 2}
674 })()`))
675 var before string
676 te.rig.Run(
677 evalInto(&before, `document.querySelector('`+body+`').textContent`),
678 chromedp.MouseClickXY(at.X, at.Y),
679 waitFor(`document.querySelector('`+body+`').contains(getSelection().anchorNode)`),
680 )
681 var caret struct{ X, Y, Char float64 }
682 te.rig.Run(evalInto(&caret, `(() => {
683 const s = getSelection(), r = s.getRangeAt(0).cloneRange()
684 const b = r.getBoundingClientRect(), c = document.createRange()
685 c.setStart(s.anchorNode, 0); c.setEnd(s.anchorNode, 1)
686 return {X: b.left, Y: b.top + b.height / 2, Char: c.getBoundingClientRect().width}
687 })()`))
688 if math.Abs(caret.X-at.X) > caret.Char+1 || math.Abs(caret.Y-at.Y) > 4 {
689 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)
690 }
691 te.rig.Run(
692 chromedp.KeyEvent("XQ"),
693 waitFor(`document.querySelector('`+body+`').textContent.includes('XQ')`),
694 waitFor(saved),
695 )
696 var after string
697 te.rig.Run(evalInto(&after, `document.querySelector('`+body+`').textContent`))
698 if len(after) != len(before)+2 {
699 t.Errorf("typing XQ made the box %q from %q", after, before)
700 }
701
702 // The canvas slide: select the rectangle a little in from its left
703 // edge — clear of the ellipse over its middle, of the heading, whose
704 // words run down over its top at a phone's width, and of the 24px
705 // handles, which cover much of a box this small.
706 te.showIn(canvas, "phone")
707 const rectSel = `[slides-stage] [data-block="shape"][data-kind="rect"]`
708 type geom struct{ Box, Overlay, Frame edges }
709 measure := func() geom {
710 var g geom
711 te.rig.Run(evalInto(&g, `(() => {
712 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} }
713 return {Box: r(document.querySelector('`+rectSel+`')), Overlay: r(document.querySelector('[slides-canvas-overlay]')),
714 Frame: r(document.querySelector('[slides-stage] [slides-slide]'))}
715 })()`))
716 return g
717 }
718 overOutline := func(when string, g geom) {
719 t.Helper()
720 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}} {
721 if math.Abs(d[1].(float64)-d[2].(float64)) > 2 {
722 t.Errorf("%s: the selection outline's %s is %.1f, the box's %.1f", when, d[0], d[2], d[1])
723 }
724 }
725 }
726 g := measure()
727 x, y := g.Box.L+g.Box.W*0.27, g.Box.T+g.Box.H*0.6
728 te.rig.Run(
729 chromedp.MouseClickXY(x, y),
730 waitFor(`document.querySelector('`+rectSel+`').getAttribute('aria-selected') === 'true'`),
731 waitFor(`!document.querySelector('[slides-canvas-overlay]').hidden`),
732 )
733 g = measure()
734 overOutline("selected", g)
735 te.rig.Screen("[slides-stage-pane]", "phone view, the rectangle selected")
736
737 // The box's left edge as a fraction of the slide, measured on
738 // screen; the drag is written as the phone override (set_phone),
739 // which the phone rendering carries as --slides-phone-left.
740 from := (g.Box.L - g.Frame.L) / g.Frame.W
741 const dx = 30.0
742 te.rig.Run(
743 dragBy(x, y, dx, 0),
744 waitFor(saved),
745 waitFor(`document.querySelector('`+rectSel+`')?.style.getPropertyValue('--slides-phone-left') !== ''`),
746 waitFor(`document.querySelector('`+rectSel+`')?.getAttribute('aria-selected') === 'true'`),
747 )
748 var phoneLeft float64
749 te.rig.Run(evalInto(&phoneLeft, `parseFloat(document.querySelector('`+rectSel+`').style.getPropertyValue('--slides-phone-left')) / 100`))
750 // The pointer moved dx screen px over a slide g.Frame.W screen px
751 // wide; snapping may pull the edge up to one per cent further.
752 want := dx / g.Frame.W
753 if got := phoneLeft - from; math.Abs(got-want) > 0.0105 {
754 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)
755 }
756 overOutline("after the drag", measure())
757 te.rig.Screen("[slides-stage-pane]", "phone view, the rectangle dragged")
758}
759
760// TestTidyPhoneFrameFitsANarrowWindow (spec §8's 320px reflow): in a
761// 320×700 window, in phone view and in Both, the phone is scaled to the
762// width it has — its frame lies inside the stages — and the page does
763// not scroll sideways.
764func TestTidyPhoneFrameFitsANarrowWindow(t *testing.T) {
765 te := openTidyEditorOn(t, 1280, 720, phoneFrameDeck(t))
766 ids, _ := te.slideIDs()
767 te.size(320, 700)
768 for _, v := range []string{"phone", "both"} {
769 te.showIn(ids[0], v)
770 var got string
771 te.rig.Run(evalInto(&got, `((v) => {
772 const frame = document.querySelector(v === 'phone' ? '[slides-stage-frame]' : '[slides-stage-phone]').getBoundingClientRect()
773 const stages = document.querySelector('[slides-stages]').getBoundingClientRect()
774 const out = []
775 if (frame.width === 0) out.push('the frame has no box')
776 if (frame.left < stages.left - 0.5 || frame.right > stages.right + 0.5)
777 out.push('the frame [' + frame.left.toFixed(1) + ', ' + frame.right.toFixed(1) + '] is outside the stages [' + stages.left.toFixed(1) + ', ' + stages.right.toFixed(1) + ']')
778 // Nothing wider than the window. Not scrollWidth === innerWidth:
779 // at 320px the editor is 305px wide in every view (a scrollbar's
780 // 15px short of the window, desktop view included), and
781 // scrollWidth reports that rather than the window.
782 const d = document.documentElement
783 if (d.scrollWidth > innerWidth || d.scrollWidth > d.clientWidth) out.push('scrollWidth ' + d.scrollWidth + ' > clientWidth ' + d.clientWidth + ' / innerWidth ' + innerWidth)
784 return out.join('; ')
785 })('`+v+`')`))
786 if got != "" {
787 t.Errorf("%s view at 320×700: %s", v, got)
788 }
789 te.rig.Screen("[slides-stage-pane]", v+" view at 320px")
790 }
791}
792
793// cardJS is the inspector card's geometry against the desk, the stages
794// and the window: its state, whether it is drawn, its box, how it
795// scrolls, and the desktop frame's box (the slide on the stage).
796const cardJS = `(() => {
797 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} }
798 const card = q('[slides-inspector]'), cs = getComputedStyle(card)
799 const fmt = q('[data-view-toggle="inspector"][aria-expanded]')
800 const slide = q('[slides-stage] > [slides-slide]')
801 const d = document.documentElement
802 return {
803 State: card.dataset.state, Display: cs.display, Position: cs.position, Shadow: cs.boxShadow, OverflowY: cs.overflowY,
804 Expanded: fmt.getAttribute('aria-expanded'), Pressed: q('[estilo-menu-item][data-view-toggle="inspector"]').getAttribute('aria-pressed'),
805 Card: box(card), Desk: box(q('[slides-desk]')), Strip: box(q('[slides-strip-nav]')), Pane: box(q('[slides-stage-pane]')),
806 Notes: box(q('[slides-notes-pane]')), Slide: slide ? box(slide) : null, Format: box(fmt),
807 ScrollH: card.scrollHeight, ClientH: card.clientHeight,
808 DocW: d.scrollWidth, DocH: d.scrollHeight, ClientW: d.clientWidth, WinW: innerWidth, WinH: innerHeight,
809 Cookie: document.cookie
810 }
811})()`
812
813type cardState struct {
814 State, Display, Position, Shadow, OverflowY, Expanded, Pressed, Cookie string
815 Card, Desk, Strip, Pane, Notes, Format edges4
816 Slide *edges4
817 ScrollH, ClientH, DocW, DocH, ClientW, WinW, WinH float64
818}
819
820type edges4 struct{ L, T, R, B, W, H float64 }
821
822func (te *tidyEditor) card() cardState {
823 var c cardState
824 te.rig.Run(evalInto(&c, cardJS))
825 return c
826}
827
828// pressFormat clicks the bar's Format button and waits for the card to
829// be in state.
830func (te *tidyEditor) pressFormat(state string) {
831 te.rig.Run(
832 chromedp.Click(chromedp.CSS(`[estilo-bar-control] > [data-view-toggle="inspector"]`)),
833 waitFor(`document.querySelector('[slides-inspector]').dataset.state === '`+state+`'`),
834 )
835}
836
837// TestTidyCardFloats (spec §2, §4): at 1280×720 the inspector is Docs'
838// card over the desk's top end corner, 12px in from the desk's top and
839// end edges, 248px wide, stopping 12px or more short of its foot and
840// scrolling inside itself when what it holds is taller; the slide is
841// never under it, and re-centres in the desk when Format hides it. The
842// state is a cookie the server reads, so the first paint is already
843// final: with the bundle blocked, a closed card is not drawn and an
844// open one is where it will stay.
845func TestTidyCardFloats(t *testing.T) {
846 te := openTidyEditor(t, 3, 1280, 720)
847 near := func(a, b float64) bool { return math.Abs(a-b) <= 1 }
848
849 c := te.card()
850 if c.State != "open" || c.Display == "none" || c.Expanded != "true" || c.Pressed != "true" {
851 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)
852 }
853 if c.Position != "absolute" {
854 t.Errorf("the card's position is %s, want absolute", c.Position)
855 }
856 if !near(c.Card.T-c.Desk.T, 12) || !near(c.Desk.R-c.Card.R, 12) || !near(c.Card.W, 248) {
857 t.Errorf("the card is %+v in the desk %+v; want 12px from its top and end, 248px wide", c.Card, c.Desk)
858 }
859 if c.Card.L < c.Desk.L || c.Card.B > c.Desk.B-12+0.5 {
860 t.Errorf("the card %+v is not inside the desk %+v, 12px short of its foot", c.Card, c.Desk)
861 }
862 if c.Slide == nil || c.Slide.R > c.Card.L-0.5 {
863 t.Errorf("the desktop frame %+v runs under the card (left %.1f)", c.Slide, c.Card.L)
864 }
865 if c.Notes.R > c.Card.L-0.5 {
866 t.Errorf("the notes card (right %.1f) runs under the inspector card (left %.1f)", c.Notes.R, c.Card.L)
867 }
868 te.rig.Screen(`[slides-editor]`, "the card over the desk")
869
870 // The slide's options (nothing selected: the card's longest on this
871 // deck, since it shows one thing at a time), in a window short enough
872 // that they are taller than the card, which scrolls inside itself;
873 // the page does not. Since the deck's options (Q2) and the list of
874 // boxes (Q5) left the card, and its layout became a row of pictures
875 // with two quiet rows (Q3), only a 252px window makes them overflow.
876 te.rig.Run(waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`))
877 c = te.card()
878 if c.ScrollH <= c.ClientH {
879 te.size(1280, 252)
880 c = te.card()
881 }
882 if c.ScrollH <= c.ClientH || (c.OverflowY != "auto" && c.OverflowY != "scroll") {
883 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)
884 }
885 if c.Card.B > c.Desk.B-12+0.5 {
886 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)
887 }
888 var scrolled float64
889 te.rig.Run(evalInto(&scrolled, `(c => { c.scrollTop = 200; return c.scrollTop })(document.querySelector('[slides-inspector]'))`))
890 if scrolled <= 0 {
891 t.Errorf("the card does not scroll (scrollTop %g)", scrolled)
892 }
893 if got := te.scrolls(t); got != "" {
894 t.Errorf("on the slide's options the page scrolls: %s", got)
895 }
896 te.rig.Screen(`[slides-editor]`, "the slide's options, the card scrolled")
897 te.size(1280, 720)
898 te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-inspector]').scrollTop = 0`))
899
900 // A selected box whose options are taller than the card (a canvas
901 // shape's, the longest a box has) in a short window: the card
902 // scrolls inside itself, and the page does not.
903 canvas := te.addCanvasShape(t)
904 // Its On a phone group is part of what makes it tall, and only the
905 // phone views draw it (Q6): the test is in Both view.
906 te.openOn(canvas)
907 te.view("both")
908 te.selectBox("shape")
909 te.size(1280, 480)
910 c = te.card()
911 if c.ScrollH <= c.ClientH || (c.OverflowY != "auto" && c.OverflowY != "scroll") {
912 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)
913 }
914 var moved struct{ Top, Shift float64 }
915 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]'))`))
916 if moved.Top <= 0 || moved.Shift <= 0 {
917 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)
918 }
919 if got := te.scrolls(t); got != "" {
920 t.Errorf("1280x480, a shape selected: the page scrolls: %s", got)
921 }
922 te.rig.Screen(`[slides-editor]`, "1280x480, a shape selected, the card scrolled")
923 te.size(1280, 720)
924 te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-inspector]').scrollTop = 0`))
925 te.view("desktop") // the one stage that re-centres alone
926
927 // Format hides it: the frame re-centres in the desk (the strip's
928 // edge to the desk's end), and the cookie says closed.
929 te.pressFormat("closed")
930 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 })()`))
931 c = te.card()
932 if c.Display != "none" || c.Expanded != "false" || c.Pressed != "false" {
933 t.Errorf("after Format: display %s, aria-expanded %s, View row aria-pressed %s", c.Display, c.Expanded, c.Pressed)
934 }
935 if !strings.Contains(c.Cookie, "slides-inspector=closed") {
936 t.Errorf("after Format the cookies are %q; want slides-inspector=closed", c.Cookie)
937 }
938 te.rig.Screen(`[slides-editor]`, "the card hidden, the slide re-centred")
939
940 // No flash: the server paints the remembered state before any
941 // script. The bundle is blocked, so what is measured is the server's
942 // HTML and CSS alone.
943 te.rig.Run(
944 cdpStep(network.Enable, network.EnableParams{}),
945 blockURLs("*/static/editor.*.js"),
946 chromedp.Navigate(te.rig.Origin+te.path),
947 chromedp.WaitReady(chromedp.CSS(`[slides-inspector]`)),
948 )
949 var bound bool
950 te.rig.Run(evalInto(&bound, editorBound))
951 if bound {
952 t.Fatal("the editor bound with its bundle blocked; this check would not be of the first paint")
953 }
954 if c := te.card(); c.Display != "none" || c.Expanded != "false" || c.Pressed != "false" {
955 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)
956 }
957 te.rig.Run(
958 cdpStep(network.DeleteCookies, network.DeleteCookiesParams{Name: "slides-inspector", URL: te.rig.Origin + "/"}),
959 chromedp.Navigate(te.rig.Origin+te.path),
960 chromedp.WaitReady(chromedp.CSS(`[slides-inspector]`)),
961 )
962 c = te.card()
963 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) {
964 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)
965 }
966 te.rig.Run(blockURLs())
967}
968
969// TestTidyNarrowAndShortWindows (Review Focus 1): under 1100px, down to
970// 320px, the card is in the flow under the stage with no shadow, Format
971// still shows and hides it, and nothing scrolls sideways; at 1280×600
972// the card and the notes scroll inside themselves and the page does not.
973func TestTidyNarrowAndShortWindows(t *testing.T) {
974 te := openTidyEditor(t, 3, 1280, 720)
975 for _, vp := range [][2]int64{{1000, 800}, {320, 700}} {
976 te.size(vp[0], vp[1])
977 name := fmt.Sprintf("%dx%d", vp[0], vp[1])
978 c := te.card()
979 if c.Display == "none" || c.Position == "absolute" || c.Shadow != "none" {
980 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)
981 }
982 if c.Card.T < c.Pane.B-0.5 {
983 t.Errorf("%s: the card (top %.1f) is not under the stage pane (bottom %.1f)", name, c.Card.T, c.Pane.B)
984 }
985 if c.DocW > c.ClientW || c.Card.R > c.WinW+0.5 {
986 t.Errorf("%s: something is wider than the window: scrollWidth %.0f, clientWidth %.0f, card right %.1f", name, c.DocW, c.ClientW, c.Card.R)
987 }
988 if c.Format.W < 24 || c.Format.H < 24 || c.Format.L < 0 || c.Format.R > c.WinW {
989 t.Errorf("%s: the Format button is %+v; want it on screen and at least 24×24", name, c.Format)
990 }
991 te.rig.Screen(`[slides-editor]`, name+", the card in the flow")
992 te.pressFormat("closed")
993 if c := te.card(); c.Display != "none" || c.Expanded != "false" || c.DocW > c.ClientW {
994 t.Errorf("%s: after Format the card is display %s, aria-expanded %s, scrollWidth %.0f", name, c.Display, c.Expanded, c.DocW)
995 }
996 te.pressFormat("open")
997 if c := te.card(); c.Display == "none" || c.Expanded != "true" {
998 t.Errorf("%s: after Format again the card is display %s, aria-expanded %s", name, c.Display, c.Expanded)
999 }
1000 }
1001
1002 // Short enough that the slide's options overflow the card (252px:
1003 // since Q2, Q5 and Q3 took the deck's options, the list of boxes and
1004 // the layout's fields out of the card, 380px is not).
1005 te.size(1280, 252)
1006 // From 320px the stacked bar's height is still published on the
1007 // root (estilo chrome.js's --estilo-bar-block-size) until the media
1008 // query's change event lands, a frame after the resize: until then
1009 // the bar is as tall as it was at 320px and the desk under it is
1010 // short. The card is measured once that is gone.
1011 te.rig.Run(waitFor(`document.documentElement.style.getPropertyValue('--estilo-bar-block-size') === ''`))
1012 c := te.card()
1013 if c.ScrollH <= c.ClientH || c.Card.B > c.Desk.B-12+0.5 {
1014 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)
1015 }
1016 var notes string
1017 te.rig.Run(evalInto(&notes, `(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]'))`))
1018 if notes != "" {
1019 t.Errorf("1280x252: %s", notes)
1020 }
1021 if got := te.scrolls(t); got != "" {
1022 t.Errorf("1280x252: the page scrolls: %s", got)
1023 }
1024 te.rig.Screen(`[slides-editor]`, "1280x252")
1025}
1026
1027// focusJS says where focus is: the element's description, whether it is
1028// drawn (a box, and not inside a closed <details> other than as its
1029// summary), and whether it is in the card.
1030const focusJS = `(() => {
1031 const a = document.activeElement
1032 if (!a || a === document.body) return {Where: 'body', Drawn: false, InCard: false}
1033 const r = a.getBoundingClientRect()
1034 const closed = a.closest('details:not([open])')
1035 const hidden = closed && !(a.matches('summary') && a.parentElement === closed)
1036 return {
1037 Where: a.matches('[slides-menu="view"] > summary') ? 'view menu' : a.matches('[estilo-bar-control] > [data-view-toggle="inspector"]') ? 'format' : a.outerHTML.slice(0, 80),
1038 Drawn: r.width > 0 && r.height > 0 && !hidden && a.checkVisibility(),
1039 InCard: !!a.closest('[slides-inspector]')
1040 }
1041})()`
1042
1043type focusState struct {
1044 Where string
1045 Drawn, InCard bool
1046}
1047
1048func (te *tidyEditor) focus() focusState {
1049 var f focusState
1050 te.rig.Run(evalInto(&f, focusJS))
1051 return f
1052}
1053
1054// tabTo presses Tab until the element sel has focus, at most n times.
1055func (te *tidyEditor) tabTo(t *testing.T, sel string, n int) {
1056 t.Helper()
1057 for range n {
1058 var on bool
1059 te.rig.Run(evalInto(&on, `document.activeElement === document.querySelector('`+sel+`')`))
1060 if on {
1061 return
1062 }
1063 te.rig.Run(chromedp.KeyEvent(kb.Tab))
1064 }
1065 t.Fatalf("Tab never reached %s; focus is %+v", sel, te.focus())
1066}
1067
1068// TestTidyCardFocusReturns (spec §4.4): opened from the keyboard, the
1069// card takes focus; dismissed, it gives focus back to where the action
1070// came from, and that is somewhere a person can see. From the View
1071// menu, that is the menu's own button (its summary): the Inspector row
1072// is hidden once the menu closes.
1073func TestTidyCardFocusReturns(t *testing.T) {
1074 te := openTidyEditor(t, 3, 1280, 720)
1075 te.pressFormat("closed")
1076
1077 const viewMenu = `[slides-menu="view"] > summary`
1078 const row = `[estilo-menu-item][data-view-toggle="inspector"]`
1079 openFromView := func() {
1080 te.rig.Run(
1081 chromedp.Evaluate[chromedp.Void](`document.querySelector('`+viewMenu+`').focus()`),
1082 chromedp.KeyEvent(kb.Enter),
1083 waitFor(`document.querySelector('[slides-menu="view"]').open`),
1084 )
1085 te.tabTo(t, row, 12)
1086 te.rig.Run(chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelector('[slides-inspector]').dataset.state === 'open'`))
1087 if f := te.focus(); !f.InCard || !f.Drawn {
1088 t.Fatalf("opened from View → Inspector by keyboard, focus is %+v; want it on a control in the card", f)
1089 }
1090 }
1091
1092 // Dismissed with Format, from the keyboard.
1093 openFromView()
1094 te.rig.Run(
1095 chromedp.Evaluate[chromedp.Void](`document.querySelector('[estilo-bar-control] > [data-view-toggle="inspector"]').focus()`),
1096 chromedp.KeyEvent(kb.Enter),
1097 waitFor(`document.querySelector('[slides-inspector]').dataset.state === 'closed'`),
1098 )
1099 if f := te.focus(); f.Where != "view menu" || !f.Drawn {
1100 t.Errorf("dismissed with Format, focus is %+v; want the View menu's button, drawn", f)
1101 }
1102
1103 // Dismissed with the View row again, from the keyboard.
1104 openFromView()
1105 te.rig.Run(
1106 chromedp.Evaluate[chromedp.Void](`document.querySelector('`+viewMenu+`').focus()`),
1107 chromedp.KeyEvent(kb.Enter),
1108 waitFor(`document.querySelector('[slides-menu="view"]').open`),
1109 )
1110 te.tabTo(t, row, 12)
1111 te.rig.Run(chromedp.KeyEvent(kb.Enter), waitFor(`document.querySelector('[slides-inspector]').dataset.state === 'closed'`))
1112 if f := te.focus(); f.Where != "view menu" || !f.Drawn {
1113 t.Errorf("dismissed with View → Inspector, focus is %+v; want the View menu's button, drawn", f)
1114 }
1115}
1116
1117// inspectJS is what the card shows: data-inspect, which of the three
1118// sections are drawn, the selected box's kind, and the card's named controls, drawn (Got)
1119// and owed to that kind on this slide's layout by the Block form's own
1120// data-types and data-layout marks (Want).
1121const inspectJS = `(() => {
1122 const root = document.querySelector('[slides-editor]'), card = document.querySelector('[slides-inspector]')
1123 const form = s => card.querySelector('form[data-section="' + s + '"]')
1124 const drawn = el => !!el && el.checkVisibility() && el.getBoundingClientRect().height > 0
1125 const sel = document.querySelector('[slides-stage] [slides-block][aria-selected="true"]')
1126 const kind = sel ? sel.dataset.block : ''
1127 const layout = document.querySelector('[slides-stage] [slides-slide]')?.dataset.layout || ''
1128 const got = [], want = []
1129 for (const el of card.querySelectorAll('[name]')) if (el.checkVisibility()) got.push(el.name)
1130 for (const el of form('block').querySelectorAll('[name]')) {
1131 let ok = true
1132 for (let p = el; p && p !== form('block'); p = p.parentElement) {
1133 if (p.hasAttribute('data-types') && !p.getAttribute('data-types').split(' ').includes(kind)) ok = false
1134 if (p.hasAttribute('data-layout') && p.getAttribute('data-layout') !== layout) ok = false
1135 // A shape's field for some kinds alone (corner radius), and
1136 // Position and size, a group closed until it is opened (Q4).
1137 if (p.hasAttribute('data-kinds') && kind === 'shape' && !p.getAttribute('data-kinds').split(' ').includes(sel.dataset.kind || 'rect')) ok = false
1138 if (p.matches('details:not([open])') && el.parentElement !== p) ok = false
1139 }
1140 if (ok) want.push(el.name)
1141 }
1142 return {
1143 Inspect: root.dataset.inspect, Kind: kind,
1144 Box: drawn(form('block')), Slide: drawn(form('slide')), Deck: drawn(form('deck')),
1145 Got: got.sort(), Want: want.sort()
1146 }
1147})()`
1148
1149type inspectState struct {
1150 Inspect, Kind string
1151 Box, Slide, Deck bool
1152 Got, Want []string
1153}
1154
1155func (te *tidyEditor) inspect() inspectState {
1156 var s inspectState
1157 te.rig.Run(evalInto(&s, inspectJS))
1158 return s
1159}
1160
1161// onSlideOptions fails the test unless the card shows the slide's
1162// options: the Slide section, and no box's. The deck's are not in the
1163// card (the Deck settings dialog, Q2), nor the slide's boxes (View →
1164// Outline, Q5).
1165func (s inspectState) onSlideOptions(t *testing.T, after string) {
1166 t.Helper()
1167 if s.Inspect != "slide" || !s.Slide || s.Deck || s.Box {
1168 t.Errorf("after %s the card is %+v; want data-inspect=slide, the Slide section, and no box's or deck's", after, s)
1169 }
1170}
1171
1172// selectBox clicks the box of this kind on the stage and waits until it
1173// is the selection.
1174func (te *tidyEditor) selectBox(kind string) {
1175 sel := `[slides-stage] [slides-block][data-block="` + kind + `"]`
1176 te.rig.Run(
1177 chromedp.Click(chromedp.CSS(sel)),
1178 waitFor(`document.querySelector('`+sel+`')?.getAttribute('aria-selected') === 'true'`),
1179 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`),
1180 )
1181}
1182
1183// openOn opens this editor afresh on a canvas slide (the hash; the
1184// reload, because a new hash alone is not a new page), mounted: the
1185// canvas overlay is on the stage.
1186func (te *tidyEditor) openOn(slide string) {
1187 te.rig.Run(
1188 chromedp.Navigate(te.rig.Origin+te.path+"#"+slide),
1189 chromedp.Reload(),
1190 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+slide+`'`),
1191 waitFor(`document.querySelector('[slides-stage] [slides-canvas-overlay]')`),
1192 )
1193}
1194
1195// editorShown is true once a newly opened editor is settled in the view
1196// it will stay in: the remembered view (localStorage, shared by every
1197// tab of the origin) is applied, and the font gate has lifted its hold
1198// on the slide (html[data-slides-fonts="shown"]). Until then the slide
1199// is drawn with visibility: hidden, which nothing can click: a click on
1200// a box lands on the stage behind it. Both view holds longer than
1201// Desktop, because the phone preview is fetched before the hold lifts.
1202const editorShown = `document.documentElement.getAttribute('data-slides-fonts') === 'shown' &&
1203 document.querySelector('[slides-stage-pane]').dataset.view === (localStorage.getItem('slides.editor.view') || 'desktop')`
1204
1205// addCanvasShape adds a canvas slide holding one shape to this editor's
1206// deck, over the API, and returns the slide's id.
1207func (te *tidyEditor) addCanvasShape(t *testing.T) string {
1208 t.Helper()
1209 sqid := strings.TrimSuffix(strings.TrimPrefix(te.path, "/d/"), "/edit")
1210 token := mintAgent(t, te.app, te.cookies, "canvas-shape")
1211 apiJSON(t, te.app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
1212 `{"ops":[{"op":"add_slide","layout":"canvas","template":"blank"}]}`, http.StatusOK)
1213 view := apiJSON(t, te.app, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK)
1214 slides, _ := view["slides"].([]any)
1215 canvas, _ := slides[len(slides)-1].(map[string]any)["id"].(string)
1216 apiJSON(t, te.app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
1217 `{"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)
1218 return canvas
1219}
1220
1221// clickNotes puts the caret in the notes, near the top of their card
1222// (the notes can be longer than it), and waits for the card to say so.
1223func (te *tidyEditor) clickNotes() {
1224 var at []float64
1225 te.rig.Run(
1226 waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open'`),
1227 evalInto(&at, `(r => [r.left + 40, r.top + 12])(document.querySelector('[slides-notes]').getBoundingClientRect())`),
1228 )
1229 te.rig.Run(
1230 chromedp.MouseClickXY(at[0], at[1]),
1231 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'notes'`),
1232 )
1233}
1234
1235// TestTidyCardFollowsSelection (spec §4.1, §4.2): the card shows one
1236// thing, and this person's selection decides it. A box of each of the
1237// twelve kinds shows exactly the named controls its kind has (read off
1238// the form's own data-types); the caret in the notes shows none of the
1239// slide's or the deck's options and no field of a box's; the desk,
1240// a slide in the strip and Esc each bring back the slide's options. A
1241// colleague selecting a box changes nothing here.
1242func TestTidyCardFollowsSelection(t *testing.T) {
1243 var slide string
1244 te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string {
1245 var path string
1246 path, slide = deckWithEveryKind(t, a, cookies)
1247 return path
1248 })
1249 te.inspect().onSlideOptions(t, "opening the editor")
1250 te.openOn(slide)
1251 te.inspect().onSlideOptions(t, "opening the canvas slide")
1252 // The On a phone group is in the card in the phone views alone (Q6),
1253 // and each kind's want list holds it: the test is in Both view.
1254 te.view("both")
1255
1256 var kinds []string
1257 te.rig.Run(evalInto(&kinds, `[...document.querySelectorAll('[slides-menu="insert"] [data-insert-block]')].map(b => b.dataset.insertBlock)`))
1258 if len(kinds) != 12 {
1259 t.Fatalf("the Insert menu lists %d kinds, want twelve: %v", len(kinds), kinds)
1260 }
1261 for _, kind := range kinds {
1262 te.selectBox(kind)
1263 s := te.inspect()
1264 if s.Kind != kind || !s.Box || s.Slide || s.Deck {
1265 t.Errorf("%s selected: the card is %+v; want the box's options alone", kind, s)
1266 }
1267 if strings.Join(s.Got, " ") != strings.Join(s.Want, " ") {
1268 t.Errorf("%s selected: the card's named controls are\n %v\nwant\n %v", kind, s.Got, s.Want)
1269 }
1270 if kind == "shape" {
1271 te.rig.Screen(`[slides-editor]`, "a shape selected, its options")
1272 }
1273 }
1274
1275 // Corner radius is Style's, for an image and a shape alike (ruling
1276 // R16): a shape shows no Image group; an image's Image group holds
1277 // its file and fit.
1278 groupsJS := `(() => {
1279 const out = {}
1280 for (const g of document.querySelectorAll('[slides-inspector] form[data-section="block"] [data-group]')) {
1281 if (!g.checkVisibility()) continue
1282 // A group's label, or its disclosure's summary (Position and size, Q4).
1283 out[(g.querySelector('[estilo-inspector-label]') || g.querySelector('summary')).textContent.trim()] = [...g.querySelectorAll('[name]')].filter(el => el.checkVisibility()).map(el => el.name)
1284 }
1285 return out
1286 })()`
1287 for _, c := range []struct {
1288 kind string
1289 image []string // nil: no Image group drawn
1290 }{
1291 {"shape", nil},
1292 {"image", []string{"rst-block-image", "rst-block-fit", "rst-block-fit"}},
1293 } {
1294 te.selectBox(c.kind)
1295 var groups map[string][]string
1296 te.rig.Run(evalInto(&groups, groupsJS))
1297 image, shown := groups["Image"]
1298 if c.image == nil && shown {
1299 t.Errorf("%s selected: an Image group is drawn, holding %v; want none", c.kind, image)
1300 }
1301 if c.image != nil && strings.Join(image, " ") != strings.Join(c.image, " ") {
1302 t.Errorf("%s selected: the Image group holds %v, want %v", c.kind, image, c.image)
1303 }
1304 if !slicesHas(groups["Style"], "rst-block-radius") {
1305 t.Errorf("%s selected: Corner radius is not drawn in Style; the groups are %v", c.kind, groups)
1306 }
1307 }
1308
1309 // Back to the same box from the notes: its options again, though
1310 // the selection itself never changed.
1311 te.selectBox("shape")
1312 te.clickNotes()
1313 te.selectBox("shape")
1314 if s := te.inspect(); s.Kind != "shape" || !s.Box || s.Slide || s.Deck {
1315 t.Errorf("the shape, the notes, the shape again: the card is %+v; want the shape's options", s)
1316 }
1317
1318 // Esc in a box: one press, on a box with no caret and on one with
1319 // the caret in its text.
1320 te.selectBox("shape")
1321 te.rig.Run(
1322 chromedp.KeyEvent(kb.Escape),
1323 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
1324 )
1325 te.inspect().onSlideOptions(t, "Esc on a shape")
1326 te.selectBox("heading")
1327 te.rig.Run(waitFor(`document.activeElement.closest('[slides-block][data-block="heading"]')`))
1328 te.rig.Run(
1329 chromedp.KeyEvent(kb.Escape),
1330 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
1331 waitFor(`!document.querySelector('[slides-stage] [aria-selected="true"]')`),
1332 )
1333 te.inspect().onSlideOptions(t, "one Esc with the caret in a heading")
1334
1335 // Something transient takes the first Esc: the link prompt (Ctrl+K)
1336 // closes, and the box is still selected; the next Esc deselects it.
1337 te.selectBox("heading")
1338 te.rig.Run(
1339 waitFor(`document.activeElement.closest('[slides-block][data-block="heading"]')`),
1340 chromedp.KeyEvent("k", chromedp.KeyModifiers(chromedp.ModifierCtrl)),
1341 waitFor(`document.querySelector('dialog[open]')`),
1342 chromedp.KeyEvent(kb.Escape),
1343 waitFor(`!document.querySelector('dialog[open]')`),
1344 waitFor(`document.activeElement.closest('[slides-block][data-block="heading"]')`),
1345 // The dialog's close event is a task of its own, and the prompt
1346 // gives the caret back to the heading when it runs: a person's
1347 // next Esc comes after it, and so does this one.
1348 chromedp.Sleep(100*time.Millisecond),
1349 )
1350 if s := te.inspect(); s.Inspect != "box" || s.Kind != "heading" {
1351 t.Errorf("Esc closing the link prompt left the card %+v; want the heading's options still", s)
1352 }
1353 te.rig.Run(
1354 chromedp.KeyEvent(kb.Escape),
1355 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
1356 )
1357 te.inspect().onSlideOptions(t, "Esc after the link prompt closed")
1358
1359 // The desk: the slide's own ground (under the grid's last row, which
1360 // every one of the twelve kinds fills now), and the pane beside the
1361 // slide.
1362 for _, where := range []struct{ name, js string }{
1363 {"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())`},
1364 {"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())`},
1365 } {
1366 te.selectBox("shape")
1367 var xy []float64
1368 te.rig.Run(evalInto(&xy, where.js))
1369 te.rig.Run(
1370 chromedp.MouseClickXY(xy[0], xy[1]),
1371 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
1372 waitFor(`!document.querySelector('[slides-stage] [aria-selected="true"]')`),
1373 )
1374 te.inspect().onSlideOptions(t, where.name)
1375 }
1376
1377 // A slide in the strip, and back.
1378 te.selectBox("list")
1379 te.rig.Run(
1380 chromedp.Click(chromedp.CSS(`[slides-strip-item]:first-child [slides-strip-link]`)),
1381 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.index === '0'`),
1382 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
1383 )
1384 te.inspect().onSlideOptions(t, "a slide picked in the strip")
1385
1386 // View → Outline, from the keyboard: the box's options, and focus on
1387 // the box it chose (Q5; the card's list of boxes is gone).
1388 var focus struct {
1389 OnBox, Shown bool
1390 }
1391 te.rig.Run(
1392 openOutline(),
1393 chromedp.KeyEvent(kb.Enter),
1394 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`),
1395 evalInto(&focus, `(a => ({OnBox: !!a.closest('[slides-stage] [slides-block][aria-selected="true"]'), Shown: a.checkVisibility()}))(document.activeElement)`),
1396 )
1397 if !focus.OnBox || !focus.Shown {
1398 t.Errorf("a box chosen from the Outline by keyboard leaves focus %+v; want it on that box", focus)
1399 }
1400
1401 // The caret in the notes (a box still selected, from the Outline):
1402 // neither the slide's options nor the deck's, and none of the box's
1403 // fields (the Text group alone, TestTidyMarksInCard).
1404 te.clickNotes()
1405 if s := te.inspect(); s.Slide || s.Deck || len(s.Got) != 0 {
1406 t.Errorf("with the caret in the notes the card is %+v; want no slide or deck options and no named control", s)
1407 }
1408 te.rig.Screen(`[slides-editor]`, "the caret in the notes")
1409 // A colleague's change to this slide re-fetches the stage and
1410 // re-marks the selected box; that is not this person choosing it,
1411 // and the card stays on the notes.
1412 var first string
1413 te.rig.Run(evalInto(&first, `document.querySelector('[slides-stage] [slides-slide]').dataset.id`))
1414 sqid := strings.TrimSuffix(strings.TrimPrefix(te.path, "/d/"), "/edit")
1415 token := mintAgent(t, te.app, te.cookies, "colleague")
1416 apiJSON(t, te.app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
1417 `{"ops":[{"op":"add_block","slide":`+quote(first)+`,"type":"text","region":"body","markdown":"From a colleague"}]}`, http.StatusOK)
1418 te.rig.Run(waitFor(`[...document.querySelectorAll('[slides-stage] [data-block="text"]')].some(b => b.textContent.includes('From a colleague'))`))
1419 if s := te.inspect(); s.Inspect != "notes" {
1420 t.Errorf("after a colleague's change re-fetched the stage, the card is %+v; want it still on the notes", s)
1421 }
1422 // Escape on the notes: the slide's options. Once with the caret
1423 // gone (the refresh rebinds the notes and takes the caret with it),
1424 // once with it in the notes.
1425 te.rig.Run(
1426 chromedp.KeyEvent(kb.Escape),
1427 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
1428 )
1429 te.inspect().onSlideOptions(t, "Esc on the notes, the caret taken by a refresh")
1430 te.clickNotes()
1431 te.rig.Run(
1432 chromedp.KeyEvent(kb.Escape),
1433 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
1434 )
1435 te.inspect().onSlideOptions(t, "Esc in the notes")
1436
1437 // A colleague's selection is theirs: a second tab on the canvas
1438 // slide selects a box; once it is drawn here, this card is as it was.
1439 te.openOn(slide)
1440 tab2, cancel := chromedp.NewContext(te.rig.Context())
1441 defer cancel()
1442 runOn(t, tab2,
1443 chromedp.EmulateViewport(1280, 720),
1444 chromedp.Navigate(te.rig.Origin+te.path+"#"+slide),
1445 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+slide+`'`),
1446 waitFor(editorShown),
1447 chromedp.Click(chromedp.CSS(`[slides-stage] [data-block="shape"]`)),
1448 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`),
1449 )
1450 te.rig.Run(waitFor(`document.querySelector('[slides-presence-mark]')`))
1451 te.inspect().onSlideOptions(t, "a colleague selected a box")
1452}
1453
1454// TestTidyCardSurvivesBoxRemoval (Review Focus 2): the box this person
1455// has selected is deleted by a colleague; within a second the card is
1456// back on the slide's options, and never shows an empty box.
1457func TestTidyCardSurvivesBoxRemoval(t *testing.T) {
1458 var slide string
1459 te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string {
1460 var path string
1461 path, slide = deckWithEveryKind(t, a, cookies)
1462 return path
1463 })
1464 te.openOn(slide)
1465 te.selectBox("shape")
1466
1467 tab2, cancel := chromedp.NewContext(te.rig.Context())
1468 defer cancel()
1469 runOn(t, tab2,
1470 chromedp.EmulateViewport(1280, 720),
1471 chromedp.Navigate(te.rig.Origin+te.path+"#"+slide),
1472 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+slide+`'`),
1473 waitFor(editorShown),
1474 chromedp.Click(chromedp.CSS(`[slides-stage] [data-block="shape"]`)),
1475 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`),
1476 )
1477 // The clock starts at the press on Delete, in the box's menu (Q4),
1478 // over there.
1479 runOn(t, tab2, openBoxMenu())
1480 start := time.Now()
1481 runOn(t, tab2, chromedp.Click(chromedp.CSS(`[slides-box-menu] [data-row="block-delete"]`)))
1482 te.rig.Run(waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide' && !document.querySelector('[slides-stage] [data-block="shape"]')`))
1483 if took := time.Since(start); took > time.Second {
1484 t.Errorf("the card took %v to leave the deleted box, want under a second", took)
1485 }
1486 te.inspect().onSlideOptions(t, "a colleague deleted the selected box")
1487 te.rig.Screen(`[slides-editor]`, "the selected box deleted elsewhere")
1488}
1489
1490// TestTidyEmptyDeck (Review Focus 4): a deck with no slides. The card
1491// shows no section (the deck's options are the Deck settings dialog's
1492// since Q2); the notes tab is disabled and the notes
1493// card cannot open; New slide is pinned in view and adds a slide.
1494func TestTidyEmptyDeck(t *testing.T) {
1495 rig, app := newRigApp(t, nil)
1496 cookies := signedIn(t, app, allowedAddress)
1497 var set []chromedp.Action[chromedp.Void]
1498 for _, c := range cookies {
1499 set = append(set, cdpStep(network.SetCookie, network.SetCookieParams{
1500 Name: c.Name, Value: c.Value, URL: rig.Origin + "/",
1501 HTTPOnly: new(c.HttpOnly), Secure: new(c.Secure), SameSite: network.CookieSameSiteLax,
1502 }))
1503 }
1504 rig.Run(set...)
1505 te := &tidyEditor{rig: rig, app: app, cookies: cookies, path: emptyDeck(t, app, cookies)}
1506 te.size(1280, 720)
1507 rig.Run(
1508 chromedp.Navigate(rig.Origin+te.path),
1509 chromedp.WaitVisible(chromedp.CSS(`[slides-stage-empty]`)),
1510 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
1511 )
1512 s := te.inspect()
1513 if s.Deck || s.Slide || s.Box {
1514 t.Errorf("with no slides the card is %+v; want no section (the deck's are the Deck settings dialog's)", s)
1515 }
1516 var notes struct {
1517 Disabled, PaneShown bool
1518 }
1519 rig.Run(evalInto(&notes, `({Disabled: document.querySelector('[slides-notes-open]').disabled, PaneShown: document.querySelector('[slides-notes-pane]').checkVisibility()})`))
1520 if !notes.Disabled || notes.PaneShown {
1521 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)
1522 }
1523 // The View menu's Speaker notes row cannot bring the card up either.
1524 rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[data-view-toggle="notes"]').click()`))
1525 rig.Run(evalInto(&notes.PaneShown, `document.querySelector('[slides-notes-pane]').checkVisibility()`))
1526 if notes.PaneShown {
1527 t.Error("with no slides the View menu's Speaker notes row shows the notes card")
1528 }
1529 rig.Screen(`[slides-editor]`, "an empty deck")
1530
1531 const pill = `[slides-strip-add] > button:first-child`
1532 var inView bool
1533 rig.Run(evalInto(&inView, `(r => r.width > 0 && r.top >= 0 && r.bottom <= innerHeight)(document.querySelector('`+pill+`').getBoundingClientRect())`))
1534 if !inView {
1535 t.Error("with no slides New slide is not in view")
1536 }
1537 rig.Run(
1538 chromedp.Click(chromedp.CSS(pill)),
1539 waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 1`),
1540 waitFor(`document.querySelector('[slides-stage] [slides-slide]')`),
1541 waitFor(`!document.querySelector('[slides-notes-open]').disabled`),
1542 )
1543 te.inspect().onSlideOptions(t, "New slide in an empty deck")
1544}
1545
1546// marksJS is the card's Text group as a person meets it: each mark's
1547// pressed and disabled state and whether it is drawn, the groups and
1548// named controls drawn, whether the slide's and the deck's options
1549// show, and whether the stage bar still has marks.
1550const marksJS = `(() => {
1551 const card = document.querySelector('[slides-inspector]')
1552 const drawn = el => !!el && el.checkVisibility() && el.getBoundingClientRect().height > 0
1553 const marks = {}
1554 for (const b of card.querySelectorAll('[data-mark]')) marks[b.dataset.mark] = {Pressed: b.getAttribute('aria-pressed') === 'true', Disabled: b.disabled, Drawn: drawn(b)}
1555 return {
1556 Inspect: document.querySelector('[slides-editor]').dataset.inspect,
1557 Marks: marks,
1558 Groups: [...card.querySelectorAll('[data-group]')].filter(drawn).map(g => g.dataset.group),
1559 Named: [...card.querySelectorAll('[name]')].filter(el => el.checkVisibility()).map(el => el.name),
1560 Slide: drawn(card.querySelector('form[data-section="slide"]')),
1561 Deck: drawn(card.querySelector('form[data-section="deck"]')),
1562 Bar: !!document.querySelector('[slides-stage-bar] [data-mark]')
1563 }
1564})()`
1565
1566type markState struct{ Pressed, Disabled, Drawn bool }
1567
1568type marksState struct {
1569 Inspect string
1570 Marks map[string]markState
1571 Groups []string
1572 Named []string
1573 Slide, Deck bool
1574 Bar bool
1575}
1576
1577func (te *tidyEditor) marks() marksState {
1578 var s marksState
1579 te.rig.Run(evalInto(&s, marksJS))
1580 return s
1581}
1582
1583// TestTidyMarksInCard (spec E3, §4.2): the five marks are the card's
1584// Text group. With the caret in a box's text and in the notes, each
1585// toggles its mark, shows it pressed, and leaves the caret in the text;
1586// the shortcuts still work; before any text has had the caret they are
1587// disabled, as the pill's were; a box with no text has no Text group;
1588// and the caret in the notes shows the Text group and nothing else.
1589func TestTidyMarksInCard(t *testing.T) {
1590 var slide string
1591 te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string {
1592 var path string
1593 path, slide = deckWithEveryKind(t, a, cookies)
1594 return path
1595 })
1596 te.openOn(slide)
1597 if s := te.marks(); s.Bar || len(s.Marks) != 5 {
1598 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)
1599 }
1600
1601 // No text has had the caret yet: the heading selected by its address
1602 // (#slide/box, which selects without the caret; the Outline puts the
1603 // caret in a heading) shows the Text group, its marks disabled.
1604 var heading string
1605 te.rig.Run(evalInto(&heading, `document.querySelector('[slides-stage] [data-block="heading"]').dataset.id`))
1606 te.rig.Run(
1607 chromedp.Evaluate[chromedp.Void](`location.hash = '`+slide+`/`+heading+`'`),
1608 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`),
1609 )
1610 s := te.marks()
1611 for m, st := range s.Marks {
1612 if !st.Drawn || !st.Disabled {
1613 t.Errorf("a heading selected before any text had the caret: mark %s is %+v; want drawn and disabled", m, st)
1614 }
1615 }
1616 // A box with no text has no Text group.
1617 te.selectBox("image")
1618 if s := te.marks(); slicesHas(s.Groups, "text") {
1619 t.Errorf("an image selected: the card's groups are %v; want no Text group", s.Groups)
1620 }
1621
1622 const inHeading = `document.activeElement.closest('[slides-stage] [data-block="heading"]')`
1623 const headingEl = `document.querySelector('[slides-stage] [data-block="heading"]')`
1624 tags := map[string]string{"b": "strong", "i": "em", "c": "code", "h": "mark"}
1625 keys := map[string]chromedp.Action[chromedp.Void]{
1626 "b": modKey("b", chromedp.ModifierCtrl),
1627 "i": modKey("i", chromedp.ModifierCtrl),
1628 "c": modKey("e", chromedp.ModifierCtrl),
1629 "h": modKey("H", chromedp.ModifierCtrl|chromedp.ModifierShift),
1630 }
1631 pressed := func(m string) string {
1632 return `document.querySelector('[slides-inspector] [data-mark="` + m + `"]').getAttribute('aria-pressed') === 'true'`
1633 }
1634
1635 // In a box: the heading, its words selected.
1636 te.selectBox("heading")
1637 te.rig.Run(waitFor(inHeading), modKey("a", chromedp.ModifierCtrl))
1638 s = te.marks()
1639 if s.Inspect != "box" || !slicesHas(s.Groups, "text") {
1640 t.Fatalf("the caret in the heading: the card is %+v; want the heading's options with its Text group", s)
1641 }
1642 for _, m := range []string{"b", "i", "c", "h"} {
1643 te.rig.Run(
1644 chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="`+m+`"]`)),
1645 waitFor(headingEl+`.querySelector('`+tags[m]+`')`),
1646 waitFor(pressed(m)),
1647 )
1648 var in bool
1649 te.rig.Run(evalInto(&in, `!!`+inHeading))
1650 if !in {
1651 t.Errorf("clicking the %s mark in the card took the caret out of the heading", m)
1652 }
1653 }
1654 te.rig.Screen(`[slides-editor]`, "the heading's marks, pressed in the card")
1655 // The link: the button opens the link prompt, as Mod+K does.
1656 te.rig.Run(
1657 chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="href"]`)),
1658 waitFor(`document.querySelector('[slides-link-dialog]').open`),
1659 chromedp.SendKeys(chromedp.CSS(`#slides-link-url`), "https://example.test/"),
1660 chromedp.KeyEvent(kb.Enter),
1661 waitFor(`!document.querySelector('[slides-link-dialog]').open`),
1662 waitFor(headingEl+`.querySelector('a[href="https://example.test/"]')`),
1663 waitFor(pressed("href")),
1664 )
1665 // The shortcuts take each off again.
1666 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))
1667 for _, m := range []string{"b", "i", "c", "h"} {
1668 te.rig.Run(
1669 keys[m],
1670 waitFor(`!`+headingEl+`.querySelector('`+tags[m]+`')`),
1671 waitFor(`!(`+pressed(m)+`)`),
1672 )
1673 }
1674 te.rig.Run(
1675 modKey("k", chromedp.ModifierCtrl),
1676 waitFor(`document.querySelector('[slides-link-dialog]').open`),
1677 chromedp.Click(chromedp.CSS(`[slides-link-dialog] button[value="remove"]`)),
1678 waitFor(`!`+headingEl+`.querySelector('a')`),
1679 waitFor(`!(`+pressed("href")+`)`),
1680 )
1681
1682 // The code block: the marks act there as the pill's did.
1683 te.rig.Run(
1684 chromedp.Click(chromedp.CSS(`[slides-stage] [data-block="code"] code`)),
1685 waitFor(`document.activeElement.closest('[slides-stage] [data-block="code"]')`),
1686 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`),
1687 modKey("a", chromedp.ModifierCtrl),
1688 chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="b"]`)),
1689 waitFor(`document.querySelector('[slides-stage] [data-block="code"] strong')`),
1690 waitFor(pressed("b")),
1691 modKey("b", chromedp.ModifierCtrl),
1692 waitFor(`!document.querySelector('[slides-stage] [data-block="code"] strong')`),
1693 )
1694
1695 // In the notes: the Text group and nothing else.
1696 te.clickNotes()
1697 s = te.marks()
1698 if strings.Join(s.Groups, " ") != "text" || len(s.Named) != 0 || s.Slide || s.Deck {
1699 t.Errorf("the caret in the notes: the card is %+v; want the Text group alone", s)
1700 }
1701 for m, st := range s.Marks {
1702 if !st.Drawn || st.Disabled {
1703 t.Errorf("the caret in the notes: mark %s is %+v; want drawn and enabled", m, st)
1704 }
1705 }
1706 te.rig.Screen(`[slides-editor]`, "the caret in the notes, the Text group alone")
1707 const inNotes = `document.activeElement.closest('[slides-notes]')`
1708 te.rig.Run(
1709 chromedp.KeyEvent("Spoken words"),
1710 waitFor(`document.querySelector('[slides-notes]').textContent.includes('Spoken words')`),
1711 modKey("a", chromedp.ModifierCtrl),
1712 )
1713 for _, m := range []string{"b", "i", "c", "h"} {
1714 te.rig.Run(
1715 chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="`+m+`"]`)),
1716 waitFor(`document.querySelector('[slides-notes]').querySelector('`+tags[m]+`')`),
1717 waitFor(pressed(m)),
1718 )
1719 var in bool
1720 te.rig.Run(evalInto(&in, `!!`+inNotes))
1721 if !in {
1722 t.Errorf("clicking the %s mark in the card took the caret out of the notes", m)
1723 }
1724 te.rig.Run(
1725 keys[m],
1726 waitFor(`!document.querySelector('[slides-notes]').querySelector('`+tags[m]+`')`),
1727 )
1728 }
1729 // The link in the notes: put on with the card's button and taken off
1730 // with Mod+K, then put on with Mod+K and taken off with the button.
1731 const notesLink = `document.querySelector('[slides-notes] a[href="https://example.test/notes"]')`
1732 link := func(open chromedp.Action[chromedp.Void], how string) {
1733 t.Helper()
1734 te.rig.Run(
1735 open,
1736 waitFor(`document.querySelector('[slides-link-dialog]').open`),
1737 chromedp.SendKeys(chromedp.CSS(`#slides-link-url`), "https://example.test/notes"),
1738 chromedp.KeyEvent(kb.Enter),
1739 waitFor(`!document.querySelector('[slides-link-dialog]').open`),
1740 waitFor(notesLink),
1741 waitFor(pressed("href")),
1742 )
1743 var in bool
1744 te.rig.Run(evalInto(&in, `!!`+inNotes))
1745 if !in {
1746 t.Errorf("a link put on the notes with %s left the caret out of the notes", how)
1747 }
1748 }
1749 unlink := func(open chromedp.Action[chromedp.Void]) {
1750 t.Helper()
1751 te.rig.Run(
1752 open,
1753 waitFor(`document.querySelector('[slides-link-dialog]').open`),
1754 chromedp.Click(chromedp.CSS(`[slides-link-dialog] button[value="remove"]`)),
1755 waitFor(`!document.querySelector('[slides-notes] a')`),
1756 waitFor(`!(`+pressed("href")+`)`),
1757 )
1758 }
1759 button := chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="href"]`))
1760 modK := modKey("k", chromedp.ModifierCtrl)
1761 link(button, "the card's button")
1762 unlink(modK)
1763 link(modK, "Mod+K")
1764 unlink(button)
1765 if s := te.marks(); s.Inspect != "notes" {
1766 t.Errorf("after the marks in the notes the card is on %q, want notes", s.Inspect)
1767 }
1768}
1769
1770func slicesHas(s []string, v string) bool {
1771 for _, x := range s {
1772 if x == v {
1773 return true
1774 }
1775 }
1776 return false
1777}
1778
1779// TestTidyKeyboardOnlyBox is TestQuieterKeyboardOnlyShape now
1780// (browser_quieter_box_test.go): the shape is changed and deleted from
1781// its menu and its keys, Delete block having left the card (Q4).
1782
1783// TestTidyDeleteSlideConfirmsInCard (spec E10, §4.3, §4.4): with the
1784// card hidden, Delete slide from the Slide menu and from a slide's own
1785// menu in the strip each show the card on the slide's options with
1786// focus on the confirmation. Cancel leaves the card showing, deletes
1787// nothing and gives focus back to the menu it came from; Delete deletes.
1788func TestTidyDeleteSlideConfirmsInCard(t *testing.T) {
1789 te := openTidyEditor(t, 3, 1280, 720)
1790 count := func() int {
1791 var n int
1792 te.rig.Run(evalInto(&n, `document.querySelectorAll('[slides-strip-item][data-slide-id]').length`))
1793 return n
1794 }
1795 const confirmDelete = `[slides-inspector] [slides-confirm] [data-command="slide-delete"]`
1796 asked := func(from string) {
1797 t.Helper()
1798 te.rig.Run(
1799 waitFor(`document.querySelector('[slides-inspector]').dataset.state === 'open'`),
1800 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
1801 waitFor(`!document.querySelector('[slides-inspector] [slides-confirm]').hidden`),
1802 )
1803 var on bool
1804 te.rig.Run(evalInto(&on, `document.activeElement === document.querySelector('`+confirmDelete+`') && document.activeElement.checkVisibility()`))
1805 if !on {
1806 t.Errorf("%s: focus is %+v; want the confirmation's Delete", from, te.focus())
1807 }
1808 }
1809 cancel := func(from, back string) {
1810 t.Helper()
1811 te.rig.Run(
1812 chromedp.KeyEvent(kb.Tab),
1813 waitFor(`document.activeElement.matches('[slides-confirm] [data-command="slide-delete-cancel"]')`),
1814 chromedp.KeyEvent(kb.Enter),
1815 waitFor(`document.querySelector('[slides-inspector] [slides-confirm]').hidden`),
1816 )
1817 if c := te.card(); c.State != "open" {
1818 t.Errorf("%s, Cancel: the card is %s; want it still showing", from, c.State)
1819 }
1820 if n := count(); n != 3 {
1821 t.Errorf("%s, Cancel: the deck has %d slides, want 3", from, n)
1822 }
1823 var on bool
1824 te.rig.Run(evalInto(&on, `document.activeElement === document.querySelector('`+back+`') && document.activeElement.checkVisibility()`))
1825 if !on {
1826 t.Errorf("%s, Cancel: focus is %+v; want %s", from, te.focus(), back)
1827 }
1828 }
1829
1830 // The Slide menu.
1831 te.pressFormat("closed")
1832 const slideMenu = `[slides-menu="slide"] > summary`
1833 te.rig.Run(
1834 chromedp.Click(chromedp.CSS(slideMenu)),
1835 waitFor(`document.querySelector('[slides-menu="slide"]').open`),
1836 chromedp.Click(chromedp.CSS(`[slides-menu="slide"] [data-command="slide-delete-ask"]`)),
1837 )
1838 asked("Slide → Delete slide")
1839 te.rig.Screen(`[slides-editor]`, "Delete slide asks in the card")
1840 cancel("Slide → Delete slide", slideMenu)
1841
1842 // A slide's own menu in the strip: the second slide's.
1843 te.pressFormat("closed")
1844 const stripMenu = `[slides-strip-item][data-slide-id]:nth-child(2) [slides-strip-menu] > summary`
1845 te.rig.Run(
1846 chromedp.Click(chromedp.CSS(stripMenu)),
1847 chromedp.Click(chromedp.CSS(`[slides-strip-item][data-slide-id]:nth-child(2) [data-slide-command="delete"]`)),
1848 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.index === '1'`),
1849 )
1850 asked("the strip's Delete")
1851 cancel("the strip's Delete", stripMenu)
1852
1853 // Delete deletes.
1854 te.pressFormat("closed")
1855 te.rig.Run(
1856 chromedp.Click(chromedp.CSS(stripMenu)),
1857 chromedp.Click(chromedp.CSS(`[slides-strip-item][data-slide-id]:nth-child(2) [data-slide-command="delete"]`)),
1858 )
1859 asked("the strip's Delete, again")
1860 te.rig.Run(
1861 chromedp.KeyEvent(kb.Enter),
1862 waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 2`),
1863 )
1864}
1865
1866// headingOnlyTitleDeck is a deck of one slide, a `title` slide with a
1867// heading and nothing under it; it returns the deck's editor path.
1868func headingOnlyTitleDeck(t *testing.T) func(a *testApp, cookies []*http.Cookie) string {
1869 return func(a *testApp, cookies []*http.Cookie) string {
1870 token := mintAgent(t, a, cookies, "cover")
1871 sqid := apiDeck(t, a, token, "Cover")
1872 view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK)
1873 slides, _ := view["slides"].([]any)
1874 ops := []string{
1875 `{"op":"add_slide","id":"slidecover01","layout":"flow","template":"title"}`,
1876 `{"op":"add_block","slide":"slidecover01","type":"heading","region":"heading","markdown":"A heading alone"}`,
1877 }
1878 for _, s := range slides {
1879 id, _ := s.(map[string]any)["id"].(string)
1880 ops = append(ops, `{"op":"remove_slide","id":`+quote(id)+`}`)
1881 }
1882 apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK)
1883 return "/d/" + sqid + "/edit"
1884 }
1885}
1886
1887// coverState is a deck tile's cover on the deck list: the picture's
1888// box in its cover's, and where the slide's text falls in the picture.
1889type coverState struct {
1890 Err string
1891 Img, Cover edges
1892 Text edges // the union of the SVG's <text> boxes, in its viewBox units
1893 FrameW, FrameH float64
1894 Texts int
1895}
1896
1897// TestTidyCoverIsCentred (spec §3): a deck's cover shows its first
1898// slide centred. For a `title` slide with a heading alone, the
1899// heading in the cover's picture (the thumbnail SVG, inlined so its
1900// text can be measured) is where the slide's own page puts it — the
1901// editor's stage, the truth the picture is of — within 0.5% each way;
1902// that is the middle across, and half the frame's row gap above the
1903// middle down (slides.css keeps the empty body row and the gap beside
1904// it, so `align-content: center` centres the heading and that gap,
1905// 2% of the frame). And the picture is centred in the cover within a
1906// pixel.
1907func TestTidyCoverIsCentred(t *testing.T) {
1908 te := openTidyEditorOn(t, 1280, 800, headingOnlyTitleDeck(t))
1909
1910 // The slide's own page: the heading's box in the frame, and the
1911 // frame's row gap, in the 1920×1080 the picture is drawn at.
1912 var stage struct{ L, T, R, B, Gap float64 }
1913 te.rig.Run(evalInto(&stage, `(() => {
1914 const s = document.querySelector('[slides-stage] [slides-slide]')
1915 const sr = s.getBoundingClientRect(), k = 1920 / sr.width
1916 const h = s.querySelector('[data-region="heading"] [slides-block]').getBoundingClientRect()
1917 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,
1918 Gap: parseFloat(getComputedStyle(s.querySelector('[slides-frame]')).rowGap) * k}
1919 })()`))
1920 if want := 540 - stage.Gap/2; math.Abs((stage.T+stage.B)/2-want) > 0.005*1080 {
1921 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)
1922 }
1923
1924 te.rig.Run(
1925 chromedp.Navigate(te.rig.Origin+"/"),
1926 chromedp.WaitVisible(chromedp.CSS(`[slides-tile][href="`+te.path+`"] [slides-cover] img`)),
1927 waitFor(`document.querySelector('[slides-tile][href="`+te.path+`"] [slides-cover] img').complete`),
1928 )
1929 var c coverState
1930 te.rig.Run(evalInto(&c, `(async () => {
1931 const img = document.querySelector('[slides-tile][href="`+te.path+`"] [slides-cover] img')
1932 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} }
1933 const res = await fetch(img.src)
1934 if (!res.ok) return {Err: 'GET ' + img.src + ': ' + res.status}
1935 const doc = new DOMParser().parseFromString(await res.text(), 'image/svg+xml')
1936 const svg = document.importNode(doc.documentElement, true)
1937 const holder = document.createElement('div')
1938 holder.style.cssText = 'position:fixed;left:0;top:0;width:480px;height:270px'
1939 svg.setAttribute('width', '480'); svg.setAttribute('height', '270')
1940 holder.append(svg); document.body.append(holder)
1941 const vb = svg.viewBox.baseVal
1942 let L = Infinity, T = Infinity, R = -Infinity, B = -Infinity
1943 const texts = svg.querySelectorAll('text')
1944 for (const el of texts) {
1945 const b = el.getBBox()
1946 if (!b.width) continue
1947 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)
1948 }
1949 holder.remove()
1950 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}
1951 })()`, func(p *runtime.EvaluateParams) { p.AwaitPromise = new(true) }))
1952 if c.Err != "" {
1953 t.Fatal(c.Err)
1954 }
1955 if c.Texts == 0 || c.FrameW != 1920 || c.FrameH != 1080 {
1956 t.Fatalf("the cover's picture has %d <text> in a %.0f×%.0f frame; want text in 1920×1080", c.Texts, c.FrameW, c.FrameH)
1957 }
1958 te.rig.Screen(`[slides-tile][href="`+te.path+`"]`, "the cover of a title slide with a heading alone")
1959
1960 cx, cy := (c.Text.L+c.Text.R)/2, (c.Text.T+c.Text.B)/2
1961 if dx := math.Abs(cx - 960); dx > 0.005*1920 {
1962 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)
1963 }
1964 // 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).
1965 if want, dy := (stage.T+stage.B)/2, math.Abs(cy-(stage.T+stage.B)/2); dy > 0.005*1080 {
1966 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)
1967 }
1968 if d := math.Abs((c.Img.L + c.Img.R - c.Cover.L - c.Cover.R) / 2); d > 1 {
1969 t.Errorf("the picture is %.1fpx off the cover's middle across: img %+v, cover %+v", d, c.Img, c.Cover)
1970 }
1971 if d := math.Abs((c.Img.T + c.Img.B - c.Cover.T - c.Cover.B) / 2); d > 1 {
1972 t.Errorf("the picture is %.1fpx off the cover's middle down: img %+v, cover %+v", d, c.Img, c.Cover)
1973 }
1974}
1975
1976// barState is the bar's buttons as drawn: each one's box, fill and
1977// border, and the history pill's.
1978type barState struct {
1979 Undo, Redo, History, Format, Share, Present edges
1980 FormatBg, ShareBg, PresentBg, PageBg string
1981 ShareBorder, PresentRadius string
1982 HistoryOutline string
1983 WinW float64
1984}
1985
1986const barJS = `(() => {
1987 const q = s => document.querySelector(s)
1988 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} }
1989 const cs = e => getComputedStyle(e)
1990 const undo = q('[slides-history] [data-command="undo"]'), redo = q('[slides-history] [data-command="redo"]')
1991 const format = q('[slides-head-end] [data-view-toggle="inspector"]'), share = q('[slides-head-share]'), present = q('[slides-present-form] button')
1992 return {Undo: box(undo), Redo: box(redo), History: box(q('[slides-history]')), Format: box(format), Share: box(share), Present: box(present),
1993 FormatBg: cs(format).backgroundColor, ShareBg: cs(share).backgroundColor, PresentBg: cs(present).backgroundColor, PageBg: cs(q('[slides-head]')).backgroundColor,
1994 ShareBorder: [cs(share).borderTopWidth, cs(share).borderRightWidth, cs(share).borderBottomWidth, cs(share).borderLeftWidth].join(' '), PresentRadius: cs(present).borderTopLeftRadius,
1995 HistoryOutline: cs(q('[slides-history]')).outlineWidth + ' ' + cs(q('[slides-history]')).outlineStyle, WinW: innerWidth}
1996})()`
1997
1998// TestTidyBarPills (spec §2): from 800px the bar's buttons are estilo's
1999// 28px pills — Format tinted while its card shows, Share… estilo's
2000// plain pill (no border, as in Docs),
2001// Present filled — and undo and redo are one pill: two buttons side by
2002// side with no gap, one outline round the pair, each at least 24×24.
2003// Narrower, every one of them is still there and at least 24×24.
2004func TestTidyBarPills(t *testing.T) {
2005 te := openTidyEditor(t, 2, 1280, 800)
2006 var b barState
2007 te.rig.Run(evalInto(&b, barJS))
2008 te.rig.Screen(`[slides-head]`, "1280, the bar")
2009 for name, e := range map[string]edges{"Format": b.Format, "Share": b.Share, "Present": b.Present} {
2010 if math.Abs(e.H-28) > 0.5 {
2011 t.Errorf("1280: %s is %.1fpx tall; want estilo's 28px pill", name, e.H)
2012 }
2013 }
2014 if b.FormatBg == "rgba(0, 0, 0, 0)" {
2015 t.Errorf("1280: Format, its card shown, has no tint")
2016 }
2017 if b.ShareBorder != "0px 0px 0px 0px" || b.ShareBg != "rgba(0, 0, 0, 0)" {
2018 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)
2019 }
2020 if b.PresentBg == "rgba(0, 0, 0, 0)" || b.PresentBg == b.PageBg {
2021 t.Errorf("1280: Present's fill is %s on a %s bar; want it filled", b.PresentBg, b.PageBg)
2022 }
2023 if b.PresentRadius != "999px" {
2024 t.Errorf("1280: Present's radius is %s; want estilo's pill", b.PresentRadius)
2025 }
2026 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 {
2027 t.Errorf("1280: undo %+v and redo %+v are not one pill (gap %.1f)", b.Undo, b.Redo, gap)
2028 }
2029 if !strings.HasSuffix(b.HistoryOutline, " none") || math.Abs(b.History.H-28) > 0.5 {
2030 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)
2031 }
2032 for _, w := range []int64{1280, 700, 320} {
2033 te.size(w, 800)
2034 te.rig.Run(evalInto(&b, barJS))
2035 for name, e := range map[string]edges{"undo": b.Undo, "redo": b.Redo, "Format": b.Format, "Share": b.Share, "Present": b.Present} {
2036 if e.W < 24 || e.H < 24 || e.L < 0 || e.R > b.WinW+0.5 {
2037 t.Errorf("%d: %s is %+v; want it on screen and at least 24×24", w, name, e)
2038 }
2039 }
2040 te.rig.Screen(`[slides-head]`, fmt.Sprintf("%d, the bar", w))
2041 }
2042}
2043
2044// TestTidyDeleteAnotherSlideWithABoxSelected (final review, finding 1):
2045// a box is selected on slide A, and Delete is chosen from slide B's own
2046// menu in the strip. Slide B is on the stage, the hash names B, the
2047// confirmation asks about B, and confirming deletes B and keeps A.
2048func TestTidyDeleteAnotherSlideWithABoxSelected(t *testing.T) {
2049 te := openTidyEditor(t, 3, 1280, 720)
2050 ids, _ := te.slideIDs()
2051 if len(ids) != 3 {
2052 t.Fatalf("the deck has slides %v, want 3", ids)
2053 }
2054 a, b := ids[0], ids[1]
2055 te.selectBox("heading")
2056 const stripMenu = `[slides-strip-item][data-slide-id]:nth-child(2) [slides-strip-menu] > summary`
2057 te.rig.Run(
2058 chromedp.Click(chromedp.CSS(stripMenu)),
2059 chromedp.Click(chromedp.CSS(`[slides-strip-item][data-slide-id]:nth-child(2) [data-slide-command="delete"]`)),
2060 waitFor(`!document.querySelector('[slides-inspector] [slides-confirm]').hidden`),
2061 )
2062 var got struct {
2063 Shown, Hash, Inspect string
2064 Selected bool
2065 }
2066 // Give a late hash write and its hashchange the time they would take.
2067 te.rig.Run(
2068 chromedp.Sleep(300*time.Millisecond),
2069 evalInto(&got, `({Shown: document.querySelector('[slides-stage] [slides-slide]')?.dataset.id || '', Hash: location.hash,
2070 Inspect: document.querySelector('[slides-editor]').dataset.inspect,
2071 Selected: !!document.querySelector('[slides-stage] [aria-selected="true"]')})`),
2072 )
2073 if got.Shown != b || got.Hash != "#"+b || got.Inspect != "slide" || got.Selected {
2074 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",
2075 a, b, got.Shown, got.Hash, got.Inspect, got.Selected)
2076 }
2077 te.rig.Run(
2078 chromedp.KeyEvent(kb.Enter),
2079 waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 2`),
2080 )
2081 left, _ := te.slideIDs()
2082 if slicesHas(left, b) || !slicesHas(left, a) {
2083 t.Errorf("confirming deleted the wrong slide: %v are left; want B (%s) gone and A (%s) kept", left, b, a)
2084 }
2085}
2086
2087// editorOf is a selector for the text editor of the box of this kind on
2088// the stage: the box itself, or the element inside it the view mounts on.
2089func editorOf(kind string) string {
2090 return `[slides-stage] [data-block="` + kind + `"][contenteditable="true"], [slides-stage] [data-block="` + kind + `"] [contenteditable="true"]`
2091}
2092
2093// TestTidyMarksActOnTheCardsBox (final review, finding 2): the marks act
2094// on the box the card shows and on no other. Text typed in box A, then
2095// heading B selected by its address: the card shows B, and its marks
2096// are disabled (they would have acted on A). A press on Bold changes
2097// nothing. The caret put in B, Bold makes B's words bold and leaves A's.
2098func TestTidyMarksActOnTheCardsBox(t *testing.T) {
2099 var slide string
2100 te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string {
2101 var path string
2102 path, slide = deckWithEveryKind(t, a, cookies)
2103 return path
2104 })
2105 te.openOn(slide)
2106 const textEl = `document.querySelector('[slides-stage] [data-block="text"]')`
2107 const headingEl = `document.querySelector('[slides-stage] [data-block="heading"]')`
2108 var heading string
2109 te.rig.Run(evalInto(&heading, headingEl+`.dataset.id`))
2110
2111 // A: the text box, typed in and its words selected.
2112 te.selectBox("text")
2113 te.rig.Run(
2114 waitFor(`document.activeElement.closest('[slides-stage] [data-block="text"]')`),
2115 chromedp.KeyEvent(" more"),
2116 waitFor(textEl+`.textContent.includes('more')`),
2117 modKey("a", chromedp.ModifierCtrl),
2118 )
2119 // Back to the slide's options, and B, the heading, by its address
2120 // (#slide/box), which selects it without the caret.
2121 te.rig.Run(
2122 chromedp.KeyEvent(kb.Escape),
2123 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'slide'`),
2124 chromedp.Evaluate[chromedp.Void](`location.hash = '`+slide+`/`+heading+`'`),
2125 waitFor(`document.querySelector('[slides-editor]').dataset.inspect === 'box'`),
2126 waitFor(headingEl+`.getAttribute('aria-selected') === 'true'`),
2127 )
2128 s := te.marks()
2129 for m, st := range s.Marks {
2130 if !st.Drawn || !st.Disabled {
2131 t.Errorf("text typed in a text box, then the heading selected: mark %s is %+v; want drawn and disabled", m, st)
2132 }
2133 }
2134 // A press anyway (a click on a disabled button does nothing; this is
2135 // the button's own click, as a stale target would have heard it).
2136 te.rig.Run(
2137 chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-inspector] [data-mark="b"]').click()`),
2138 chromedp.Sleep(200*time.Millisecond),
2139 )
2140 var bold struct{ A, B bool }
2141 read := `({A: !!` + textEl + `.querySelector('strong'), B: !!` + headingEl + `.querySelector('strong')})`
2142 te.rig.Run(evalInto(&bold, read))
2143 if bold.A || bold.B {
2144 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)
2145 }
2146
2147 // The caret in B: Bold is B's.
2148 te.rig.Run(
2149 chromedp.Focus(chromedp.CSS(editorOf("heading"))),
2150 waitFor(`document.activeElement.closest('[slides-stage] [data-block="heading"]')`),
2151 modKey("a", chromedp.ModifierCtrl),
2152 waitFor(`!document.querySelector('[slides-inspector] [data-mark="b"]').disabled`),
2153 chromedp.Click(chromedp.CSS(`[slides-inspector] [data-mark="b"]`)),
2154 waitFor(headingEl+`.querySelector('strong')`),
2155 )
2156 te.rig.Run(evalInto(&bold, read))
2157 if bold.A || !bold.B {
2158 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)
2159 }
2160}
2161
2162// TestTidyFocusSelectsTheBox (final review, finding 3): a box's text
2163// taking focus by any means makes that box the selection. Tab into the
2164// heading's text with no click, then on to the next text box, then
2165// on to a table's cell: the card shows each box's options in turn (the
2166// table's for its cell), with the marks enabled for it.
2167func TestTidyFocusSelectsTheBox(t *testing.T) {
2168 var slide string
2169 te := openTidyEditorOn(t, 1280, 720, func(a *testApp, cookies []*http.Cookie) string {
2170 var path string
2171 path, slide = deckWithEveryKind(t, a, cookies)
2172 return path
2173 })
2174 te.openOn(slide)
2175 te.inspect().onSlideOptions(t, "opening the canvas slide")
2176 check := func(kind, how string) {
2177 t.Helper()
2178 te.rig.Run(chromedp.Sleep(100 * time.Millisecond))
2179 s := te.inspect()
2180 if s.Inspect != "box" || s.Kind != kind || !s.Box {
2181 t.Errorf("%s: the card is %+v; want the %s's options", how, s, kind)
2182 }
2183 for m, st := range te.marks().Marks {
2184 if !st.Drawn || st.Disabled {
2185 t.Errorf("%s: mark %s is %+v; want drawn and enabled", how, m, st)
2186 }
2187 }
2188 }
2189 te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.activeElement.blur()`))
2190 te.tabTo(t, editorOf("heading"), 80)
2191 check("heading", "Tab into the heading's text")
2192 te.tabTo(t, `[slides-stage] [data-block="text"]`, 6)
2193 check("text", "Tab on to the text box")
2194
2195 // With a box already selected, Tab on to a table's cell.
2196 te.tabTo(t, `[slides-stage] [data-block="table"] td, [slides-stage] [data-block="table"] th`, 40)
2197 check("table", "Tab on to a table's cell")
2198}
2199
2200// TestTidyLastSlideRemovedFromTheNotes (final review, finding 4): this
2201// person has the caret in the notes of a deck's only slide when a
2202// colleague, in another tab, deletes that slide. The card goes to the
2203// slide's options, which an empty deck does not draw (and the deck's
2204// are the Deck settings dialog's since Q2): data-inspect is slide, no
2205// section shows, and no mark is drawn.
2206func TestTidyLastSlideRemovedFromTheNotes(t *testing.T) {
2207 te := openTidyEditor(t, 1, 1280, 720)
2208 te.clickNotes()
2209
2210 tab2, cancel := chromedp.NewContext(te.rig.Context())
2211 defer cancel()
2212 runOn(t, tab2,
2213 chromedp.EmulateViewport(1280, 720),
2214 chromedp.Navigate(te.rig.Origin+te.path),
2215 waitFor(editorBound),
2216 chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-menu="slide"] [data-command="slide-delete-ask"]').click()`),
2217 waitFor(`!document.querySelector('[slides-inspector] [slides-confirm]').hidden`),
2218 chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-inspector] [slides-confirm] [data-command="slide-delete"]').click()`),
2219 waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 0`),
2220 )
2221 te.rig.Run(
2222 waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 0`),
2223 waitFor(`!document.querySelector('[slides-stage] [slides-slide]')`),
2224 chromedp.Sleep(200*time.Millisecond),
2225 )
2226 s := te.inspect()
2227 m := te.marks()
2228 drawn := 0
2229 for _, st := range m.Marks {
2230 if st.Drawn {
2231 drawn++
2232 }
2233 }
2234 if s.Inspect != "slide" || s.Deck || s.Slide || s.Box || drawn != 0 {
2235 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)
2236 }
2237}
2238
2239// fitJS is the desktop slide against the room it has: the slide's own
2240// rect, the stage's (the visible stage area), the notes card's top (or
2241// null when it is not drawn) and the inspector card's left (null when
2242// hidden), the stage's scroll and client heights, and its width over
2243// its height.
2244const fitJS = `(() => {
2245 const q = s => document.querySelector(s)
2246 const drawn = el => !!el && el.checkVisibility() && el.getBoundingClientRect().height > 0
2247 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} }
2248 const stage = q('[slides-stage]'), slide = q('[slides-stage] > [slides-slide]')
2249 const notes = q('[slides-notes-pane]'), card = q('[slides-inspector]')
2250 return {
2251 Slide: box(slide), Stage: box(stage),
2252 NotesTop: drawn(notes) ? notes.getBoundingClientRect().top : -1,
2253 CardLeft: drawn(card) ? card.getBoundingClientRect().left : -1,
2254 ScrollH: stage.scrollHeight, ClientH: stage.clientHeight,
2255 ScrollW: stage.scrollWidth, ClientW: stage.clientWidth
2256 }
2257})()`
2258
2259type fitState struct {
2260 Slide, Stage edges4
2261 NotesTop, CardLeft float64
2262 ScrollH, ClientH, ScrollW, ClientW float64
2263}
2264
2265// fits says how the slide fails to fit its room; "" is the pass.
2266func (f fitState) fits() string {
2267 var out []string
2268 const e = 0.5
2269 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 {
2270 out = append(out, fmt.Sprintf("the slide %+v is not inside the stage %+v", f.Slide, f.Stage))
2271 }
2272 if f.NotesTop >= 0 && f.Slide.B > f.NotesTop+e {
2273 out = append(out, fmt.Sprintf("the slide ends at %.1f, under the notes card's top %.1f", f.Slide.B, f.NotesTop))
2274 }
2275 if f.CardLeft >= 0 && f.Slide.R > f.CardLeft+e {
2276 out = append(out, fmt.Sprintf("the slide ends at %.1f, under the inspector card's left %.1f", f.Slide.R, f.CardLeft))
2277 }
2278 if f.Slide.H <= 0 || math.Abs(f.Slide.W/f.Slide.H-16.0/9)/(16.0/9) > 0.01 {
2279 out = append(out, fmt.Sprintf("the slide is %.1f×%.1f, not 16:9 within 1%%", f.Slide.W, f.Slide.H))
2280 }
2281 if f.ScrollH != f.ClientH {
2282 out = append(out, fmt.Sprintf("the stage scrolls: scrollHeight %g, clientHeight %g", f.ScrollH, f.ClientH))
2283 }
2284 return strings.Join(out, "; ")
2285}
2286
2287// TestTidyDesktopSlideFits (final review, finding 5, V1): the desktop
2288// slide fits the room above the notes, both ways, at 16:9. At 1280×720
2289// and 1920×1080, in desktop view and in Both, with the notes open at
2290// their default height, at their maximum and closed, and with the card
2291// shown and hidden: the slide's own rect is inside the stage, above the
2292// notes card, left of the inspector card, 16:9 within 1%, and the stage
2293// does not scroll.
2294func TestTidyDesktopSlideFits(t *testing.T) {
2295 te := openTidyEditor(t, 2, 1280, 720)
2296 notes := map[string]func(){
2297 "the notes at their default height": func() {
2298 te.rig.Run(
2299 chromedp.Evaluate[chromedp.Void](`(p => { if (p.dataset.state !== 'open') document.querySelector('[data-view-toggle="notes"]').click() })(document.querySelector('[slides-notes-pane]'))`),
2300 waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'open'`),
2301 chromedp.Focus(chromedp.CSS(`[slides-notes-resize]`)),
2302 chromedp.KeyEvent(kb.Home),
2303 )
2304 // From the minimum up to the default, 144px, by script: the
2305 // default is not a multiple of the arrow's step.
2306 te.rig.Run(chromedp.Evaluate[chromedp.Void](`document.querySelector('[slides-notes-pane]').style.setProperty('--slides-notes-block-size', '144px')`))
2307 },
2308 "the notes at their maximum": func() {
2309 te.rig.Run(
2310 chromedp.Focus(chromedp.CSS(`[slides-notes-resize]`)),
2311 chromedp.KeyEvent(kb.End),
2312 )
2313 },
2314 "the notes closed": func() {
2315 te.rig.Run(
2316 chromedp.Evaluate[chromedp.Void](`document.querySelector('[data-view-toggle="notes"]').click()`),
2317 waitFor(`document.querySelector('[slides-notes-pane]').dataset.state === 'closed'`),
2318 )
2319 },
2320 }
2321 for _, vp := range [][2]int64{{1280, 720}, {1920, 1080}} {
2322 te.size(vp[0], vp[1])
2323 for _, v := range []string{"desktop", "both"} {
2324 te.view(v)
2325 for _, card := range []string{"open", "closed"} {
2326 var now string
2327 te.rig.Run(evalInto(&now, `document.querySelector('[slides-inspector]').dataset.state`))
2328 if now != card {
2329 te.pressFormat(card)
2330 }
2331 for _, n := range []string{"the notes at their default height", "the notes at their maximum", "the notes closed"} {
2332 notes[n]()
2333 te.rig.Run(chromedp.Sleep(100 * time.Millisecond))
2334 var f fitState
2335 te.rig.Run(evalInto(&f, fitJS))
2336 if got := f.fits(); got != "" {
2337 t.Errorf("%dx%d, %s view, the card %s, %s: %s", vp[0], vp[1], v, card, n, got)
2338 }
2339 }
2340 }
2341 }
2342 }
2343 te.view("desktop")
2344}
2345
2346// statusJS is the strip's top against the bar's bottom, and where the
2347// stage and the view switch are.
2348const statusJS = `(() => {
2349 const r = s => document.querySelector(s).getBoundingClientRect()
2350 const stage = r('[slides-stage]'), sw = r('[slides-switcher]')
2351 return {StripTop: r('[slides-strip-nav]').top, BarBottom: r('[slides-head]').bottom,
2352 Stage: [stage.left, stage.top, stage.width, stage.height], Switch: [sw.left, sw.top, sw.width, sw.height]}
2353})()`
2354
2355type statusState struct {
2356 StripTop, BarBottom float64
2357 Stage, Switch []float64
2358}
2359
2360// TestTidyStripMeetsTheBar (final review, finding 7, V2): the strip's
2361// surface starts directly under the bar, with no band of desk between
2362// them, and the font status keeps its room in the stage's column, so a
2363// note appearing and clearing moves neither the stage nor the view
2364// switch.
2365func TestTidyStripMeetsTheBar(t *testing.T) {
2366 te := openTidyEditor(t, 2, 1280, 720)
2367 read := func() statusState {
2368 var s statusState
2369 te.rig.Run(evalInto(&s, statusJS))
2370 return s
2371 }
2372 before := read()
2373 if math.Abs(before.StripTop-before.BarBottom) > 1 {
2374 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)
2375 }
2376 // A note, said as font-status.mjs says one (the longest the catalog
2377 // has, which stays a while), then cleared.
2378 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]'))`))
2379 said := read()
2380 te.rig.Run(chromedp.Evaluate[chromedp.Void](`(s => { s.removeAttribute('data-state'); s.querySelector('[slides-fonts-status-text]').textContent = '' })(document.querySelector('[slides-fonts-status]'))`))
2381 cleared := read()
2382 for _, c := range []struct {
2383 when string
2384 s statusState
2385 }{{"with a font note shown", said}, {"with the note cleared", cleared}} {
2386 if fmt.Sprint(c.s.Stage) != fmt.Sprint(before.Stage) || fmt.Sprint(c.s.Switch) != fmt.Sprint(before.Switch) {
2387 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)
2388 }
2389 }
2390}
2391
2392// TestTidyNotesFirstPaint (final review, finding 6; ruling R21): the
2393// notes card's remembered state and height are cookies the server
2394// renders, so with the bundle blocked — before any script — the card
2395// is already closed, or open at the remembered height; and once the
2396// bundle has bound, it is exactly as it was.
2397func TestTidyNotesFirstPaint(t *testing.T) {
2398 te := openTidyEditor(t, 2, 1280, 720)
2399 const paneJS = `(() => {
2400 const p = document.querySelector('[slides-notes-pane]'), i = document.querySelector('[slides-notes-open]')
2401 return {State: p.dataset.state, Shown: p.checkVisibility(), Height: p.getBoundingClientRect().height,
2402 Icon: i.checkVisibility(), Pressed: document.querySelector('[data-view-toggle="notes"]').getAttribute('aria-pressed')}
2403 })()`
2404 type pane struct {
2405 State string
2406 Shown, Icon bool
2407 Height float64
2408 Pressed string
2409 }
2410 set := func(kv ...string) chromedp.Action[chromedp.Void] {
2411 var acts []chromedp.Action[chromedp.Void]
2412 for i := 0; i < len(kv); i += 2 {
2413 acts = append(acts, cdpStep(network.SetCookie, network.SetCookieParams{Name: kv[i], Value: kv[i+1], URL: te.rig.Origin + "/", SameSite: network.CookieSameSiteLax}))
2414 }
2415 return chromedp.Steps(acts...)
2416 }
2417 blocked := func(what string) pane {
2418 t.Helper()
2419 te.rig.Run(
2420 cdpStep(network.Enable, network.EnableParams{}),
2421 blockURLs("*/static/editor.*.js"),
2422 chromedp.Navigate(te.rig.Origin+te.path),
2423 chromedp.WaitReady(chromedp.CSS(`[slides-notes-pane]`)),
2424 )
2425 var bound bool
2426 te.rig.Run(evalInto(&bound, editorBound))
2427 if bound {
2428 t.Fatalf("%s: the editor bound with its bundle blocked; this check would not be of the first paint", what)
2429 }
2430 var p pane
2431 te.rig.Run(evalInto(&p, paneJS))
2432 return p
2433 }
2434
2435 te.rig.Run(set("slides-notes", "closed"))
2436 if p := blocked("closed"); p.State != "closed" || p.Shown || !p.Icon || p.Pressed != "false" {
2437 t.Errorf("first paint with slides-notes=closed: %+v; want closed, the card not drawn, the tab drawn, the View row unpressed", p)
2438 }
2439 te.rig.Run(set("slides-notes", "open", "slides-notes-height", "220"))
2440 if p := blocked("open at 220"); p.State != "open" || !p.Shown || p.Icon || math.Abs(p.Height-220) > 0.5 || p.Pressed != "true" {
2441 t.Errorf("first paint with slides-notes=open and slides-notes-height=220: %+v; want open, drawn 220px tall", p)
2442 }
2443 // The bundle let through: once bound, nothing has moved.
2444 te.rig.Run(
2445 blockURLs(),
2446 chromedp.Navigate(te.rig.Origin+te.path),
2447 waitFor(editorBound),
2448 chromedp.Sleep(200*time.Millisecond),
2449 )
2450 var p pane
2451 te.rig.Run(evalInto(&p, paneJS))
2452 if p.State != "open" || math.Abs(p.Height-220) > 0.5 {
2453 t.Errorf("once the editor bound, the notes are %+v; want them as the server painted them, open and 220px", p)
2454 }
2455}
2456