//go:build browser // Editing in place in a real Chromium (level-up §15): LU9, the scriptless // floor; LU10, the keyboard and accessibility; LU11, phones. package fichastest import ( "context" "fmt" "os" "path/filepath" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/chromedp" "github.com/chromedp/chromedp/kb" fichas "amadan.net/oficina/fichas/internal/fichas" ) // seeded is a rig over customers named "Card 000" onwards, with a text // field, City, beside the catalogue's; it keeps the database and config // so a test can act as a teammate mid-drive. type seeded struct { rig *harness.Rig d *db.DB cfg fichas.Config ids []int64 city string } func seedCards(t *testing.T, n int) *seeded { s := &seeded{} s.rig = browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) { s.d, s.cfg = d, cfg m, _ := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner) fd, err := fichas.AddField(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), fichas.FieldSpec{Label: "City", Kind: fichas.KindText, Tier: fichas.TierSealed}) if err != nil { t.Fatalf("seed: %v", err) } s.city = fd.Key for i := 0; i < n; i++ { c, err := fichas.CreateCard(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), map[string]string{fichas.FieldName: fmt.Sprintf("Card %03d", i), fichas.FieldStage: "Lead", fichas.FieldEmail: fmt.Sprintf("c%d@example.com", i)}) if err != nil { t.Fatalf("seed: %v", err) } s.ids = append(s.ids, c.ID) } }) return s } func (s *seeded) value(t *testing.T, id int64, key string) string { t.Helper() c, err := fichas.LoadCard(context.Background(), s.d.G, s.cfg.Sealer, id) if err != nil { t.Fatal(err) } return c.Field(key).Value } // teammate changes a field as another admitted person would. func (s *seeded) teammate(t *testing.T, id int64, key, value, was string) { t.Helper() m, _ := fichas.EnsureMember(context.Background(), s.d.G, s.cfg.Sealer, "niamh@example.com") if _, err := fichas.SetField(context.Background(), s.d.G, s.cfg.Sealer, id, fichas.Person(m.ID), key, value, was); err != nil { t.Fatalf("teammate: %v", err) } } func wide() chromedp.Action[chromedp.Void] { return send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1440, Height: 900, DeviceScaleFactor: 1}) } // LU9: with scripts off, with no console error, edit a cell through the // edit form, meet a conflict and resolve it, Undo, and open a card // beside the list and follow Next across a page. Page scripts are off // (Emulation.setScriptExecutionDisabled), so the drive reads the DOM // through DevTools' DOM domain only: waits are WaitReady, clicks are on // ready nodes, and what is on screen is read as HTML. // // It caught, on its first run, the list's "Saved. Undo" posting to // /cards/0/undo; putting that back (2026-11-17) fails it again. func TestTheScriptlessFloor(t *testing.T) { s := seedCards(t, 101) first := s.ids[0] ready := chromedp.NodeReady page := func(steps ...chromedp.Action[chromedp.Void]) (string, string) { var html, url string s.rig.Run(append(steps, harness.Into(&html, chromedp.OuterHTML("html", ready)), harness.Into(&url, chromedp.Location()))...) return html, url } html, url := page( wide(), send(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}), chromedp.Navigate(s.rig.Origin+"/t/t_customer?sort=f_name"), chromedp.WaitReady(`[fichas-grid] tbody tr`), // A cell is a link to the edit form with that field focused. chromedp.Click(`[fichas-grid] tbody tr:first-child td[data-field="`+s.city+`"] a`, ready), chromedp.WaitReady(`input#`+s.city), chromedp.SendKeys(`input#`+s.city, "Oslo", ready), chromedp.Click(`form[fichas-form] [rst-btn~="primary"]`, ready), chromedp.WaitReady(`[fichas-notice="saved"] button`), ) if !strings.Contains(url, "/t/t_customer?") || !strings.Contains(html, "Saved.") || s.value(t, first, s.city) != "Oslo" { t.Fatalf("the scriptless edit landed on %q, City %q", url, s.value(t, first, s.city)) } html, _ = page( chromedp.Click(`[fichas-notice="saved"] button`, ready), chromedp.WaitReady(`[fichas-notice="undone"]`), ) if !strings.Contains(html, "Undone.") || s.value(t, first, s.city) != "" { t.Fatalf("the scriptless Undo left City as %q", s.value(t, first, s.city)) } // A conflict: the form is drawn, a teammate saves first, then this // form is posted: nothing lands, and theirs and mine are offered. page( chromedp.Navigate(s.rig.Origin+cardPath(first)+"/edit?field="+fichas.FieldStage), chromedp.WaitReady(`select#`+fichas.FieldStage), ) s.teammate(t, first, fichas.FieldStage, "Won", "Lead") s.rig.Allow("POST", cardPath(first), 409) html, _ = page( chromedp.SetValue(`select#`+fichas.FieldStage, "Lost", ready), chromedp.Click(`form[fichas-form] [rst-btn~="primary"]`, ready), chromedp.WaitReady(`[fichas-conflict]`), ) if !strings.Contains(html, `value="Won" checked`) || !strings.Contains(html, `value="Lost"`) || s.value(t, first, fichas.FieldStage) != "Won" { t.Fatalf("the conflict page does not offer theirs and mine, or wrote: stage %q", s.value(t, first, fichas.FieldStage)) } page( chromedp.Click(`input[type=radio][name="f_stage"][value="Lost"]`, ready), chromedp.Click(`form[fichas-form] [rst-btn~="primary"]`, ready), chromedp.WaitReady(`[fichas-notice="saved"]`), ) if got := s.value(t, first, fichas.FieldStage); got != "Lost" { t.Fatalf("Use mine left the stage as %q", got) } // The card beside the list, and Next across a page: the 100th card by // name is Card 099; its Next is Card 100, on page 2. html, url = page( chromedp.Navigate(s.rig.Origin+"/t/t_customer?sort=f_name&card="+itoa(s.ids[99])), chromedp.WaitReady(`[fichas-pane] a[rel="next"]`), chromedp.Click(`[fichas-pane] a[rel="next"]`, ready), chromedp.WaitReady(`[fichas-narrow] a[aria-current]`), ) if !strings.Contains(url, "card="+itoa(s.ids[100])) || !strings.Contains(html, `aria-current="true"> Card 100`) { t.Fatalf("Next from the 100th card went to %q", url) } } // LU10: the grid's keys, Undo with ⌘Z, J and K only in the pane, the live // region, and axe-core on the table, the card and the phone's sheet. // // Mutations, 2026-11-17, each failing it: J and K scoped to the whole // page; the live region never written; the bar's brand name hidden from // screen readers (axe-core's link-name). One survives, and is named: a // printable key's preventDefault, because DevTools sends the character // as its own event, which no keydown handler can cancel. func TestTheKeyboardWalk(t *testing.T) { s := seedCards(t, 3) var editing, stayed bool var announced, afterUndo string s.rig.Run( wide(), chromedp.Navigate(s.rig.Origin+"/t/t_customer?sort=f_name"), chromedp.WaitVisible(`[fichas-grid][role="grid"]`), // One tab stop: Tab from the Find box reaches the grid's first cell. chromedp.Focus(`[data-live-search] input[name="q"]`), chromedp.KeyEvent("\t"), chromedp.KeyEvent("\t"), chromedp.Evaluate[chromedp.Void](`document.querySelector('[fichas-grid] tbody td[tabindex="0"], [fichas-grid] tbody th[tabindex="0"]').focus()`), // Arrows to City, then typing "Oslo" edits it and opens nothing. 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 })()`), ) var steps int s.rig.Run(harness.Into(&steps, chromedp.Evaluate[int](`window.__steps`))) for i := 0; i < steps; i++ { s.rig.Run(chromedp.KeyEvent(kb.ArrowRight)) } s.rig.Run( chromedp.KeyEvent("O"), harness.Into(&editing, chromedp.Evaluate[bool](`!!document.querySelector('[fichas-editor] input') && document.activeElement === document.querySelector('[fichas-editor] input')`)), chromedp.KeyEvent("slo"), chromedp.KeyEvent("\r"), chromedp.WaitVisible(`[fichas-toast]`), harness.Into(&stayed, chromedp.Evaluate[bool](`location.search === '?sort=f_name'`)), chromedp.Sleep(100*time.Millisecond), harness.Into(&announced, chromedp.Evaluate[string](`document.querySelector('[fichas-live]').textContent`)), ) if !editing || !stayed { t.Fatalf("typing in a cell: editing %v, stayed on the list %v", editing, stayed) } if !strings.Contains(announced, "City changed to Oslo.") { t.Errorf("the live region said %q", announced) } if got := s.value(t, s.ids[0], s.city); got != "Oslo" { t.Fatalf("City is %q after typing Oslo and Enter", got) } s.rig.Run( chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)), chromedp.Sleep(400*time.Millisecond), harness.Into(&afterUndo, chromedp.Evaluate[string](`document.querySelector('[fichas-toast]') ? document.querySelector('[fichas-toast]').textContent : ''`)), ) if got := s.value(t, s.ids[0], s.city); got != "" || !strings.Contains(afterUndo, "Undone.") { t.Fatalf("⌘Z: City %q, toast %q", got, afterUndo) } // J and K: inert in the grid, active in the card pane. var inGrid, inBar, inPane string s.rig.Run( chromedp.Evaluate[chromedp.Void](`document.querySelector('[fichas-grid] tbody td[data-field]').focus()`), chromedp.KeyEvent("j"), chromedp.Sleep(200*time.Millisecond), harness.Into(&inGrid, chromedp.Evaluate[string](`location.search`)), chromedp.Click(`[fichas-title-link]`), chromedp.WaitVisible(`[fichas-pane]`), // With the card open, J is still inert outside the pane and the // narrowed list: here, on the rail's Search. chromedp.Focus(`[fichas-rail] a[data-fichas-search]`), chromedp.KeyEvent("j"), chromedp.Sleep(300*time.Millisecond), harness.Into(&inBar, chromedp.Evaluate[string](`location.search`)), chromedp.Focus(`[fichas-pane] a[rel="next"]`), chromedp.KeyEvent("j"), chromedp.WaitVisible(`[fichas-pane] a[rel="prev"]`), harness.Into(&inPane, chromedp.Evaluate[string](`location.search`)), ) if inGrid != "?sort=f_name" { t.Errorf("J in the grid went to %q; it must be inert there", inGrid) } if inBar != "?card="+itoa(s.ids[0])+"&sort=f_name" { t.Errorf("J on the rail went to %q; it must be inert outside the pane", inBar) } if !strings.Contains(inPane, "card="+itoa(s.ids[1])) { t.Errorf("J in the pane went to %q, want the second card", inPane) } axeCheck(t, s.rig, "/t/t_customer?sort=f_name", 1440, "") axeCheck(t, s.rig, "/t/t_customer?sort=f_name&card="+itoa(s.ids[0]), 1440, "") axeCheck(t, s.rig, cardPath(s.ids[0])+"/history", 1440, "") axeCheck(t, s.rig, "/t/t_customer?sort=f_name", 390, `[fichas-grid] tbody td[data-field="`+fichas.FieldEmail+`"]`) } // axeCheck runs axe-core on a page, after clicking open if it is set, // and fails on any serious or critical violation. axe-core comes from // FICHAS_AXE, or the copy the Ruby gem ships; a missing axe fails, since // a skip is not a pass. func axeCheck(t *testing.T, rig *harness.Rig, path string, width int64, open string) { t.Helper() var steps []chromedp.Action[chromedp.Void] if open != "" { steps = append(steps, chromedp.Click(open), chromedp.WaitVisible(`dialog[fichas-sheet]`)) } axeCheckWith(t, rig, path, width, steps...) } // axeCheckWith is axeCheck with the page put in a state by before (a // menu opened, say) once it has loaded. func axeCheckWith(t *testing.T, rig *harness.Rig, path string, width int64, before ...chromedp.Action[chromedp.Void]) { t.Helper() steps := []chromedp.Action[chromedp.Void]{ send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: width, Height: 900, DeviceScaleFactor: 1}), chromedp.Navigate(rig.Origin + path), chromedp.WaitReady(`[fichas-main]`), } steps = append(steps, before...) rig.Run(steps...) for _, v := range axeHere(t, rig) { t.Errorf("%s at %dpx: axe: %s", path, width, v) } } // axeHere runs axe-core on the page the rig is on and returns its serious // and critical violations. axe-core comes from FICHAS_AXE, or the copy // the Ruby gem ships; a missing axe fails, since a skip is not a pass. func axeHere(t *testing.T, rig *harness.Rig) []string { t.Helper() src := os.Getenv("FICHAS_AXE") if src == "" { matches, _ := filepath.Glob(filepath.Join(os.Getenv("HOME"), ".rbenv/versions/*/lib/ruby/gems/*/gems/axe-core-api-*/node_modules/axe-core/axe.min.js")) if len(matches) > 0 { src = matches[len(matches)-1] } } body, err := os.ReadFile(src) if err != nil { t.Fatalf("no axe-core (set FICHAS_AXE to axe.min.js): %v", err) } var found []string rig.Run( chromedp.Evaluate[chromedp.Void](string(body)), 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)), ) return found } // Mutations, 2026-11-17, each failing it: the sheet opened with show() // rather than showModal(); a cell's link at 30px. // // LU11: at 390px the table is a list of rows; a value opens a modal sheet // that holds focus, with Save at its foot; the card is its own screen // with Next; nothing zooms and every target is at least 44px. func TestPhones(t *testing.T) { s := seedCards(t, 3) type facts struct { RowsAsList bool SheetModal bool FocusInSheet bool InputFont float64 SmallTargets []string } var f facts var narrowHidden, hasNext bool s.rig.Run( send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 390, Height: 844, DeviceScaleFactor: 2, Mobile: true}), chromedp.Navigate(s.rig.Origin+"/t/t_customer?sort=f_name"), chromedp.WaitVisible(`[fichas-grid] tbody tr`), harness.Into(&f.RowsAsList, chromedp.Evaluate[bool](`getComputedStyle(document.querySelector('[fichas-grid] tbody tr')).display === 'grid' && getComputedStyle(document.querySelector('[fichas-grid] thead')).position === 'absolute'`)), 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))`)), chromedp.Click(`[fichas-grid] tbody tr:first-child td[data-field="`+fichas.FieldEmail+`"]`), chromedp.WaitVisible(`dialog[fichas-sheet]`), harness.Into(&f.SheetModal, chromedp.Evaluate[bool](`document.querySelector('dialog[fichas-sheet]').matches(':modal')`)), harness.Into(&f.FocusInSheet, chromedp.Evaluate[bool](`document.querySelector('dialog[fichas-sheet]').contains(document.activeElement)`)), harness.Into(&f.InputFont, chromedp.Evaluate[float64](`parseFloat(getComputedStyle(document.querySelector('dialog[fichas-sheet] input')).fontSize)`)), chromedp.SetValue(`dialog[fichas-sheet] input`, "new@example.com"), chromedp.Click(`dialog[fichas-sheet] button[type=submit]`), chromedp.WaitVisible(`[fichas-toast]`), chromedp.Click(`[fichas-grid] tbody tr:first-child [fichas-title-link]`), chromedp.WaitVisible(`[fichas-pane]`), harness.Into(&narrowHidden, chromedp.Evaluate[bool](`getComputedStyle(document.querySelector('[fichas-narrow]')).display === 'none'`)), harness.Into(&hasNext, chromedp.Evaluate[bool](`!!document.querySelector('[fichas-pane] a[rel="next"]') && document.querySelector('[fichas-pane] a[rel="next"]').getBoundingClientRect().height >= 44`)), ) if !f.RowsAsList { t.Error("at 390px the table is not a list of rows") } if len(f.SmallTargets) > 0 { t.Errorf("targets under 44px: %v", f.SmallTargets) } if !f.SheetModal || !f.FocusInSheet { t.Errorf("the sheet: modal %v, focus inside %v", f.SheetModal, f.FocusInSheet) } if f.InputFont < 16 { t.Errorf("the sheet's input is %.0fpx; iOS zooms under 16px", f.InputFont) } if got := s.value(t, s.ids[0], fichas.FieldEmail); got != "new@example.com" { t.Errorf("the sheet's Save left Email as %q", got) } if !narrowHidden || !hasNext { t.Errorf("the card on a phone: its own screen %v, a Next of 44px %v", narrowHidden, hasNext) } } // The grid's header is reachable by keyboard (Fable, Phase 1 review, // M1): ArrowUp from the first row reaches it, and Enter sorts. // // Mutation, 2026-11-17: clamping the grid's rows to the body again // failed it. func TestTheHeaderSortsByKeyboard(t *testing.T) { s := seedCards(t, 2) var onHeader bool var search string s.rig.Run( wide(), chromedp.Navigate(s.rig.Origin+"/t/t_customer"), chromedp.WaitVisible(`[fichas-grid][role="grid"]`), chromedp.Evaluate[chromedp.Void](`document.querySelector('[fichas-grid] tbody [fichas-title-cell]').focus()`), chromedp.KeyEvent(kb.ArrowUp), harness.Into(&onHeader, chromedp.Evaluate[bool](`document.activeElement.tagName === 'TH' && document.activeElement.closest('thead') !== null`)), chromedp.KeyEvent("\r"), chromedp.Sleep(500*time.Millisecond), harness.Into(&search, chromedp.Evaluate[string](`location.search`)), ) if !onHeader || !strings.Contains(search, "sort=") { t.Fatalf("the header by keyboard: reached %v, sorted %q", onHeader, search) } }