oficina / memoria Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3// The iOS zoom-on-tap check, in a real Chromium through chromedp. Not
4// part of `make ci`, because it needs a Chromium (on PATH, or via
5// RASTRILLO_CHROME; the Makefile finds the Playwright cache's on a Mac):
6//
7// make browser
8//
9// `make vet` vets this package with the tag, so it cannot stop compiling
10// unnoticed.
11package memoriatest
12
13import (
14 "bytes"
15 "context"
16 "fmt"
17 "io"
18 "log/slog"
19 "mime/multipart"
20 "net/http"
21 "path/filepath"
22 "regexp"
23 "strings"
24 "testing"
25 "time"
26
27 "amadan.net/rastrillo/rastrillo/db"
28 "amadan.net/rastrillo/rastrillo/harness"
29 "github.com/chromedp/cdproto/emulation"
30 "github.com/chromedp/chromedp"
31
32 memoria "amadan.net/oficina/memoria/internal/memoria"
33)
34
35// textControls is every control a tap puts a caret in. A checkbox, a
36// radio, a file picker or a button raises no keyboard, so iOS never
37// zooms for them.
38const 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`
39
40// TestNoZoomOnTap: iOS Safari zooms the whole page into any text control
41// whose type is under 16px, and rastrillo's base type is 14px. Its
42// tokens.css brings text controls up to 16px where the pointer is coarse
43// ("Touch: the two zooms nobody asked for"); an app on a tokens.css
44// without that block, or with a rule of its own that sets a control
45// smaller, zooms on the first tap of every field.
46//
47// Emulated as pointer: coarse, which is how the CSS decides (touch
48// emulation and a reload; the coarse check proves it took). Every page
49// with a field is measured: the door (signed out, through the production
50// App), the search box on the index and on results, Add content, a
51// document, the connectors and the Notion connector's token.
52func TestNoZoomOnTap(t *testing.T) {
53 t.Run("signed out", func(t *testing.T) {
54 rig := harness.New(t, func(origin string) http.Handler {
55 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
56 d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
57 if err != nil {
58 t.Fatalf("db.Open: %v", err)
59 }
60 t.Cleanup(func() { d.Close() })
61 mux, a, err := memoria.App(d, origin, testDEK(t), logger)
62 if err != nil {
63 t.Fatalf("App: %v", err)
64 }
65 // The door is rastrillo's screen (the smart door), which needs
66 // sign-in wired, as production has it.
67 au, err := memoria.NewAuth(d.Writer(), memoria.AuthEnv{
68 Origin: origin, InstanceKey: "zoom-test-instance-key",
69 Owners: []string{dialTestOwner}, Mailer: &stubMailer{},
70 }, logger, a)
71 if err != nil {
72 t.Fatalf("NewAuth: %v", err)
73 }
74 a.UseAuth(au)
75 a.SetOwners([]string{dialTestOwner})
76 a.MountAuth(mux, origin)
77 return mux
78 })
79 var coarse bool
80 var small []string
81 ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second)
82 defer cancel()
83 if err := chromedp.Do(ctx,
84 cdpStep(emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: true, MaxTouchPoints: 5}),
85 chromedp.Navigate(rig.Origin+"/signin"),
86 chromedp.Reload(),
87 chromedp.WaitVisible(chromedp.CSS(`input[name="address"]`)),
88 evalInto(&coarse, `matchMedia('(pointer: coarse)').matches`),
89 evalInto(&small, smallControls(textControls)),
90 ); err != nil {
91 t.Fatalf("/signin: %v", err)
92 }
93 if !coarse {
94 t.Fatal("/signin: the touch-screen emulation did not apply")
95 }
96 if len(small) > 0 {
97 t.Errorf("/signin: iOS zooms when these are tapped (under 16px on a touch screen): %s", strings.Join(small, "; "))
98 }
99 })
100 t.Run("signed in", testNoZoomSignedIn)
101}
102
103func testNoZoomSignedIn(t *testing.T) {
104 rig := harness.New(t, func(origin string) http.Handler {
105 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
106 d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
107 if err != nil {
108 t.Fatalf("db.Open: %v", err)
109 }
110 t.Cleanup(func() { d.Close() })
111 mux, _, err := memoria.AppForTest(d, origin, testDEK(t), logger)
112 if err != nil {
113 t.Fatalf("AppForTest: %v", err)
114 }
115 return mux
116 })
117
118 run := func(what string, actions ...chromedp.Action[chromedp.Void]) {
119 t.Helper()
120 ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second)
121 defer cancel()
122 if err := chromedp.Do(ctx, actions...); err != nil {
123 var at string
124 _ = chromedp.Do(rig.Context(), locationInto(&at))
125 t.Fatalf("%s: %v (the browser is at %s)", what, err, at)
126 }
127 }
128 measure := func(path, ready string) {
129 t.Helper()
130 var coarse bool
131 var small []string
132 run(path,
133 chromedp.Navigate(rig.Origin+path),
134 chromedp.Reload(),
135 chromedp.WaitVisible(chromedp.CSS(ready)),
136 evalInto(&coarse, `matchMedia('(pointer: coarse)').matches`),
137 evalInto(&small, smallControls(textControls)),
138 )
139 if !coarse {
140 t.Fatalf("%s: the touch-screen emulation did not apply; this would measure desktop styles", path)
141 }
142 if len(small) > 0 {
143 t.Errorf("%s: iOS zooms when these are tapped (under 16px on a touch screen): %s", path, strings.Join(small, "; "))
144 }
145 }
146
147 run("touch emulation", cdpStep(emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: true, MaxTouchPoints: 5}))
148
149 // A document, posted as the Add content form posts one.
150 var buf bytes.Buffer
151 mw := multipart.NewWriter(&buf)
152 _ = mw.WriteField("title", "Office handbook")
153 _ = mw.WriteField("body", "The Lisbon office is at Rua Augusta 100.")
154 mw.Close()
155 req, _ := http.NewRequest(http.MethodPost, rig.Origin+"/documents", &buf)
156 req.Header.Set("Content-Type", mw.FormDataContentType())
157 req.Header.Set("Origin", rig.Origin)
158 res, err := http.DefaultClient.Do(req)
159 if err != nil {
160 t.Fatalf("store a document: %v", err)
161 }
162 res.Body.Close()
163 var at string
164 run("find the document",
165 chromedp.Navigate(rig.Origin+"/"),
166 chromedp.WaitVisible(chromedp.CSS(`a[href^="/documents/"]`)),
167 attributeInto(chromedp.CSS(`a[href^="/documents/"]`), "href", &at, nil),
168 )
169 doc := regexp.MustCompile(`^/documents/\d+$`).FindString(at)
170 if doc == "" {
171 t.Fatalf("the index links no document (got %q)", at)
172 }
173
174 measure("/", `main`)
175 measure("/?q=Lisbon", `main`)
176 measure("/add", `textarea[name="body"]`)
177 measure(doc, `main`)
178 measure(doc+"/delete", `main`)
179 measure("/connectors", `main`)
180 measure("/connectors/notion", `input[name="token"]`)
181}
182
183// smallControls is a script listing each visible control matching sel
184// whose computed font-size is under 16px, described well enough to find.
185func smallControls(sel string) string {
186 return fmt.Sprintf(`[...document.querySelectorAll(%q)]
187 .filter(e => e.getClientRects().length > 0)
188 .filter(e => parseFloat(getComputedStyle(e).fontSize) < 16)
189 .map(e => e.tagName.toLowerCase() + (e.name ? '[name=' + e.name + ']' : '') + (e.id ? '#' + e.id : '') + ' ' + getComputedStyle(e).fontSize)`, sel)
190}
191