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 browser checks: Docs in a real Chromium. Not part of the plain
4// suite or the gate, because they need a Chromium (on PATH, via
5// RASTRILLO_CHROME, or in a Playwright cache):
6//
7// CGO_ENABLED=0 go test -tags browser -run OnTap ./internal/docs/
8//
9// The gate vets this file with the tag (.amadan/ci.d/10-gate), so it
10// cannot stop compiling unnoticed.
11package docs_test
12
13import (
14 "context"
15 "fmt"
16 "net/http"
17 "net/http/httptest"
18 "strings"
19 "testing"
20 "time"
21
22 "amadan.net/rastrillo/rastrillo/harness"
23 "github.com/chromedp/cdproto/cdp"
24 "github.com/chromedp/cdproto/emulation"
25 "github.com/chromedp/chromedp"
26
27 "github.com/carlosframework/docs/internal/docs"
28)
29
30// textControls is every control a tap puts a caret in. A checkbox, a
31// radio, a file picker or a button raises no keyboard, so iOS never
32// zooms for them. The editor's own text (contenteditable) is not here:
33// it is the document, set at the document's own sizes, and the person
34// chose them.
35const textControls = `input:not([type=checkbox]):not([type=radio]):not([type=hidden]):not([type=file]):not([type=submit]):not([type=button]):not([type=color]):not([type=range]), select, textarea`
36
37// TestNoZoomOnTap: iOS Safari zooms the whole page into any text control
38// whose type is under 16px, and rastrillo's base type is 14px. Its
39// tokens.css brings text controls up to 16px where the pointer is coarse
40// ("Touch: the two zooms nobody asked for"); an app on a tokens.css
41// without that block, or with a rule of its own that outweighs it, zooms
42// on the first tap of every field.
43//
44// Emulated as pointer: coarse, which is how the CSS decides. The
45// jump-to palette is measured open: it is hidden until Control-K, and a
46// hidden field measures as nothing.
47func TestNoZoomOnTap(t *testing.T) {
48 var app *docs.App
49 rig := harness.New(t, func(origin string) http.Handler {
50 var err error
51 app, err = docs.NewForTestWith(t, docs.Config{Origin: origin})
52 if err != nil {
53 t.Fatalf("NewForTestWith: %v", err)
54 }
55 return app.Handler()
56 })
57 cookies := signInCookies(t, app, "alice@example.com")
58 // Same-origin POSTs: this app's origin is the rig's, not DefaultOrigin.
59 sameOrigin := func(path, body string) *httptest.ResponseRecorder {
60 req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
61 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
62 req.Header.Set("Sec-Fetch-Site", "same-origin")
63 for _, c := range cookies {
64 req.AddCookie(c)
65 }
66 rec := httptest.NewRecorder()
67 app.Handler().ServeHTTP(rec, req)
68 return rec
69 }
70 created := sameOrigin("/documents", "title=Zoom")
71 if created.Code != http.StatusSeeOther {
72 t.Fatalf("POST /documents: %d", created.Code)
73 }
74 sqid := strings.TrimPrefix(created.Header().Get("Location"), "/d/")
75
76 run := func(what string, actions ...chromedp.Action[chromedp.Void]) {
77 t.Helper()
78 ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second)
79 defer cancel()
80 if err := chromedp.Do(ctx, actions...); err != nil {
81 at, _ := chromedp.Run(rig.Context(), chromedp.Location())
82 t.Fatalf("%s: %v (the browser is at %s)", what, err, at)
83 }
84 }
85 // Touch emulation, then a reload on every page so it re-evaluates
86 // its media queries. SetEmulatedMedia's "pointer" feature is not
87 // emulated by this Chromium; the coarse check below is what proves
88 // the emulation took.
89 run("touch emulation", command(emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: true, MaxTouchPoints: 5}))
90
91 once := false
92 measure := func(path, ready string, open ...chromedp.Action[chromedp.Void]) {
93 t.Helper()
94 var coarse bool
95 var small []string
96 actions := []chromedp.Action[chromedp.Void]{chromedp.Navigate(rig.Origin + path)}
97 if !once {
98 actions = append(actions, chromedp.Reload())
99 }
100 actions = append(actions,
101 chromedp.WaitVisible(chromedp.CSS(ready)),
102 evalInto(&coarse, `matchMedia('(pointer: coarse)').matches`),
103 )
104 actions = append(actions, open...)
105 actions = append(actions, evalInto(&small, smallControls(textControls)))
106 run(path, actions...)
107 if !coarse {
108 t.Fatalf("%s: the touch-screen emulation did not apply; this would measure desktop styles", path)
109 }
110 if len(small) > 0 {
111 t.Errorf("%s: iOS zooms when these are tapped (under 16px on a touch screen): %s", path, strings.Join(small, "; "))
112 }
113 }
114
115 // Signed out first: the door is the field every visit starts on.
116 measure("/signin", `input[name="address"]`)
117
118 var set []chromedp.Action[chromedp.Void]
119 for _, c := range cookies {
120 set = append(set, setCookie(rig.Origin, c))
121 }
122 run("sign in", set...)
123
124 measure("/", `input[name="q"]`)
125 // The toolbar's three selects, once select.js has enhanced them, and
126 // the title field. This rig's window (756x356, a finger) is a phone
127 // held sideways, where the bar is compact (design/phone-web): the
128 // strip shows when Aa asks for it and the title is renamed in the
129 // large title's own field, so both are opened before measuring.
130 measure("/d/"+sqid, `[contenteditable="true"]`,
131 chromedp.Evaluate[chromedp.Void](`(() => {
132 const aa = document.querySelector('[docs-aa]')
133 if (aa && aa.getClientRects().length && aa.getAttribute('aria-expanded') !== 'true') aa.click()
134 const title = document.querySelector('[docs-title-edit]')
135 if (title && title.getClientRects().length) title.click()
136 return true
137 })()`),
138 // WaitVisible waits on the first match in the page's order, and
139 // the compact bar's own title field comes first and is hidden: so
140 // the large title's field, then the strip's controls.
141 chromedp.WaitVisible(chromedp.CSS(`[docs-title-input], [docs-toolbar] input, [docs-toolbar] select`)))
142 // The share page, then published: the link field shows only in the
143 // one render that follows the publish.
144 // A wide touch screen (an iPad in landscape, 1280px): from 64rem the
145 // toolbar is the inspector (spec I2), whose own font size beat the
146 // strip's max(1rem, 1em) and dropped its pickers to 13px (review on
147 // #106).
148 // The header's undo/redo are 32px targets there too, in a 32px pill.
149 var inspector string
150 var lead []float64
151 run("a wide touch screen", command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1280, Height: 900, DeviceScaleFactor: 1}))
152 measure("/d/"+sqid, `[contenteditable="true"]`,
153 chromedp.WaitVisible(chromedp.CSS(`[docs-inspector] [docs-toolbar] input`)),
154 evalInto(&inspector, `getComputedStyle(document.querySelector('[docs-inspector]')).position`),
155 evalInto(&lead, `(() => { const b = document.querySelector('[estilo-bar-lead] [data-docs-command="undo"]').getBoundingClientRect(); const p = document.querySelector('[estilo-bar-lead] [docs-history]').getBoundingClientRect(); return [b.width, b.height, p.height] })()`))
156 if inspector != "fixed" {
157 t.Errorf("at 1280px the toolbar is not the inspector (position %q); this measured the strip", inspector)
158 }
159 if len(lead) != 3 || lead[0] < 32 || lead[1] < 32 || lead[2] != 32 {
160 t.Errorf("on a touch screen the header's undo is %vx%v in a %vpx pill, want 32x32 in 32", lead[0], lead[1], lead[2])
161 }
162 run("back to the default width", command(emulation.ClearDeviceMetricsOverride, cdp.Empty{}))
163 measure("/d/"+sqid+"/share", `input[name="address"]`)
164 if rec := sameOrigin("/d/"+sqid+"/share/link", "on=1"); rec.Code != http.StatusSeeOther {
165 t.Fatalf("publishing: %d", rec.Code)
166 }
167 // Once only: the reload measure makes would render the page without it.
168 once = true
169 measure("/d/"+sqid+"/share", `[docs-share-url-input]`)
170 once = false
171 measure("/", `input[name="q"]`,
172 chromedp.Evaluate[chromedp.Void](`document.dispatchEvent(new KeyboardEvent('keydown', {key: 'k', ctrlKey: true, bubbles: true}))`),
173 chromedp.WaitVisible(chromedp.CSS(`[docs-jumpto-input]`)))
174}
175
176// smallControls is a script listing each visible, tappable control matching sel
177// whose computed font-size is under 16px, described well enough to find.
178func smallControls(sel string) string {
179 return fmt.Sprintf(`[...document.querySelectorAll(%q)]
180 .filter(e => e.getClientRects().length > 0)
181 // select.js hides the native select it enhances (aria-hidden,
182 // clipped, out of the tab order); its combobox is what is tapped.
183 .filter(e => !e.closest('[aria-hidden=true]'))
184 .filter(e => parseFloat(getComputedStyle(e).fontSize) < 16)
185 .map(e => e.tagName.toLowerCase() + [...e.attributes].filter(a => a.name !== 'class' && a.name !== 'style' && a.name !== 'value' && a.name !== 'placeholder').map(a => '[' + a.name + (a.value && a.value.length < 24 ? '=' + a.value : '') + ']').join('') + ' ' + getComputedStyle(e).fontSize)`, sel)
186}
187