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
3package fichastest
4
5import (
6 "context"
7 "encoding/json"
8 "fmt"
9 "strings"
10 "testing"
11 "time"
12
13 "amadan.net/rastrillo/rastrillo/harness"
14 "github.com/chromedp/cdproto/cdp"
15 "github.com/chromedp/cdproto/emulation"
16 "github.com/chromedp/cdproto/network"
17 "github.com/chromedp/cdproto/page"
18 "github.com/chromedp/chromedp"
19)
20
21// The header has no Search (Paul, 2026-11-18: "I think we can just lose
22// the search icon in the header"). Search is the rail's first row, with
23// ⌘K beside it while the rail is open and "Search" its tooltip when
24// folded; the Menu sheet's first row below 800px, once, so a phone has
25// it on a card and on History, which have no Find box; and ⌘K or Ctrl+K
26// anywhere but inside a field. Each goes to the list's Find box, and
27// with scripts off links to #find.
28
29// railSearch is the rail's Search.
30const railSearch = `[fichas-rail] a[data-fichas-search]`
31
32// barSearch counts what in the bar, outside the Menu sheet, is a Search
33// on screen: a link to the Find box, an icon-only action, or a control
34// with a shortcut.
35const barSearch = `Array.prototype.filter.call(
36 document.querySelectorAll('[estilo-bar] a[href$="#find"], [estilo-bar] [estilo-bar-icon], [estilo-bar] [aria-keyshortcuts]'),
37 function (el) { return !el.closest('[estilo-menu="sheet"]') && el.checkVisibility(); }).length`
38
39// whereAt is the page's path and fragment.
40const whereAt = `location.pathname + location.hash`
41
42// findFocused is whether the list's Find box has focus.
43const findFocused = `document.activeElement === document.querySelector('[data-live-search] input[name="q"]')`
44
45func scriptsOn(on bool) chromedp.Action[chromedp.Void] {
46 return send(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: !on})
47}
48
49func viewport(width int64) chromedp.Action[chromedp.Void] {
50 return send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: width, Height: 900, DeviceScaleFactor: 1})
51}
52
53// railCookie sets the rail's fold, "" for none (the width decides).
54func railCookie(rig *harness.Rig, state string) chromedp.Action[chromedp.Void] {
55 if state == "" {
56 return send(network.DeleteCookies, network.DeleteCookiesParams{Name: "fichas-rail", URL: rig.Origin + "/"})
57 }
58 return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
59 _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: "fichas-rail", Value: state, URL: rig.Origin + "/"})
60 return err
61 })
62}
63
64func TestTheBarHasNoSearch(t *testing.T) {
65 s := seedCards(t, 3)
66 card := cardPath(s.ids[0])
67 for _, live := range []bool{false, true} {
68 for _, width := range []int64{1440, 1000, 800, 390} {
69 for _, path := range []string{"/t/t_customer", card, card + "/history", "/t/t_customer/fields"} {
70 var shown int
71 var html string
72 s.rig.Run(scriptsOn(live), viewport(width),
73 chromedp.Navigate(s.rig.Origin+path), chromedp.WaitReady(`[estilo-bar]`),
74 harness.Into(&shown, chromedp.Evaluate[int](barSearch)),
75 harness.Into(&html, chromedp.Evaluate[string](`document.documentElement.outerHTML`)))
76 if shown != 0 {
77 t.Errorf("%s at %dpx, scripts %v: the bar shows %d Search controls", path, width, live, shown)
78 }
79 if strings.Contains(html, "Search ⌘K") {
80 t.Errorf("%s at %dpx, scripts %v: \"Search ⌘K\" is still drawn", path, width, live)
81 }
82 }
83 }
84 }
85 s.rig.Run(scriptsOn(true))
86 for _, path := range []string{"/t/t_customer", card} {
87 for _, width := range []int64{1440, 1000, 800, 390} {
88 axeCheck(t, s.rig, path, width, "")
89 }
90 }
91}
92
93// The rail's Search, open and folded (by width, and by choice), scripts
94// on and off, from the list and from a card.
95func TestTheRailsSearchGoesToFind(t *testing.T) {
96 s := seedCards(t, 3)
97 card := cardPath(s.ids[0])
98 cases := []struct {
99 width int64
100 cookie string
101 open bool
102 }{{1440, "", true}, {1000, "", false}, {1440, "rail", false}, {1000, "open", true}}
103 for _, c := range cases {
104 for _, live := range []bool{false, true} {
105 name := fmt.Sprintf("%dpx, cookie %q, scripts %v", c.width, c.cookie, live)
106 var facts struct {
107 Label, Title, Keys, Kbd string
108 LabelShown, KbdShown bool
109 }
110 var raw string
111 s.rig.Run(scriptsOn(live), railCookie(s.rig, c.cookie), viewport(c.width),
112 chromedp.Navigate(s.rig.Origin+"/t/t_customer"), chromedp.WaitVisible(railSearch),
113 harness.Into(&raw, chromedp.Evaluate[string](`(function () {
114 var a = document.querySelector('`+railSearch+`');
115 var label = a.querySelector('[fichas-rail-label]'), kbd = a.querySelector('kbd');
116 // Folded, the rail keeps the words for screen readers and clips them
117 // to nothing.
118 var seen = function (el) { var b = el.getBoundingClientRect(); return b.width > 1 && b.height > 1 && getComputedStyle(el).clipPath === 'none'; };
119 return JSON.stringify({Label: label.textContent, Title: a.title, Keys: a.getAttribute('aria-keyshortcuts'),
120 Kbd: kbd.textContent, LabelShown: seen(label), KbdShown: seen(kbd)});
121})()`)))
122 if err := json.Unmarshal([]byte(raw), &facts); err != nil {
123 t.Fatal(err)
124 }
125 if facts.Label != "Search" || facts.Title != "Search" || facts.Keys != "Meta+K Control+K" || facts.Kbd != "⌘K" {
126 t.Errorf("%s: the rail's Search is %+v", name, facts)
127 }
128 if facts.LabelShown != c.open || facts.KbdShown != c.open {
129 t.Errorf("%s: open %v, but the label shows %v and ⌘K %v", name, c.open, facts.LabelShown, facts.KbdShown)
130 }
131 // From the list: the Find box (with scripts, focus; without,
132 // the link to #find).
133 var at string
134 var focused bool
135 s.rig.Run(chromedp.Click(railSearch), chromedp.Sleep(300*time.Millisecond),
136 harness.Into(&at, chromedp.Evaluate[string](whereAt)),
137 harness.Into(&focused, chromedp.Evaluate[bool](findFocused)))
138 if live && !focused {
139 t.Errorf("%s: from the list the rail's Search did not focus the Find box (at %s)", name, at)
140 }
141 if !live && at != "/t/t_customer#find" {
142 t.Errorf("%s: from the list the rail's Search went to %s", name, at)
143 }
144 // From a card, which has no Find box: the list's.
145 s.rig.Run(chromedp.Navigate(s.rig.Origin+card), chromedp.WaitVisible(railSearch),
146 chromedp.Click(railSearch), chromedp.WaitReady(`[data-live-search] input[name="q"]`),
147 harness.Into(&at, chromedp.Evaluate[string](whereAt)))
148 if at != "/t/t_customer#find" {
149 t.Errorf("%s: from a card the rail's Search went to %s", name, at)
150 }
151 }
152 }
153 s.rig.Run(scriptsOn(true), railCookie(s.rig, ""))
154}
155
156// Below 800px Search is the Menu sheet's first row, once, on the list,
157// a card and History.
158func TestTheMenuSheetHasSearch(t *testing.T) {
159 s := seedCards(t, 3)
160 card := cardPath(s.ids[0])
161 const sheetSearch = `[estilo-menu="sheet"] a[href$="#find"]`
162 for _, live := range []bool{false, true} {
163 for _, path := range []string{"/t/t_customer", card, card + "/history"} {
164 name := fmt.Sprintf("%s, scripts %v", path, live)
165 var rows, at string
166 var focused bool
167 s.rig.Run(scriptsOn(live), viewport(390),
168 chromedp.Navigate(s.rig.Origin+path), chromedp.WaitVisible("[estilo-bar-more] > summary"),
169 chromedp.Click("[estilo-bar-more] > summary"), chromedp.WaitVisible(sheetSearch),
170 harness.Into(&rows, chromedp.Evaluate[string](`Array.prototype.map.call(document.querySelectorAll('[estilo-menu="sheet"] [estilo-menu-item]'), function (row) { return row.textContent.trim(); }).join("|")`)),
171 chromedp.Click(sheetSearch), chromedp.Sleep(300*time.Millisecond),
172 chromedp.WaitReady(`[data-live-search] input[name="q"]`),
173 harness.Into(&at, chromedp.Evaluate[string](whereAt)),
174 harness.Into(&focused, chromedp.Evaluate[bool](findFocused)))
175 if !strings.HasPrefix(rows, "Search|") || strings.Count("|"+rows+"|", "|Search|") != 1 {
176 t.Errorf("%s: the Menu sheet's rows are %q", name, rows)
177 }
178 if live && path == "/t/t_customer" {
179 if !focused {
180 t.Errorf("%s: the sheet's Search did not focus the Find box", name)
181 }
182 } else if at != "/t/t_customer#find" {
183 t.Errorf("%s: the sheet's Search went to %s", name, at)
184 }
185 }
186 }
187 s.rig.Run(scriptsOn(true))
188}
189
190// ⌘K and Ctrl+K: the Find box on the list; from a card or History, the
191// list's Find box, at any width (below 800px too, where no rail is
192// drawn); and nothing from inside a field.
193func TestTheShortcutGoesToFind(t *testing.T) {
194 s := seedCards(t, 3)
195 card := cardPath(s.ids[0])
196 for _, mod := range []chromedp.Modifier{chromedp.ModifierMeta, chromedp.ModifierCtrl} {
197 for _, width := range []int64{1440, 1000, 390} {
198 name := fmt.Sprintf("%dpx, modifier %v", width, mod)
199 var focused bool
200 s.rig.Run(viewport(width), chromedp.Navigate(s.rig.Origin+"/t/t_customer"),
201 chromedp.WaitVisible(`[data-live-search] input[name="q"]`),
202 chromedp.Evaluate[chromedp.Void](`document.activeElement && document.activeElement.blur()`),
203 chromedp.KeyEvent("k", chromedp.KeyModifiers(mod)), chromedp.Sleep(200*time.Millisecond),
204 harness.Into(&focused, chromedp.Evaluate[bool](findFocused)))
205 if !focused {
206 t.Errorf("%s: on the list the shortcut did not focus the Find box", name)
207 }
208 for _, path := range []string{card, card + "/history"} {
209 var at string
210 s.rig.Run(chromedp.Navigate(s.rig.Origin+path), chromedp.WaitReady(`[fichas-main]`),
211 chromedp.Evaluate[chromedp.Void](`document.activeElement && document.activeElement.blur()`),
212 chromedp.KeyEvent("k", chromedp.KeyModifiers(mod)),
213 chromedp.WaitVisible(`[data-live-search] input[name="q"]`),
214 harness.Into(&at, chromedp.Evaluate[string](whereAt)))
215 if at != "/t/t_customer#find" {
216 t.Errorf("%s: the shortcut on %s went to %s", name, path, at)
217 }
218 }
219 }
220 // Inside a field it does nothing: typing is never left unsaved.
221 var at string
222 var stayed bool
223 s.rig.Run(wide(), chromedp.Navigate(s.rig.Origin+card+"/edit"), chromedp.WaitReady(`[fichas-main] form`),
224 chromedp.Evaluate[chromedp.Void](`Array.prototype.find.call(document.querySelectorAll('[fichas-main] input, [fichas-main] textarea'), function (el) { return !/^(hidden|radio|checkbox|submit)$/.test(el.type) && el.checkVisibility(); }).focus()`),
225 chromedp.KeyEvent("k", chromedp.KeyModifiers(mod)), chromedp.Sleep(400*time.Millisecond),
226 harness.Into(&at, chromedp.Evaluate[string](`location.pathname`)),
227 harness.Into(&stayed, chromedp.Evaluate[bool](`document.activeElement.matches('[fichas-main] input, [fichas-main] textarea')`)))
228 if at != card+"/edit" || !stayed {
229 t.Errorf("modifier %v: the shortcut inside a field went to %s (focus kept: %v)", mod, at, stayed)
230 }
231 }
232}
233
234// shiftRecorder keeps every layout shift from the start of the load
235// that moved something in the bar (this gate's subject; the page body
236// is not), naming what moved.
237const shiftRecorder = `(function () {
238 window.__shifts = [];
239 try {
240 new PerformanceObserver(function (list) {
241 list.getEntries().forEach(function (entry) {
242 (entry.sources || []).forEach(function (source) {
243 var el = source.node && (source.node.nodeType === 1 ? source.node : source.node.parentElement);
244 if (el && el.closest("[estilo-bar]")) __shifts.push(el.outerHTML.slice(0, 80) + " " + entry.value);
245 });
246 });
247 }).observe({ type: "layout-shift", buffered: true });
248 } catch (error) {}
249})()`
250
251// No shift (Mapa's L5, for the bar): every control in the bar is where
252// the server drew it (scripts off) once the page's scripts have run, and
253// no layout shift moves anything in the bar from the start of the load,
254// on the list and on a card.
255func TestTheBarMovesNothing(t *testing.T) {
256 s := seedCards(t, 3)
257 const bar = `JSON.stringify(Array.prototype.map.call(
258 document.querySelectorAll("[estilo-bar-end] > *, [estilo-bar-actions] a, [estilo-bar-actions] button"),
259 function (el) { var b = el.getBoundingClientRect();
260 return [el.nodeName, b.left, b.top, b.width, b.height].join(" "); }))`
261 s.rig.Run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
262 _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument,
263 page.AddScriptToEvaluateOnNewDocumentParams{Source: shiftRecorder})
264 return err
265 }))
266 for _, path := range []string{"/t/t_customer", cardPath(s.ids[0])} {
267 for _, width := range []int64{1440, 1000} {
268 load := func(live bool) string {
269 var boxes string
270 s.rig.Run(scriptsOn(live), viewport(width),
271 chromedp.Navigate(s.rig.Origin+path), chromedp.WaitReady(`[estilo-bar-end]`), chromedp.Sleep(300*time.Millisecond),
272 harness.Into(&boxes, chromedp.Evaluate[string](bar)))
273 return boxes
274 }
275 off, on := load(false), load(true)
276 if off != on {
277 t.Errorf("%s at %dpx: the bar moved once scripts ran:\noff %s\non %s", path, width, off, on)
278 }
279 var shifts string
280 s.rig.Run(harness.Into(&shifts, chromedp.Evaluate[string](`JSON.stringify(window.__shifts || [])`)))
281 if shifts != "[]" {
282 t.Errorf("%s at %dpx: the bar shifted: %s", path, width, shifts)
283 }
284 }
285 }
286 s.rig.Run(scriptsOn(true))
287}
288