oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1package layout
2
3import (
4 "strings"
5 "unicode"
6
7 "amadan.net/oficina/slides/internal/slides/deck"
8 "amadan.net/oficina/slides/internal/slides/fonts"
9)
10
11// text.go measures and breaks lines. It is the one place spec §4.2
12// admits divergence from the browser, so it is worth saying exactly
13// what it does and does not do.
14//
15// Greedy: a line takes words until the next one would not fit, then
16// breaks. No hyphenation dictionary, no Knuth-Plass, no shaping — the
17// same unkerned sum of advance widths a browser without GPOS would
18// get (internal/slides/fonts' parser reads no GPOS, and says so).
19// Break opportunities are spaces and the inside of a hyphenated word,
20// which are the two a browser takes without being asked.
21//
22// A word wider than the box is placed on its own line and left to
23// overflow, rather than being broken mid-word. That is what the
24// stylesheet does (`overflow-wrap` is never set, so a long URL runs
25// past its column), and print has the same rule as screen: never clip.
26
27// style is how one stretch of text is set: a face, a size, a colour,
28// and the two things that are drawn around it rather than in it.
29type style struct {
30 face fonts.Face
31 size float64
32 fill Fill
33 href string
34 // track is letter-spacing in ems (headings only).
35 track float64
36 // mark is §2.6's highlight, drawn as a rectangle behind the run in
37 // markFill (the stylesheet mixes it from the accent).
38 mark bool
39 markFill Fill
40}
41
42// token is one word or one run of spaces, with the style it is set in
43// and its measured width. Splitting into tokens before wrapping is
44// what lets a line break fall between two runs with different marks —
45// "very **bold** words" wraps between "very" and "bold" like any other
46// text.
47type token struct {
48 s string
49 st style
50 space bool
51 w float64
52}
53
54// line is one assembled line: its tokens, its width, and the box it
55// occupies. asc and desc are the strut's — the block's own face at the
56// block's own size — because that is what CSS centres the content box
57// of a line against.
58type line struct {
59 toks []token
60 w float64
61 height float64
62 // gapBefore is the space above this line that is not leading: the
63 // margin between two paragraphs of one block.
64 gapBefore float64
65 asc, desc float64
66 overflowed bool
67}
68
69// block is a measured, wrapped run of text: the lines and how tall
70// they are together. Nothing in it is positioned yet.
71type textBlock struct {
72 lines []line
73 h float64
74}
75
76// measure is the width of s in st, letter-spacing included, and it is
77// the only place a rune the faces cannot draw is noticed.
78func (e *engine) measure(st style, s string) float64 {
79 w, missing := fonts.Advance(st.face, st.size, s)
80 if len(missing) > 0 {
81 e.noteGlyphs(missing)
82 }
83 if st.track != 0 {
84 w += st.track * st.size * float64(len([]rune(s)))
85 }
86 return w
87}
88
89// styleFor turns a run's marks into a style over a base one (§2.6).
90//
91// Bold and italic pick a different face of the same family. Code
92// changes family AND size, because the stylesheet does
93// (`:not(pre) > code` is 0.88em in the mono face). A link takes the
94// accent colour and carries its href so the caller can underline it —
95// §8 does not let colour alone say "this is a link".
96func (e *engine) styleFor(base style, r deck.Run) style {
97 st := base
98 if r.B {
99 st.face.Bold = true
100 }
101 if r.I {
102 st.face.Italic = true
103 }
104 if r.C {
105 st.face.Family = fonts.Mono
106 st.face.Uploaded = nil
107 st.size = base.size * inlineEm
108 }
109 if r.H {
110 st.mark, st.markFill = true, e.highlight
111 }
112 if r.Href != "" && safeHref(r.Href) {
113 st.fill = e.accent
114 st.href = r.Href
115 }
116 return st
117}
118
119// tokenize splits one paragraph's runs into words and spaces.
120func (e *engine) tokenize(runs []deck.Run, base style) []token {
121 var out []token
122 for _, r := range runs {
123 st := e.styleFor(base, r)
124 for _, piece := range splitRuns(r.T) {
125 out = append(out, token{
126 s: piece,
127 st: st,
128 space: isSpaceRun(piece),
129 w: e.measure(st, piece),
130 })
131 }
132 }
133 return out
134}
135
136// splitRuns cuts a string into alternating words and runs of
137// whitespace, and cuts a word after each hyphen — "context-free" is
138// two tokens, so a line may end on the hyphen the way a browser lets
139// it.
140func splitRuns(s string) []string {
141 var out []string
142 var cur strings.Builder
143 var inSpace bool
144 flush := func() {
145 if cur.Len() > 0 {
146 out = append(out, cur.String())
147 cur.Reset()
148 }
149 }
150 for _, r := range s {
151 sp := unicode.IsSpace(r)
152 if cur.Len() > 0 && sp != inSpace {
153 flush()
154 }
155 inSpace = sp
156 cur.WriteRune(r)
157 if !sp && r == '-' {
158 flush()
159 }
160 }
161 flush()
162 return out
163}
164
165func isSpaceRun(s string) bool {
166 for _, r := range s {
167 if !unicode.IsSpace(r) {
168 return false
169 }
170 }
171 return s != ""
172}
173
174// wrap breaks t into lines no wider than w, one paragraph after
175// another with paraGap between them, and returns the measured block.
176//
177// lead is the CSS line-height ratio, applied to the block's own size,
178// so every line of a block is the same height whatever is on it —
179// which is what a `line-height: 1.3` inherited as a NUMBER does.
180func (e *engine) wrap(t deck.Text, base style, w, lead, paraGap float64) *textBlock {
181 asc, desc, _ := fonts.Metrics(base.face, base.size)
182 lineH := lead * base.size
183 out := &textBlock{}
184
185 // pending is the paragraph margin owed to the next line emitted.
186 var pending float64
187 emit := func(toks []token, width float64, over bool) {
188 out.lines = append(out.lines, line{
189 toks: toks, w: width, height: lineH, gapBefore: pending,
190 asc: asc, desc: desc, overflowed: over,
191 })
192 pending = 0
193 }
194
195 for i, para := range t {
196 if i > 0 {
197 pending = paraGap
198 out.h += paraGap
199 }
200 start := len(out.lines)
201 toks := e.tokenize(para, base)
202
203 var cur []token
204 var curW float64
205 flush := func() {
206 // A line never ends on a space: the trailing space is
207 // dropped, as a browser drops it at a soft break.
208 for len(cur) > 0 && cur[len(cur)-1].space {
209 curW -= cur[len(cur)-1].w
210 cur = cur[:len(cur)-1]
211 }
212 emit(cur, curW, curW > w)
213 cur, curW = nil, 0
214 }
215 for _, tk := range toks {
216 if tk.space {
217 // A line never opens with a space either.
218 if len(cur) == 0 {
219 continue
220 }
221 cur = append(cur, tk)
222 curW += tk.w
223 continue
224 }
225 if len(cur) > 0 && curW+tk.w > w {
226 flush()
227 }
228 cur = append(cur, tk)
229 curW += tk.w
230 }
231 if len(cur) > 0 || len(out.lines) == start {
232 // The second half puts an empty line box under an empty
233 // paragraph, which is what `<p></p>` is on screen.
234 flush()
235 }
236 out.h += float64(len(out.lines)-start) * lineH
237 }
238 return out
239}
240
241// paint places a wrapped block with its top-left at (x, y) in a column
242// w wide, and returns the ops that draw it.
243//
244// The baseline is where CSS puts it: the text's content box is centred
245// in the line box (half the leading above, half below) and the
246// baseline is one ascent down from the top of that box.
247func (e *engine) paint(tb *textBlock, x, y, w float64, align Align) []Op {
248 var ops []Op
249 top := y
250 for _, ln := range tb.lines {
251 lineX := x
252 switch align {
253 case Center:
254 lineX = x + (w-ln.w)/2
255 case End:
256 lineX = x + w - ln.w
257 }
258 top += ln.gapBefore
259 baseline := top + (ln.height-(ln.asc+ln.desc))/2 + ln.asc
260 ops = append(ops, lineOps(lineX, baseline, ln)...)
261 top += ln.height
262 }
263 return ops
264}
265
266// lineOps draws one line: the marks behind the words, the words, and
267// the underline beneath a link.
268//
269// Adjacent tokens in the same style become one Run, because a paint
270// list is read by people as well as by the serialisers and a line
271// spelled one word per run is unreadable. The marks and underlines are
272// separate ops for the reason §8 gives: a link that is only a colour
273// is not a link anybody colour-blind can see, and a PDF annotation
274// draws nothing on the page.
275func lineOps(x, baseline float64, ln line) []Op {
276 var marks, unders []Op
277 var runs []Run
278 cx := x
279
280 // A run of tokens sharing a style, accumulated then flushed.
281 var pend strings.Builder
282 var pendSt style
283 var pendW, pendX float64
284 flush := func() {
285 if pend.Len() == 0 {
286 return
287 }
288 if pendSt.mark {
289 // `mark` is a background behind the words, one ascent up
290 // and one descent down, with the stylesheet's own 0.15em
291 // of breathing room either side.
292 pad := 0.15 * pendSt.size
293 marks = append(marks, Rect{
294 X: pendX - pad, Y: baseline - ln.asc, W: pendW + 2*pad, H: ln.asc + ln.desc,
295 Fill: pendSt.markFill, Radius: 0.2 * pendSt.size,
296 })
297 }
298 if pendSt.href != "" {
299 // `text-underline-offset: 0.15em`,
300 // `text-decoration-thickness: 0.07em`.
301 off := 0.15 * pendSt.size
302 unders = append(unders, Line{
303 X1: pendX, Y1: baseline + off, X2: pendX + pendW, Y2: baseline + off,
304 Stroke: pendSt.fill, W: 0.07 * pendSt.size,
305 })
306 }
307 runs = append(runs, Run{
308 S: pend.String(), Face: pendSt.face, Size: pendSt.size,
309 Fill: pendSt.fill, Href: pendSt.href,
310 })
311 pend.Reset()
312 pendW = 0
313 }
314
315 for _, tk := range ln.toks {
316 if pend.Len() > 0 && tk.st != pendSt {
317 flush()
318 }
319 if pend.Len() == 0 {
320 pendSt, pendX = tk.st, cx
321 }
322 pend.WriteString(tk.s)
323 pendW += tk.w
324 cx += tk.w
325 }
326 flush()
327
328 if len(runs) == 0 {
329 return nil
330 }
331 // Marks first (they are behind), then the words, then the
332 // underlines, which sit under the letters and over the mark.
333 out := append([]Op{}, marks...)
334 out = append(out, Text{X: x, Y: baseline, Runs: runs})
335 return append(out, unders...)
336}
337
338// safeHref is render's own rule, restated: a link that does not point
339// at http, https or mailto is not drawn as a link. It is restated
340// rather than exported because the two answers are about different
341// media — this one decides whether to underline something on a page,
342// not whether to write an <a> — and one of them changing should not
343// silently change the other.
344func safeHref(raw string) bool {
345 if raw == "" || strings.TrimSpace(raw) != raw {
346 return false
347 }
348 scheme, _, ok := strings.Cut(raw, ":")
349 if !ok {
350 return false
351 }
352 switch strings.ToLower(scheme) {
353 case "http", "https", "mailto":
354 return true
355 }
356 return false
357}
358