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 "html"
6 "net/http"
7 "regexp"
8 "sort"
9 "strings"
10 "testing"
11
12 "github.com/carlosframework/docs/internal/export"
13 "github.com/carlosframework/docs/internal/fonts"
14)
15
16// pageFonts is what a document page asks for: its preloads, and the
17// faces its gate waits for.
18func pageFonts(t *testing.T, body string) (preloads, need []string) {
19 t.Helper()
20 for _, m := range regexp.MustCompile(`<link rel="preload" as="font" type="font/woff2" crossorigin href="([^"]+)">`).FindAllStringSubmatch(body, -1) {
21 preloads = append(preloads, m[1])
22 }
23 m := regexp.MustCompile(`data-docs-fonts-need="([^"]*)"`).FindStringSubmatch(body)
24 if m == nil {
25 t.Fatal("the canvas carries no data-docs-fonts-need: the gate has nothing to wait for and the sheet would stay hidden")
26 }
27 for _, f := range regexp.MustCompile(`\{"key":"([a-z]+)","family":"([^"]+)","weight":(\d+),"style":"([a-z]+)"\}`).FindAllStringSubmatch(html.UnescapeString(m[1]), -1) {
28 need = append(need, f[2]+" "+f[3]+" "+f[4])
29 }
30 sort.Strings(preloads)
31 sort.Strings(need)
32 return preloads, need
33}
34
35func facePath(t *testing.T, key string, bold, italic bool) string {
36 t.Helper()
37 f, ok := fonts.ByKey(key)
38 if !ok {
39 t.Fatalf("no family %s", key)
40 }
41 return f.Face(bold, italic).Path
42}
43
44func sorted(s ...string) []string {
45 sort.Strings(s)
46 return s
47}
48
49// Paul, 2026-10-24: new documents are in Carlito. A new, empty document
50// shows a caret in Carlito regular, so that is the one face its page
51// preloads and waits for; a writer's page also preloads Carlito's
52// picker preview, which the closed font control is drawn in.
53func TestANewDocumentIsInCarlito(t *testing.T) {
54 app, err := NewForTest(t)
55 if err != nil {
56 t.Fatal(err)
57 }
58 doc, err := app.Store().Create(context.Background(), app.TestPerson(t, "new@example.com"), "New")
59 if err != nil {
60 t.Fatal(err)
61 }
62 body := serve(app, app.TestRequest(t, "new@example.com", http.MethodGet, "/d/"+doc.Sqid, nil)).Body.String()
63 preloads, need := pageFonts(t, body)
64 carlito, _ := fonts.ByKey("carlito")
65 // Every style of the family, not just the face the caret is in
66 // (branch review 4: gate on families, not faces).
67 want := sorted(facePath(t, "carlito", false, false), facePath(t, "carlito", true, false),
68 facePath(t, "carlito", false, true), facePath(t, "carlito", true, true), carlito.PreviewPath())
69 if strings.Join(preloads, " ") != strings.Join(want, " ") {
70 t.Errorf("a new document preloads %v, want %v", preloads, want)
71 }
72 var docNeed []string
73 for _, n := range need {
74 if !strings.HasPrefix(n, "Docs Preview ") {
75 docNeed = append(docNeed, n)
76 }
77 }
78 if w := sorted("Docs Carlito 400 normal", "Docs Carlito 700 normal", "Docs Carlito 400 italic", "Docs Carlito 700 italic"); strings.Join(docNeed, ", ") != strings.Join(w, ", ") {
79 t.Errorf("a new document's gate waits for %v, want all four of Carlito's styles", docNeed)
80 }
81 if !strings.Contains(string(fonts.Stylesheet()), `[docs-text]{font-family:"Docs Carlito"`) {
82 t.Error("[docs-text] is not set in Carlito")
83 }
84}
85
86// Each document page gates on exactly the families it uses, every style
87// of each, and preloads the faces that draw its text first: faces.bin is
88// a heading, bold, italic, code and a Caladea run, so Carlito, Caladea
89// and Liberation Mono, all twelve of their faces, of which the five that
90// draw text are preloaded, then one more to the cap. The gate also waits
91// for every family's preview. A reader's page is the same: it shows the
92// same (disabled) font control.
93func TestADocumentPagePreloadsExactlyTheFacesItUses(t *testing.T) {
94 app, err := NewForTestWith(t, Config{AllowedAddresses: "owner@example.com,reader@example.com"})
95 if err != nil {
96 t.Fatal(err)
97 }
98 ctx := context.Background()
99 doc, err := app.Store().Create(ctx, app.TestPerson(t, "owner@example.com"), "Faces")
100 if err != nil {
101 t.Fatal(err)
102 }
103 if _, err := app.Store().ApplyUpdate(ctx, doc, app.TestActorFor(t, doc), readFixture(t, "../../fixtures/vectors/fragment/faces.bin")); err != nil {
104 t.Fatal(err)
105 }
106 if err := app.Store().Grant(ctx, doc.OwnerID, doc.Sqid, "reader@example.com", RoleReader); err != nil {
107 t.Fatal(err)
108 }
109 drawing := []string{
110 facePath(t, "carlito", false, false),
111 facePath(t, "carlito", true, false),
112 facePath(t, "carlito", false, true),
113 facePath(t, "mono", false, false),
114 facePath(t, "caladea", false, false),
115 }
116 var wantNeed []string
117 for _, n := range []string{"Docs Carlito", "Docs Caladea", "Docs Liberation Mono"} {
118 wantNeed = append(wantNeed, n+" 400 normal", n+" 700 normal", n+" 400 italic", n+" 700 italic")
119 }
120 sort.Strings(wantNeed)
121 var writer string
122 for _, who := range []string{"owner@example.com", "reader@example.com"} {
123 body := serve(app, app.TestRequest(t, who, http.MethodGet, "/d/"+doc.Sqid, nil)).Body.String()
124 if who == "owner@example.com" {
125 writer = body
126 }
127 preloads, need := pageFonts(t, body)
128 if len(preloads) != maxPreloads {
129 t.Errorf("%s's page preloads %d faces, want the cap of %d", who, len(preloads), maxPreloads)
130 }
131 for _, p := range drawing {
132 if !strings.Contains(strings.Join(preloads, " "), p) {
133 t.Errorf("%s's page does not preload %s, which draws its text", who, p)
134 }
135 }
136 var doc []string
137 previews := 0
138 for _, n := range need {
139 if strings.HasPrefix(n, "Docs Preview ") {
140 previews++
141 } else {
142 doc = append(doc, n)
143 }
144 }
145 if strings.Join(doc, ", ") != strings.Join(wantNeed, ", ") {
146 t.Errorf("%s's gate waits for %v, want %v", who, doc, wantNeed)
147 }
148 if previews != len(fonts.Families) {
149 t.Errorf("%s's gate waits for %d previews, want one per family (%d)", who, previews, len(fonts.Families))
150 }
151 }
152
153 // The preloads come before every stylesheet, so they start with the
154 // page; and the sheet is rendered held.
155 head := writer[:strings.Index(writer, "</head>")]
156 if i, j := strings.Index(head, `rel="preload"`), strings.Index(head, `rel="stylesheet"`); i < 0 || j < i {
157 t.Error("the font preloads are not ahead of the stylesheets")
158 }
159 // The hold is never rendered by the server, only set by the blocking
160 // script in <head> (fixtures/fonts-hold.js), so a reader without
161 // JavaScript is never held; and the font rules add no inline style
162 // (review finding 7).
163 if strings.Contains(writer, `data-docs-fonts="pending"`) || strings.Contains(head, "<noscript") {
164 t.Error("the page is rendered held, or relies on a noscript style to undo it")
165 }
166 hold := `<script src="` + fontsHoldScriptPath() + `"></script>`
167 if i, j := strings.Index(head, `<link rel="stylesheet" href="`+fonts.StylesheetPath()+`">`), strings.Index(head, hold); i < 0 || j < i {
168 t.Error("the hold script is not a blocking script in <head> after the font stylesheet")
169 }
170 if strings.Contains(head, hold[:len(hold)-len("></script>")]+` defer`) || strings.Contains(head, hold[:len(hold)-len("></script>")]+` async`) {
171 t.Error("the hold script must block the first paint")
172 }
173}
174
175// The cap: a document in more faces than are worth preloading preloads
176// the ones setting the most text, and the gate still waits for all.
177func TestThePreloadsAreCapped(t *testing.T) {
178 g := newFontGate(mustStructure(t, `{"type":"doc","content":[{"type":"paragraph","content":[`+
179 `{"type":"text","text":"a much longer run of plain text here"},`+
180 `{"type":"text","text":"b","marks":[{"type":"font_inter"}]},`+
181 `{"type":"text","text":"c","marks":[{"type":"font_literata"}]},`+
182 `{"type":"text","text":"d","marks":[{"type":"font_zilla"}]},`+
183 `{"type":"text","text":"e","marks":[{"type":"font_caveat"}]},`+
184 `{"type":"text","text":"f","marks":[{"type":"font_playfair"}]},`+
185 `{"type":"text","text":"g","marks":[{"type":"font_notosans"}]},`+
186 `{"type":"text","text":"h","marks":[{"type":"font_garamond"}]}]}]}`))
187 if len(g.Preloads) != maxPreloads {
188 t.Fatalf("%d preloads, want the cap of %d", len(g.Preloads), maxPreloads)
189 }
190 if g.Preloads[0] != facePath(t, "carlito", false, false) {
191 t.Errorf("the face setting the most text is not first: %v", g.Preloads)
192 }
193 // Eight families, each with all its styles (Caveat has two).
194 if n := strings.Count(g.Need, `"key"`) - strings.Count(g.Need, `"previews"`); n != 7*4+2 {
195 t.Errorf("the gate waits for %d document faces, want every style of all eight families (30)", n)
196 }
197}
198
199func mustStructure(t *testing.T, js string) export.Document {
200 t.Helper()
201 doc, err := export.Parse("", js)
202 if err != nil {
203 t.Fatal(err)
204 }
205 return doc
206}
207