package memoriatest
import (
"io/fs"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"testing"
"amadan.net/oficina/estilo.git/theme"
)
// The chrome is set in the system UI face and downloads no font, so it
// can never flash (Paul, 2026-10-25: "There should never be a flash of
// unstyled text. Ever." estilo AGENTS.md row 9). No page links or
// preloads a webfont: not estilo's retired Onest, and no font file at
// all. estilo's v1 files stay mounted (app.go) so a page cached before
// this still resolves its stylesheet; nothing may name them.
//
// The layout linked v1's fonts.css until this test went in.
func TestNoPageLinksOrPreloadsAChromeWebfont(t *testing.T) {
// Every template, as source: whichever route renders a page, it is
// made of these.
pages := 0
root := filepath.Join("..", "memoria", "templates")
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || filepath.Ext(p) != ".html" {
return err
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
pages++
for _, why := range chromeWebfonts(string(b)) {
t.Errorf("%s %s", p, why)
}
return nil
})
if err != nil {
t.Fatal(err)
}
if pages < 10 {
t.Fatalf("read only %d templates under %s; the scan would pass vacuously", pages, root)
}
// And as served, on the page every visitor meets first.
h, _ := signinApp(t)
rec := get(t, h, "/signin")
if rec.Code != http.StatusOK {
t.Fatalf("GET /signin = %d", rec.Code)
}
for _, why := range chromeWebfonts(rec.Body.String()) {
t.Errorf("GET /signin %s", why)
}
// The retired files still answer, for pages cached before the change.
for _, name := range []string{"fonts.css", "onest-latin.woff2"} {
if rec := get(t, h, theme.FontPrefix+name); rec.Code != http.StatusOK {
t.Errorf("GET %s%s = %d; keep estilo's font handler mounted for old pages", theme.FontPrefix, name, rec.Code)
}
}
}
var (
linkTag = regexp.MustCompile(`(?is)]*>`)
asFont = regexp.MustCompile(`(?i)\bas\s*=\s*["']?font\b`)
fontFile = regexp.MustCompile(`(?i)\.(woff2?|ttf|otf|eot)\b`)
)
// chromeWebfonts names each way html would download a font for the
// chrome: estilo's font path at any version, a that preloads a
// font or names a font file, or a face declared inline.
func chromeWebfonts(html string) []string {
var found []string
if dir := path.Dir(strings.TrimSuffix(theme.FontPrefix, "/")) + "/"; strings.Contains(html, dir) {
found = append(found, "names estilo's webfont path "+dir)
}
for _, tag := range linkTag.FindAllString(html, -1) {
if asFont.MatchString(tag) || fontFile.MatchString(tag) {
found = append(found, "links or preloads a font: "+tag)
}
}
if strings.Contains(strings.ToLower(html), "@font-face") {
found = append(found, "declares a font face inline")
}
return found
}