oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package fonts is CARLOS Docs' font set: the same font programs the
2// browser renders a document with, the PDF exporter embeds, and the Mac
3// app bundles, so all three measure identically.
4//
5// "Identically" is spec §11.1's requirement. A document that paginates
6// one way on screen and another in its own PDF is two documents.
7//
8// # One manifest
9//
10// fonts.json is the whole vocabulary: each family's key (its mark is
11// font_<key>), its name, its category, its Word name, its fallback stack
12// and its files. This package embeds and reads it. fixtures/fonts.mjs
13// imports the same file into the editor bundle, core/src/fragment.rs is
14// tested against it, and scripts/vendor-fonts.py builds files/ from it.
15// Adding a family is a manifest entry, a vendoring run and a MARKS row.
16//
17// # The default carries no mark
18//
19// An unmarked run is in the manifest's "default" family, Carlito
20// (Paul's ruling, 2026-10-24: Calibri's metrics, so a document breaks
21// lines in Word the way it does here). Moving the default moves every
22// unmarked run in every document. The keys sans, serif and mono are
23// Liberation Sans, Serif and Mono, as they were before there were more
24// than three; old documents carrying those marks keep their faces.
25//
26// # Files
27//
28// Every style is two files cut from one static instance: a TrueType file
29// (files/<dir>/<name>.ttf), which the PDF exporter parses and subsets,
30// and a woff2 of exactly that file, which is all the browser is served.
31// woff2 is lossless, so the glyphs and advances are the same program.
32// Each family also has a name-only preview subset for the picker,
33// renamed "Docs Preview NN" because a subset is a modified font and
34// several of these licences reserve the family's name.
35package fonts
36
37import (
38 "bytes"
39 "crypto/sha256"
40 "embed"
41 "encoding/hex"
42 "encoding/json"
43 "fmt"
44 "io/fs"
45 "path"
46 "sort"
47 "strings"
48)
49
50//go:embed fonts.json
51var manifestJSON []byte
52
53//go:embed files
54var files embed.FS
55
56// Style is one of a family's four faces.
57type Style uint8
58
59const (
60 Regular Style = iota
61 Bold
62 Italic
63 BoldItalic
64)
65
66var styleNames = map[string]Style{"regular": Regular, "bold": Bold, "italic": Italic, "boldItalic": BoldItalic}
67
68// StyleOf is the style for a weight and slope.
69func StyleOf(bold, italic bool) Style {
70 switch {
71 case bold && italic:
72 return BoldItalic
73 case bold:
74 return Bold
75 case italic:
76 return Italic
77 }
78 return Regular
79}
80
81func (s Style) Bold() bool { return s == Bold || s == BoldItalic }
82func (s Style) Italic() bool { return s == Italic || s == BoldItalic }
83
84// Weight and CSSStyle are the @font-face descriptors.
85func (s Style) Weight() int {
86 if s.Bold() {
87 return 700
88 }
89 return 400
90}
91
92func (s Style) CSSStyle() string {
93 if s.Italic() {
94 return "italic"
95 }
96 return "normal"
97}
98
99// Code is the short name the page and the editor use for a style:
100// r, b, i, bi.
101func (s Style) Code() string { return [...]string{"r", "b", "i", "bi"}[s] }
102
103// Docx is how a family is written into a .docx (fontTable.xml).
104type Docx struct {
105 Name string `json:"name"`
106 Family string `json:"family"`
107 Pitch string `json:"pitch"`
108 Panose string `json:"panose"`
109 AltName string `json:"altName"`
110}
111
112// Family is one typeface.
113type Family struct {
114 Key string
115 Name string
116 Category string
117 // Twin is the proprietary face this one is metric-compatible with,
118 // if any (Carlito: Calibri), for Help → Fonts to name. DOCX export and
119 // paste name the Word face through Docx.Name, not this.
120 Twin string
121 // Reserved is the OFL Reserved Font Name, if the licence has one.
122 // Such a family is vendored from its authors' files unchanged.
123 Reserved string
124 Docx Docx
125 // Fallback is the CSS stack a page commits to when this family has
126 // not arrived in time (NO-FOUT §2). It never includes the private
127 // name, so a font that arrives late is never swapped in.
128 Fallback []string
129
130 // Index is the family's position in the manifest, from 1. The
131 // preview subset is named after it.
132 Index int
133
134 faces [4]*Face
135 licence asset
136 preview asset
137}
138
139// Mark is the CRDT mark that selects this family.
140func (f *Family) Mark() string { return "font_" + f.Key }
141
142// Class is the class core/src/fragment.rs and the editor put on a run
143// carrying the mark.
144func (f *Family) Class() string { return "docs-font-" + f.Key }
145
146// CSSName is the private family name the stylesheet declares. Not the
147// real name, so a reader's locally installed copy (another version,
148// other metrics) can never win the match.
149func (f *Family) CSSName() string { return "Docs " + f.Name }
150
151// PreviewCSSName is the picker preview's family name. A separate name,
152// so a subset holding a dozen glyphs can never satisfy document text.
153func (f *Family) PreviewCSSName() string { return fmt.Sprintf("Docs Preview %02d", f.Index) }
154
155// PreviewClass is the class a picker row wears to be drawn in its face.
156func (f *Family) PreviewClass() string { return "docs-preview-" + f.Key }
157
158// PreviewPath is the preview subset's URL.
159func (f *Family) PreviewPath() string { return f.preview.path }
160
161// Monospace reports whether the family is fixed-pitch.
162func (f *Family) Monospace() bool { return f.Category == "mono" }
163
164// Serif reports whether the family has serifs, for the PDF descriptor.
165func (f *Family) Serif() bool {
166 return f.Category == "serif" || f.Category == "slab" || f.Category == "display"
167}
168
169// Has reports whether the family has a real face for the style. Caveat
170// has no italic.
171func (f *Family) Has(s Style) bool { return f.faces[s] != nil }
172
173// Styles is every style the family has.
174func (f *Family) Styles() []Style {
175 var out []Style
176 for s := Regular; s <= BoldItalic; s++ {
177 if f.Has(s) {
178 out = append(out, s)
179 }
180 }
181 return out
182}
183
184// Face is the face for a weight and slope. A family without an italic
185// stays upright, on screen (font-synthesis: none) and here alike.
186func (f *Family) Face(bold, italic bool) *Face {
187 if face := f.faces[StyleOf(bold, italic)]; face != nil {
188 return face
189 }
190 if face := f.faces[StyleOf(bold, false)]; face != nil {
191 return face
192 }
193 return f.faces[Regular]
194}
195
196// FallbackCSS is Fallback as a font-family value.
197func (f *Family) FallbackCSS() string { return cssFamilies(f.Fallback) }
198
199// Face is one font program.
200type Face struct {
201 Family *Family
202 Style Style
203
204 // File is the TrueType file inside files/ ("carlito/Carlito-Regular.ttf").
205 File string
206 // Path is the woff2's served URL, content-hashed, so it can be cached
207 // as immutable.
208 Path string
209
210 // Data is the TrueType program; Web is the woff2 of it.
211 Data []byte
212 Web []byte
213}
214
215func (f *Face) Bold() bool { return f.Style.Bold() }
216func (f *Face) Italic() bool { return f.Style.Italic() }
217
218// ID names the face to the page's font gate: "carlito:b".
219func (f *Face) ID() string { return f.Family.Key + ":" + f.Style.Code() }
220
221// PostScriptName is the face's name inside a PDF. Its file's name, which
222// is the authors' own PostScript name for every family vendored here.
223func (f *Face) PostScriptName() string {
224 return strings.TrimSuffix(path.Base(f.File), ".ttf")
225}
226
227// asset is one served file that is not a face.
228type asset struct {
229 path string
230 contentType string
231 data []byte
232}
233
234var (
235 // Families is every family, in the picker's order.
236 Families []*Family
237 // Default is what an unmarked run is set in.
238 Default *Family
239 // Code is the family a code run is set in.
240 Code *Family
241
242 byKey = map[string]*Family{}
243 byDocx = map[string]*Family{}
244 byPath = map[string]*Face{}
245 assets = map[string]asset{}
246 faces []*Face
247 cssPath string
248)
249
250// PathPrefix is where the app serves this package's files.
251const PathPrefix = "/static/fonts/"
252
253type manifest struct {
254 Default string `json:"default"`
255 Code string `json:"code"`
256 Families []struct {
257 Key string `json:"key"`
258 Name string `json:"name"`
259 Category string `json:"category"`
260 Twin string `json:"twin"`
261 Reserved string `json:"reserved"`
262 Docx Docx `json:"docx"`
263 Fallback []string `json:"fallback"`
264 Dir string `json:"dir"`
265 Licence string `json:"licence"`
266 Styles map[string]string `json:"styles"`
267 } `json:"families"`
268}
269
270func init() {
271 var m manifest
272 if err := json.Unmarshal(manifestJSON, &m); err != nil {
273 panic(fmt.Sprintf("fonts: fonts.json: %v", err))
274 }
275 for i, mf := range m.Families {
276 f := &Family{
277 Key: mf.Key, Name: mf.Name, Category: mf.Category, Twin: mf.Twin,
278 Reserved: mf.Reserved, Docx: mf.Docx, Fallback: mf.Fallback, Index: i + 1,
279 }
280 if byKey[f.Key] != nil {
281 panic("fonts: duplicate key " + f.Key)
282 }
283 for name, file := range mf.Styles {
284 s, ok := styleNames[name]
285 if !ok {
286 panic(fmt.Sprintf("fonts: %s: unknown style %q", f.Key, name))
287 }
288 ttf := mf.Dir + "/" + file + ".ttf"
289 face := &Face{Family: f, Style: s, File: ttf, Data: mustRead(ttf), Web: mustRead(mf.Dir + "/" + file + ".woff2")}
290 face.Path = hashedPath(file, ".woff2", face.Web)
291 f.faces[s] = face
292 faces = append(faces, face)
293 byPath[face.Path] = face
294 }
295 if f.faces[Regular] == nil {
296 panic("fonts: " + f.Key + " has no regular face")
297 }
298 lic := mf.Dir + "/" + mf.Licence
299 f.licence = addAsset(PathPrefix+lic, "text/plain; charset=utf-8", mustRead(lic))
300 prev := mustRead(mf.Dir + "/preview-" + f.Key + ".woff2")
301 f.preview = addAsset(hashedPath("preview-"+f.Key, ".woff2", prev), "font/woff2", prev)
302 Families = append(Families, f)
303 byKey[f.Key] = f
304 }
305 var ok bool
306 if Default, ok = byKey[m.Default]; !ok {
307 panic("fonts: the default " + m.Default + " is not a family")
308 }
309 if Code, ok = byKey[m.Code]; !ok {
310 panic("fonts: the code family " + m.Code + " is not a family")
311 }
312 for _, f := range Families {
313 byDocx[strings.ToLower(f.Name)] = f
314 }
315 // A twin's Word name wins over a family that happens to be called
316 // that: Calibri is Carlito, whatever else is installed.
317 for _, f := range Families {
318 byDocx[strings.ToLower(f.Docx.Name)] = f
319 }
320 sort.Slice(faces, func(i, j int) bool { return faces[i].Path < faces[j].Path })
321 css := stylesheet()
322 cssPath = hashedPath("fonts", ".css", css)
323 addAsset(cssPath, "text/css; charset=utf-8", css)
324}
325
326func mustRead(name string) []byte {
327 b, err := fs.ReadFile(files, "files/"+name)
328 if err != nil {
329 // A missing file is a build mistake that would otherwise reach a
330 // running instance as an export without its bold text.
331 panic(fmt.Sprintf("fonts: embedded file %q missing: %v", name, err))
332 }
333 return b
334}
335
336func hashedPath(base, ext string, data []byte) string {
337 sum := sha256.Sum256(data)
338 return PathPrefix + base + "." + hex.EncodeToString(sum[:])[:16] + ext
339}
340
341func addAsset(p string, contentType string, data []byte) asset {
342 a := asset{path: p, contentType: contentType, data: data}
343 assets[a.path] = a
344 return a
345}
346
347// ByKey resolves a key from a mark name. The false return matters: a
348// document can carry any bytes at all, and an unknown key is the
349// caller's decision, not a silent default.
350func ByKey(key string) (*Family, bool) {
351 f, ok := byKey[key]
352 return f, ok
353}
354
355// ForMarks is the family a run carrying these marks is set in: the font
356// mark latest in manifest order, which is the innermost span
357// fragment.rs writes and so the one the cascade draws, or the default.
358// The editor's schema makes two font marks on one run impossible;
359// POST /d/{sqid}/updates does not.
360func ForMarks(names []string) *Family {
361 var found *Family
362 for _, n := range names {
363 key, ok := strings.CutPrefix(n, "font_")
364 if !ok {
365 continue
366 }
367 if f, ok := byKey[key]; ok && (found == nil || f.Index > found.Index) {
368 found = f
369 }
370 }
371 if found == nil {
372 return Default
373 }
374 return found
375}
376
377// ByDocxName is the family a .docx font name imports as: a metric
378// twin's Word name (Calibri, Cambria, Arial, Times New Roman, Courier
379// New) or a family's own name, case-insensitively.
380func ByDocxName(name string) (*Family, bool) {
381 f, ok := byDocx[strings.ToLower(strings.TrimSpace(name))]
382 return f, ok
383}
384
385// All is every face, in a stable order.
386func All() []*Face { return append([]*Face(nil), faces...) }
387
388// Get is the face for a family, weight and slope.
389func Get(f *Family, bold, italic bool) *Face { return f.Face(bold, italic) }
390
391// Asset is what a request path under PathPrefix serves: its bytes and
392// content type.
393func Asset(p string) (data []byte, contentType string, ok bool) {
394 if face, ok := byPath[p]; ok {
395 return face.Web, "font/woff2", true
396 }
397 if a, ok := assets[p]; ok {
398 return a.data, a.contentType, true
399 }
400 return nil, "", false
401}
402
403// LicencePaths is where each family's licence is served, one per
404// distinct file. The OFL requires the text to travel with the fonts.
405func LicencePaths() []string {
406 seen := map[string]bool{}
407 var out []string
408 for _, f := range Families {
409 if !seen[f.licence.path] {
410 seen[f.licence.path] = true
411 out = append(out, f.licence.path)
412 }
413 }
414 return out
415}
416
417// StylesheetPath is the generated stylesheet's URL.
418func StylesheetPath() string { return cssPath }
419
420// Stylesheet is the generated stylesheet.
421func Stylesheet() []byte { return assets[cssPath].data }
422
423func cssFamilies(names []string) string {
424 out := make([]string, len(names))
425 for i, n := range names {
426 switch n {
427 case "serif", "sans-serif", "monospace", "cursive", "system-ui":
428 out[i] = n
429 default:
430 out[i] = `"` + n + `"`
431 }
432 }
433 return strings.Join(out, ", ")
434}
435
436// stylesheet is every document and preview face, the family rules, and
437// the gate's states (NO-FOUT §1, §2, §4). An external file because
438// rastrillo's CSP no longer allows inline styles, and because it caches.
439func stylesheet() []byte {
440 var b bytes.Buffer
441 b.WriteString("/* Generated by internal/fonts from fonts.json. */\n")
442 for _, f := range Families {
443 for _, s := range f.Styles() {
444 face := f.faces[s]
445 // block, never swap: the page's gate holds the text until
446 // the face is ready and commits to the fallback before the
447 // browser's own three seconds run out.
448 fmt.Fprintf(&b, "@font-face{font-family:%q;src:url(%q) format(\"woff2\");font-weight:%d;font-style:%s;font-display:block}\n",
449 f.CSSName(), face.Path, s.Weight(), s.CSSStyle())
450 }
451 fmt.Fprintf(&b, "@font-face{font-family:%q;src:url(%q) format(\"woff2\");font-weight:400;font-style:normal;font-display:block}\n",
452 f.PreviewCSSName(), f.preview.path)
453 }
454 // The system faces first, and they are what a page without the font
455 // gate uses for the whole visit: no JavaScript, a script that never
456 // arrived, or a family committed to its fallback. They reference no
457 // web face, so the browser has nothing to download for them, nothing
458 // to hold invisible and nothing to swap in later (review finding 7).
459 // font-synthesis: none, so a missing bold or italic is never faked on
460 // screen and then replaced; the PDF cannot fake them either.
461 fmt.Fprintf(&b, "[docs-text]{font-family:%s;font-synthesis:none}\n", Default.FallbackCSS())
462 for _, f := range Families {
463 fmt.Fprintf(&b, "[docs-text] .%s{font-family:%s}\n", f.Class(), f.FallbackCSS())
464 }
465 fmt.Fprintf(&b, "[docs-text] code{font-family:%s}\n", Code.FallbackCSS())
466 // The web faces, once fixtures/fonts-gate.mjs has loaded them and set
467 // data-docs-faces="web", for every family it has not committed to
468 // its fallback.
469 for _, f := range Families {
470 web := fmt.Sprintf(`html[data-docs-faces="web"]:not([data-docs-fonts-fallback~=%q])`, f.Key)
471 if f == Default {
472 fmt.Fprintf(&b, "%s [docs-text]{font-family:%q, %s}\n", web, f.CSSName(), f.FallbackCSS())
473 }
474 if f == Code {
475 fmt.Fprintf(&b, "%s [docs-text] code{font-family:%q, %s}\n", web, f.CSSName(), f.FallbackCSS())
476 }
477 fmt.Fprintf(&b, "%s [docs-text] .%s{font-family:%q, %s}\n", web, f.Class(), f.CSSName(), f.FallbackCSS())
478 }
479 // Previews: the font control's rows and its closed box, which
480 // ui/select.js gives the option's data-rst-class. Only once they have
481 // loaded (data-docs-previews="web"); scoped to the toolbar's combobox
482 // and heavy enough to beat its `font: inherit`. A row is the family's
483 // name and nothing else (no description since 2026-10-26), so the
484 // subset, which has only the name's letters, draws all of it.
485 for _, f := range Families {
486 fmt.Fprintf(&b, "html[data-docs-previews=\"web\"] [docs-toolbar] [rst-combo] .%s{font-family:%q, var(--rst-font, system-ui), sans-serif}\n",
487 f.PreviewClass(), f.PreviewCSSName())
488 }
489 // The holds, set by fixtures/fonts-hold.js before the first paint and
490 // never by the server, so a page with no script is never held. The
491 // sheet, not just the text, so nothing shows an empty page with the
492 // words missing from it; and the font control, whose closed box is
493 // drawn in its own face. Screen only: a page printed while held
494 // prints, in its system faces.
495 b.WriteString("@media screen{html[data-docs-fonts=\"pending\"] [docs-page]{visibility:hidden}}\n")
496 b.WriteString("html[data-docs-previews=\"pending\"] [docs-toolbar] [data-docs-select=\"font\"],html[data-docs-previews=\"pending\"] #docs-select-font-combo{visibility:hidden}\n")
497 return b.Bytes()
498}
499