oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "context"
5 "fmt"
6 "net/http"
7 "os"
8 "regexp"
9 "strings"
10 "testing"
11
12 "github.com/carlosframework/docs/internal/export"
13 "github.com/carlosframework/docs/internal/fonts"
14)
15
16// exportable creates a document owned by address with the styled
17// fixture applied — headings, lists, a blockquote and the font and
18// size marks — so an export test exercises every shape at once.
19func exportable(t *testing.T, app *App, address, title string) *Document {
20 t.Helper()
21 ctx := context.Background()
22 owner := app.TestPerson(t, address)
23 doc, err := app.Store().createDocument(ctx, owner, title, "", VisibilityPrivate)
24 if err != nil {
25 t.Fatalf("Create: %v", err)
26 }
27 update := readFixture(t, "../../fixtures/vectors/fragment/styled.bin")
28 // ApplyUpdate returns the accepted row's seq alongside its error
29 // since the live-update stream landed (store.go); this test does not
30 // care which seq, only that the update went in.
31 if _, err := app.Store().ApplyUpdate(ctx, doc, app.TestActorFor(t, doc), update); err != nil {
32 t.Fatalf("ApplyUpdate: %v", err)
33 }
34 return doc
35}
36
37func TestExportMarkdown(t *testing.T) {
38 app, err := NewForTest(t)
39 if err != nil {
40 t.Fatalf("NewForTest: %v", err)
41 }
42 doc := exportable(t, app, "writer@example.com", "Meeting notes")
43
44 rec := serve(app, app.TestRequest(t, "writer@example.com", http.MethodGet, "/d/"+doc.Sqid+"/export.md", nil))
45 if rec.Code != http.StatusOK {
46 t.Fatalf("got %d, want 200", rec.Code)
47 }
48 if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/markdown") {
49 t.Errorf("Content-Type is %q", ct)
50 }
51 if cd := rec.Header().Get("Content-Disposition"); cd != `attachment; filename="Meeting-notes.md"` {
52 t.Errorf("Content-Disposition is %q", cd)
53 }
54 body := rec.Body.String()
55 for _, want := range []string{"# Meeting notes", "> Quoted.", "1. First", "2. Second"} {
56 if !strings.Contains(body, want) {
57 t.Errorf("markdown is missing %q\n%s", want, body)
58 }
59 }
60}
61
62func TestExportPDF(t *testing.T) {
63 app, err := NewForTest(t)
64 if err != nil {
65 t.Fatalf("NewForTest: %v", err)
66 }
67 doc := exportable(t, app, "writer@example.com", "Meeting notes")
68
69 rec := serve(app, app.TestRequest(t, "writer@example.com", http.MethodGet, "/d/"+doc.Sqid+"/export.pdf", nil))
70 if rec.Code != http.StatusOK {
71 t.Fatalf("got %d, want 200", rec.Code)
72 }
73 if ct := rec.Header().Get("Content-Type"); ct != "application/pdf" {
74 t.Errorf("Content-Type is %q", ct)
75 }
76 if cd := rec.Header().Get("Content-Disposition"); cd != `attachment; filename="Meeting-notes.pdf"` {
77 t.Errorf("Content-Disposition is %q", cd)
78 }
79 if !strings.HasPrefix(rec.Body.String(), "%PDF-1.") {
80 t.Errorf("the body is not a PDF: %q", firstBytes(rec.Body.String()))
81 }
82}
83
84// Spec §4.2: a document you cannot see is indistinguishable from one
85// that does not exist. Both export routes go through the same
86// owner-scoped lookup as every other document route, and this is what
87// holds them to it — an export route that forgot the scope would be a
88// way to read anybody's document by guessing a sqid.
89func TestExportIsOwnerScoped(t *testing.T) {
90 app, err := NewForTest(t)
91 if err != nil {
92 t.Fatalf("NewForTest: %v", err)
93 }
94 doc := exportable(t, app, "owner@example.com", "Private")
95 app.TestPerson(t, "stranger@example.com")
96
97 for _, path := range []string{"/export.md", "/export.pdf"} {
98 rec := serve(app, app.TestRequest(t, "stranger@example.com", http.MethodGet, "/d/"+doc.Sqid+path, nil))
99 if rec.Code != http.StatusNotFound {
100 t.Errorf("%s: a stranger got %d, want 404", path, rec.Code)
101 }
102 // Unknown and not-yours must be the same answer, byte for
103 // byte, or the difference is an oracle for which sqids exist.
104 missing := serve(app, app.TestRequest(t, "stranger@example.com", http.MethodGet, "/d/zzzzzzzzzz"+path, nil))
105 if missing.Code != rec.Code || missing.Body.String() != rec.Body.String() {
106 t.Errorf("%s: a document that exists but is not yours answers differently from one that does not exist", path)
107 }
108 }
109}
110
111func TestExportRequiresASession(t *testing.T) {
112 app, err := NewForTest(t)
113 if err != nil {
114 t.Fatalf("NewForTest: %v", err)
115 }
116 doc := exportable(t, app, "owner@example.com", "Private")
117
118 for _, path := range []string{"/export.md", "/export.pdf"} {
119 req, _ := http.NewRequest(http.MethodGet, "/d/"+doc.Sqid+path, nil)
120 rec := serve(app, req)
121 if rec.Code == http.StatusOK {
122 t.Errorf("%s: served a document to a signed-out request", path)
123 }
124 }
125}
126
127// A title is arbitrary text somebody typed, and it ends up in a header
128// and then in a filesystem. Both are places where a quote, a newline
129// or a slash means something.
130func TestExportFilenameIsSanitised(t *testing.T) {
131 cases := []struct {
132 title string
133 want string
134 }{
135 {"Meeting notes", "Meeting-notes.md"},
136 {`say "hello"`, "say-hello.md"},
137 {"../../etc/passwd", "etc-passwd.md"},
138 {"a\r\nSet-Cookie: x=y", "a-Set-Cookie-x-y.md"},
139 {"Café notes", "Caf-notes.md"},
140 {"日報", "SQIDSQIDSQ.md"},
141 {"", "SQIDSQIDSQ.md"},
142 {"!!!", "SQIDSQIDSQ.md"},
143 }
144 for _, c := range cases {
145 doc := &Document{Title: c.title, Sqid: "SQIDSQIDSQ"}
146 if got := exportFilename(doc, ".md"); got != c.want {
147 t.Errorf("title %q: got %q, want %q", c.title, got, c.want)
148 }
149 }
150 // Long titles are capped, and nothing in the result can end a
151 // quoted header value early.
152 long := exportFilename(&Document{Title: strings.Repeat("word ", 40), Sqid: "x"}, ".pdf")
153 if len(long) > 70 {
154 t.Errorf("filename is %d characters: %q", len(long), long)
155 }
156 if strings.ContainsAny(long, `"\/;`+"\r\n") {
157 t.Errorf("filename contains a character that means something in a header: %q", long)
158 }
159}
160
161// The exported PDF and the exported Markdown must be of the SAME
162// document — both read the CRDT through the same core, and a route
163// that read a stale column instead would still return a valid file.
164func TestBothExportsSeeTheSameContent(t *testing.T) {
165 app, err := NewForTest(t)
166 if err != nil {
167 t.Fatalf("NewForTest: %v", err)
168 }
169 doc := exportable(t, app, "writer@example.com", "Both")
170
171 md := serve(app, app.TestRequest(t, "writer@example.com", http.MethodGet, "/d/"+doc.Sqid+"/export.md", nil)).Body.String()
172 structure, err := app.Store().JSON(context.Background(), doc)
173 if err != nil {
174 t.Fatal(err)
175 }
176 parsed, err := export.Parse(doc.Title, structure)
177 if err != nil {
178 t.Fatal(err)
179 }
180 if md != export.Markdown(parsed) {
181 t.Error("the route's Markdown differs from the exporter's own")
182 }
183}
184
185// --- the geometry the PDF and the screen must agree about ---
186
187// internal/export lays a PDF out from Go constants; views/show.html
188// lays the same document out from CSS. Nothing makes one drive the
189// other, so this is what stops them drifting: it reads the stylesheet
190// and fails if a number in it stops matching the exporter's.
191//
192// Every lookup below must FIND its pattern, not merely fail to
193// contradict it. A test that silently passes when the stylesheet is
194// restructured would be worse than no test — it is the shape AGENTS.md
195// warns about, a check that cannot tell "no" from "I can't see it".
196func TestPageGeometryMatchesTheStylesheet(t *testing.T) {
197 css, err := os.ReadFile("views/show.html")
198 if err != nil {
199 t.Fatal(err)
200 }
201 sheet := string(css)
202
203 cases := []struct {
204 what string
205 pattern string
206 want float64
207 }{
208 {"page width", `\[docs-page\][^}]*inline-size:\s*min\(100%,\s*([\d.]+)in\)`, export.PageWidthPt / 72},
209 {"page height", `\[docs-page\][^}]*min-block-size:\s*([\d.]+)in`, export.PageHeightPt / 72},
210 {"page margin", `\[docs-page\][^}]*padding:\s*([\d.]+)in`, export.MarginPt / 72},
211 {"body size", `\[docs-text\]\s*\{[^}]*font-size:\s*([\d.]+)pt`, export.BodySizePt},
212 {"body line-height", `\[docs-text\]\s*\{[^}]*line-height:\s*([\d.]+)`, export.BodyLeading},
213 // The indent step, which the stylesheet states in inches and the
214 // exporter in points.
215 {"indent step", `\.docs-indent-1[^}]*margin-inline-start:\s*([\d.]+)in`, export.IndentStepPt / 72},
216 {"deepest indent", `\.docs-indent-8[^}]*margin-inline-start:\s*([\d.]+)in`, export.IndentStepPt * export.MaxIndent / 72},
217 }
218 // Every size mark, in pt on both sides.
219 //
220 // This used to be three hand-written rows comparing `em` — the four
221 // step scale was a multiplier of the body size. The ladder is
222 // absolute now, so the unit changed, and with fourteen marks the
223 // rows are generated from the exporter's own list rather than
224 // written out: a mark added to internal/export and forgotten here
225 // would otherwise be a size the stylesheet never styles, which is
226 // text that renders at the wrong size for every reader.
227 //
228 // Driven from export.SizeMarks() rather than from a list in this
229 // file, because a list here is a list that stops matching.
230 for _, mark := range export.SizeMarks() {
231 pt, ok := export.SizePt(mark)
232 if !ok {
233 t.Errorf("internal/export lists the size mark %q and then does not know its size", mark)
234 continue
235 }
236 cases = append(cases, struct {
237 what string
238 pattern string
239 want float64
240 }{
241 what: "size mark " + mark,
242 pattern: `\.docs-` + regexp.QuoteMeta(strings.ReplaceAll(strings.TrimPrefix(mark, ""), "_", "-")) + `[^}]*font-size:\s*([\d.]+)pt`,
243 want: pt,
244 })
245 }
246 for _, c := range cases {
247 m := regexp.MustCompile(c.pattern).FindStringSubmatch(sheet)
248 if m == nil {
249 t.Errorf("%s: found nothing matching %s in views/show.html — the stylesheet was restructured and this test can no longer see what it is checking", c.what, c.pattern)
250 continue
251 }
252 var got float64
253 if _, err := fmt.Sscanf(m[1], "%g", &got); err != nil {
254 t.Errorf("%s: %q is not a number", c.what, m[1])
255 continue
256 }
257 if got != c.want {
258 t.Errorf("%s: the stylesheet says %v, internal/export says %v", c.what, got, c.want)
259 }
260 }
261
262 // The faces, which the table above cannot see either: it compares
263 // numbers, and a face is a name.
264 //
265 // This is the pairing nothing forced before. The screen's default
266 // family is a literal in a CSS rule and the exporter's is a Go
267 // constant reached through a switch, in two languages, in two
268 // binaries — and a document paginates the same on screen and in its
269 // own PDF only while both measure with the SAME font program. When
270 // they disagree the export does not fail; it just breaks its lines
271 // somewhere else, and the page breaks move with them.
272 //
273 // The want side goes through export.FontCSSName, which resolves a
274 // run through styleFor rather than restating its answer, so this
275 // compares the stylesheet against what the exporter actually does.
276 // The default row (no marks) is the one that matters most: it is
277 // what every paragraph nobody has marked is set in, which is most of
278 // the text in most documents.
279 // The font rules live in internal/fonts' generated stylesheet, not
280 // in show.html, so that is what is read here. show.html must not set
281 // a font-family on [docs-text] of its own, or it would override it.
282 fontSheet := string(fonts.Stylesheet())
283 if regexp.MustCompile(`\[docs-text\]\s*\{[^}]*font-family`).MatchString(sheet) {
284 t.Error("views/show.html sets [docs-text]'s font-family, overriding the generated font stylesheet")
285 }
286 type faceCase struct{ what, pattern, want string }
287 faceCases := []faceCase{
288 {"default body face", `html\[data-docs-faces="web"\]:not\(\[data-docs-fonts-fallback~="carlito"\]\) \[docs-text\]\{font-family:"([^"]+)"`, export.FontCSSName()},
289 {"code face", `html\[data-docs-faces="web"\]:not\(\[data-docs-fonts-fallback~="mono"\]\) \[docs-text\] code\{font-family:"([^"]+)"`, export.FontCSSName("code")},
290 }
291 for _, f := range fonts.Families {
292 faceCases = append(faceCases, faceCase{f.Name + " mark face", `:not\(\[data-docs-fonts-fallback~="` + f.Key + `"\]\) \[docs-text\] \.` + f.Class() + `\{font-family:"([^"]+)"`, export.FontCSSName(f.Mark())})
293 }
294 for _, c := range faceCases {
295 m := regexp.MustCompile(c.pattern).FindStringSubmatch(fontSheet)
296 if m == nil {
297 t.Errorf("%s: found nothing matching %s in the font stylesheet — either the rule is missing or the stylesheet was restructured and this test can no longer see what it is checking", c.what, c.pattern)
298 continue
299 }
300 if m[1] != c.want {
301 t.Errorf("%s: the stylesheet names %q, internal/export lays it out in %q", c.what, m[1], c.want)
302 }
303 }
304
305 // The block-level margins, which the table above cannot see.
306 //
307 // internal/export/pdf.go states these three as constants and its
308 // own header calls them a mirror of this stylesheet, but until now
309 // nothing held any of them to it — the table reads eight numbers
310 // and none of them is a margin. That gap bites precisely because
311 // the three are now load-bearing ZEROES: a later edit putting the
312 // paragraph spacing back (`margin-block: 0 1em`, a plausible
313 // "revert the density change") would move the page and leave the
314 // PDF where it was, and only the line-height half of that drift
315 // would have been caught.
316 //
317 // margin-block is a one-or-two-value shorthand and the number that
318 // matters is the END margin, so these read the whole value list and
319 // take its last field rather than capturing the first number they
320 // see — a pattern that captured the first would read "0" out of
321 // "margin-block: 0 1em" and pass while the stylesheet said the
322 // opposite of what pdf.go says.
323 for _, c := range []struct {
324 what string
325 pattern string
326 constant string
327 }{
328 {"paragraph bottom margin", `\[docs-text\] p \{[^}]*margin-block:\s*([^;}]+)`, "paragraph"},
329 {"list bottom margin", `\[docs-text\] ul,\s*\[docs-text\] ol \{[^}]*margin-block:\s*([^;}]+)`, "list"},
330 } {
331 want, ok := export.BlockSpace(c.constant)
332 if !ok {
333 t.Errorf("%s: internal/export has no %q margin — it was renamed and this case is no longer comparing anything", c.what, c.constant)
334 continue
335 }
336 m := regexp.MustCompile(c.pattern).FindStringSubmatch(sheet)
337 if m == nil {
338 t.Errorf("%s: found nothing matching %s in views/show.html — the stylesheet was restructured and this test can no longer see what it is checking", c.what, c.pattern)
339 continue
340 }
341 got, err := blockEndEm(m[1])
342 if err != nil {
343 t.Errorf("%s: %v", c.what, err)
344 continue
345 }
346 if got != want {
347 t.Errorf("%s: the stylesheet says %vem, internal/export says %vem", c.what, got, want)
348 }
349 }
350
351 // listItemSpace has no rule of its own to read: the stylesheet says
352 // "an li has no margin" by having no `[docs-text] li` margin rule at
353 // all, because a browser-default li has none and an explicit 0 would
354 // be a no-op rule.
355 //
356 // An absence is a weak thing to assert alone — it would hold just as
357 // well against an empty file — so this pins a landmark first. If the
358 // `[docs-text] li > :last-child` rule is gone, the list rules were
359 // restructured and the absence below has stopped meaning anything,
360 // which is a failure rather than a pass. And it checks in whichever
361 // direction the constant points, so putting the margin back on both
362 // sides stays possible and putting it back on one does not.
363 itemSpace, ok := export.BlockSpace("list_item")
364 if !ok {
365 t.Error(`internal/export has no "list_item" margin — it was renamed and this case is no longer comparing anything`)
366 } else if !strings.Contains(sheet, "[docs-text] li > :last-child {") {
367 t.Error("list item margin: views/show.html no longer has a `[docs-text] li > :last-child` rule — the list rules were restructured and this check can no longer see what it is checking")
368 } else {
369 liMargin := regexp.MustCompile(`\[docs-text\] li \{[^}]*margin[^}]*\}`).FindString(sheet)
370 switch {
371 case itemSpace == 0 && liMargin != "":
372 t.Errorf("list item margin: internal/export says an li has none, the stylesheet gives it one: %q", liMargin)
373 case itemSpace != 0 && liMargin == "":
374 t.Errorf("list item margin: internal/export says %vem, the stylesheet gives an li no margin rule at all", itemSpace)
375 }
376 }
377}
378
379// blockEndEm reads the block-END margin out of a `margin-block`
380// shorthand, in em: one value sets both edges, two set start then end.
381//
382// A unit other than em is an error rather than a guess. internal/export
383// states these margins in em of the body size, so a value in px or rem
384// is not something this comparison can honestly turn into a number —
385// and saying so loudly is the point, because the alternative is a test
386// that quietly compares the wrong quantity.
387func blockEndEm(value string) (float64, error) {
388 fields := strings.Fields(strings.TrimSpace(value))
389 if len(fields) == 0 || len(fields) > 2 {
390 return 0, fmt.Errorf("margin-block: %q is not one or two values", value)
391 }
392 end := fields[len(fields)-1]
393 if end == "0" {
394 return 0, nil
395 }
396 num, found := strings.CutSuffix(end, "em")
397 if !found {
398 return 0, fmt.Errorf("margin-block ends in %q — internal/export states these margins in em, so this cannot be compared", end)
399 }
400 var f float64
401 if _, err := fmt.Sscanf(num, "%g", &f); err != nil {
402 return 0, fmt.Errorf("margin-block ends in %q, which is not a number", end)
403 }
404 return f, nil
405}
406
407// Every class the Rust renderer can put in the page has to be a class
408// this stylesheet styles.
409//
410// The classes are a contract between core/src/fragment.rs and
411// views/show.html, and nothing but a test holds it: a class the
412// renderer emits and the sheet does not style is formatting that
413// silently does nothing for a reader, and it fails in exactly the way
414// that never produces an error anywhere.
415//
416// It scrapes the classes out of a REAL rendering rather than listing
417// them, so a class added to the renderer and forgotten here is caught
418// by this test rather than missed by it. aligned.bin, styled.bin and
419// fonts.bin between them exercise the whole vocabulary — the block
420// alignments, the size marks, and all three faces.
421func TestEveryClassTheRendererEmitsIsStyled(t *testing.T) {
422 app, err := NewForTest(t)
423 if err != nil {
424 t.Fatalf("NewForTest: %v", err)
425 }
426 ctx := context.Background()
427 owner := app.TestPerson(t, "classes@example.com")
428
429 // One document per fixture: each .bin is a whole Yjs document in
430 // its own right, and applying two of them to one document is a
431 // merge the core rejects rather than the union this wants.
432 classes := map[string]bool{}
433 for _, name := range []string{"aligned.bin", "styled.bin", "fonts.bin"} {
434 doc, err := app.Store().Create(ctx, owner, "Classes: "+name)
435 if err != nil {
436 t.Fatalf("Create: %v", err)
437 }
438 if _, err := app.Store().ApplyUpdate(ctx, doc, app.TestActorFor(t, doc), readFixture(t, "../../fixtures/vectors/fragment/"+name)); err != nil {
439 t.Fatalf("ApplyUpdate %s: %v", name, err)
440 }
441 html, err := app.Store().HTML(ctx, doc)
442 if err != nil {
443 t.Fatalf("HTML %s: %v", name, err)
444 }
445 for _, m := range regexp.MustCompile(`class="([^"]+)"`).FindAllStringSubmatch(string(html), -1) {
446 for _, c := range strings.Fields(m[1]) {
447 classes[c] = true
448 }
449 }
450 }
451 // A rendering with no classes at all would make every assertion
452 // below vacuous, and that is the failure mode this whole file keeps
453 // warning about.
454 if len(classes) < 2 {
455 t.Fatalf("the rendered fixtures carry %d classes between them — the fixtures or the renderer changed and this test can no longer see what it is checking: %v", len(classes), classes)
456 }
457 if !classes["docs-align-center"] || !classes["docs-align-right"] {
458 t.Errorf("the renderer emitted no alignment classes at all: %v", classes)
459 }
460
461 sheet, err := os.ReadFile("views/show.html")
462 if err != nil {
463 t.Fatal(err)
464 }
465 // The font classes are styled by internal/fonts' generated
466 // stylesheet, which every document page links.
467 sheet = append(sheet, fonts.Stylesheet()...)
468 for class := range classes {
469 if !regexp.MustCompile(`\[docs-text\][^{]*\.` + regexp.QuoteMeta(class) + `[^{]*\{`).Match(sheet) {
470 t.Errorf("core/src/fragment.rs emits class %q and neither views/show.html nor the font stylesheet has a [docs-text] rule for it — the formatting does nothing for a reader", class)
471 }
472 }
473}
474
475// And alignment specifically has to be styled as alignment. The test
476// above only proves a rule EXISTS; a rule that set a colour would
477// satisfy it while a centred paragraph stayed flush left, so this reads
478// the declaration.
479//
480// The property has to agree with internal/export/pdf.go, which offsets
481// a centred line by half the free space in its column and a right
482// aligned one by all of it — the same two answers CSS's `center` and
483// `right` give.
484func TestTheAlignmentClassesSetTextAlign(t *testing.T) {
485 sheet, err := os.ReadFile("views/show.html")
486 if err != nil {
487 t.Fatal(err)
488 }
489 for _, c := range []struct{ class, want string }{
490 {"docs-align-center", "center"},
491 {"docs-align-right", "right"},
492 } {
493 pattern := `\[docs-text\] \.` + c.class + `\s*\{[^}]*text-align:\s*([a-z-]+)`
494 m := regexp.MustCompile(pattern).FindSubmatch(sheet)
495 if m == nil {
496 t.Errorf("%s: found nothing matching %s in views/show.html — either the rule is missing or the stylesheet was restructured and this test can no longer see what it is checking", c.class, pattern)
497 continue
498 }
499 if got := string(m[1]); got != c.want {
500 t.Errorf("%s sets text-align: %s, want %s", c.class, got, c.want)
501 }
502 }
503}
504
505// The pressed state of a toolbar button must be visible without
506// relying on colour (the spec's rule that colour never carries meaning
507// alone, and AGENTS.md's "WCAG 2.2 AA, no exemptions").
508//
509// This is a regression test for a real defect, found in review: the
510// rule leaned on `font-weight: 700`, which does nothing to an SVG icon,
511// and six of the nine controls here are icon-only -- while the pressed
512// background was the SAME token as :hover, so a hovered unpressed
513// button and a pressed one differed by icon hue alone. The comment
514// beside the rule asserted the mechanism was handled while it was not,
515// which is the failure this codebase names specifically.
516//
517// It compares the two rules rather than looking for one named property,
518// so it stays true to what is actually being asked: whatever
519// distinguishes pressed from hover, at least one of those things must
520// be something an ICON can show. That leaves the choice of cue open --
521// a bar, a ring, an outline -- and still fails if the cue goes away.
522//
523// The first draft of this test passed against the shipped defect,
524// because it excluded only colour and therefore counted the useless
525// `font-weight`. See noCueOnAnIcon below: getting that set right is the
526// whole test.
527func TestThePressedToolbarStateDoesNotRelyOnColour(t *testing.T) {
528 sheet, err := os.ReadFile("views/show.html")
529 if err != nil {
530 t.Fatal(err)
531 }
532 body := func(selector string) string {
533 t.Helper()
534 m := regexp.MustCompile(regexp.QuoteMeta(selector) + `\s*\{([^}]*)\}`).FindSubmatch(sheet)
535 if m == nil {
536 t.Fatalf("no %s rule in views/show.html -- the toolbar styles were restructured and this test can no longer see what it is checking", selector)
537 }
538 return string(m[1])
539 }
540
541 // Properties that cannot distinguish a PRESSED icon button from a
542 // hovered one, and so must not be counted as the cue.
543 //
544 // The three colour properties are obvious. `font-weight` is the one
545 // that matters, and leaving it out of this set is what made the
546 // first draft of this test pass against the very defect it is named
547 // for: weight is not a colour, so a naive reading counts it, but it
548 // does nothing whatsoever to an SVG icon. Six of the nine controls
549 // in this bar are icon-only. A cue has to be something that
550 // actually renders on them.
551 noCueOnAnIcon := map[string]bool{
552 "color": true,
553 "background": true,
554 "background-color": true,
555 "font-weight": true,
556 }
557
558 declared := func(rule string) map[string]string {
559 out := map[string]string{}
560 for _, decl := range strings.Split(rule, ";") {
561 name, value, ok := strings.Cut(decl, ":")
562 if !ok {
563 continue
564 }
565 out[strings.TrimSpace(name)] = strings.TrimSpace(value)
566 }
567 return out
568 }
569
570 hover := declared(body(`[docs-tool]:hover:not(:disabled)`))
571 pressed := declared(body(`[docs-tool][aria-pressed="true"]`))
572 if len(pressed) == 0 {
573 t.Fatal("the pressed rule declares nothing at all")
574 }
575
576 var cues []string
577 for name, value := range pressed {
578 if noCueOnAnIcon[name] {
579 continue
580 }
581 if hover[name] == value {
582 continue // hover has it too, so it distinguishes nothing
583 }
584 cues = append(cues, name)
585 }
586 if len(cues) == 0 {
587 t.Errorf("aria-pressed carries no cue an icon button can show: pressed declares %v, hover declares %v -- colour and font-weight are all that separate them, and weight does nothing to an SVG", pressed, hover)
588 }
589
590 // The trap that was actually shipped: pressed and hover sharing a
591 // background means the background does none of the work, so the cue
592 // found above is carrying the whole distinction on its own.
593 if pressed["background"] != "" && pressed["background"] == hover["background"] {
594 t.Logf("pressed and hover share background %q, so %v carries the whole distinction", pressed["background"], cues)
595 }
596}
597
598// The toolbar's option values are a vocabulary shared by three files:
599// this template, fixtures/toolbar.mjs, and core/src/fragment.rs's mark
600// names. A value here that the bundle does not understand is a control
601// that silently does nothing.
602func TestToolbarOptionValuesMatchTheBundle(t *testing.T) {
603 page, err := os.ReadFile("views/show.html")
604 if err != nil {
605 t.Fatal(err)
606 }
607 // The undo/redo pair (the bar's lead slot's and the strip's) and the
608 // menu bar's markup live in a partial since I2; its literal commands
609 // are held to the bundle too.
610 partial, err := os.ReadFile("views/partials/editor_bar.html")
611 if err != nil {
612 t.Fatal(err)
613 }
614 if !strings.Contains(string(partial), `data-docs-command="undo"`) || !strings.Contains(string(partial), `data-docs-command="redo"`) {
615 t.Fatal("views/partials/editor_bar.html renders no undo/redo pair")
616 }
617 page = append(append(page, '\n'), partial...)
618 bundle, err := os.ReadFile("../../fixtures/toolbar.mjs")
619 if err != nil {
620 t.Fatal(err)
621 }
622 entry, err := os.ReadFile("../../fixtures/editor-entry.js")
623 if err != nil {
624 t.Fatal(err)
625 }
626
627 menu, err := os.ReadFile("../../fixtures/menu.mjs")
628 if err != nil {
629 t.Fatal(err)
630 }
631
632 if !strings.Contains(string(page), "docs-toolbar") {
633 t.Fatal("views/show.html renders no toolbar")
634 }
635
636 // Every command the template names LITERALLY must be handled by one
637 // of the two modules that implement commands.
638 //
639 // "Literally" is the whole scope of this test, and it is worth
640 // being exact about, because the menu bar arriving made that limit
641 // load-bearing for the first time. This reads views/show.html as a
642 // FILE — the template source, not its output — so it only ever sees
643 // names written out in the markup. The toolbar's are
644 // (data-docs-command="strong"); the menu's are not, because
645 // menu.go builds the items and the template renders
646 // data-docs-command="{{.Command}}", which matches no name pattern
647 // at all.
648 //
649 // So this test says nothing whatever about the menu, and adding the
650 // menu bar did not make it fail — it made it silently skip an
651 // entire second surface while continuing to report success. That is
652 // the exact shape AGENTS.md warns about: a check that cannot
653 // distinguish "no" from "I looked at nothing". The menu's half of
654 // the property is checked in menu_test.go's
655 // TestMenuCommandsExistInTheBundle, driven from the Go model rather
656 // than from the markup, which is the only side that can see those
657 // names.
658 //
659 // The pattern is [\w-]+ rather than \w+ so that a hyphenated name
660 // written out literally in a future template edit (insert-link,
661 // insert-page-break) is checked rather than skipped, and
662 // data-docs-unavailable is honoured for the same reason: those
663 // items name commands nobody has built yet, and requiring them to
664 // exist would mean writing stubs — which is what turns "disabled
665 // because unbuilt" into "enabled and does nothing".
666 //
667 // fixtures/menu.mjs is searched alongside toolbar.mjs, for the
668 // commands that are not editor commands. Print is the only one.
669 tag := regexp.MustCompile(`<(?:button|a)[^>]*\sdata-docs-command="([\w-]+)"[^>]*>`)
670 for _, m := range tag.FindAllStringSubmatch(string(page), -1) {
671 if strings.Contains(m[0], "data-docs-unavailable") {
672 continue
673 }
674 if strings.Contains(string(bundle), m[1]) || strings.Contains(string(menu), m[1]) {
675 continue
676 }
677 t.Errorf("the template has a %q control that neither fixtures/toolbar.mjs nor fixtures/menu.mjs implements", m[1])
678 }
679 // Every mark the schema defines must be one core/src/fragment.rs
680 // renders — checked here rather than in Rust because this is the
681 // side that can drift silently: an unknown mark renders in the
682 // browser and vanishes for a reader with no JavaScript.
683 //
684 // The font marks are built from internal/fonts/fonts.json's
685 // families (fixtures/fonts.mjs's FAMILIES), one per key, so that is
686 // what is looked for; fragment.rs is tested against the same
687 // manifest in Rust.
688 // The schema lives in fixtures/schema.mjs now, which editor-entry.js
689 // mounts the editor with.
690 schemaSrc, err := os.ReadFile("../../fixtures/schema.mjs")
691 if err != nil {
692 t.Fatal(err)
693 }
694 if !strings.Contains(string(schemaSrc), `spanMark('docs-font-' + f.key, 'fontFamily')`) ||
695 !strings.Contains(string(schemaSrc), `spec.addToStart('font_' + f.key, mark)`) ||
696 !strings.Contains(string(schemaSrc), `import { FAMILIES`) ||
697 !strings.Contains(string(entry), `from './schema.mjs'`) {
698 t.Error("fixtures/schema.mjs no longer builds a font mark for every family in the manifest, or the editor no longer uses it")
699 }
700 // The size marks are NOT, and this clause moved rather than being
701 // deleted.
702 //
703 // They used to be three names written out in editor-entry.js beside
704 // the faces, and this loop found them there. The point ladder made
705 // that fourteen names whose class is mechanically the mark name, so
706 // the schema builds them from fixtures/sizes.mjs's SIZE_MARKS — and
707 // this loop stopped finding anything, which it reported honestly as
708 // three missing marks rather than passing while checking nothing.
709 // That is the better of the two failures and it is why the clause is
710 // worth keeping.
711 //
712 // So it looks where the vocabulary actually is now. The stronger
713 // version of this property — every size the editor can write is one
714 // Rust renders AND the exporter measures — is
715 // sizes_test.go's TestEverySizeMarkIsRenderedAndMeasured, which
716 // derives the list from that same file instead of restating it.
717 sizes, err := os.ReadFile("../../fixtures/sizes.mjs")
718 if err != nil {
719 t.Fatal(err)
720 }
721 for _, mark := range []string{"size_sm", "size_lg", "size_xl"} {
722 if !strings.Contains(string(sizes), mark) {
723 t.Errorf("fixtures/sizes.mjs no longer carries the legacy %q mark — every document using it loses its size on the next edit", mark)
724 }
725 }
726}
727
728// The toolbar's idea of the default face has to be the app's. Both read
729// internal/fonts/fonts.json now, so what is left to hold is the
730// scriptless case: a <select> shows its first option until something
731// sets a value, and with no JavaScript nothing ever does. Listing the
732// default anywhere but first means the control names a face the
733// document is not in, for every reader without scripting.
734func TestTheToolbarDefaultFontIsTheDefaultFace(t *testing.T) {
735 module, err := os.ReadFile("../../fixtures/fonts.mjs")
736 if err != nil {
737 t.Fatal(err)
738 }
739 if !strings.Contains(string(module), `import manifest from '../internal/fonts/fonts.json'`) ||
740 !strings.Contains(string(module), `export const DEFAULT_FONT = manifest.default`) {
741 t.Fatal("fixtures/fonts.mjs no longer reads its default from internal/fonts/fonts.json; the toolbar and the server can disagree")
742 }
743
744 app, err := NewForTest(t)
745 if err != nil {
746 t.Fatalf("NewForTest: %v", err)
747 }
748 doc := exportable(t, app, "toolbar@example.com", "Fonts")
749 body := serve(app, app.TestRequest(t, "toolbar@example.com", http.MethodGet, "/d/"+doc.Sqid, nil)).Body.String()
750
751 block := regexp.MustCompile(`(?s)data-docs-select="font"[^>]*>(.*?)</select>`).FindStringSubmatch(body)
752 if block == nil {
753 t.Fatal("the page renders no font select — the toolbar markup was restructured and this check can no longer see what it is checking")
754 }
755 options := regexp.MustCompile(`<option value="([^"]+)" data-rst-class="([^"]+)"`).FindAllStringSubmatch(block[1], -1)
756 if len(options) != len(fonts.Families) {
757 t.Fatalf("the font control offers %d faces, the manifest has %d", len(options), len(fonts.Families))
758 }
759 if got := options[0][1]; got != fonts.Default.Key || got != "carlito" {
760 t.Errorf("the font control shows %q before any script runs, internal/fonts lays an unmarked run out in %q", got, fonts.Default.Key)
761 }
762 if options[1][1] != "caladea" {
763 t.Errorf("Caladea is not second: %q", options[1][1])
764 }
765}
766
767// Paul, 2026-10-24: "the font dropdown must show each font in its own
768// face". Each option wears its family's preview class (ui/select.js puts
769// data-rst-class on the row and the closed box), the class is drawn in
770// that family's preview subset, and the subset is served.
771func TestEachPickerEntryIsInItsOwnFace(t *testing.T) {
772 app, err := NewForTest(t)
773 if err != nil {
774 t.Fatalf("NewForTest: %v", err)
775 }
776 doc := exportable(t, app, "picker@example.com", "Fonts")
777 body := serve(app, app.TestRequest(t, "picker@example.com", http.MethodGet, "/d/"+doc.Sqid, nil)).Body.String()
778 css := string(fonts.Stylesheet())
779 for _, f := range fonts.Families {
780 opt := regexp.MustCompile(`<option value="` + f.Key + `" data-rst-class="([^"]+)"[^>]*>([^<]+)</option>`).FindStringSubmatch(body)
781 if opt == nil {
782 t.Errorf("%s: no option", f.Name)
783 continue
784 }
785 if opt[1] != f.PreviewClass() {
786 t.Errorf("%s wears %q, want %q", f.Name, opt[1], f.PreviewClass())
787 }
788 if opt[2] != f.Name {
789 t.Errorf("%s is labelled %q, want its name and nothing else", f.Name, opt[2])
790 }
791 rule := regexp.MustCompile(`\[docs-toolbar\] \[rst-combo\] \.` + f.PreviewClass() + `\{font-family:"([^"]+)"`).FindStringSubmatch(css)
792 if rule == nil || rule[1] != f.PreviewCSSName() {
793 t.Errorf("%s: .%s is not drawn in its preview face (%v)", f.Name, f.PreviewClass(), rule)
794 }
795 face := regexp.MustCompile(`@font-face\{font-family:"` + f.PreviewCSSName() + `";src:url\("([^"]+)"\)`).FindStringSubmatch(css)
796 if face == nil {
797 t.Errorf("%s: no @font-face for its preview", f.Name)
798 continue
799 }
800 req, _ := http.NewRequest(http.MethodGet, face[1], nil)
801 if rec := serve(app, req); rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "font/woff2" {
802 t.Errorf("%s: preview %s served %d %q", f.Name, face[1], rec.Code, rec.Header().Get("Content-Type"))
803 }
804 }
805 // No entry says whose metrics it has (Paul, 2026-10-26: "We don't need
806 // to mention the compatibility"): no description for ui/select.js to
807 // draw, and no copy for one. Only the picker stops saying so: DOCX
808 // export and paste still write and read the Word name, docx.name
809 // (internal/fonts' TestDocxNames holds that).
810 sel := regexp.MustCompile(`(?s)<select[^>]*id="docs-select-font".*?</select>`).FindString(body)
811 if sel == "" {
812 t.Fatal("no font control")
813 }
814 if strings.Contains(sel, "data-rst-desc") || strings.Contains(sel, "data-rst-name") || strings.Contains(sel, "compatible") {
815 t.Errorf("a font entry carries a compatibility description: %s", sel)
816 }
817 if _, ok := Catalog["docs.editor.toolbar.font.compatible"]; ok {
818 t.Error("the catalog still carries the compatibility copy")
819 }
820}
821
822// Every face the stylesheet declares must be a face the app serves,
823// and it must actually serve it, as woff2.
824func TestFontFacesAreDeclaredAndServed(t *testing.T) {
825 app, err := NewForTest(t)
826 if err != nil {
827 t.Fatalf("NewForTest: %v", err)
828 }
829 doc := exportable(t, app, "reader@example.com", "Fonts")
830 body := serve(app, app.TestRequest(t, "reader@example.com", http.MethodGet, "/d/"+doc.Sqid, nil)).Body.String()
831 if !strings.Contains(body, `<link rel="stylesheet" href="`+fonts.StylesheetPath()+`">`) {
832 t.Fatal("the document page does not link the font stylesheet")
833 }
834 req, _ := http.NewRequest(http.MethodGet, fonts.StylesheetPath(), nil)
835 sheet := serve(app, req)
836 if sheet.Code != http.StatusOK || !strings.HasPrefix(sheet.Header().Get("Content-Type"), "text/css") {
837 t.Fatalf("the font stylesheet: %d %q", sheet.Code, sheet.Header().Get("Content-Type"))
838 }
839
840 paths := regexp.MustCompile(`font-family:"Docs [^"]+";src:url\("(/static/fonts/[^"]+)"\)`).FindAllStringSubmatch(sheet.Body.String(), -1)
841 if len(paths) != len(fonts.All())+len(fonts.Families) {
842 t.Fatalf("the stylesheet declares %d @font-face rules, want %d faces and %d previews", len(paths), len(fonts.All()), len(fonts.Families))
843 }
844 for _, p := range paths {
845 req, _ := http.NewRequest(http.MethodGet, p[1], nil)
846 rec := serve(app, req)
847 if rec.Code != http.StatusOK {
848 t.Errorf("%s: got %d", p[1], rec.Code)
849 continue
850 }
851 if ct := rec.Header().Get("Content-Type"); ct != "font/woff2" {
852 t.Errorf("%s: Content-Type is %q", p[1], ct)
853 }
854 if cc := rec.Header().Get("Cache-Control"); !strings.Contains(cc, "immutable") {
855 t.Errorf("%s: content-hashed assets should be immutable, got %q", p[1], cc)
856 }
857 if rec.Body.Len() < 1_000 {
858 t.Errorf("%s: served %d bytes, which is not a font", p[1], rec.Body.Len())
859 }
860 }
861
862 // The licences have to travel with the fonts, and be reachable.
863 for _, p := range fonts.LicencePaths() {
864 req, _ := http.NewRequest(http.MethodGet, p, nil)
865 if rec := serve(app, req); rec.Code != http.StatusOK || !strings.Contains(strings.ToUpper(rec.Body.String()), "OPEN FONT LICENSE") {
866 t.Errorf("the font licence is not served at %s (got %d)", p, rec.Code)
867 }
868 }
869}
870
871// A path under the font prefix that names no face must not be served —
872// and must fall through to the rest of /static rather than being
873// answered by the font handler at all.
874func TestUnknownFontPathIsNotServed(t *testing.T) {
875 app, err := NewForTest(t)
876 if err != nil {
877 t.Fatalf("NewForTest: %v", err)
878 }
879 for _, path := range []string{
880 fonts.PathPrefix + "nope.ttf",
881 fonts.PathPrefix + "../../../etc/passwd",
882 fonts.PathPrefix + "LiberationSerif-Regular.ttf", // real name, no hash
883 fonts.PathPrefix + "Carlito-Regular.woff2", // real name, no hash
884 } {
885 req, _ := http.NewRequest(http.MethodGet, path, nil)
886 if rec := serve(app, req); rec.Code == http.StatusOK {
887 t.Errorf("%s: served something (%d bytes)", path, rec.Body.Len())
888 }
889 }
890}
891
892func firstBytes(s string) string {
893 if len(s) > 40 {
894 return s[:40]
895 }
896 return s
897}
898