oficina / fichas Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3// Editing in place in a real Chromium (level-up §15): LU9, the scriptless
4// floor; LU10, the keyboard and accessibility; LU11, phones.
5package fichastest
6
7import (
8 "context"
9 "fmt"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/rastrillo/rastrillo/db"
17 "amadan.net/rastrillo/rastrillo/harness"
18 "github.com/chromedp/cdproto/emulation"
19 "github.com/chromedp/chromedp"
20 "github.com/chromedp/chromedp/kb"
21
22 fichas "amadan.net/oficina/fichas/internal/fichas"
23)
24
25// seeded is a rig over customers named "Card 000" onwards, with a text
26// field, City, beside the catalogue's; it keeps the database and config
27// so a test can act as a teammate mid-drive.
28type seeded struct {
29 rig *harness.Rig
30 d *db.DB
31 cfg fichas.Config
32 ids []int64
33 city string
34}
35
36func seedCards(t *testing.T, n int) *seeded {
37 s := &seeded{}
38 s.rig = browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) {
39 s.d, s.cfg = d, cfg
40 m, _ := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner)
41 fd, err := fichas.AddField(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID),
42 fichas.FieldSpec{Label: "City", Kind: fichas.KindText, Tier: fichas.TierSealed})
43 if err != nil {
44 t.Fatalf("seed: %v", err)
45 }
46 s.city = fd.Key
47 for i := 0; i < n; i++ {
48 c, err := fichas.CreateCard(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID),
49 map[string]string{fichas.FieldName: fmt.Sprintf("Card %03d", i), fichas.FieldStage: "Lead", fichas.FieldEmail: fmt.Sprintf("c%d@example.com", i)})
50 if err != nil {
51 t.Fatalf("seed: %v", err)
52 }
53 s.ids = append(s.ids, c.ID)
54 }
55 })
56 return s
57}
58
59func (s *seeded) value(t *testing.T, id int64, key string) string {
60 t.Helper()
61 c, err := fichas.LoadCard(context.Background(), s.d.G, s.cfg.Sealer, id)
62 if err != nil {
63 t.Fatal(err)
64 }
65 return c.Field(key).Value
66}
67
68// teammate changes a field as another admitted person would.
69func (s *seeded) teammate(t *testing.T, id int64, key, value, was string) {
70 t.Helper()
71 m, _ := fichas.EnsureMember(context.Background(), s.d.G, s.cfg.Sealer, "niamh@example.com")
72 if _, err := fichas.SetField(context.Background(), s.d.G, s.cfg.Sealer, id, fichas.Person(m.ID), key, value, was); err != nil {
73 t.Fatalf("teammate: %v", err)
74 }
75}
76
77func wide() chromedp.Action[chromedp.Void] {
78 return send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1440, Height: 900, DeviceScaleFactor: 1})
79}
80
81// LU9: with scripts off, with no console error, edit a cell through the
82// edit form, meet a conflict and resolve it, Undo, and open a card
83// beside the list and follow Next across a page. Page scripts are off
84// (Emulation.setScriptExecutionDisabled), so the drive reads the DOM
85// through DevTools' DOM domain only: waits are WaitReady, clicks are on
86// ready nodes, and what is on screen is read as HTML.
87//
88// It caught, on its first run, the list's "Saved. Undo" posting to
89// /cards/0/undo; putting that back (2026-11-17) fails it again.
90func TestTheScriptlessFloor(t *testing.T) {
91 s := seedCards(t, 101)
92 first := s.ids[0]
93 ready := chromedp.NodeReady
94 page := func(steps ...chromedp.Action[chromedp.Void]) (string, string) {
95 var html, url string
96 s.rig.Run(append(steps, harness.Into(&html, chromedp.OuterHTML("html", ready)), harness.Into(&url, chromedp.Location()))...)
97 return html, url
98 }
99 html, url := page(
100 wide(),
101 send(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}),
102 chromedp.Navigate(s.rig.Origin+"/t/t_customer?sort=f_name"),
103 chromedp.WaitReady(`[fichas-grid] tbody tr`),
104 // A cell is a link to the edit form with that field focused.
105 chromedp.Click(`[fichas-grid] tbody tr:first-child td[data-field="`+s.city+`"] a`, ready),
106 chromedp.WaitReady(`input#`+s.city),
107 chromedp.SendKeys(`input#`+s.city, "Oslo", ready),
108 chromedp.Click(`form[fichas-form] [rst-btn~="primary"]`, ready),
109 chromedp.WaitReady(`[fichas-notice="saved"] button`),
110 )
111 if !strings.Contains(url, "/t/t_customer?") || !strings.Contains(html, "Saved.") || s.value(t, first, s.city) != "Oslo" {
112 t.Fatalf("the scriptless edit landed on %q, City %q", url, s.value(t, first, s.city))
113 }
114 html, _ = page(
115 chromedp.Click(`[fichas-notice="saved"] button`, ready),
116 chromedp.WaitReady(`[fichas-notice="undone"]`),
117 )
118 if !strings.Contains(html, "Undone.") || s.value(t, first, s.city) != "" {
119 t.Fatalf("the scriptless Undo left City as %q", s.value(t, first, s.city))
120 }
121
122 // A conflict: the form is drawn, a teammate saves first, then this
123 // form is posted: nothing lands, and theirs and mine are offered.
124 page(
125 chromedp.Navigate(s.rig.Origin+cardPath(first)+"/edit?field="+fichas.FieldStage),
126 chromedp.WaitReady(`select#`+fichas.FieldStage),
127 )
128 s.teammate(t, first, fichas.FieldStage, "Won", "Lead")
129 s.rig.Allow("POST", cardPath(first), 409)
130 html, _ = page(
131 chromedp.SetValue(`select#`+fichas.FieldStage, "Lost", ready),
132 chromedp.Click(`form[fichas-form] [rst-btn~="primary"]`, ready),
133 chromedp.WaitReady(`[fichas-conflict]`),
134 )
135 if !strings.Contains(html, `value="Won" checked`) || !strings.Contains(html, `value="Lost"`) || s.value(t, first, fichas.FieldStage) != "Won" {
136 t.Fatalf("the conflict page does not offer theirs and mine, or wrote: stage %q", s.value(t, first, fichas.FieldStage))
137 }
138 page(
139 chromedp.Click(`input[type=radio][name="f_stage"][value="Lost"]`, ready),
140 chromedp.Click(`form[fichas-form] [rst-btn~="primary"]`, ready),
141 chromedp.WaitReady(`[fichas-notice="saved"]`),
142 )
143 if got := s.value(t, first, fichas.FieldStage); got != "Lost" {
144 t.Fatalf("Use mine left the stage as %q", got)
145 }
146
147 // The card beside the list, and Next across a page: the 100th card by
148 // name is Card 099; its Next is Card 100, on page 2.
149 html, url = page(
150 chromedp.Navigate(s.rig.Origin+"/t/t_customer?sort=f_name&card="+itoa(s.ids[99])),
151 chromedp.WaitReady(`[fichas-pane] a[rel="next"]`),
152 chromedp.Click(`[fichas-pane] a[rel="next"]`, ready),
153 chromedp.WaitReady(`[fichas-narrow] a[aria-current]`),
154 )
155 if !strings.Contains(url, "card="+itoa(s.ids[100])) || !strings.Contains(html, `aria-current="true">
156 <strong>Card 100</strong>`) {
157 t.Fatalf("Next from the 100th card went to %q", url)
158 }
159}
160
161// LU10: the grid's keys, Undo with ⌘Z, J and K only in the pane, the live
162// region, and axe-core on the table, the card and the phone's sheet.
163//
164// Mutations, 2026-11-17, each failing it: J and K scoped to the whole
165// page; the live region never written; the bar's brand name hidden from
166// screen readers (axe-core's link-name). One survives, and is named: a
167// printable key's preventDefault, because DevTools sends the character
168// as its own event, which no keydown handler can cancel.
169func TestTheKeyboardWalk(t *testing.T) {
170 s := seedCards(t, 3)
171 var editing, stayed bool
172 var announced, afterUndo string
173 s.rig.Run(
174 wide(),
175 chromedp.Navigate(s.rig.Origin+"/t/t_customer?sort=f_name"),
176 chromedp.WaitVisible(`[fichas-grid][role="grid"]`),
177 // One tab stop: Tab from the Find box reaches the grid's first cell.
178 chromedp.Focus(`[data-live-search] input[name="q"]`),
179 chromedp.KeyEvent("\t"),
180 chromedp.KeyEvent("\t"),
181 chromedp.Evaluate[chromedp.Void](`document.querySelector('[fichas-grid] tbody td[tabindex="0"], [fichas-grid] tbody th[tabindex="0"]').focus()`),
182 // Arrows to City, then typing "Oslo" edits it and opens nothing.
183 chromedp.Evaluate[chromedp.Void](`(() => { const cells = [...document.querySelector('[fichas-grid] tbody tr').children]; const i = cells.findIndex(c => c.dataset.field === '`+s.city+`'); window.__steps = i })()`),
184 )
185 var steps int
186 s.rig.Run(harness.Into(&steps, chromedp.Evaluate[int](`window.__steps`)))
187 for i := 0; i < steps; i++ {
188 s.rig.Run(chromedp.KeyEvent(kb.ArrowRight))
189 }
190 s.rig.Run(
191 chromedp.KeyEvent("O"),
192 harness.Into(&editing, chromedp.Evaluate[bool](`!!document.querySelector('[fichas-editor] input') && document.activeElement === document.querySelector('[fichas-editor] input')`)),
193 chromedp.KeyEvent("slo"),
194 chromedp.KeyEvent("\r"),
195 chromedp.WaitVisible(`[fichas-toast]`),
196 harness.Into(&stayed, chromedp.Evaluate[bool](`location.search === '?sort=f_name'`)),
197 chromedp.Sleep(100*time.Millisecond),
198 harness.Into(&announced, chromedp.Evaluate[string](`document.querySelector('[fichas-live]').textContent`)),
199 )
200 if !editing || !stayed {
201 t.Fatalf("typing in a cell: editing %v, stayed on the list %v", editing, stayed)
202 }
203 if !strings.Contains(announced, "City changed to Oslo.") {
204 t.Errorf("the live region said %q", announced)
205 }
206 if got := s.value(t, s.ids[0], s.city); got != "Oslo" {
207 t.Fatalf("City is %q after typing Oslo and Enter", got)
208 }
209 s.rig.Run(
210 chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)),
211 chromedp.Sleep(400*time.Millisecond),
212 harness.Into(&afterUndo, chromedp.Evaluate[string](`document.querySelector('[fichas-toast]') ? document.querySelector('[fichas-toast]').textContent : ''`)),
213 )
214 if got := s.value(t, s.ids[0], s.city); got != "" || !strings.Contains(afterUndo, "Undone.") {
215 t.Fatalf("⌘Z: City %q, toast %q", got, afterUndo)
216 }
217
218 // J and K: inert in the grid, active in the card pane.
219 var inGrid, inBar, inPane string
220 s.rig.Run(
221 chromedp.Evaluate[chromedp.Void](`document.querySelector('[fichas-grid] tbody td[data-field]').focus()`),
222 chromedp.KeyEvent("j"),
223 chromedp.Sleep(200*time.Millisecond),
224 harness.Into(&inGrid, chromedp.Evaluate[string](`location.search`)),
225 chromedp.Click(`[fichas-title-link]`),
226 chromedp.WaitVisible(`[fichas-pane]`),
227 // With the card open, J is still inert outside the pane and the
228 // narrowed list: here, on the rail's Search.
229 chromedp.Focus(`[fichas-rail] a[data-fichas-search]`),
230 chromedp.KeyEvent("j"),
231 chromedp.Sleep(300*time.Millisecond),
232 harness.Into(&inBar, chromedp.Evaluate[string](`location.search`)),
233 chromedp.Focus(`[fichas-pane] a[rel="next"]`),
234 chromedp.KeyEvent("j"),
235 chromedp.WaitVisible(`[fichas-pane] a[rel="prev"]`),
236 harness.Into(&inPane, chromedp.Evaluate[string](`location.search`)),
237 )
238 if inGrid != "?sort=f_name" {
239 t.Errorf("J in the grid went to %q; it must be inert there", inGrid)
240 }
241 if inBar != "?card="+itoa(s.ids[0])+"&sort=f_name" {
242 t.Errorf("J on the rail went to %q; it must be inert outside the pane", inBar)
243 }
244 if !strings.Contains(inPane, "card="+itoa(s.ids[1])) {
245 t.Errorf("J in the pane went to %q, want the second card", inPane)
246 }
247
248 axeCheck(t, s.rig, "/t/t_customer?sort=f_name", 1440, "")
249 axeCheck(t, s.rig, "/t/t_customer?sort=f_name&card="+itoa(s.ids[0]), 1440, "")
250 axeCheck(t, s.rig, cardPath(s.ids[0])+"/history", 1440, "")
251 axeCheck(t, s.rig, "/t/t_customer?sort=f_name", 390, `[fichas-grid] tbody td[data-field="`+fichas.FieldEmail+`"]`)
252}
253
254// axeCheck runs axe-core on a page, after clicking open if it is set,
255// and fails on any serious or critical violation. axe-core comes from
256// FICHAS_AXE, or the copy the Ruby gem ships; a missing axe fails, since
257// a skip is not a pass.
258func axeCheck(t *testing.T, rig *harness.Rig, path string, width int64, open string) {
259 t.Helper()
260 var steps []chromedp.Action[chromedp.Void]
261 if open != "" {
262 steps = append(steps, chromedp.Click(open), chromedp.WaitVisible(`dialog[fichas-sheet]`))
263 }
264 axeCheckWith(t, rig, path, width, steps...)
265}
266
267// axeCheckWith is axeCheck with the page put in a state by before (a
268// menu opened, say) once it has loaded.
269func axeCheckWith(t *testing.T, rig *harness.Rig, path string, width int64, before ...chromedp.Action[chromedp.Void]) {
270 t.Helper()
271 steps := []chromedp.Action[chromedp.Void]{
272 send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: width, Height: 900, DeviceScaleFactor: 1}),
273 chromedp.Navigate(rig.Origin + path),
274 chromedp.WaitReady(`[fichas-main]`),
275 }
276 steps = append(steps, before...)
277 rig.Run(steps...)
278 for _, v := range axeHere(t, rig) {
279 t.Errorf("%s at %dpx: axe: %s", path, width, v)
280 }
281}
282
283// axeHere runs axe-core on the page the rig is on and returns its serious
284// and critical violations. axe-core comes from FICHAS_AXE, or the copy
285// the Ruby gem ships; a missing axe fails, since a skip is not a pass.
286func axeHere(t *testing.T, rig *harness.Rig) []string {
287 t.Helper()
288 src := os.Getenv("FICHAS_AXE")
289 if src == "" {
290 matches, _ := filepath.Glob(filepath.Join(os.Getenv("HOME"), ".rbenv/versions/*/lib/ruby/gems/*/gems/axe-core-api-*/node_modules/axe-core/axe.min.js"))
291 if len(matches) > 0 {
292 src = matches[len(matches)-1]
293 }
294 }
295 body, err := os.ReadFile(src)
296 if err != nil {
297 t.Fatalf("no axe-core (set FICHAS_AXE to axe.min.js): %v", err)
298 }
299 var found []string
300 rig.Run(
301 chromedp.Evaluate[chromedp.Void](string(body)),
302 harness.Into(&found, chromedp.Evaluate[[]string](`axe.run(document, {resultTypes: ['violations']}).then(r => r.violations.filter(v => v.impact === 'serious' || v.impact === 'critical').map(v => v.id + ': ' + v.nodes.map(n => n.target.join(' ')).slice(0, 3).join(', ')))`, chromedp.EvalAwaitPromise)),
303 )
304 return found
305}
306
307// Mutations, 2026-11-17, each failing it: the sheet opened with show()
308// rather than showModal(); a cell's link at 30px.
309//
310// LU11: at 390px the table is a list of rows; a value opens a modal sheet
311// that holds focus, with Save at its foot; the card is its own screen
312// with Next; nothing zooms and every target is at least 44px.
313func TestPhones(t *testing.T) {
314 s := seedCards(t, 3)
315 type facts struct {
316 RowsAsList bool
317 SheetModal bool
318 FocusInSheet bool
319 InputFont float64
320 SmallTargets []string
321 }
322 var f facts
323 var narrowHidden, hasNext bool
324 s.rig.Run(
325 send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 390, Height: 844, DeviceScaleFactor: 2, Mobile: true}),
326 chromedp.Navigate(s.rig.Origin+"/t/t_customer?sort=f_name"),
327 chromedp.WaitVisible(`[fichas-grid] tbody tr`),
328 harness.Into(&f.RowsAsList, chromedp.Evaluate[bool](`getComputedStyle(document.querySelector('[fichas-grid] tbody tr')).display === 'grid' && getComputedStyle(document.querySelector('[fichas-grid] thead')).position === 'absolute'`)),
329 harness.Into(&f.SmallTargets, chromedp.Evaluate[[]string](`[...document.querySelectorAll('[fichas-grid] a')].filter(e => e.offsetParent !== null && e.getBoundingClientRect().height < 44).map(e => e.outerHTML.slice(0, 80))`)),
330 chromedp.Click(`[fichas-grid] tbody tr:first-child td[data-field="`+fichas.FieldEmail+`"]`),
331 chromedp.WaitVisible(`dialog[fichas-sheet]`),
332 harness.Into(&f.SheetModal, chromedp.Evaluate[bool](`document.querySelector('dialog[fichas-sheet]').matches(':modal')`)),
333 harness.Into(&f.FocusInSheet, chromedp.Evaluate[bool](`document.querySelector('dialog[fichas-sheet]').contains(document.activeElement)`)),
334 harness.Into(&f.InputFont, chromedp.Evaluate[float64](`parseFloat(getComputedStyle(document.querySelector('dialog[fichas-sheet] input')).fontSize)`)),
335 chromedp.SetValue(`dialog[fichas-sheet] input`, "new@example.com"),
336 chromedp.Click(`dialog[fichas-sheet] button[type=submit]`),
337 chromedp.WaitVisible(`[fichas-toast]`),
338 chromedp.Click(`[fichas-grid] tbody tr:first-child [fichas-title-link]`),
339 chromedp.WaitVisible(`[fichas-pane]`),
340 harness.Into(&narrowHidden, chromedp.Evaluate[bool](`getComputedStyle(document.querySelector('[fichas-narrow]')).display === 'none'`)),
341 harness.Into(&hasNext, chromedp.Evaluate[bool](`!!document.querySelector('[fichas-pane] a[rel="next"]') && document.querySelector('[fichas-pane] a[rel="next"]').getBoundingClientRect().height >= 44`)),
342 )
343 if !f.RowsAsList {
344 t.Error("at 390px the table is not a list of rows")
345 }
346 if len(f.SmallTargets) > 0 {
347 t.Errorf("targets under 44px: %v", f.SmallTargets)
348 }
349 if !f.SheetModal || !f.FocusInSheet {
350 t.Errorf("the sheet: modal %v, focus inside %v", f.SheetModal, f.FocusInSheet)
351 }
352 if f.InputFont < 16 {
353 t.Errorf("the sheet's input is %.0fpx; iOS zooms under 16px", f.InputFont)
354 }
355 if got := s.value(t, s.ids[0], fichas.FieldEmail); got != "new@example.com" {
356 t.Errorf("the sheet's Save left Email as %q", got)
357 }
358 if !narrowHidden || !hasNext {
359 t.Errorf("the card on a phone: its own screen %v, a Next of 44px %v", narrowHidden, hasNext)
360 }
361}
362
363// The grid's header is reachable by keyboard (Fable, Phase 1 review,
364// M1): ArrowUp from the first row reaches it, and Enter sorts.
365//
366// Mutation, 2026-11-17: clamping the grid's rows to the body again
367// failed it.
368func TestTheHeaderSortsByKeyboard(t *testing.T) {
369 s := seedCards(t, 2)
370 var onHeader bool
371 var search string
372 s.rig.Run(
373 wide(),
374 chromedp.Navigate(s.rig.Origin+"/t/t_customer"),
375 chromedp.WaitVisible(`[fichas-grid][role="grid"]`),
376 chromedp.Evaluate[chromedp.Void](`document.querySelector('[fichas-grid] tbody [fichas-title-cell]').focus()`),
377 chromedp.KeyEvent(kb.ArrowUp),
378 harness.Into(&onHeader, chromedp.Evaluate[bool](`document.activeElement.tagName === 'TH' && document.activeElement.closest('thead') !== null`)),
379 chromedp.KeyEvent("\r"),
380 chromedp.Sleep(500*time.Millisecond),
381 harness.Into(&search, chromedp.Evaluate[string](`location.search`)),
382 )
383 if !onHeader || !strings.Contains(search, "sort=") {
384 t.Fatalf("the header by keyboard: reached %v, sorted %q", onHeader, search)
385 }
386}
387