oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1package slidestest
2
3import (
4 "encoding/json"
5 "fmt"
6 "html"
7 "net/http"
8 "regexp"
9 "strings"
10 "testing"
11)
12
13// The font gate's server half (internal/slides/fontgate.go): which
14// pages carry it, and what they preload. The browser half — that the
15// slides are then never painted in a face they will leave — is
16// fonts_browser_test.go.
17
18// opsDeck makes a deck over the API with the given batch and returns
19// its viewer path.
20func opsDeck(t *testing.T, a *testApp, token, title, ops string) string {
21 t.Helper()
22 sqid := apiDeck(t, a, token, title)
23 apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":`+ops+`}`, http.StatusOK)
24 return "/d/" + sqid
25}
26
27var (
28 preloadTag = regexp.MustCompile(`<link rel="preload"[^>]*>`)
29 preloadHref = regexp.MustCompile(`href="([^"]+)"`)
30 deckFaceURL = regexp.MustCompile(`^/static/fonts/Liberation(Sans|Serif|Mono)-(Regular|Bold|Italic|BoldItalic)\.[0-9a-f]{16}\.woff2$`)
31 // A deck's own font, under the surface's base (deckfonts.go).
32 uploadedFaceURL = regexp.MustCompile(`^/(d|s|p)/[^/]+/fonts/[0-9a-f]{64}$`)
33 holdScript = regexp.MustCompile(`<script src="/static/fontshold\.[0-9a-f]{16}(\.[0-9a-f]{16})?\.js"></script>`)
34 gateScript = regexp.MustCompile(`<script type="module" src="/static/fontsgate\.[0-9a-f]{16}(\.[0-9a-f]{16})?\.js"></script>`)
35 firstSheet = regexp.MustCompile(`<link rel="stylesheet"`)
36 heldByServer = regexp.MustCompile(`data-slides-fonts=`)
37)
38
39// gateOn reports what a page carries of the gate, and fails on any
40// part of it that is malformed.
41func gateOn(t *testing.T, where, page string) (preloads []string, carries bool) {
42 t.Helper()
43 head, _, _ := strings.Cut(page, "</head>")
44 for _, tag := range preloadTag.FindAllString(page, -1) {
45 if !strings.Contains(head, tag) {
46 t.Errorf("%s: a preload outside <head>: %s", where, tag)
47 }
48 m := preloadHref.FindStringSubmatch(tag)
49 if m == nil || !deckFaceURL.MatchString(m[1]) && !uploadedFaceURL.MatchString(m[1]) {
50 t.Errorf("%s: %s preloads something that is not one of the deck's faces", where, tag)
51 continue
52 }
53 kind := `type="font/woff2"`
54 if uploadedFaceURL.MatchString(m[1]) {
55 kind = `type="font/`
56 }
57 if !strings.Contains(tag, `as="font"`) || !strings.Contains(tag, kind) || !strings.Contains(tag, " crossorigin") {
58 t.Errorf("%s: %s is not a CORS font preload of its type (without crossorigin it is a second download)", where, tag)
59 }
60 preloads = append(preloads, m[1])
61 }
62 _, hasManifest := readManifest(t, page)
63 hold := holdScript.FindStringIndex(head)
64 gate := gateScript.FindStringIndex(head)
65 sheet := firstSheet.FindStringIndex(head)
66 if heldByServer.MatchString(page) {
67 t.Errorf("%s: the server rendered the hold; a page with no script must never be held", where)
68 }
69 carries = hasManifest || hold != nil || gate != nil || len(preloads) > 0
70 if !carries {
71 return nil, false
72 }
73 if !hasManifest || hold == nil || gate == nil {
74 t.Errorf("%s: half a gate (manifest %v, hold %v, gate %v)", where, hasManifest, hold != nil, gate != nil)
75 return preloads, true
76 }
77 // Ahead of every stylesheet, so the fonts start with the page and
78 // the hold runs before anything can be painted.
79 if sheet == nil || hold[0] > sheet[0] || gate[0] > sheet[0] {
80 t.Errorf("%s: the hold and the gate must come before the first stylesheet", where)
81 }
82 for _, tag := range preloadTag.FindAllStringIndex(head, -1) {
83 if sheet != nil && tag[0] > sheet[0] {
84 t.Errorf("%s: a preload after the first stylesheet", where)
85 }
86 }
87 return preloads, true
88}
89
90// Every page that draws a slide in the deck's faces carries the gate —
91// the viewer in each of its modes, the projector, the follow view and
92// the editor, and the presenter window, whose slides are live — and no
93// other page does. The remote shows its slides as pictures and its
94// notes in the chrome's face, so there is nothing on it a web face
95// could reach.
96func TestOnlySlideSurfacesCarryTheGateAndPreloadOnlyDeckFaces(t *testing.T) {
97 a := newApp(t)
98 cookies := signedIn(t, a, allowedAddress)
99 list := mustGet(t, a, "/", http.StatusOK, cookies).Body.String()
100 deck := deckPath.FindString(list)
101 if deck == "" {
102 t.Fatal("the sample deck is not on the list")
103 }
104 share := "/s/" + mintShareLink(t, a, deck, cookies)
105 session, token := startPresenting(t, a, deck, cookies)
106
107 for _, c := range []struct {
108 path string
109 cookies []*http.Cookie
110 gated bool
111 }{
112 {deck + "?slide=1", cookies, true},
113 {deck + "?slide=2&vp=phone", cookies, true},
114 {deck + "?present=1", cookies, true},
115 {deck + "/edit", cookies, true},
116 {share, nil, true},
117 {share + "?present=1", nil, true},
118 {share + "?follow=1", nil, true},
119 {"/p/" + session, nil, true},
120 {"/p/" + session + "?t=" + token, nil, true},
121 {"/p/" + session + "/notes?t=" + token, nil, true},
122 {"/p/" + session + "/remote?t=" + token, nil, false},
123 {"/", cookies, false},
124 {"/signin", nil, false},
125 {deck + "/settings", cookies, false},
126 {deck + "/notes", cookies, false},
127 {deck + "/share", cookies, false},
128 } {
129 page := mustGet(t, a, c.path, http.StatusOK, c.cookies).Body.String()
130 preloads, carries := gateOn(t, c.path, page)
131 if carries != c.gated {
132 t.Errorf("%s: carries the font gate = %v, want %v", c.path, carries, c.gated)
133 }
134 // The sample deck is on paper, with code marks in it: every
135 // style of all three families, exactly once each.
136 if c.gated && len(preloads) != 12 {
137 t.Errorf("%s: %d preloads, want the sample deck's three families × four styles", c.path, len(preloads))
138 }
139 }
140}
141
142// The preloads are exact: every style of every family the deck's slides
143// can be drawn in (render.FamiliesUsed), on every slide of the deck and
144// not only the one shown, and nothing else. The manifest's need is the
145// same families.
146func TestThePreloadsAreEveryStyleOfEveryFamilyTheDeckUses(t *testing.T) {
147 a := newApp(t)
148 cookies := signedIn(t, a, allowedAddress)
149 token := mintAgent(t, a, cookies, "fonts")
150 code := `{"op":"add_block","slide":"s3","type":"code","region":"body","markdown":"x := 1"}`
151 slides := `{"op":"add_slide","id":"s1","layout":"flow","template":"title-body"},` +
152 `{"op":"add_block","slide":"s1","type":"heading","region":"heading","props":{"level":1},"markdown":"Hello"},` +
153 `{"op":"add_slide","id":"s2","layout":"flow"},{"op":"add_slide","id":"s3","layout":"flow"}`
154 for _, c := range []struct {
155 name, ops string
156 want []string
157 }{
158 {"ink", `[{"op":"set_meta","theme":"ink"},` + slides + `]`, []string{"sans"}},
159 {"paper", `[{"op":"set_meta","theme":"paper"},` + slides + `]`, []string{"sans", "serif"}},
160 {"code on a later slide", `[{"op":"set_meta","theme":"ink"},` + slides + `,` + code + `]`, []string{"sans", "mono"}},
161 {"inline code", `[{"op":"set_meta","theme":"slate"},` + slides + `,{"op":"add_block","slide":"s2","type":"text","region":"body","markdown":"run ` + "`go test`" + `"}]`, []string{"sans", "mono"}},
162 {"system heading on paper", `[{"op":"set_meta","theme":"paper","fonts":{"heading":"system-ui, sans-serif","body":""}},` + slides + `]`, []string{"sans"}},
163 {"system faces only", `[{"op":"set_meta","theme":"paper","fonts":{"heading":"Georgia, serif","body":"system-ui, sans-serif"}},` + slides + `]`, nil},
164 } {
165 t.Run(c.name, func(t *testing.T) {
166 deck := opsDeck(t, a, token, c.name, c.ops)
167 for _, path := range []string{deck, deck + "/edit"} {
168 page := mustGet(t, a, path+"?slide=1", http.StatusOK, cookies).Body.String()
169 preloads, carries := gateOn(t, path, page)
170 if !carries {
171 t.Fatalf("%s carries no gate", path)
172 }
173 m, _ := readManifest(t, page)
174 if strings.Join(m.Need, " ") != strings.Join(c.want, " ") {
175 t.Errorf("%s: the gate waits for %v, want %v", path, m.Need, c.want)
176 }
177 var want []string
178 for _, key := range c.want {
179 for _, f := range m.Families[key].Faces {
180 want = append(want, f.URL)
181 }
182 }
183 if strings.Join(preloads, " ") != strings.Join(want, " ") {
184 t.Errorf("%s: preloads\n %v\nwant every style of %v:\n %v", path, preloads, c.want, want)
185 }
186 }
187 })
188 }
189}
190
191// The follow view's heartbeat is for a reader with no scripts. With
192// them, present.js follows the stream and swaps the slide in place; a
193// reload every five seconds would blink the follower's slide.
194func TestTheFollowViewRefreshesOnlyWithoutScripts(t *testing.T) {
195 a := newApp(t)
196 cookies := signedIn(t, a, allowedAddress)
197 deck := deckPath.FindString(mustGet(t, a, "/", http.StatusOK, cookies).Body.String())
198 share := "/s/" + mintShareLink(t, a, deck, cookies)
199 startPresenting(t, a, deck, cookies)
200 page := mustGet(t, a, share+"?follow=1", http.StatusOK, nil).Body.String()
201 if !strings.Contains(page, `<noscript><meta http-equiv="refresh" content="5"></noscript>`) {
202 t.Errorf("the follow view's refresh is not inside a <noscript>:\n%s", page)
203 }
204}
205
206// uploadedDeck is a paper deck whose headings lead with an uploaded
207// family of two faces — a static TrueType regular and a variable WOFF2
208// italic — and which lists a second family nothing uses. The manifest
209// does not read the files, so the refs need not be served.
210func uploadedDeck(t *testing.T, a *testApp, token string) string {
211 t.Helper()
212 files := `[{"family":"Oddity Sans™ 2","css":"Oddity Sans 2","faces":[` +
213 `{"ref":"` + strings.Repeat("a", 64) + `","format":"ttf","weight":[400,400],"italic":false,"pictures":true},` +
214 `{"ref":"` + strings.Repeat("b", 64) + `","format":"woff2","weight":[100,900],"italic":true,"pictures":false}]},` +
215 `{"family":"Unused","css":"Unused Face","faces":[` +
216 `{"ref":"` + strings.Repeat("c", 64) + `","format":"otf","weight":[700,700],"italic":false,"pictures":false}]}]`
217 return opsDeck(t, a, token, "Uploaded", `[{"op":"set_meta","theme":"paper","fontFiles":`+files+
218 `,"fonts":{"heading":"'Oddity Sans 2', Liberation Serif, Georgia, serif","body":""}},`+
219 `{"op":"add_slide","id":"s1","layout":"flow","template":"title-body"},`+
220 `{"op":"add_block","slide":"s1","type":"heading","region":"heading","props":{"level":1},"markdown":"Hello"}]`)
221}
222
223// The manifest lists the deck's uploaded faces beside the catalog's, on
224// every surface, each at that surface's own base: the editor and the
225// viewer under /d/{sqid}, a share link and its follow view under
226// /s/{token}, the projector and the presenter window under
227// /p/{session}. A variable face declares its weight range, each face its
228// format. The gate waits for, and the page preloads, the uploaded
229// family the deck's stacks lead with, and not the one it only lists.
230func TestTheManifestListsTheDecksUploadedFaces(t *testing.T) {
231 a := newApp(t)
232 cookies := signedIn(t, a, allowedAddress)
233 token := mintAgent(t, a, cookies, "fonts")
234 deck := uploadedDeck(t, a, token)
235 share := "/s/" + mintShareLink(t, a, deck, cookies)
236 session, ptoken := startPresenting(t, a, deck, cookies)
237 a64, b64, c64 := strings.Repeat("a", 64), strings.Repeat("b", 64), strings.Repeat("c", 64)
238
239 for _, c := range []struct {
240 path, base string
241 cookies []*http.Cookie
242 }{
243 {deck + "?slide=1", deck, cookies},
244 {deck + "/edit", deck, cookies},
245 {share, share, nil},
246 {share + "?follow=1", share, nil},
247 {"/p/" + session, "/p/" + session, nil},
248 {"/p/" + session + "/notes?t=" + ptoken, "/p/" + session, nil},
249 } {
250 page := mustGet(t, a, c.path, http.StatusOK, c.cookies).Body.String()
251 preloads, carries := gateOn(t, c.path, page)
252 if !carries {
253 t.Errorf("%s carries no gate", c.path)
254 continue
255 }
256 m, _ := readManifest(t, page)
257 type face struct{ weight, style, url, format string }
258 got := map[string][]face{}
259 for key, fam := range m.Uploaded {
260 if fam.CSS != strings.TrimPrefix(key, "u:") {
261 t.Errorf("%s: %s has css %q", c.path, key, fam.CSS)
262 }
263 for _, f := range fam.Faces {
264 got[key] = append(got[key], face{string(f.Weight), f.Style, f.URL, f.Format})
265 }
266 }
267 want := map[string][]face{
268 "u:Oddity Sans 2": {
269 {"400", "normal", c.base + "/fonts/" + a64, "truetype"},
270 {`"100 900"`, "italic", c.base + "/fonts/" + b64, "woff2"},
271 },
272 "u:Unused Face": {{"700", "normal", c.base + "/fonts/" + c64, "opentype"}},
273 }
274 if fmt.Sprint(got) != fmt.Sprint(want) {
275 t.Errorf("%s: the uploaded faces are\n %v\nwant\n %v", c.path, got, want)
276 }
277 if strings.Join(m.Need, " ") != "sans serif u:Oddity Sans 2" {
278 t.Errorf("%s: the gate waits for %q", c.path, m.Need)
279 }
280 var wantPreloads []string
281 for _, key := range []string{"sans", "serif"} {
282 for _, f := range m.Families[key].Faces {
283 wantPreloads = append(wantPreloads, f.URL)
284 }
285 }
286 wantPreloads = append(wantPreloads, c.base+"/fonts/"+a64, c.base+"/fonts/"+b64)
287 if strings.Join(preloads, " ") != strings.Join(wantPreloads, " ") {
288 t.Errorf("%s: preloads\n %v\nwant\n %v", c.path, preloads, wantPreloads)
289 }
290 for url, typ := range map[string]string{c.base + "/fonts/" + a64: "font/ttf", c.base + "/fonts/" + b64: "font/woff2"} {
291 if !strings.Contains(page, `<link rel="preload" as="font" type="`+typ+`" crossorigin href="`+url+`">`) {
292 t.Errorf("%s: no %s preload of %s", c.path, typ, url)
293 }
294 }
295 }
296}
297
298// legacyManifest is the manifest as it was before decks had fonts of
299// their own, field for field and in order.
300type legacyManifest struct {
301 Need []string `json:"need"`
302 Families map[string]struct {
303 CSS string `json:"css"`
304 Faces []struct {
305 Weight int `json:"weight"`
306 Style string `json:"style"`
307 URL string `json:"url"`
308 } `json:"faces"`
309 } `json:"families"`
310 Themes map[string][2]string `json:"themes"`
311 DefaultTheme string `json:"defaultTheme"`
312 Code string `json:"code"`
313}
314
315// A deck with no fonts of its own carries the manifest byte for byte as
316// before: nothing in it that the old shape does not have, nothing
317// spelled differently, and its preloads in the old form.
318func TestAnExistingDecksManifestIsUnchanged(t *testing.T) {
319 a, deck, cookies := sampleViewer(t)
320 for _, path := range []string{deck + "?slide=1", deck + "/edit"} {
321 page := mustGet(t, a, path, http.StatusOK, cookies).Body.String()
322 raw := manifestMeta.FindStringSubmatch(page)
323 if raw == nil {
324 t.Fatalf("%s carries no manifest", path)
325 }
326 content := html.UnescapeString(raw[1])
327 dec := json.NewDecoder(strings.NewReader(content))
328 dec.DisallowUnknownFields()
329 var old legacyManifest
330 if err := dec.Decode(&old); err != nil {
331 t.Fatalf("%s: the manifest is not the old shape: %v", path, err)
332 }
333 again, err := json.Marshal(old)
334 if err != nil {
335 t.Fatal(err)
336 }
337 if string(again) != content {
338 t.Errorf("%s: the manifest is\n %s\nthe old shape writes\n %s", path, content, again)
339 }
340 for _, tag := range preloadTag.FindAllString(page, -1) {
341 if !regexp.MustCompile(`^<link rel="preload" as="font" type="font/woff2" crossorigin href="/static/fonts/[^"]+">$`).MatchString(tag) {
342 t.Errorf("%s: %s is not the old preload", path, tag)
343 }
344 }
345 }
346}
347