//go:build browser
// The compact bar (Bar.Compact) and the touch sizes, in real engines:
// a stacked, compact bar as Docs draws it on a document, at phone,
// tablet and desktop widths, with a coarse pointer where a phone or a
// tablet has one. Not part of `make test`: it needs Node 22+ and
// Playwright (ESTILO_PLAYWRIGHT, ESTILO_BROWSERS as for the title
// check). ESTILO_SHOTS=
saves a screenshot of every case there,
// light and dark, in English, Arabic and Russian.
package chrome
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"amadan.net/oficina/estilo.git/base"
"amadan.net/oficina/estilo.git/brand"
"amadan.net/oficina/estilo.git/menu"
"amadan.net/oficina/estilo.git/theme"
"github.com/carlosframework/rastrillo/ui"
)
const compactPage = `
%s
%s
%s
%s
`
// compactLabels are the demo's words per locale: Arabic to see the bar
// mirrored, Russian for long labels.
var compactLabels = map[string]map[string]string{
"en": {"app": "Docs", "title": "A History of the Millbrook Waterworks", "sub": "Oficina · Saved", "file": "File", "edit": "Edit", "view": "View", "share": "Share…", "rename": "Rename", "pdf": "Download as PDF", "paged": "Paged", "infinite": "Infinite", "delete": "Delete…", "format": "Format", "more": "More", "undo": "Undo", "redo": "Redo", "body": "Before 1887, Millbrook drew its water the way most small towns did: from private wells and a handful of shared pumps."},
"ar": {"app": "المستندات", "title": "ملاحظات الاجتماع الأسبوعي حول مشروع المكتبة الجديدة", "sub": "أوفيسينا · تم الحفظ", "file": "ملف", "edit": "تحرير", "view": "عرض", "share": "مشاركة…", "rename": "إعادة التسمية", "pdf": "تنزيل بصيغة PDF", "paged": "صفحات", "infinite": "متواصل", "delete": "حذف…", "format": "تنسيق", "more": "المزيد", "undo": "تراجع", "redo": "إعادة", "body": "اجتمع الفريق يوم الثلاثاء لمناقشة الجدول الزمني لمشروع المكتبة."},
"ru": {"app": "Документы", "title": "Очень длинное название документа, которое кто-то набрал целиком", "sub": "Oficina · Сохранено", "file": "Файл", "edit": "Правка", "view": "Вид", "share": "Поделиться…", "rename": "Переименовать", "pdf": "Скачать как PDF", "paged": "Постранично", "infinite": "Непрерывно", "delete": "Удалить…", "format": "Формат", "more": "Ещё", "undo": "Отменить", "redo": "Повторить", "body": "До 1887 года Миллбрук брал воду так же, как большинство маленьких городов."},
}
const glyph = ``
func compactBar(L map[string]string) Bar {
item := func(label, key string) template.HTML {
var b bytes.Buffer
_ = template.Must(template.New("").ParseFS(menu.Templates(), "templates/*.html")).ExecuteTemplate(&b, "estilo-menu-item", menu.Item{Href: "#", Label: label, Key: key, Icon: glyph})
return template.HTML(b.String())
}
menubar := template.HTML(``
lead := template.HTML(``)
more := template.HTML(``+glyph+`
`
trail := template.HTML(``) + more
b := signedIn("x")
b.App = App{Name: L["app"], Slug: "docs", Home: "/", Icon: brand.Path("docs")}
b.ContextEdit = &TitleEdit{Action: "/t", Name: "title", Value: L["title"], Label: "Title", Submit: L["rename"]}
b.Nav = nil
b.Actions = []Action{{Item: menu.Item{Controls: "inspector", Label: L["format"]}, WideOnly: true}, {Item: menu.Item{Href: "#", Label: L["share"]}, Primary: true}}
b.Menubar, b.Lead, b.Sticky = menubar, lead, true
b.Compact = &Compact{Trail: trail}
return b
}
// standIn is a stacked bar that is not compact, shaped as Mapa's and
// Fichas' are (frame.go in each): Menubar, Lead and Nav, with page
// actions, one of them WideOnly (Mapa's Links). Below 800px their nav and
// actions are only in the Menu sheet, and their own layouts change at
// 800px, so nothing about them may move to 704px (Fable on c56314e).
func standIn(kind string, L map[string]string) Bar {
b := compactBar(L)
b.Compact = nil
b.Lead = `Saved`
switch kind {
case "mapa":
b.App.Name = "Mapa"
b.Nav = []Link{{Href: "#home", Label: "Home", Current: true}, {Href: "#pages", Label: "Pages"}, {Href: "#recent", Label: "Recent"}, {Href: "#starred", Label: "Starred"}}
b.Actions = []Action{{Item: menu.Item{Href: "#history", Label: "History"}, Icon: glyph},
{Item: menu.Item{Controls: "mapa-links", Label: "Links"}, WideOnly: true, Icon: glyph}}
default:
b.App.Name = "Fichas"
b.ContextEdit, b.Context, b.Switcher = nil, "People", nil
b.Nav = []Link{{Href: "#search", Label: "Search"}, {Href: "#people", Label: "People", Current: true}, {Href: "#companies", Label: "Companies"}}
b.Actions = []Action{{Item: menu.Item{Href: "#history", Label: "History"}, Icon: glyph},
{Item: menu.Item{Href: "#new", Label: "New person"}, Primary: true, Icon: glyph}}
}
return b
}
// standInCase is what the driver measured on a stand-in: every nav link
// and every action that is not WideOnly, and those a person can reach:
// shown in the bar, or a row in the open Menu sheet.
type standInCase struct {
Name string `json:"name"`
Error string `json:"error"`
Width int `json:"width"`
Header float64 `json:"header"`
Var float64 `json:"var"`
Overflow bool `json:"overflow"`
Wanted []string `json:"wanted"`
Reached []string `json:"reached"`
}
type compactCase struct {
Engine string `json:"engine"`
Version string `json:"version"`
Error string `json:"error"`
Cases []struct {
Name string `json:"name"`
Error string `json:"error"`
Width int `json:"width"`
Touch bool `json:"touch"`
Coarse bool `json:"coarse"`
Header float64 `json:"header"`
Var float64 `json:"var"`
Overflow bool `json:"overflow"`
Shown map[string]bool `json:"shown"`
Boxes map[string][]float64 `json:"boxes"` // x, y, w, h
Panel []float64 `json:"panel"`
Rows []float64 `json:"rows"`
Keys int `json:"keys"`
Ellipsis string `json:"ellipsis"`
// The large-title idiom (Compact.Title), at rest and folded.
Rest largeTitle `json:"rest"`
Folded largeTitle `json:"folded"`
// A public page's brand (App.Home empty): its colour and the
// accent's.
Public struct {
Brand string `json:"brand"`
Accent string `json:"accent"`
} `json:"public"`
} `json:"cases"`
StandIns []standInCase `json:"standIns"`
Extra struct {
Resized struct {
From, Header, Var float64
} `json:"resized"`
ResizedError string `json:"resizedError"`
Forced map[string]struct {
Border float64 `json:"border"`
Forced bool `json:"forced"`
Error string `json:"error"`
} `json:"forced"`
} `json:"extra"`
}
type largeTitle struct {
Title bool `json:"title"` // the compact title is visible
Name float64 `json:"name"` // Back's name, its drawn width
Label string `json:"label"` // Back's text, its accessible name
Border string `json:"border"` // the bar's bottom border colour
Box []float64 `json:"box"` // the compact title
Back []float64 `json:"back"`
End []float64 `json:"end"`
}
func TestTheCompactBarInRealEngines(t *testing.T) {
if _, err := exec.LookPath("node"); err != nil {
t.Fatal("node is required (Node 22+)")
}
view := parse(t)
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
lang := r.URL.Query().Get("lang")
L, ok := compactLabels[lang]
if !ok {
lang, L = "en", compactLabels["en"]
}
// Light is named, not left to the system: this Mac is in dark
// mode and headless engines follow it.
dir, scheme := "ltr", ` data-theme="light"`
if lang == "ar" {
dir = "rtl"
}
if r.URL.Query().Get("scheme") == "dark" {
scheme = ` data-theme="dark"`
}
var bar bytes.Buffer
b := compactBar(L)
if kind := r.URL.Query().Get("kind"); kind != "" {
b = standIn(kind, L)
}
if r.URL.Query().Get("public") != "" {
b.App.Home = ""
}
if r.URL.Query().Get("inline") != "" {
b.Compact.Title = template.HTML(`
`)
}
if err := view.ExecuteTemplate(&bar, "estilo-bar", b); err != nil {
t.Error(err)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, compactPage, lang, dir, scheme, bar.String(), template.HTMLEscapeString(L["title"]), template.HTMLEscapeString(L["sub"]), template.HTMLEscapeString(L["body"]))
})
assets := map[string][]byte{"/tokens.css": ui.TokensCSS(), "/theme.css": theme.CSS(), "/base.css": base.CSS(), "/menu.css": menu.CSS(), "/chrome.css": CSS(), "/chrome.js": JS()}
for path, body := range assets {
mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
ct := "text/css; charset=utf-8"
if strings.HasSuffix(path, ".js") {
ct = "text/javascript; charset=utf-8"
}
w.Header().Set("Content-Type", ct)
_, _ = w.Write(body)
})
}
mux.Handle("GET "+brand.Prefix, brand.Handler())
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
engines := strings.Split(os.Getenv("ESTILO_BROWSERS"), ",")
if engines[0] == "" {
engines = []string{"chromium", "webkit"}
}
job, _ := json.Marshal(map[string]any{"origin": srv.URL, "engines": engines, "shots": os.Getenv("ESTILO_SHOTS")})
cmd := exec.Command("node", "compact.browser.mjs", string(job))
cmd.Stderr = os.Stderr
raw, err := cmd.Output()
if err != nil {
t.Fatalf("node compact.browser.mjs: %v", err)
}
var results []compactCase
if err := json.Unmarshal(raw, &results); err != nil {
t.Fatalf("driver output: %v\n%s", err, raw)
}
if len(results) != len(engines) {
t.Fatalf("%d engines asked for, %d reported", len(engines), len(results))
}
for _, r := range results {
if r.Error != "" {
t.Errorf("%s did not launch: %s", r.Engine, r.Error)
continue
}
if len(r.Cases) == 0 {
t.Errorf("%s measured nothing", r.Engine)
}
for _, c := range r.Cases {
where := fmt.Sprintf("%s %s, %s", r.Engine, r.Version, c.Name)
if c.Error != "" {
t.Errorf("%s: could not be driven: %s", where, c.Error)
continue
}
t.Logf("%s: header %.1f (var %.1f), shown %v, panel %v, rows %v, keys %d", where, c.Header, c.Var, c.Shown, c.Panel, c.Rows, c.Keys)
if c.Touch != c.Coarse {
t.Errorf("%s: (pointer: coarse) is %v with touch %v; the emulation is not what the case says", where, c.Coarse, c.Touch)
}
if c.Overflow {
t.Errorf("%s: the page scrolls sideways", where)
}
compact := strings.HasPrefix(c.Name, "phone") || strings.HasPrefix(c.Name, "landscape")
if compact {
if c.Header < 51.5 || c.Header > 52.5 || c.Var != 52 {
t.Errorf("%s: the compact bar is %.1fpx tall, published %.1f; want one 52px row", where, c.Header, c.Var)
}
for _, hidden := range []string{"menubar", "actions", "switcher", "account", "more", "icon"} {
if c.Shown[hidden] {
t.Errorf("%s: %s is shown in a compact bar", where, hidden)
}
}
for _, shown := range []string{"back", "name", "title", "lead", "trail"} {
if !c.Shown[shown] {
t.Errorf("%s: %s is not shown in a compact bar", where, shown)
}
}
// Back, then the title, then the end group, left to right
// (right to left in Arabic), none on top of another.
back, title, end := c.Boxes["back"], c.Boxes["title"], c.Boxes["end"]
rtl := strings.Contains(c.Name, " ar")
if !rtl && !(back[0]+back[2] <= title[0]+0.5 && title[0]+title[2] <= end[0]+0.5) {
t.Errorf("%s: Back %v, title %v and end %v overlap or are out of order", where, back, title, end)
}
if rtl && !(end[0]+end[2] <= title[0]+0.5 && title[0]+title[2] <= back[0]+0.5) {
t.Errorf("%s: in Arabic, end %v, title %v and Back %v overlap or are out of order", where, end, title, back)
}
// The large-title idiom: hidden at rest, then folded into
// the bar between the chevron and the end group, Back still
// named, the hairline drawn.
if c.Rest.Title || c.Rest.Name < 10 || c.Rest.Border == c.Folded.Border {
t.Errorf("%s: at rest the compact title shows %v, Back's name is %.1fpx, the border %q (folded %q)", where, c.Rest.Title, c.Rest.Name, c.Rest.Border, c.Folded.Border)
}
if len(c.Folded.Back) == 4 && (c.Folded.Back[2] < 43.5 || c.Folded.Back[3] < 43.5) {
t.Errorf("%s: folded, Back is %.1fx%.1fpx, under 44", where, c.Folded.Back[2], c.Folded.Back[3])
}
if c.Public.Brand == "" || c.Public.Brand == c.Public.Accent {
t.Errorf("%s: a public page's plain-text brand is %q, the accent %q: it looks like a link", where, c.Public.Brand, c.Public.Accent)
}
if !c.Folded.Title || c.Folded.Name > 1 || strings.TrimSpace(c.Folded.Label) == "" {
t.Errorf("%s: folded, the compact title shows %v, Back's name is %.1fpx wide and Back reads %q", where, c.Folded.Title, c.Folded.Name, c.Folded.Label)
}
if f := c.Folded; len(f.Box) == 4 && len(f.Back) == 4 && len(f.End) == 4 {
rtl := strings.Contains(c.Name, " ar")
if !rtl && !(f.Back[0]+f.Back[2] <= f.Box[0]+0.5 && f.Box[0]+f.Box[2] <= f.End[0]+0.5) || rtl && !(f.End[0]+f.End[2] <= f.Box[0]+0.5 && f.Box[0]+f.Box[2] <= f.Back[0]+0.5) {
t.Errorf("%s: folded, Back %v, the compact title %v and the end %v overlap", where, f.Back, f.Box, f.End)
}
if f.Box[2] < 100 {
t.Errorf("%s: folded, the compact title has %.1fpx", where, f.Box[2])
}
}
if c.Ellipsis != "ellipsis" {
t.Errorf("%s: the title field's overflow is %q, not an ellipsis", where, c.Ellipsis)
}
for _, tool := range []string{"tool-0", "tool-1", "tool-2", "tool-3"} {
if b := c.Boxes[tool]; len(b) != 4 || b[2] < 43.5 || b[3] < 43.5 {
t.Errorf("%s: %s is %v, under 44px", where, tool, b)
}
}
// The ••• panel drops from the inline end, inside the
// viewport, rows 44px, no shortcut hints.
p := c.Panel
if len(p) != 4 || p[0] < 0 || p[0]+p[2] > float64(c.Width)+0.5 || p[1] < c.Header-0.5 {
t.Errorf("%s: the ••• panel %v is not under the bar inside a %dpx viewport", where, p, c.Width)
} else if !rtl && float64(c.Width)-(p[0]+p[2]) > 9 || rtl && p[0] > 9 {
t.Errorf("%s: the ••• panel %v does not hang from the inline end", where, p)
}
for _, h := range c.Rows {
if h < 43.5 {
t.Errorf("%s: a ••• row is %.1fpx, under 44", where, h)
}
}
if c.Keys != 0 {
t.Errorf("%s: %d shortcut hints show in the ••• panel", where, c.Keys)
}
continue
}
// Wide: the stacked header, as without Compact.
if c.Header < 55.5 || c.Header > 56.5 {
t.Errorf("%s: the stacked header is %.1fpx, want 56", where, c.Header)
}
for _, hidden := range []string{"trail", "back", "more"} {
if c.Shown[hidden] {
t.Errorf("%s: %s is shown from 44rem", where, hidden)
}
}
// The stack is the title over the menu row, never one row.
if ti, mb := c.Boxes["title"], c.Boxes["menubar"]; len(ti) != 4 || len(mb) != 4 || mb[1] < ti[1]+ti[3]/2 { // the title row sits 2.5px low by design
t.Errorf("%s: the title %v is not over the menu row %v", where, ti, mb)
}
for _, shown := range []string{"menubar", "actions", "account", "switcher", "icon"} {
if !c.Shown[shown] {
t.Errorf("%s: %s is not shown from 44rem", where, shown)
}
}
want := 28.0
if c.Coarse {
want = 44
}
for _, h := range c.Rows {
if h < want-0.5 || (!c.Coarse && h > want+0.5) {
t.Errorf("%s: a File row is %.1fpx, want %v", where, h, want)
}
}
if c.Coarse && c.Keys != 0 {
t.Errorf("%s: %d shortcut hints show on a touch screen", where, c.Keys)
}
if !c.Coarse && c.Keys == 0 {
t.Errorf("%s: no shortcut hints with a mouse", where)
}
}
}
// Mapa and Fichas, as their bars are: everything in reach at every
// width, the header the height it publishes, and 56px only from 800px.
for _, r := range results {
if r.Error != "" {
continue
}
if len(r.StandIns) == 0 {
t.Errorf("%s measured no stand-in", r.Engine)
}
for _, c := range r.StandIns {
where := fmt.Sprintf("%s %s, %s", r.Engine, r.Version, c.Name)
t.Logf("%s: header %.1f (var %.1f), reached %v of %v", where, c.Header, c.Var, c.Reached, c.Wanted)
if c.Error != "" {
t.Errorf("%s: could not be driven: %s", where, c.Error)
continue
}
if c.Overflow {
t.Errorf("%s: the page scrolls sideways", where)
}
reached := map[string]bool{}
for _, l := range c.Reached {
reached[strings.TrimSpace(l)] = true
}
if len(c.Wanted) < 3 {
t.Errorf("%s: only %v to reach; the check is not reading the bar", where, c.Wanted)
}
for _, w := range c.Wanted {
if !reached[strings.TrimSpace(w)] {
t.Errorf("%s: %q is out of reach: not in the bar and not in an open Menu sheet", where, w)
}
}
if d := c.Header - c.Var; d > 0.5 || d < -0.5 {
t.Errorf("%s: the header is %.1fpx and publishes %.1f", where, c.Header, c.Var)
}
wide := c.Width >= 800
if wide != (c.Header > 55.5 && c.Header < 56.5) {
t.Errorf("%s: the header is %.1fpx at %dpx; a stacked bar that is not compact is the 56px header exactly from 800px", where, c.Header, c.Width)
}
}
}
// A compact bar loaded below 704px and widened to 768px is the 56px
// header: the script must not hold it at the 52px it measured (Fable's
// delta review, item 1). And in forced colours the band's controls
// keep their border, as from 800px (item 2).
for _, r := range results {
if r.Error != "" {
continue
}
x := r.Extra
if x.ResizedError != "" {
t.Errorf("%s: the resize could not be driven: %s", r.Engine, x.ResizedError)
} else if x.Resized.From < 51.5 || x.Resized.From > 52.5 || x.Resized.Header < 55.5 || x.Resized.Header > 56.5 || x.Resized.Var < 55.5 || x.Resized.Var > 56.5 {
t.Errorf("%s: 650px then 768px: the bar went from %.1fpx to %.1fpx (publishing %.1f); want 52 then 56", r.Engine, x.Resized.From, x.Resized.Header, x.Resized.Var)
}
for _, w := range []string{"768", "1280"} {
f := x.Forced[w]
switch {
case f.Error != "":
t.Errorf("%s: forced colours at %s could not be driven: %s", r.Engine, w, f.Error)
case !f.Forced:
t.Errorf("%s: forced colours at %s were not emulated; the check is blind", r.Engine, w)
case f.Border < 1:
t.Errorf("%s: in forced colours at %spx the primary control's border is %.1fpx: it has no edge", r.Engine, w, f.Border)
}
}
}
}