Files
yetano-webui-template/appearance_test.go
T

229 lines
8.0 KiB
Go
Raw Normal View History

package layout
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"testing"
)
// paletteBlocks returns the --yw-* declarations of every top-level
// :root block in static/style.css that declares palette tokens, keyed by
// palette ID (the bare :root block is PaletteDefault).
func paletteBlocks(t *testing.T) map[string]map[string]string {
t.Helper()
css, err := staticFS.ReadFile("static/style.css")
if err != nil {
t.Fatal(err)
}
blocks := map[string]map[string]string{}
rxBlock := regexp.MustCompile(`(?m)^(:root[^{]*)\{([^}]*)\}`)
rxDecl := regexp.MustCompile(`(?m)^\s*(--yw-[a-z0-9-]+):\s*(.*?);\s*$`)
for _, m := range rxBlock.FindAllStringSubmatch(string(css), -1) {
sel := strings.TrimSpace(m[1])
var id string
switch {
case sel == ":root":
id = PaletteDefault
case strings.HasPrefix(sel, `:root[data-palette="`):
id = strings.TrimSuffix(strings.TrimPrefix(sel, `:root[data-palette="`), `"]`)
default:
continue
}
decls := map[string]string{}
for _, d := range rxDecl.FindAllStringSubmatch(m[2], -1) {
if !strings.HasPrefix(d[1], "--yw-if-") {
decls[d[1]] = d[2]
}
}
if len(decls) == 0 {
continue
}
if blocks[id] != nil {
t.Fatalf("style.css: palette %q declared twice", id)
}
blocks[id] = decls
}
return blocks
}
func hexTriplet(h string) string {
var r, g, b int
fmt.Sscanf(h, "#%02x%02x%02x", &r, &g, &b)
return fmt.Sprintf("%d, %d, %d", r, g, b)
}
// TestPaletteTokens checks the palette blocks of static/style.css: every
// palette in Palettes has one; each color is one light-dark() pair, so
// no mode repeats another's values; each *-rgb triplet matches its
// color; a palette only overrides tokens the default declares; and the
// default keeps the cross-project nav-link color.
func TestPaletteTokens(t *testing.T) {
blocks := paletteBlocks(t)
for _, p := range Palettes {
if blocks[p.ID] == nil {
t.Errorf("style.css: no block for palette %q", p.ID)
}
}
if len(blocks) != len(Palettes) {
t.Errorf("style.css has %d palette blocks, Palettes lists %d", len(blocks), len(Palettes))
}
rxColor := regexp.MustCompile(`^light-dark\((#[0-9a-f]{6}), (#[0-9a-f]{6})\)$`)
rxTriplet := regexp.MustCompile(`^var\(--yw-if-light, (\d+, \d+, \d+)\) var\(--yw-if-dark, (\d+, \d+, \d+)\)$`)
def := blocks[PaletteDefault]
for id, decls := range blocks {
for name, value := range decls {
if _, ok := def[name]; !ok {
t.Errorf("palette %q: %s is not a default token", id, name)
}
if base, ok := strings.CutSuffix(name, "-rgb"); ok {
tm := rxTriplet.FindStringSubmatch(value)
cm := rxColor.FindStringSubmatch(decls[base])
if tm == nil || cm == nil {
t.Errorf("palette %q: %s = %q needs %s in the same block", id, name, value, base)
continue
}
if tm[1] != hexTriplet(cm[1]) || tm[2] != hexTriplet(cm[2]) {
t.Errorf("palette %q: %s = %q does not match %s = %q", id, name, value, base, decls[base])
}
continue
}
if !rxColor.MatchString(value) {
t.Errorf("palette %q: %s = %q, want light-dark(#rrggbb, #rrggbb)", id, name, value)
}
if _, hasRGB := def[name+"-rgb"]; hasRGB {
if _, ok := decls[name+"-rgb"]; !ok {
t.Errorf("palette %q: overrides %s but not %s-rgb", id, name, name)
}
}
}
}
if got, want := def["--yw-nav-link"], "light-dark(#0b82b8, #0b82b8)"; got != want {
t.Errorf("default --yw-nav-link = %q, want %q (cross-project design token)", got, want)
}
}
func TestPaletteAttribute(t *testing.T) {
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
if err != nil {
t.Fatalf("NewRenderer: %v", err)
}
for palette, want := range map[string]string{
"": `<html lang="en" data-theme="light">`,
PaletteGraphite: `<html lang="en" data-theme="light" data-palette="graphite">`,
} {
var buf bytes.Buffer
if err := r.Page(&buf, "dashboard", PageHeader{Theme: ThemeLight, Palette: palette}); err != nil {
t.Fatalf("Page: %v", err)
}
if !strings.Contains(buf.String(), want) {
t.Errorf("palette %q: rendered output missing %q\n---\n%s", palette, want, buf.String())
}
}
}
func TestApplyAppearance(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/ui/tasks?f=1", nil)
req.AddCookie(&http.Cookie{Name: ThemeCookie, Value: ThemeLight})
req.AddCookie(&http.Cookie{Name: PaletteCookie, Value: "nope"})
h := PageHeader{BasePath: "/ui", Theme: ThemeSystem, Palette: PaletteContrast}
h.ApplyAppearance(req)
if h.Theme != ThemeLight {
t.Errorf("Theme = %q, want %q from the cookie", h.Theme, ThemeLight)
}
if h.Palette != PaletteContrast {
t.Errorf("Palette = %q, want the consumer default %q (cookie value unknown)", h.Palette, PaletteContrast)
}
if h.AppearanceBack != "/tasks?f=1" {
t.Errorf("AppearanceBack = %q, want %q", h.AppearanceBack, "/tasks?f=1")
}
// Behind http.StripPrefix the path is already relative to BasePath.
for path, want := range map[string]string{"/release-notes": "/release-notes", "/r": "/", "/r/x": "/x"} {
h := PageHeader{BasePath: "/r"}
h.ApplyAppearance(httptest.NewRequest(http.MethodGet, path, nil))
if h.AppearanceBack != want {
t.Errorf("BasePath /r, path %s: AppearanceBack = %q, want %q", path, h.AppearanceBack, want)
}
}
}
func TestAppearanceHandler(t *testing.T) {
h := AppearanceHandler("/ui")
post := func(form url.Values) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/ui/appearance", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
rec := post(url.Values{"palette": {PaletteGraphite}, "back": {"/tasks?f=1"}})
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/ui/tasks?f=1" {
t.Errorf("palette: got %d to %q, want 303 to /ui/tasks?f=1", rec.Code, rec.Header().Get("Location"))
}
cookies := rec.Result().Cookies()
if len(cookies) != 1 || cookies[0].Name != PaletteCookie || cookies[0].Value != PaletteGraphite ||
cookies[0].Path != "/ui/" || !cookies[0].HttpOnly {
t.Errorf("palette: cookies = %+v", cookies)
}
for _, back := range []string{"https://evil.example/", "//evil.example/", "/\\evil.example", "tasks", ""} {
rec := post(url.Values{"theme": {ThemeDark}, "back": {back}})
if loc := rec.Header().Get("Location"); loc != "/ui/" {
t.Errorf("back %q: redirected to %q, want /ui/", back, loc)
}
}
for _, form := range []url.Values{{}, {"theme": {"pink"}}, {"palette": {"nope"}}} {
if rec := post(form); rec.Code != http.StatusBadRequest {
t.Errorf("form %v: got %d, want 400", form, rec.Code)
}
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ui/appearance?theme=dark", nil))
if rec.Code != http.StatusMethodNotAllowed || rec.Header().Get("Allow") != http.MethodPost {
t.Errorf("GET: got %d, Allow %q; want 405, POST", rec.Code, rec.Header().Get("Allow"))
}
}
func TestAppearanceMenu(t *testing.T) {
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
if err != nil {
t.Fatalf("NewRenderer: %v", err)
}
var buf bytes.Buffer
if err := r.Page(&buf, "dashboard", PageHeader{Title: "Dashboard"}); err != nil {
t.Fatalf("Page: %v", err)
}
if strings.Contains(buf.String(), "yw-appearance") {
t.Errorf("menu rendered without AppearancePath\n---\n%s", buf.String())
}
buf.Reset()
data := PageHeader{Title: "Dashboard", Lang: "de", BasePath: "/ui", AppearancePath: "/appearance",
AppearanceBack: "/tasks", Theme: ThemeLight, Palette: PaletteGraphite}
if err := r.Page(&buf, "dashboard", data); err != nil {
t.Fatalf("Page: %v", err)
}
out := buf.String()
for _, want := range []string{
`<form method="post" action="/ui/appearance"`,
`name="back" value="/tasks"`,
`name="theme" value="light" aria-pressed="true"><span aria-hidden="true">☀</span> Hell</button>`,
`name="theme" value="dark" aria-pressed="false">`,
`name="palette" value="graphite" aria-pressed="true">Graphit</button>`,
`<h6>Farben</h6>`,
} {
if !strings.Contains(out, want) {
t.Errorf("rendered output missing %q\n---\n%s", want, out)
}
}
}