oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3// The phone's Format sheet in the corners Fable's review of P2 found
4// (#181): how it opens and closes from a keyboard and from the document,
5// what it does to the caret and the selection, and the visual viewport's
6// odd shapes. Chromium with a touch screen, 390×844, and the scripted
7// visualViewport of phone_format_browser_test.go.
8//
9// CGO_ENABLED=0 go test -tags browser -run Sheet ./internal/docs/
10package docs_test
11
12import (
13 "bytes"
14 "context"
15 "encoding/json"
16 "math"
17 "net/http"
18 "net/http/httptest"
19 "os"
20 "strings"
21 "testing"
22 "time"
23
24 "amadan.net/rastrillo/rastrillo/harness"
25 "github.com/chromedp/cdproto/emulation"
26 "github.com/chromedp/cdproto/input"
27 "github.com/chromedp/cdproto/page"
28 "github.com/chromedp/chromedp"
29
30 "github.com/carlosframework/docs/internal/docs"
31)
32
33// sheetRig is one signed-in phone on one document.
34type sheetRig struct {
35 t *testing.T
36 rig *harness.Rig
37 app *docs.App
38 cookies []*http.Cookie
39 sqid string
40}
41
42const sheetPerson = "sheet@example.com"
43
44// newSheetRig opens a document holding the fragment vector (simple.bin:
45// "First paragraph." and "Second paragraph.") on a phone, at path's
46// query (?novv drops visualViewport).
47func newSheetRig(t *testing.T, vector, query string) *sheetRig {
48 t.Helper()
49 s := &sheetRig{t: t}
50 s.rig = harness.New(t, func(origin string) http.Handler {
51 var err error
52 s.app, err = docs.NewForTestWith(t, docs.Config{Origin: origin})
53 if err != nil {
54 t.Fatalf("NewForTestWith: %v", err)
55 }
56 return s.app.Handler()
57 })
58 s.cookies = signInCookies(t, s.app, sheetPerson)
59 ctx := context.Background()
60 doc, err := s.app.Store().Create(ctx, s.app.TestPerson(t, sheetPerson), "Minutes")
61 if err != nil {
62 t.Fatal(err)
63 }
64 update, err := os.ReadFile("../../fixtures/vectors/fragment/" + vector)
65 if err != nil {
66 t.Fatal(err)
67 }
68 if _, err := s.app.Store().ApplyUpdate(ctx, doc, s.app.TestActorFor(t, doc), update); err != nil {
69 t.Fatal(err)
70 }
71 s.sqid = doc.Sqid
72 var set []chromedp.Action[chromedp.Void]
73 for _, c := range s.cookies {
74 set = append(set, setCookie(s.rig.Origin, c))
75 }
76 s.run("a phone", append(set,
77 command(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: fakeViewport}),
78 command(emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: true, MaxTouchPoints: 5}),
79 command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 390, Height: 844, DeviceScaleFactor: 2, Mobile: true}),
80 chromedp.Navigate(s.rig.Origin+"/d/"+s.sqid+query), chromedp.WaitVisible(chromedp.CSS(`[contenteditable="true"]`)),
81 chromedp.WaitNotPresent(chromedp.CSS(`[docs-quickbar] [data-docs-command="strong"][disabled]`)),
82 chromedp.Sleep(400*time.Millisecond))...)
83 return s
84}
85
86func (s *sheetRig) run(what string, actions ...chromedp.Action[chromedp.Void]) {
87 s.t.Helper()
88 ctx, cancel := context.WithTimeout(s.rig.Context(), 25*time.Second)
89 defer cancel()
90 if err := chromedp.Do(ctx, actions...); err != nil {
91 s.t.Fatalf("%s: %v", what, err)
92 }
93}
94
95func (s *sheetRig) eval(what, js string, out any) {
96 s.t.Helper()
97 var raw json.RawMessage
98 s.run(what, evalInto(&raw, js))
99 if err := json.Unmarshal(raw, out); err != nil {
100 s.t.Fatalf("%s: %v (%s)", what, err, raw)
101 }
102}
103
104func (s *sheetRig) probe(what string) formatProbe {
105 s.t.Helper()
106 var p formatProbe
107 s.eval(what, formatProbeJS, &p)
108 return p
109}
110
111// settle is long enough for phone.js and the editor to answer a step.
112var settle = chromedp.Sleep(400 * time.Millisecond)
113
114// do runs a script for its effect.
115func do(js string) chromedp.Action[chromedp.Void] {
116 return chromedp.Evaluate[chromedp.Void]("(() => {" + js + "; return true })()")
117}
118
119// post is a collaborator's change: a fragment vector posted to the
120// document's update log, as another tab posts one.
121func (s *sheetRig) post(vector string) {
122 s.t.Helper()
123 update := mustRead(s.t, "../../fixtures/vectors/fragment/"+vector)
124 req := httptest.NewRequest(http.MethodPost, "/d/"+s.sqid+"/updates", bytes.NewReader(update))
125 req.Header.Set("Content-Type", "application/octet-stream")
126 req.Header.Set("Sec-Fetch-Site", "same-origin")
127 for _, c := range s.cookies {
128 req.AddCookie(c)
129 }
130 rec := httptest.NewRecorder()
131 s.app.Handler().ServeHTTP(rec, req)
132 if rec.Code/100 != 2 {
133 s.t.Fatalf("POST %s: %d %s", vector, rec.Code, rec.Body.String())
134 }
135}
136
137// Review 1: Enter on Aa opens the sheet with focus in it, on its title;
138// Escape closes it, and focus is back on Aa.
139func TestTheSheetFromAKeyboard(t *testing.T) {
140 s := newSheetRig(t, "simple.bin", "")
141 s.run("Enter on Aa", chromedp.Focus(chromedp.CSS(`[docs-aa]`)), chromedp.KeyEvent("\r"), settle)
142 var at struct {
143 Open bool
144 Active string
145 InSheet bool
146 }
147 where := `(() => { const a = document.activeElement; return { Open: document.documentElement.getAttribute('data-docs-sheet') === 'open',
148 Active: a ? a.outerHTML.slice(0, 40) : '', InSheet: !!a && !!a.closest('[docs-inspector]') } })()`
149 s.eval("opened", where, &at)
150 if !at.Open || !at.InSheet {
151 t.Errorf("Enter on Aa: sheet open %v, focus on %q, want it in the sheet", at.Open, at.Active)
152 }
153 s.run("Escape", chromedp.KeyEvent("\u001b"), settle)
154 var back bool
155 s.eval("closed", where, &at)
156 s.eval("on Aa", `document.activeElement === document.querySelector('[docs-aa]')`, &back)
157 if at.Open || !back {
158 t.Errorf("Escape: sheet open %v, focus on %q, want it closed and focus back on Aa", at.Open, at.Active)
159 }
160}
161
162// openWithKeyboard puts the caret in the second paragraph, raises a
163// 336px keyboard, selects that paragraph and opens the sheet from the
164// capsule's Aa.
165func (s *sheetRig) openWithKeyboard() {
166 s.t.Helper()
167 s.run("the caret, a keyboard", chromedp.Click(chromedp.CSS(`[docs-text] p:last-child`)), settle,
168 do(`__keyboard(336, 0)`), settle,
169 do(`getSelection().selectAllChildren(document.querySelector('[docs-text] p:last-child'))`), settle,
170 chromedp.Click(chromedp.CSS(`[docs-quickbar-aa]`)), settle)
171 if p := s.probe("sheet open"); !p.Sheet || !p.Kept || p.Focused {
172 s.t.Fatalf("the sheet did not open over a kept selection: %+v", p)
173 }
174}
175
176// Review 2: a tap in the document while the sheet is open closes it:
177// the keyboard comes up with the capsule on it, nothing kept is drawn
178// over the live selection, and Aa is no longer expanded.
179func TestATapInTheDocumentClosesTheSheet(t *testing.T) {
180 s := newSheetRig(t, "simple.bin", "")
181 s.openWithKeyboard()
182 // The tap is just after "First" in the first paragraph, and the caret
183 // goes there (follow-up D on #181), not back to the kept selection.
184 var at struct{ X, Y float64 }
185 s.eval("where", `(() => { const t = document.querySelector('[docs-text] p:first-child').firstChild; const r = document.createRange();
186 r.setStart(t, 4); r.setEnd(t, 5); const b = r.getBoundingClientRect(); return { X: b.right - 1, Y: b.top + b.height / 2 } })()`, &at)
187 s.run("a tap in the document", chromedp.MouseClickXY(at.X, at.Y), settle)
188 if p := s.probe("tapped"); p.Sheet || p.Kept || !p.Focused || p.Quick != "keyboard" || p.Expanded != "false" {
189 t.Errorf("after a tap in the document: sheet %v, kept drawn %v, caret %v, quick bar %q, Aa expanded %q; want closed, none, the caret, the capsule, false",
190 p.Sheet, p.Kept, p.Focused, p.Quick, p.Expanded)
191 }
192 var caret struct {
193 Collapsed, InFirst bool
194 Offset int
195 }
196 s.eval("the caret", `(() => { const s = getSelection(), p = document.querySelector('[docs-text] p:first-child');
197 return { Collapsed: s.isCollapsed, InFirst: p.contains(s.anchorNode), Offset: s.anchorOffset } })()`, &caret)
198 if !caret.Collapsed || !caret.InFirst || caret.Offset != 5 {
199 t.Errorf("the caret after the tap: collapsed %v, in the first paragraph %v, at %d; want a caret after \"First\" (5)", caret.Collapsed, caret.InFirst, caret.Offset)
200 }
201}
202
203// Review 3: Aa in the middle of an IME composition (Gboard, a Japanese
204// or Chinese input method) must not draw the kept selection into the
205// text being composed: the editor blurs first, which ends the
206// composition, and draws the kept caret after. The composition's words
207// land once. A guard more than a reproduction: Chromium's ProseMirror
208// holds a decoration's DOM until the composition ends, so the old order
209// (the kept meta, then the blur) passes here too; Android's keyboards
210// are where it went wrong.
211func TestAaMidCompositionWaitsForIt(t *testing.T) {
212 s := newSheetRig(t, "simple.bin", "")
213 s.run("the caret at the end, a keyboard", chromedp.Click(chromedp.CSS(`[docs-text] p:last-child`)), settle,
214 do(`const p = document.querySelector('[docs-text] p:last-child'); const r = document.createRange(); r.selectNodeContents(p); r.collapse(false); getSelection().removeAllRanges(); getSelection().addRange(r)`),
215 do(`__keyboard(336, 0)`), settle,
216 do(`window.__order = []; const text = document.querySelector('[docs-text]');
217 text.addEventListener('compositionend', () => __order.push('compositionend'));
218 new MutationObserver((rs) => { for (const r of rs) for (const n of r.addedNodes)
219 if (n.nodeType === 1 && (n.matches('[data-docs-kept], [data-docs-kept-caret]') || n.querySelector('[data-docs-kept], [data-docs-kept-caret]'))) __order.push('kept') })
220 .observe(text, { subtree: true, childList: true })`),
221 command(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "かな", SelectionStart: 2, SelectionEnd: 2}), settle,
222 // The click from script: a mouse press in Chromium commits the
223 // composition itself, before Aa's handler runs, where a tap on a
224 // phone's touch keyboard need not.
225 do(`document.querySelector('[docs-quickbar-aa]').click()`),
226 chromedp.Sleep(800*time.Millisecond))
227 var got struct {
228 Order []string
229 Last string
230 Open bool
231 }
232 s.eval("after Aa", `({ Order: window.__order, Last: document.querySelector('[docs-text] p:last-child').textContent,
233 Open: document.documentElement.getAttribute('data-docs-sheet') === 'open' })`, &got)
234 first := map[string]int{}
235 for i, e := range got.Order {
236 if _, ok := first[e]; !ok {
237 first[e] = i
238 }
239 }
240 k, kept := first["kept"]
241 e, ended := first["compositionend"]
242 if !got.Open || !kept || !ended || k < e {
243 t.Errorf("Aa mid-composition: sheet open %v, events %v; want the composition ended before the kept caret is drawn", got.Open, got.Order)
244 }
245 if got.Last != "Second paragraph.かな" {
246 t.Errorf("the paragraph reads %q, want %q", got.Last, "Second paragraph.かな")
247 }
248}
249
250// Review 4: the font and size pickers in the sheet. The list opens
251// downward inside the sheet; a pick applies to the kept selection and
252// leaves no text box focused (on a phone that would raise the keyboard
253// over the sheet); the sheet stays open.
254func TestPickersInTheSheet(t *testing.T) {
255 s := newSheetRig(t, "simple.bin", "")
256 s.run("select, Aa", do(`getSelection().selectAllChildren(document.querySelector('[docs-text] p:last-child'))`), settle,
257 chromedp.Click(chromedp.CSS(`[docs-aa]`)), settle)
258 type picked struct {
259 Value string
260 Typing, Open bool
261 ListTop, BoxEnd float64
262 ListEnd, SheetEnd float64
263 }
264 pick := func(what, id, option string) picked {
265 t.Helper()
266 list := `[rst-combo]:has(#` + id + `-combo) [role="listbox"]`
267 s.run(what+": open", chromedp.Click(chromedp.CSS(`#`+id+`-combo`)), chromedp.WaitVisible(chromedp.CSS(list)), settle)
268 var p picked
269 s.eval(what+": the list", `(() => { const l = document.querySelector('`+list+`').getBoundingClientRect(), b = document.querySelector('#`+id+`-combo').getBoundingClientRect(),
270 sh = document.querySelector('[docs-inspector]').getBoundingClientRect(); return { ListTop: l.top, BoxEnd: b.bottom, ListEnd: l.bottom, SheetEnd: sh.bottom } })()`, &p)
271 var at picked
272 s.run(what+": pick", do(`[...document.querySelectorAll('`+list+` [role="option"]')].find((o) => o.textContent.trim() === '`+option+`').dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true }))`),
273 do(`[...document.querySelectorAll('`+list+` [role="option"]')].find((o) => o.textContent.trim() === '`+option+`').click()`), settle)
274 s.eval(what+": after", `(() => { const a = document.activeElement; return { Value: document.querySelector('#`+id+`').value,
275 Typing: !!a && (a.tagName === 'INPUT' || a.isContentEditable), Open: document.documentElement.getAttribute('data-docs-sheet') === 'open' } })()`, &at)
276 at.ListTop, at.BoxEnd, at.ListEnd, at.SheetEnd = p.ListTop, p.BoxEnd, p.ListEnd, p.SheetEnd
277 return at
278 }
279 for _, c := range []struct{ what, id, option, want string }{
280 {"the font", "docs-select-font", "Caladea", "caladea"},
281 {"the size", "docs-select-size", "18", "18"},
282 } {
283 p := pick(c.what, c.id, c.option)
284 if p.ListTop < p.BoxEnd-1 || p.ListEnd > p.SheetEnd+1 {
285 t.Errorf("%s: the list runs %.0f to %.0f, want it below the box (%.0f) and inside the sheet (to %.0f)", c.what, p.ListTop, p.ListEnd, p.BoxEnd, p.SheetEnd)
286 }
287 if p.Value != c.want || p.Typing || !p.Open {
288 t.Errorf("%s: picked %q (want %q), a text box focused %v, the sheet open %v", c.what, p.Value, c.want, p.Typing, p.Open)
289 }
290 }
291}
292
293// Review 5: the bar follows the visual viewport only while the keyboard
294// is up. Pinch-zoomed, with or without the caret, it stays on the page.
295func TestAPinchZoomLeavesTheBarAlone(t *testing.T) {
296 s := newSheetRig(t, "simple.bin", "")
297 s.run("zoomed, no caret", do(`__zoom(2, 300)`), settle)
298 if p := s.probe("zoomed"); p.BarTop != 0 {
299 t.Errorf("pinch-zoomed with no keyboard: the bar's top at %.1f, want 0 (not moved)", p.BarTop)
300 }
301 s.run("zoomed, the caret", chromedp.Click(chromedp.CSS(`[docs-text] p:first-child`)), do(`__zoom(2, 300)`), settle)
302 if p := s.probe("zoomed with the caret"); p.BarTop != 0 {
303 t.Errorf("pinch-zoomed with the caret: the bar's top at %.1f, want 0", p.BarTop)
304 }
305}
306
307// Review 6: when the keyboard is up. A pinch-zoom shrinks the visual
308// viewport too, so the threshold is measured in layout pixels (height
309// times scale): zoomed, with the caret, there is no capsule. Where a
310// keyboard shrinks the layout viewport itself (interactive-widget=
311// resizes-content, Firefox for Android) the visual viewport never looks
312// short; the quick bar is then the strip under the bar.
313func TestWhenTheKeyboardIsUp(t *testing.T) {
314 s := newSheetRig(t, "simple.bin", "")
315 s.run("zoomed, the caret", chromedp.Click(chromedp.CSS(`[docs-text] p:first-child`)), do(`__zoom(2, 300)`), settle)
316 if p := s.probe("zoomed with the caret"); p.Quick != "" {
317 t.Errorf("pinch-zoomed with the caret and no keyboard: the quick bar is %q, want none", p.Quick)
318 }
319 s.run("unzoomed", do(`__zoom(1, 0)`), settle)
320 // The layout viewport 336px shorter, and the visual one with it.
321 s.run("resizes-content", command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 390, Height: 508, DeviceScaleFactor: 2, Mobile: true}),
322 settle, do(`__keyboard(0, 0)`), settle)
323 if p := s.probe("resizes-content"); p.Quick != "strip" || !near(p.QuickTop, p.BarBottom) {
324 t.Errorf("the layout viewport shrunk by a keyboard: the quick bar is %q at %.1f, want the strip under the bar at %.1f", p.Quick, p.QuickTop, p.BarBottom)
325 }
326 // Zoomed in with that keyboard up, where innerWidth reports the
327 // visual viewport's width (as Mobile Safari's long did): the page is
328 // as wide as it was, so the strip stays (follow-up C on #181).
329 s.run("zoomed, innerWidth the visual viewport's", do(`Object.defineProperty(window, 'innerWidth', { configurable: true, get: () => 195 }); __zoom(2, 0)`), settle)
330 if p := s.probe("zoomed, resizes-content"); p.Quick != "strip" {
331 t.Errorf("zoomed in with the layout viewport shrunk by a keyboard: the quick bar is %q, want the strip still", p.Quick)
332 }
333 s.run("unzoomed again", do(`delete window.innerWidth; __zoom(1, 0)`), settle)
334 s.run("the keyboard down", command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 390, Height: 844, DeviceScaleFactor: 2, Mobile: true}),
335 settle, do(`__keyboard(0, 0)`), settle)
336 if p := s.probe("the keyboard down"); p.Quick != "" {
337 t.Errorf("the layout viewport back to full height: the quick bar is %q, want none", p.Quick)
338 }
339}
340
341func near(a, b float64) bool { return math.Abs(a-b) <= 1.5 }
342
343// Review 7: a resync replaces the editor while the sheet is open; the
344// new one draws the kept selection too, so the person still sees what
345// the sheet acts on.
346func TestAResyncKeepsTheSelectionDrawn(t *testing.T) {
347 // A step keeps the text's own Yjs items, so the selection's relative
348 // positions resolve in the rebuilt document; a style chip makes the
349 // paragraph anew, so they do not, and the old positions stand in.
350 for _, c := range []struct{ name, control string }{
351 {"a size step", `[docs-step="up"]`},
352 {"a style chip", `[docs-chip="heading-2"]`},
353 } {
354 t.Run(c.name, func(t *testing.T) { resyncWithTheSheetOpen(t, c.control) })
355 }
356}
357
358func resyncWithTheSheetOpen(t *testing.T, control string) {
359 s := newSheetRig(t, "simple.bin", "")
360 // The caret in the document first: ProseMirror takes up a selection
361 // only while it has focus.
362 s.run("select, Aa", chromedp.Click(chromedp.CSS(`[docs-text] p:last-child`)), settle,
363 do(`getSelection().selectAllChildren(document.querySelector('[docs-text] p:last-child'))`), settle,
364 chromedp.Click(chromedp.CSS(`[docs-aa]`)), settle,
365 // The next save is answered 413, which sends the editor into a
366 // resync (resync_browser_test.go).
367 do(`window.__desc = document.querySelector('[docs-text]').pmViewDesc; const f = window.fetch; let first = true; window.__posts = [];
368 window.fetch = async function (u, o) {
369 if (String(u).endsWith('/updates') && o && o.method === 'POST') {
370 if (first) { first = false; window.__posts.push(413); return new Response('', { status: 413 }) }
371 const r = await f.call(this, u, o); window.__posts.push(r.status); return r }
372 return f.call(this, u, o) }`),
373 chromedp.Click(chromedp.CSS(control)), chromedp.Sleep(3*time.Second))
374 var got struct {
375 Posts []int
376 Remounted bool
377 Open bool
378 Kept string
379 }
380 s.eval("after the resync", `(() => { const k = document.querySelector('[data-docs-kept]');
381 return { Posts: window.__posts, Remounted: document.querySelector('[docs-text]').pmViewDesc !== window.__desc,
382 Open: document.documentElement.getAttribute('data-docs-sheet') === 'open', Kept: k ? k.textContent : '' } })()`, &got)
383 if len(got.Posts) < 1 || got.Posts[0] != 413 || !got.Remounted {
384 t.Fatalf("saves answered %v, the editor remounted %v; the check needs a refusal and the resync it sends the editor into", got.Posts, got.Remounted)
385 }
386 // The refused change is dropped by the resync, as any refused change
387 // is; the selection it was made on is still drawn.
388 if !got.Open || got.Kept != "Second paragraph." {
389 t.Errorf("after the resync: sheet open %v, kept drawn over %q; want open, over \"Second paragraph.\"", got.Open, got.Kept)
390 }
391}
392
393// Review 10: a collaborator's paragraph arrives above the selection
394// while the sheet is open; the kept selection moves with its text, and
395// a chip then applies to that text, not to what is now at its old
396// place.
397func TestARemoteEditWhileTheSheetIsOpen(t *testing.T) {
398 s := newSheetRig(t, "simple.bin", "")
399 s.run("select, Aa", chromedp.Click(chromedp.CSS(`[docs-text] p:last-child`)), settle,
400 do(`getSelection().selectAllChildren(document.querySelector('[docs-text] p:last-child'))`), settle,
401 chromedp.Click(chromedp.CSS(`[docs-aa]`)), settle)
402 s.post("remote-before.bin")
403 s.run("the collaborator's line arrives", chromedp.WaitVisible(chromedp.CSS(`[docs-text] > :nth-child(3)`)), settle)
404 var kept string
405 s.eval("kept", `(document.querySelector('[data-docs-kept]') || {}).textContent || ''`, &kept)
406 if kept != "Second paragraph." {
407 t.Errorf("after the collaborator's line: the kept selection is drawn over %q, want \"Second paragraph.\"", kept)
408 }
409 s.run("Heading 2", chromedp.Click(chromedp.CSS(`[docs-chip="heading-2"]`)), settle)
410 var blocks []string
411 s.eval("the blocks", `[...document.querySelectorAll('[docs-text] > *')].map((b) => b.tagName + ' ' + b.textContent)`, &blocks)
412 want := []string{"P A collaborator's first line.", "P First paragraph.", "H2 Second paragraph."}
413 if strings.Join(blocks, "|") != strings.Join(want, "|") {
414 t.Errorf("after Heading 2 from the sheet: %q, want %q", blocks, want)
415 }
416}
417
418// Review 10: B in the sheet at a caret, × (the keyboard comes back),
419// then typing: the typed letter is bold.
420func TestBoldAtACaretFromTheSheet(t *testing.T) {
421 s := newSheetRig(t, "simple.bin", "")
422 s.run("the caret at the end, a keyboard", chromedp.Click(chromedp.CSS(`[docs-text] p:last-child`)), settle,
423 do(`const p = document.querySelector('[docs-text] p:last-child'); const r = document.createRange(); r.selectNodeContents(p); r.collapse(false); getSelection().removeAllRanges(); getSelection().addRange(r)`), settle,
424 do(`__keyboard(336, 0)`), settle,
425 chromedp.Click(chromedp.CSS(`[docs-quickbar-aa]`)), settle,
426 chromedp.Click(chromedp.CSS(`[docs-inspector] [docs-toolbar-group="text"] [data-docs-command="strong"]`)), settle,
427 chromedp.Click(chromedp.CSS(`[docs-sheet-close]`)), settle,
428 chromedp.KeyEvent("Z"), settle)
429 var got struct{ Last, Bold string }
430 s.eval("typed", `(() => { const p = document.querySelector('[docs-text] p:last-child'), b = p.querySelector('strong');
431 return { Last: p.textContent, Bold: b ? b.textContent : '' } })()`, &got)
432 if got.Last != "Second paragraph.Z" || got.Bold != "Z" {
433 t.Errorf("B, ×, then Z: the paragraph reads %q with %q bold, want \"Second paragraph.Z\" with \"Z\" bold", got.Last, got.Bold)
434 }
435}
436
437// Fable's nit on #181: in forced colours, where a pressed button's tint
438// is taken away, the capsule's pressed B is outlined.
439func TestTheQuickBarInForcedColours(t *testing.T) {
440 s := newSheetRig(t, "simple.bin", "")
441 s.run("forced colours, the caret, a keyboard, B",
442 command(emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{{Name: "forced-colors", Value: "active"}}}),
443 chromedp.Click(chromedp.CSS(`[docs-text] p:last-child`)), settle, do(`__keyboard(336, 0)`), settle,
444 chromedp.Click(chromedp.CSS(`[docs-quickbar] [data-docs-command="strong"]`)), settle)
445 var got struct{ Pressed, Outline string }
446 s.eval("B", `(() => { const b = document.querySelector('[docs-quickbar] [data-docs-command="strong"]');
447 return { Pressed: b.getAttribute('aria-pressed'), Outline: getComputedStyle(b).outlineStyle } })()`, &got)
448 if got.Pressed != "true" || got.Outline != "solid" {
449 t.Errorf("forced colours, B pressed %q: its outline is %q, want solid", got.Pressed, got.Outline)
450 }
451}
452
453// Follow-up A on #181: a resync whose rebuilt document holds a
454// collaborator's change the page never saw (it landed on the server
455// before the page's save was refused, and live updates are not taken
456// while the editor is diverged). The kept selection's old positions
457// may now be other text: the sheet keeps the selection only where its
458// words are, in the block nearest where it was, and otherwise closes.
459func TestAResyncAfterACollaboratorsChange(t *testing.T) {
460 for _, c := range []struct {
461 name, vector string
462 open bool
463 }{
464 {"a line above the selection", "remote-before.bin", true},
465 {"words written into the selection", "remote-edit-second.bin", false},
466 } {
467 t.Run(c.name, func(t *testing.T) {
468 s := newSheetRig(t, "simple.bin", "")
469 s.run("select, Aa", chromedp.Click(chromedp.CSS(`[docs-text] p:last-child`)), settle,
470 do(`getSelection().selectAllChildren(document.querySelector('[docs-text] p:last-child'))`), settle,
471 chromedp.Click(chromedp.CSS(`[docs-aa]`)), settle,
472 // Live updates asked for before the refusal never arrive;
473 // the next save is refused (413), which resyncs.
474 do(`window.__desc = document.querySelector('[docs-text]').pmViewDesc; const f = window.fetch; let first = true, held = true;
475 window.fetch = async function (u, o) {
476 const url = String(u);
477 if (url.includes('/updates') && o && o.method === 'POST' && first) { first = false; held = false; return new Response('', { status: 413 }) }
478 if (held && url.includes('/updates?since=')) return new Promise(() => {});
479 return f.call(this, u, o) }`))
480 s.post(c.vector)
481 s.run("the change, refused", chromedp.Sleep(800*time.Millisecond), chromedp.Click(chromedp.CSS(`[docs-chip="heading-2"]`)), chromedp.Sleep(3*time.Second))
482 var got struct {
483 Remounted, Open bool
484 Kept string
485 Blocks []string
486 }
487 s.eval("after the resync", `(() => { const k = document.querySelector('[data-docs-kept]');
488 return { Remounted: document.querySelector('[docs-text]').pmViewDesc !== window.__desc,
489 Open: document.documentElement.getAttribute('data-docs-sheet') === 'open', Kept: k ? k.textContent : '',
490 Blocks: [...document.querySelectorAll('[docs-text] > *')].map((b) => b.textContent) } })()`, &got)
491 if !got.Remounted || len(got.Blocks) != 3 && c.vector == "remote-before.bin" {
492 t.Fatalf("remounted %v, blocks %q: the check needs the resync to bring in the collaborator's change", got.Remounted, got.Blocks)
493 }
494 if c.open && (!got.Open || got.Kept != "Second paragraph.") {
495 t.Errorf("after the resync: sheet open %v, kept drawn over %q (blocks %q); want it open over \"Second paragraph.\"", got.Open, got.Kept, got.Blocks)
496 }
497 if !c.open && (got.Open || got.Kept != "") {
498 t.Errorf("after the resync: sheet open %v, kept drawn over %q (blocks %q); want it closed, nothing drawn, since the words are no longer anywhere", got.Open, got.Kept, got.Blocks)
499 }
500 })
501 }
502}
503
504// Follow-up E on #181: Escape in a dialog opened over the sheet closes
505// the dialog, not the sheet too.
506func TestEscapeInADialogLeavesTheSheet(t *testing.T) {
507 s := newSheetRig(t, "simple.bin", "")
508 s.run("Aa, then a dialog", chromedp.Click(chromedp.CSS(`[docs-aa]`)), settle,
509 do(`const d = document.createElement('dialog'); d.id = 'probe'; d.innerHTML = '<button>OK</button>'; document.body.append(d); d.showModal(); d.querySelector('button').focus()`), settle,
510 chromedp.KeyEvent("\u001b"), settle)
511 var got struct{ Dialog, Sheet bool }
512 s.eval("after Escape", `({ Dialog: document.querySelector('#probe').open, Sheet: document.documentElement.getAttribute('data-docs-sheet') === 'open' })`, &got)
513 if got.Dialog || !got.Sheet {
514 t.Errorf("Escape in a dialog over the sheet: dialog open %v, sheet open %v; want the dialog closed and the sheet still open", got.Dialog, got.Sheet)
515 }
516}
517
518// Follow-up E on #181: an activation of Aa with no pointer before it
519// (a keyboard, or an assistive technology's click, whose detail need not
520// be 0) takes focus into the sheet, as Enter does.
521func TestAaActivatedWithoutAPointer(t *testing.T) {
522 s := newSheetRig(t, "simple.bin", "")
523 s.run("a click with detail 1 and no pointer", do(`const a = document.querySelector('[docs-aa]'); a.focus(); a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }))`), settle)
524 var inSheet bool
525 s.eval("focus", `!!document.activeElement && !!document.activeElement.closest('[docs-inspector]')`, &inSheet)
526 if !inSheet {
527 t.Error("Aa activated with no pointer: focus did not go into the sheet")
528 }
529 // A tap (a pointer first) leaves focus where it was.
530 s.run("close, then a tap", chromedp.KeyEvent("\u001b"), settle, chromedp.Click(chromedp.CSS(`[docs-aa]`)), settle)
531 s.eval("focus after a tap", `!!document.activeElement && !!document.activeElement.closest('[docs-inspector]')`, &inSheet)
532 if inSheet {
533 t.Error("Aa tapped: focus went into the sheet")
534 }
535}
536