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 browser drive: the whole app in a real Chromium, wired exactly
4// as cmd/slides/main.go wires it — loud on any console error, failed
5// request, 4xx/5xx, or JS value that leaked to the screen unrendered.
6// Not part of the plain suite:
7//
8// go test -tags browser ./...
9//
10// It needs a Chromium: on PATH, via RASTRILLO_CHROME, or in a
11// Playwright cache. A skip is not a pass — with no browser this fails,
12// unless RASTRILLO_BROWSER_OPTIONAL is set, which makes the skip a
13// deliberate visible choice rather than an accident.
14package slidestest
15
16import (
17 "bytes"
18 "context"
19 "fmt"
20 "html"
21 "io"
22 "log/slog"
23 "net/http"
24 "net/http/cookiejar"
25 "net/url"
26 "path/filepath"
27 "strings"
28 "testing"
29 "time"
30
31 "amadan.net/rastrillo/rastrillo"
32 "amadan.net/rastrillo/rastrillo/blobs"
33 "amadan.net/rastrillo/rastrillo/db"
34 "amadan.net/rastrillo/rastrillo/harness"
35 "github.com/chromedp/cdproto/cdp"
36 "github.com/chromedp/cdproto/input"
37 "github.com/chromedp/cdproto/runtime"
38 "github.com/chromedp/chromedp"
39 "github.com/chromedp/chromedp/kb"
40
41 slides "amadan.net/oficina/slides/internal/slides"
42)
43
44// newRig boots the app under the rig, wired as main.go wires it, and
45// returns the rig with the mailer the app sends through — the seam a
46// browser sign-in needs, because the magic link only exists in mail.
47func newRig(t *testing.T) (*harness.Rig, *fakeMailer) {
48 return newRigWith(t, nil)
49}
50
51// newRigWithStore is newRig with the object store development binds — a
52// directory beside the database — so the image upload has somewhere to
53// put bytes. Nothing else about the app differs.
54func newRigWithStore(t *testing.T) (*harness.Rig, *fakeMailer) {
55 t.Helper()
56 store, err := blobs.Dir(t.TempDir())
57 if err != nil {
58 t.Fatalf("blobs.Dir: %v", err)
59 }
60 return newRigWith(t, store)
61}
62
63func newRigWith(t *testing.T, store blobs.Store) (*harness.Rig, *fakeMailer) {
64 t.Helper()
65 rig, served := newRigApp(t, store)
66 return rig, served.mailer
67}
68
69// newRigApp is newRigWith that also hands back the app the rig serves,
70// behind the same serving stack, so a test can make what it needs over
71// HTTP (signedIn, an agent, a deck) before the browser looks at it.
72func newRigApp(t *testing.T, store blobs.Store) (*harness.Rig, *testApp) {
73 t.Helper()
74 return newRigAppWrapped(t, store, nil)
75}
76
77// newRigAppWrapped is newRigApp with wrap put around the whole serving
78// stack, outermost, so a test can see every request the browser makes
79// of the server (scenes_browser_test.go's request log). Nil wraps
80// nothing.
81func newRigAppWrapped(t *testing.T, store blobs.Store, wrap func(http.Handler) http.Handler) (*harness.Rig, *testApp) {
82 t.Helper()
83 mailer := &fakeMailer{}
84 served := &testApp{mailer: mailer}
85 rig := harness.New(t, func(origin string) http.Handler {
86 // The same wiring main.go does, origin included: the rig hands
87 // the app its localhost origin before serving — the same seam
88 // main.go fills from SLIDES_ORIGIN.
89 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
90 d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
91 if err != nil {
92 t.Fatalf("db.Open: %v", err)
93 }
94 t.Cleanup(func() { d.Close() })
95 mux, a, err := slides.New(d, slides.Config{
96 KeymailServers: testKeymailServers,
97 Origin: origin,
98 InstanceKey: testInstanceKey,
99 Mailer: mailer,
100 AllowedAddresses: []string{allowedAddress},
101 Blobs: store,
102 Logger: logger,
103 })
104 if err != nil {
105 t.Fatalf("slides.New: %v", err)
106 }
107 t.Cleanup(func() { a.Close() })
108 mailer.flush = a.FlushMail
109 // Behind rastrillo's serving stack, built from the ServeOptions
110 // main hands rastrillo.Serve: its security headers, the locale
111 // middleware and Slides' CSP. Serving the bare mux would leave
112 // every drive here blind to the policy a browser is really told,
113 // and a style the policy refused is a console error the rig
114 // fails on.
115 h, closeFn, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: logger}, mux))
116 if err != nil {
117 t.Fatalf("rastrillo.Handler: %v", err)
118 }
119 t.Cleanup(func() { _ = closeFn() })
120 served.Handler, served.db, served.mux, served.app = h, d, mux, a
121 if wrap != nil {
122 return wrap(h)
123 }
124 return h
125 })
126 return rig, served
127}
128
129// TestBrowserWalk is the minimal loud walk: the front door arrives with
130// nothing wrong anywhere the rig watches. It walks /signin rather than
131// "/" because "/" is behind the session gate now, and a redirect is not
132// a screen. Grow it with the app — each screen a flow reaches earns a
133// Screen() line, and an expected probe earns a rig.Allow.
134func TestBrowserWalk(t *testing.T) {
135 rig, _ := newRig(t)
136 rig.Run(chromedp.Navigate(rig.Origin + "/signin"))
137 rig.Screen("body", "signin")
138}
139
140// browserSignIn signs the browser in the way a person does: the form,
141// the mail, the link, and the confirm door's one Sign in button. Ends on
142// the deck list.
143func browserSignIn(t *testing.T, rig *harness.Rig, mailer *fakeMailer) {
144 t.Helper()
145 rig.Run(
146 chromedp.Navigate(rig.Origin+"/signin"),
147 chromedp.WaitVisible(chromedp.CSS(`input[name="address"]`)),
148 chromedp.SendKeys(chromedp.CSS(`input[name="address"]`), allowedAddress),
149 chromedp.Submit(chromedp.CSS(`input[name="address"]`)),
150 // POST /signin answers 303 to the door's Sent (?sent=1, with
151 // rastrillo's attempt id); the mail exists once the browser has
152 // landed there.
153 waitFor(`new URLSearchParams(location.search).get('sent') === '1'`),
154 )
155 rig.Screen("body", "after sign-in post")
156 msgs := mailer.messages()
157 if len(msgs) == 0 {
158 t.Fatal("the sign-in form sent no mail")
159 }
160 link := magicLinkPattern.FindString(msgs[len(msgs)-1].Body)
161 if link == "" {
162 t.Fatalf("no magic link in the mailed body:\n%s", msgs[len(msgs)-1].Body)
163 }
164 rig.Run(
165 chromedp.Navigate(link),
166 chromedp.WaitVisible(chromedp.CSS(`form[action="/auth/verify"] button[type="submit"]`)),
167 )
168 rig.Screen("body", "confirm door")
169 rig.Run(
170 chromedp.Click(chromedp.CSS(`form[action="/auth/verify"] button[type="submit"]`)),
171 waitFor(`location.pathname === '/'`),
172 chromedp.WaitVisible(chromedp.CSS(`[rst-page]`)),
173 )
174 rig.Screen("[rst-page]", "signed in")
175}
176
177// waitFor polls a JS expression until it is true, bounded at 20 s, and
178// fails with the expression and the status line when it never is.
179func waitFor(expr string) chromedp.Action[chromedp.Void] {
180 return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
181 deadline := time.Now().Add(20 * time.Second)
182 for {
183 var ok bool
184 if _, err := evalInto(&ok, `!!(`+expr+`)`)(ctx, t); err != nil {
185 return err
186 }
187 if ok {
188 return nil
189 }
190 if time.Now().After(deadline) {
191 var status string
192 _, _ = evalInto(&status, `document.querySelector('[estilo-save-status]')?.textContent ?? 'no status line'`)(ctx, t)
193 return fmt.Errorf("never true within 20s: %s (status line: %q)", expr, status)
194 }
195 select {
196 case <-ctx.Done():
197 return ctx.Err()
198 case <-time.After(100 * time.Millisecond):
199 }
200 }
201 })
202}
203
204// TestBrowserEditsTheTitle is the editor's own drive (plan task 3):
205// open the sample deck's editor, type into the title heading, wait for
206// "Saved", reload, the text is still there, and the viewer shows it.
207// The rig is loud on any console error or failed request, so this is
208// also the check that the bundle loads and runs at all — a syntax
209// error in it takes the whole client down and no Go test would know.
210func TestBrowserEditsTheTitle(t *testing.T) {
211 rig, mailer := newRig(t)
212 browserSignIn(t, rig, mailer)
213
214 var deck string
215 rig.Run(evalInto(&deck, `(document.querySelector('a[href^="/d/"]')?.getAttribute('href') ?? '').replace(/\/edit$/, '')`))
216 if !deckPath.MatchString(deck) {
217 t.Fatalf("the deck list links no deck: %q", deck)
218 }
219
220 const heading = `[slides-stage] [data-block="heading"]`
221 typed := " edited in a browser"
222 rig.Run(
223 chromedp.Navigate(rig.Origin+deck+"/edit"),
224 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
225 // The bundle has bound the heading once it is contenteditable.
226 waitFor(`document.querySelector('`+heading+`')?.getAttribute('contenteditable') === 'true'`),
227 chromedp.Click(chromedp.CSS(heading)),
228 chromedp.SendKeys(chromedp.CSS(heading), string(kb.End)+typed),
229 waitFor(`document.querySelector('`+heading+`').textContent.includes('`+typed+`')`),
230 waitFor(`document.querySelector('[estilo-save-status]').dataset.state === 'saved'`),
231 )
232 rig.Screen("[slides-editor]", "typed into the title")
233
234 rig.Run(
235 chromedp.Reload(),
236 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
237 )
238 rig.Screen("[slides-editor]", "reloaded")
239 var after string
240 rig.Run(harness.Into(&after, chromedp.Text(chromedp.CSS(heading))))
241 if !strings.Contains(after, sampleDeckTitle+typed) {
242 t.Errorf("after a reload the heading reads %q, want it to carry %q", after, sampleDeckTitle+typed)
243 }
244 var stripLabel string
245 rig.Run(harness.Into(&stripLabel, chromedp.Text(chromedp.CSS(`[slides-strip-item][data-current="true"] [slides-strip-label]`))))
246 if !strings.Contains(stripLabel, typed) {
247 t.Errorf("the strip's label for the current slide reads %q, want the typed text", stripLabel)
248 }
249
250 rig.Run(chromedp.Navigate(rig.Origin + deck + "?slide=1"))
251 rig.Screen("[slides-viewer]", "viewer")
252 var shown string
253 rig.Run(harness.Into(&shown, chromedp.Text(chromedp.CSS(`[slides-stage] [data-block="heading"]`))))
254 if !strings.Contains(shown, sampleDeckTitle+typed) {
255 t.Errorf("the viewer's heading reads %q, want it to carry %q", shown, sampleDeckTitle+typed)
256 }
257}
258
259// TestBrowserNewSlideAndUndo: New slide (the menu's item, Ctrl+Enter's
260// visible equivalent) makes a slide after the current one and the
261// stage moves to it once it is saved; Undo takes it back through the
262// same ops path, and the strip and the stage agree on what is shown.
263func TestBrowserNewSlideAndUndo(t *testing.T) {
264 rig, mailer := newRig(t)
265 browserSignIn(t, rig, mailer)
266 var deck string
267 rig.Run(evalInto(&deck, `(document.querySelector('a[href^="/d/"]')?.getAttribute('href') ?? '').replace(/\/edit$/, '')`))
268
269 rig.Run(
270 chromedp.Navigate(rig.Origin+deck+"/edit"),
271 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
272 waitFor(`document.querySelector('[slides-stage] [data-block="heading"]')?.getAttribute('contenteditable') === 'true'`),
273 )
274 var first string
275 rig.Run(evalInto(&first, `document.querySelector('[slides-editor]').dataset.slide`))
276
277 // The menu's New slide, which is Ctrl+Enter's visible equivalent:
278 // open the menu, press the item.
279 rig.Run(
280 chromedp.Click(chromedp.CSS(`[slides-menu="slide"] > summary`)),
281 chromedp.WaitVisible(chromedp.CSS(`[data-command="new-slide"]`)),
282 chromedp.Click(chromedp.CSS(`[data-command="new-slide"]`)),
283 waitFor(`document.querySelectorAll('[slides-strip-item]').length === 9`),
284 waitFor(`location.hash.length === 13 && location.hash !== '#`+first+`'`),
285 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === location.hash.slice(1)`),
286 waitFor(`document.querySelector('[estilo-save-status]').dataset.state === 'saved'`),
287 )
288 rig.Screen("[slides-editor]", "new slide")
289 var order int
290 rig.Run(evalInto(&order, `Array.from(document.querySelectorAll('[slides-strip-item]')).map(li => li.dataset.slideId).indexOf(location.hash.slice(1))`))
291 if order != 1 {
292 t.Errorf("the new slide sits at strip index %d, want 1 (right after the first)", order)
293 }
294 var made string
295 rig.Run(evalInto(&made, `location.hash.slice(1)`))
296
297 // Undo takes the slide away again, and the stage moves to one that
298 // still exists — the strip and the stage agree on which.
299 rig.Run(
300 chromedp.Click(chromedp.CSS(`[slides-menu="edit"] > summary`)),
301 // A closed <details> still leaves its descendants in the DOM, so
302 // WaitVisible can report the Undo button before a person can reach
303 // it. Wait for the native menu state instead.
304 waitFor(`document.querySelector('[slides-menu="edit"]')?.open === true`),
305 chromedp.Click(chromedp.CSS(`[data-command="undo"]`)),
306 waitFor(`document.querySelectorAll('[slides-strip-item]').length === 8`),
307 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id !== '`+made+`'`),
308 waitFor(`document.querySelector('[slides-strip-item][data-current="true"]')?.dataset.slideId === document.querySelector('[slides-stage] [slides-slide]')?.dataset.id`),
309 waitFor(`document.querySelector('[estilo-save-status]').dataset.state === 'saved'`),
310 )
311 rig.Screen("[slides-editor]", "undone")
312}
313
314// serverClient is a signed-in http.Client against the rig's real
315// server: the second writer in a collaboration drive. It signs in the
316// way a person does, through the same mailer the browser used.
317func serverClient(t *testing.T, rig *harness.Rig, mailer *fakeMailer) *http.Client {
318 t.Helper()
319 jar, err := cookiejar.New(nil)
320 if err != nil {
321 t.Fatalf("cookiejar: %v", err)
322 }
323 c := &http.Client{Jar: jar}
324 before := len(mailer.messages())
325 req, _ := http.NewRequest(http.MethodPost, rig.Origin+"/signin", strings.NewReader(url.Values{"address": {allowedAddress}}.Encode()))
326 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
327 req.Header.Set("Origin", rig.Origin)
328 req.Header.Set("Sec-Fetch-Site", "same-origin")
329 res, err := c.Do(req)
330 if err != nil {
331 t.Fatalf("POST /signin: %v", err)
332 }
333 res.Body.Close()
334 msgs := mailer.messages()
335 if len(msgs) != before+1 {
336 t.Fatalf("POST /signin sent %d mails, want 1", len(msgs)-before)
337 }
338 link := magicLinkPattern.FindString(msgs[len(msgs)-1].Body)
339 // Opening the link is the confirm door and spends nothing; its Sign
340 // in button POSTs the token back with a browser's same-origin
341 // evidence, and that POST is what signs in.
342 u, err := url.Parse(link)
343 if err != nil {
344 t.Fatalf("parse the magic link: %v", err)
345 }
346 open, err := c.Get(link)
347 if err != nil {
348 t.Fatalf("GET the magic link: %v", err)
349 }
350 page, _ := io.ReadAll(open.Body)
351 open.Body.Close()
352 m := confirmForm.FindStringSubmatch(string(page))
353 if open.StatusCode != http.StatusOK || m == nil {
354 t.Fatalf("GET the magic link = %d, want the confirm door:\n%s", open.StatusCode, page)
355 }
356 req, _ = http.NewRequest(http.MethodPost, rig.Origin+html.UnescapeString(m[1]), strings.NewReader(url.Values{"token": {html.UnescapeString(m[2])}}.Encode()))
357 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
358 req.Header.Set("Origin", rig.Origin)
359 req.Header.Set("Sec-Fetch-Site", "same-origin")
360 verify, err := c.Do(req)
361 if err != nil {
362 t.Fatalf("POST %s: %v", u.Path, err)
363 }
364 verify.Body.Close()
365 if verify.StatusCode != http.StatusOK || verify.Request.URL.Path != "/" {
366 t.Fatalf("signing in ended at %d %s, want 200 on the deck list", verify.StatusCode, verify.Request.URL.Path)
367 }
368 return c
369}
370
371// TestBrowserSeesAnotherWriter: a second writer — the core's own bytes
372// posted over the wire, as another tab or an agent would — changes the
373// title while the editor is open, and the stage shows the new text
374// without a reload: the stream said so, the tab fetched it, and
375// y-prosemirror redrew the bound heading.
376func TestBrowserSeesAnotherWriter(t *testing.T) {
377 rig, mailer := newRig(t)
378 browserSignIn(t, rig, mailer)
379 var deck string
380 rig.Run(evalInto(&deck, `(document.querySelector('a[href^="/d/"]')?.getAttribute('href') ?? '').replace(/\/edit$/, '')`))
381
382 const heading = `[slides-stage] [data-block="heading"]`
383 rig.Run(
384 chromedp.Navigate(rig.Origin+deck+"/edit"),
385 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
386 waitFor(`document.querySelector('`+heading+`')?.getAttribute('contenteditable') === 'true'`),
387 )
388 var slide, block string
389 rig.Run(evalInto(&slide, `document.querySelector('[slides-editor]').dataset.slide`))
390 rig.Run(evalInto(&block, `document.querySelector('`+heading+`').dataset.id`))
391
392 // The other writer: caught up from the server's log, then one op.
393 c := serverClient(t, rig, mailer)
394 res, err := c.Get(rig.Origin + deck + "/updates?since=0")
395 if err != nil {
396 t.Fatalf("GET the log: %v", err)
397 }
398 body, _ := io.ReadAll(res.Body)
399 res.Body.Close()
400 m := newMirror(t, strings.TrimPrefix(deck, "/d/"), frames(t, body))
401 update := m.ops(t, `[{"op":"set_text","slide":"`+slide+`","id":"`+block+`","markdown":"Rewritten elsewhere"}]`)
402 req, _ := http.NewRequest(http.MethodPost, rig.Origin+deck+"/updates", bytes.NewReader(update))
403 req.Header.Set("Content-Type", "application/octet-stream")
404 req.Header.Set("Origin", rig.Origin)
405 req.Header.Set("Sec-Fetch-Site", "same-origin")
406 post, err := c.Do(req)
407 if err != nil {
408 t.Fatalf("POST the update: %v", err)
409 }
410 post.Body.Close()
411 if post.StatusCode != http.StatusNoContent {
412 t.Fatalf("POST the update: status %d, want 204", post.StatusCode)
413 }
414
415 rig.Run(waitFor(`document.querySelector('` + heading + `').textContent === 'Rewritten elsewhere'`))
416 rig.Screen("[slides-editor]", "after a remote write")
417 // The remote write is not this tab's to save back: the status line
418 // never left "Saved".
419 var state string
420 rig.Run(evalInto(&state, `document.querySelector('[estilo-save-status]').dataset.state`))
421 if state != "saved" {
422 t.Errorf("after a remote write the status is %q, want saved", state)
423 }
424}
425
426// runOn drives a second tab the way rig.Run drives the rig's own:
427// plain chromedp actions, a t.Fatalf on failure. It has no screen to
428// report — chromedp's own error already names the action.
429func runOn(t *testing.T, ctx context.Context, actions ...chromedp.Action[chromedp.Void]) {
430 t.Helper()
431 if err := chromedp.Do(ctx, actions...); err != nil {
432 t.Fatalf("second tab: %v", err)
433 }
434}
435
436// TestBrowserPresenceShowsEachOther (task 5, spec §3.3): two tabs on
437// the same deck — the same signed-in cookie, the same browser, but a
438// mount of the bundle each, a client id of its own each (presence.mjs's
439// newClientId, per tab rather than per person) and a real heartbeat
440// each. What this drives is the half node tests cannot reach:
441// presence.mjs's diff and presence-view.mjs's DOM rules are exercised
442// under a fake clock and a DOM stub (presence.test.mjs,
443// presence-view.test.mjs); this is the wiring between them and the
444// real thing on screen — the POST, the stream's `presence` event, and
445// paintItem/mark actually drawing.
446func TestBrowserPresenceShowsEachOther(t *testing.T) {
447 rig, mailer := newRig(t)
448 browserSignIn(t, rig, mailer)
449 var deck string
450 rig.Run(evalInto(&deck, `(document.querySelector('a[href^="/d/"]')?.getAttribute('href') ?? '').replace(/\/edit$/, '')`))
451
452 const bound = `document.querySelector('[slides-stage] [data-block="heading"]')?.getAttribute('contenteditable') === 'true'`
453 rig.Run(
454 chromedp.Navigate(rig.Origin+deck+"/edit"),
455 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
456 waitFor(bound),
457 )
458 var slide string
459 rig.Run(evalInto(&slide, `document.querySelector('[slides-editor]').dataset.slide`))
460
461 // A second tab: the browser context the sign-in cookie already
462 // lives in, chromedp.NewContext's own page — a fresh mountEditor(),
463 // a fresh client id, a fresh heartbeat.
464 tab2, cancel := chromedp.NewContext(rig.Context())
465 defer cancel()
466 runOn(t, tab2,
467 chromedp.Navigate(rig.Origin+deck+"/edit"),
468 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
469 waitFor(bound),
470 )
471
472 stripAvatar := `document.querySelector('[slides-strip-item][data-slide-id="` + slide + `"] [slides-presence-avatar]')`
473 // Tab one draws tab two's avatar on the strip item both are on —
474 // presence.start()'s immediate beat, POST /d/{sqid}/presence,
475 // live.go's presence stream event, and paintItem, all for real.
476 rig.Run(waitFor(stripAvatar + ` !== null`))
477 // And symmetrically: presence is mutual, not a one-way broadcast.
478 runOn(t, tab2, waitFor(stripAvatar+` !== null`))
479
480 var label string
481 rig.Run(evalInto(&label, stripAvatar+`.getAttribute('aria-label')`))
482 if label == "" {
483 t.Error("the strip avatar carries no accessible name — colour alone would fail WCAG 1.4.1")
484 }
485 rig.Screen(`[slides-strip]`, "an avatar for the other tab")
486
487 // Tab two selects the heading block; tab one draws an outline over
488 // it with a name chip.
489 runOn(t, tab2, chromedp.Click(chromedp.CSS(`[slides-stage] [data-block="heading"]`)))
490 rig.Run(waitFor(`document.querySelector('[slides-presence-mark] [slides-presence-chip]')?.textContent.length > 0`))
491
492 // The mark sits directly over the block the other tab selected:
493 // same rect, checked against the block itself rather than trusting
494 // the JS that placed it.
495 var aligned bool
496 rig.Run(evalInto(&aligned, `(() => {
497 const block = document.querySelector('[slides-stage] [data-block="heading"]')
498 const mark = document.querySelector('[slides-presence-mark]')
499 if (!block || !mark) return false
500 const b = block.getBoundingClientRect(), m = mark.getBoundingClientRect()
501 // Within a couple of px: the marks container is positioned off
502 // the stage's own border box (canvas.mjs's overlay reads its
503 // origin the same way, and the stage carries a 1px border), so
504 // exact equality is not the contract — visibly over the block is.
505 return Math.abs(b.left - m.left) <= 2 && Math.abs(b.top - m.top) <= 2
506 })()`))
507 if !aligned {
508 t.Error("the presence mark is not drawn over the block the other tab selected")
509 }
510 rig.Screen(`[slides-stage]`, "a block outline for the other tab's selection")
511
512 // The arrival is announced once, politely — never a move, which
513 // would make the deck unusable with a screen reader.
514 var live string
515 rig.Run(evalInto(&live, `document.querySelector('[slides-presence-live]').textContent`))
516 if live == "" {
517 t.Error("presence never announced the second tab's arrival")
518 }
519}
520
521// setValue sets a form control's value the way a person would have
522// left it, then fires the change event the bundle listens for.
523func setValue(selector, value string) chromedp.Action[chromedp.Void] {
524 return chromedp.Evaluate[chromedp.Void](`(() => {
525 const el = document.querySelector('` + selector + `')
526 el.value = '` + value + `'
527 el.dispatchEvent(new Event('change', { bubbles: true }))
528 return true
529 })()`)
530}
531
532// dragBy presses the mouse at (x, y), moves it by (dx, dy) in a few
533// steps and releases: the pointer gesture canvas.mjs turns into one
534// set_block (or set_phone) on release.
535func dragBy(x, y, dx, dy float64) chromedp.Action[chromedp.Void] {
536 return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
537 if _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, input.DispatchMouseEventParams{Type: chromedp.MousePressed, X: x, Y: y, Button: input.MouseButtonLeft, ClickCount: 1}); err != nil {
538 return err
539 }
540 for i := 1; i <= 4; i++ {
541 f := float64(i) / 4
542 if _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, input.DispatchMouseEventParams{Type: chromedp.MouseMoved, X: x + dx*f, Y: y + dy*f, Button: input.MouseButtonLeft}); err != nil {
543 return err
544 }
545 }
546 _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, input.DispatchMouseEventParams{Type: chromedp.MouseReleased, X: x + dx, Y: y + dy, Button: input.MouseButtonLeft, ClickCount: 1})
547 return err
548 })
549}
550
551// TestBrowserInspectorAndCanvas is task 4's drive: add a slide from the
552// inspector and set its template; on the canvas slide select a shape,
553// drag it, switch to the phone view and hide it there; reload and find
554// every one of those persisted — the slide, its template, the moved
555// box, the phone override and the chosen view.
556func TestBrowserInspectorAndCanvas(t *testing.T) {
557 rig, mailer := newRig(t)
558 browserSignIn(t, rig, mailer)
559 var deck string
560 rig.Run(evalInto(&deck, `(document.querySelector('a[href^="/d/"]')?.getAttribute('href') ?? '').replace(/\/edit$/, '')`))
561
562 const bound = `document.querySelector('[slides-stage] [data-block="heading"]')?.getAttribute('contenteditable') === 'true'`
563 const saved = `document.querySelector('[estilo-save-status]').dataset.state === 'saved'`
564 rig.Run(
565 chromedp.Navigate(rig.Origin+deck+"/edit"),
566 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
567 waitFor(bound),
568 )
569 var first string
570 rig.Run(evalInto(&first, `document.querySelector('[slides-editor]').dataset.slide`))
571
572 // What the inspector hides has to be off the SCREEN, not merely
573 // marked hidden: every author `display` in the stylesheets beats the
574 // UA's own [hidden]{display:none}. checkVisibility() is the
575 // assertion that notices. With nothing selected the card is the
576 // slide's options (data-inspect, the editor tidied §4.1): no Block
577 // section, and the delete question not asked.
578 const blockForm = `document.querySelector('[slides-inspector-form][data-section="block"]')`
579 const confirm = `document.querySelector('[slides-confirm]')`
580 rig.Run(
581 waitFor(blockForm+`.checkVisibility() === false`),
582 waitFor(confirm+`.checkVisibility() === false`),
583 waitFor(`document.querySelector('[slides-inspector-form][data-section="slide"]').checkVisibility() === true`),
584 )
585
586 // Add a slide after the current one from its menu in the strip (the
587 // card holds no slide commands, the editor tidied E10), then set its
588 // template.
589 rig.Run(
590 chromedp.Click(chromedp.CSS(`[slides-strip-item][data-current="true"] [slides-strip-menu] > summary`)),
591 chromedp.Click(chromedp.CSS(`[slides-strip-item][data-current="true"] [data-slide-command="add-after"]`)),
592 waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 9`),
593 waitFor(`location.hash.length === 13 && location.hash !== '#`+first+`'`),
594 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === location.hash.slice(1)`),
595 waitFor(saved),
596 )
597 var added string
598 rig.Run(evalInto(&added, `location.hash.slice(1)`))
599 rig.Run(
600 pickLayout("section"),
601 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.template === 'section'`),
602 waitFor(saved),
603 )
604 rig.Screen("[slides-editor]", "added a section slide")
605
606 // Undo is a structural change too (its origin is the undo manager,
607 // not this tab's ops): the stage re-fetches after it. It takes back
608 // the template alone — the add and the template change were two
609 // commands, however quickly they followed each other — so the slide
610 // is still there. Redo puts the template back for the rest.
611 rig.Run(
612 chromedp.Click(chromedp.CSS(`[slides-menu="edit"] > summary`)),
613 waitFor(`document.querySelector('[slides-menu="edit"]')?.open === true`),
614 chromedp.Click(chromedp.CSS(`[data-command="undo"]`)),
615 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.template === 'title-body'`),
616 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+added+`'`),
617 waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 9`),
618 waitFor(`JSON.stringify(`+litPictures+`) === '["title-body"]'`),
619 waitFor(saved),
620 chromedp.Click(chromedp.CSS(`[slides-menu="edit"] > summary`)),
621 waitFor(`document.querySelector('[slides-menu="edit"]')?.open === true`),
622 chromedp.Click(chromedp.CSS(`[data-command="redo"]`)),
623 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.template === 'section'`),
624 waitFor(saved),
625 )
626
627 // The canvas slide, found by the words under its thumbnail. It used
628 // to be found by looking for a canvas SECTION in the strip; a
629 // thumbnail is an <img> of an SVG now (thumbs.go), so there is no
630 // markup of the slide in the strip to interrogate — which is the
631 // point of the change, and the label is what a person would use to
632 // find it too.
633 var canvas string
634 rig.Run(evalInto(&canvas, `Array.from(document.querySelectorAll('[slides-strip-item][data-slide-id]'))`+
635 `.find(li => li.querySelector('[slides-strip-label]')?.textContent.startsWith('Canvas:'))`+
636 `?.dataset.slideId ?? ''`))
637 if canvas == "" {
638 t.Fatal("the sample deck has no canvas slide in the strip")
639 }
640 const rect = `[slides-stage] [data-block="shape"][data-kind="rect"]`
641 rig.Run(
642 chromedp.Navigate(rig.Origin+deck+"/edit#"+canvas),
643 chromedp.WaitVisible(chromedp.CSS(rect)),
644 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === '`+canvas+`'`),
645 waitFor(bound),
646 )
647 var before string
648 rig.Run(evalInto(&before, `document.querySelector('`+rect+`').style.left`))
649
650 // Select the rectangle by clicking near its top-left (clear of the
651 // ellipse over its middle), then drag the overlay's body surface.
652 var box []float64
653 rig.Run(
654 chromedp.ScrollIntoView(chromedp.CSS(rect)),
655 evalInto(&box, `(() => { const r = document.querySelector('`+rect+`').getBoundingClientRect(); return [r.left, r.top, r.width, r.height] })()`),
656 )
657 rig.Run(
658 chromedp.MouseClickXY(box[0]+30, box[1]+30),
659 waitFor(`document.querySelector('`+rect+`').getAttribute('aria-selected') === 'true'`),
660 waitFor(`!document.querySelector('[slides-canvas-overlay]').hidden`),
661 waitFor(`location.hash.split('/')[1] === document.querySelector('`+rect+`').dataset.id`),
662 waitFor(`document.querySelector('[slides-inspector] form[data-section="block"]').checkVisibility()`),
663 )
664 rig.Screen("[slides-editor]", "selected the rectangle")
665 rig.Run(
666 dragBy(box[0]+30, box[1]+30, box[2]/2, 0),
667 waitFor(saved),
668 waitFor(`document.querySelector('`+rect+`').style.left !== '`+before+`'`),
669 waitFor(`document.querySelector('`+rect+`').getAttribute('aria-selected') === 'true'`),
670 )
671 var moved string
672 rig.Run(evalInto(&moved, `document.querySelector('`+rect+`').style.left`))
673 if moved == before || moved == "" {
674 t.Fatalf("after the drag the rectangle's left is %q, was %q", moved, before)
675 }
676 var shownX string
677 rig.Run(evalInto(&shownX, `document.querySelector('#rst-block-x').value`))
678 if shownX == "" || shownX == "8.0" {
679 t.Errorf("the inspector's Left field reads %q after the drag", shownX)
680 }
681 rig.Screen("[slides-editor]", "dragged the rectangle")
682
683 // The phone view: the stage re-renders at ?vp=phone; hiding the
684 // selected block there is a phone override, and the badge says so.
685 rig.Run(
686 chromedp.Click(chromedp.CSS(`[slides-switcher] input[value="phone"]`)),
687 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.vp === 'phone'`),
688 waitFor(`document.querySelector('[slides-stage-pane]').dataset.view === 'phone'`),
689 waitFor(`document.querySelector('`+rect+`')?.getAttribute('aria-selected') === 'true'`),
690 chromedp.Click(chromedp.CSS(`input[name="rst-block-phone-hidden"]`)),
691 waitFor(saved),
692 waitFor(`document.querySelector('`+rect+`')?.dataset.phoneHidden === 'true'`),
693 waitFor(`!document.querySelector('[slides-phone-badge]').hidden`),
694 )
695 rig.Screen("[slides-editor]", "hidden on a phone")
696
697 // Reload: the slide, its template, the box, the override and the
698 // view are all still there.
699 rig.Run(
700 chromedp.Reload(),
701 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
702 waitFor(`document.querySelector('[slides-stage-pane]').dataset.view === 'phone'`),
703 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.vp === 'phone'`),
704 waitFor(`document.querySelector('`+rect+`')?.dataset.phoneHidden === 'true'`),
705 )
706 rig.Screen("[slides-editor]", "reloaded in the phone view")
707 var after string
708 rig.Run(evalInto(&after, `document.querySelector('`+rect+`').style.left`))
709 if after != moved {
710 t.Errorf("after a reload the rectangle's left is %q, want the dragged %q", after, moved)
711 }
712 // The added slide survived the reload as a section. Read off the
713 // server rather than out of the strip, which holds a picture of
714 // each slide now and not a copy of it: the slide's own HTML route
715 // is where its template is a fact.
716 var template string
717 rig.Run(evalInto(
718 &template, `fetch('`+deck+`/slides/`+added+`.html', { credentials: 'same-origin' })`+
719 `.then(r => r.text()).then(t => t.match(/data-template="([a-z-]+)"/)?.[1] ?? '')`, func(p *runtime.EvaluateParams) {
720 p.AwaitPromise = new(true)
721 }))
722 if template != "section" {
723 t.Errorf("after a reload the added slide's template is %q, want section", template)
724 }
725 // And the strip shows a picture of it, from the route that draws
726 // one.
727 var thumb string
728 rig.Run(evalInto(&thumb, `document.querySelector('[slides-strip-item][data-slide-id="`+added+`"] [slides-thumb-img]')?.getAttribute('src') ?? ''`))
729 if !strings.Contains(thumb, "/slides/"+added+".svg") {
730 t.Errorf("the added slide's thumbnail is %q, want the SVG route", thumb)
731 }
732 var n int
733 rig.Run(evalInto(&n, `document.querySelectorAll('[slides-strip-item][data-slide-id]').length`))
734 if n != 9 {
735 t.Errorf("after a reload the strip lists %d slides, want 9", n)
736 }
737 // Back to the desktop, so the stored view does not follow the next drive.
738 rig.Run(
739 chromedp.Click(chromedp.CSS(`[slides-switcher] input[value="desktop"]`)),
740 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.vp !== 'phone'`),
741 )
742}
743
744// TestBrowserDeleteToEmptyThenNewSlide (task 3 review, finding 1): the
745// stage exists on an empty deck, so deleting a deck's only slide from
746// the Slide section (ask, then confirm) leaves an editor New slide can
747// fill — and does.
748func TestBrowserDeleteToEmptyThenNewSlide(t *testing.T) {
749 rig, mailer := newRig(t)
750 browserSignIn(t, rig, mailer)
751 rig.Run(
752 chromedp.Navigate(rig.Origin+"/"),
753 chromedp.WaitVisible(chromedp.CSS(`[slides-create] button`)),
754 chromedp.Click(chromedp.CSS(`[slides-create] button`)),
755 waitFor(`/^\/d\/[^/]+\/edit$/.test(location.pathname)`),
756 )
757 var deck string
758 rig.Run(evalInto(&deck, `location.pathname.replace(/\/edit$/, "")`))
759
760 const saved = `document.querySelector('[estilo-save-status]').dataset.state === 'saved'`
761 rig.Run(
762 chromedp.Navigate(rig.Origin+deck+"/edit"),
763 chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)),
764 waitFor(`document.querySelector('[slides-stage] [data-block="heading"]')?.getAttribute('contenteditable') === 'true'`),
765 waitFor(`document.querySelector('[slides-confirm]').checkVisibility() === false`),
766 chromedp.Click(chromedp.CSS(`[slides-menu="slide"] > summary`)),
767 chromedp.Click(chromedp.CSS(`[slides-menu="slide"] [data-command="slide-delete-ask"]`)),
768 // Rendered visibility, not the property: the confirmation is
769 // only a confirmation if it was not on the screen until asked
770 // for, and `.hidden` cannot tell those apart (see the
771 // checkVisibility assertions in the inspector drive).
772 waitFor(`document.querySelector('[slides-confirm]').checkVisibility()`),
773 chromedp.Click(chromedp.CSS(`[slides-confirm] [data-command="slide-delete"]`)),
774 waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 0`),
775 waitFor(`document.querySelector('[slides-stage] [slides-slide]') === null`),
776 waitFor(saved),
777 )
778 rig.Screen("[slides-editor]", "emptied the deck")
779
780 rig.Run(
781 chromedp.Click(chromedp.CSS(`[slides-menu="slide"] > summary`)),
782 chromedp.WaitVisible(chromedp.CSS(`[data-command="new-slide"]`)),
783 chromedp.Click(chromedp.CSS(`[data-command="new-slide"]`)),
784 waitFor(`document.querySelectorAll('[slides-strip-item][data-slide-id]').length === 1`),
785 waitFor(`document.querySelector('[slides-stage] [slides-slide]')?.dataset.id === location.hash.slice(1)`),
786 waitFor(`document.querySelector('[slides-stage] [data-block="heading"]')?.getAttribute('contenteditable') === 'true'`),
787 waitFor(saved),
788 )
789 rig.Screen("[slides-editor]", "new slide on an empty deck")
790}
791