oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package render turns a slide from the core's JSON view (the deck
2// package's types) into the HTML every live surface shows: the viewer,
3// the presenter, the remote's thumbnails and the editor stage. Spec
4// §4.1.
5//
6// One slide is one `<section slides-slide>`. The theme arrives as CSS
7// custom properties inline on that section, the template's regions and
8// the canvas frame arrive as attributes, and the phone layer arrives as
9// data-phone-* attributes that internal/slides/static/slides.css
10// honours. Nothing here writes a style rule; the stylesheet holds the
11// looks, and this package holds the tree.
12//
13// The one rule (§0.1) is the shape of the whole file: a slide is one
14// block tree rendered many ways, so Slide takes a Viewport and never a
15// second document. The phone layer only ever adds — a block hidden on a
16// phone is still in the output, carrying the attribute the stylesheet
17// hides it by, because the notes, the search index and the presenter
18// still want its words. The phone layer's `order` is applied to the
19// document when rendering FOR a phone (codex 10): the blocks are
20// emitted in the sequence a phone reads them, so a screen reader and
21// the Tab key follow the same order a sighted reader sees, and the
22// stylesheet's `order` property is a convenience for a desktop
23// rendering opened on a narrow screen, not the thing that makes the
24// order true.
25//
26// ── Why the markup is built rather than templated ─────────────────────
27//
28// Everything a person typed goes through html/template: Text renders
29// runs and links through a real template, so link marks get contextual
30// URL filtering on top of this package's own scheme allowlist. The
31// surrounding elements are assembled by hand because html/template
32// cannot take a dynamic tag name (`<{{.Tag}}`) or a dynamic attribute
33// name, and eleven block types across seven elements would otherwise
34// mean a template per element with the attribute block copied into each
35// one. The invariants that make it safe are narrow enough to state:
36//
37// - Tag and attribute names are string literals in this file. Nothing
38// from a deck ever becomes one.
39// - Every attribute VALUE goes through template.HTMLEscapeString and
40// sits in double quotes.
41// - Values that land in CSS or in a URL — colours, font stacks, asset
42// ids, hrefs — pass an allowlist first (safeColor, safeFontStack,
43// safeAssetID, safeHref), which is stricter than escaping: an
44// unsafe value is dropped, not neutered.
45// - Every run of text goes through esc or through the template.
46package render
47
48import (
49 "bytes"
50 "encoding/json"
51 "fmt"
52 "html/template"
53 "net/url"
54 "regexp"
55 "slices"
56 "strconv"
57 "strings"
58
59 "amadan.net/oficina/slides/internal/slides/deck"
60 "amadan.net/oficina/slides/internal/slides/qr"
61)
62
63// Viewport is which of the two shapes a slide is being rendered for.
64// There are exactly two because there are exactly two in the model: the
65// desktop layout is the base and the phone layer adds to it (§2.5).
66type Viewport int
67
68const (
69 // Desktop is the base: the 16:9 frame, the template's grid as the
70 // template drew it, canvas boxes where they were put.
71 Desktop Viewport = iota
72 // Phone marks the section data-vp="phone" and, on a canvas slide
73 // whose phone is "reflow", lays the blocks out as a single column.
74 Phone
75)
76
77func (v Viewport) String() string {
78 if v == Phone {
79 return "phone"
80 }
81 return "desktop"
82}
83
84// Slide renders d's slide at index for vp: exactly one <section>, with
85// no surrounding whitespace, ready to drop into a page.
86//
87// It fails only on a caller mistake — no deck, or an index that is not
88// a slide. Everything a deck can contain renders as something: an
89// unknown theme falls back to the default, an unknown block type
90// renders nothing rather than breaking the slide around it, and a prop
91// with the wrong type takes its default. A half-written document that
92// arrived from a peer mid-edit is the ordinary case, not an error.
93func Slide(d *deck.Deck, index int, vp Viewport) (template.HTML, error) {
94 return SlideWith(d, index, vp, Options{})
95}
96
97// Options is what a surface tells the renderer about itself. One field
98// so far, and it is a struct rather than a fourth argument because the
99// next one should not change eight call sites again.
100type Options struct {
101 // AssetBase is the path an image's bytes are served from on THIS
102 // surface, with no trailing slash: "/d/{sqid}/assets" signed in,
103 // "/s/{token}/assets" over a share link, "/p/{session}/assets"
104 // while presenting.
105 //
106 // Every one of those is the deck's own capability with /assets on
107 // the end, because one slide is rendered on surfaces authenticated
108 // four different ways and the <img> has to be fetchable by whoever
109 // is looking at it. Empty falls back to DefaultAssetBase.
110 AssetBase string
111 // Editing draws every text the way the editor's ProseMirror views
112 // will once they bind to it (editing.go): the editor's stage, and
113 // nothing else.
114 Editing bool
115 // Placeholders is what an empty text block says on the editor's
116 // stage, by block type ("heading", "text", …): written as the
117 // block's data-placeholder when Editing, and shown by editor.css
118 // only while the block is empty. It is the catalog's copy, handed
119 // in by the caller, because this package has no locale.
120 Placeholders map[string]string
121 // Reveal draws the slide as it stands after that many presses: a box
122 // or list item that arrives on a later press is marked data-waiting,
123 // and one that arrives on any press data-press. nil is the finished
124 // slide with none of those attributes, and so is the editor's stage
125 // whatever this says. See reveal.go.
126 Reveal *int
127 // QRAlt is a follow-along code's alternative text, the catalog's
128 // slides.qr.alt with "{address}" where the short address goes,
129 // handed in for the reason Placeholders is. Empty (a test, a
130 // fixture) names the code by its address alone.
131 QRAlt string
132 // QR is the follow-along codes this surface may draw: a qr block's
133 // stored url to the follow address its code is drawn for. The app
134 // fills it (qrlink.go's followCodes): only this instance's own
135 // links that are live share links of this deck, and on a share
136 // link's surfaces the reader's own link in place of the stored one.
137 // A url not in it — or no map at all — draws no code: nothing for
138 // a reader, an empty frame in the editor.
139 QR map[string]string
140}
141
142// DefaultAssetBase is what a caller that passed no Options gets. It is
143// no surface's real base — nothing is mounted there — so a caller that
144// forgot to say which surface it is rendering for gets visibly broken
145// images rather than a URL that quietly works from the wrong place.
146const DefaultAssetBase = "/assets"
147
148// SlideWith is Slide with the surface's own options. Slide stays for
149// the callers that do not care (a test, a fixture); every real surface
150// passes its asset base.
151func SlideWith(d *deck.Deck, index int, vp Viewport, opt Options) (template.HTML, error) {
152 if d == nil {
153 return "", fmt.Errorf("render: no deck")
154 }
155 if index < 0 || index >= len(d.Slides) {
156 return "", fmt.Errorf("render: slide %d is outside a deck of %d", index, len(d.Slides))
157 }
158 s := d.Slides[index]
159
160 layout := s.Layout
161 if layout != "canvas" {
162 layout = "flow"
163 }
164 tmpl := s.Template
165 if !slices.Contains(templates, tmpl) {
166 tmpl = "blank"
167 }
168
169 // §2.3: a canvas slide set to phone: reflow becomes a blank flow
170 // slide on a phone, its blocks in z then top-left reading order.
171 // The slide says it was a canvas so the editor stage and the
172 // presenter can tell what they are looking at.
173 reflowed := false
174 if layout == "canvas" && vp == Phone && s.Phone == "reflow" {
175 layout, tmpl, reflowed = "flow", "blank", true
176 }
177
178 base := strings.TrimSuffix(strings.TrimSpace(opt.AssetBase), "/")
179 if base == "" {
180 base = DefaultAssetBase
181 }
182 c := &renderer{deck: d, canvas: layout == "canvas", phone: vp == Phone, assetBase: base, late: map[string]bool{}, editing: opt.Editing, placeholders: opt.Placeholders, reveal: newReveal(s, d.Scenes, opt), qrAlt: opt.QRAlt, qr: opt.QR}
183
184 attrs := []attr{
185 {name: "slides-slide", bare: true},
186 {name: "data-index", value: strconv.Itoa(index)},
187 {name: "data-id", value: s.ID},
188 {name: "data-layout", value: layout},
189 {name: "data-template", value: tmpl},
190 {name: "data-theme", value: c.themeID(d.Meta.Theme)},
191 }
192 if kind := s.Background.Kind; kind == "color" || kind == "image" {
193 attrs = append(attrs, attr{name: "data-background", value: kind})
194 }
195 if t := s.Transition; t != "" && t != "none" {
196 attrs = append(attrs, attr{name: "data-transition", value: t})
197 }
198 if vp == Phone {
199 attrs = append(attrs, attr{name: "data-vp", value: "phone"})
200 }
201 if reflowed {
202 attrs = append(attrs, attr{name: "data-reflowed", value: "canvas"})
203 }
204
205 attrs = append(attrs, c.reveal.sectionAttrs(d.Meta.Arrive)...)
206
207 children := c.body(s, reflowed)
208 if !c.canvas {
209 // A flow slide's regions sit on a frame inside the section
210 // rather than on the section itself. slides.css says why at
211 // length: `gap: var(--slides-gap)` is a container-query length
212 // USED on the element it is written on, and an element is
213 // never its own query container, so on the section it measured
214 // the page outside the slide and the space between a heading
215 // and a body moved with the browser window. One element of
216 // markup is what makes that gap a fixed fraction of the slide
217 // — which is what lets internal/slides/layout state a number
218 // for it, and what makes a thumbnail the same shape as the
219 // stage.
220 //
221 // A canvas slide has none: its blocks are absolutely placed on
222 // the section and there is no gap in the first place.
223 children = []template.HTML{elBlock("div", []attr{{name: "slides-frame", bare: true}}, "", children)}
224 }
225 return elBlock("section", attrs, c.sectionStyle(s), children), nil
226}
227
228// Text renders the §2.6 text schema: one <p> per paragraph, runs inside
229// carrying <strong>, <em>, <code>, <mark> and <a>. It is the seam every
230// text-bearing block goes through, and the only place a link is made.
231func Text(t deck.Text) template.HTML {
232 if len(t) == 0 {
233 return ""
234 }
235 out := make([]template.HTML, 0, len(t))
236 for _, p := range t {
237 out = append(out, elInline("p", nil, "", inline(p)))
238 }
239 return join(out)
240}
241
242// Notes renders speaker notes — the presenter's pane, the scriptless
243// deck page's notes under the slide, the printed handout.
244//
245// It is Text under another name, and a function rather than an alias
246// because the two surfaces are not the same surface: notes are the one
247// text a viewer is never supposed to see, and having a name for them
248// means a later change (a heading, a lang attribute, stripping links
249// from a projected pane) has one place to land instead of touching
250// every caller of Text.
251func Notes(t deck.Text) template.HTML { return Text(t) }
252
253// templates is the flow template vocabulary (§2.2). Anything else is
254// rendered as blank, which has a single body region and always works.
255var templates = []string{"title", "title-body", "two-column", "section", "image-full", "quote", "blank"}
256
257// regionOrder is the order regions appear in the section, whatever
258// order the blocks arrived in. It is the reading order the phone
259// collapses to, so it is also the order a screen reader hears: the
260// heading, then the body, then the aside, then the media.
261//
262// image-full puts the heading over the media, and does it with a grid
263// area and a z-index in the stylesheet rather than by moving the
264// heading down the document — the picture is not the first thing the
265// slide is about.
266var regionOrder = []string{"heading", "body", "aside", "media"}
267
268// unreachedRegion is the wrapper the blocks nothing reaches land in
269// (codex 7): a block named as a child by a columns block that no root
270// arrives at — a cycle merged in from two peers, or a document written
271// past the ops. It comes after every real region so the content is on
272// the slide and in the reading order, at the end, rather than gone.
273const unreachedRegion = "unreached"
274
275// renderer is one Slide call's state: the deck it is reading, whether
276// this slide's blocks carry boxes, and whether it is being rendered for
277// a phone. The phone flag is the one viewport-dependent decision that
278// reaches a block (codex 10): the blocks are EMITTED in the phone
279// layer's reading order, so the sequence a screen reader hears and the
280// Tab key walks is the one a sighted reader sees, rather than the
281// stylesheet's `order` moving boxes over a document that still reads
282// in desktop order. The desktop rendering keeps the desktop order.
283type renderer struct {
284 deck *deck.Deck
285 canvas bool
286 phone bool
287 // assetBase is Options.AssetBase, already trimmed and defaulted.
288 assetBase string
289 // editing is Options.Editing.
290 editing bool
291 // placeholders is Options.Placeholders.
292 placeholders map[string]string
293 // late is the set of blocks rendered in the unreached pass, so
294 // attrs can mark them (data-unreached) and the stylesheet can
295 // show them for what they are.
296 late map[string]bool
297 // reveal is Options.Reveal worked out; nil draws the finished slide.
298 reveal *reveal
299 // qrAlt is Options.QRAlt.
300 qrAlt string
301 // qr is Options.QR.
302 qr map[string]string
303}
304
305// assetRef resolves an asset id — a block's props.asset, a slide
306// background's value — to the object store address the deck registered
307// for it (§2.7). An id nothing registered, or a ref that is not a
308// single safe path segment, resolves to nothing, and every caller then
309// draws "no image" rather than a URL nobody can serve.
310func (c *renderer) assetRef(id string) string {
311 a, ok := c.deck.Assets[id]
312 if !ok {
313 return ""
314 }
315 return safeRef(a.Ref)
316}
317
318// assetPath is where an asset's bytes are served from on this surface:
319// the caller's own base and the ref. Keyed by the deck's capability
320// rather than global, so a link that opens one deck cannot fetch
321// another one's pictures.
322func (c *renderer) assetPath(ref string) string { return c.assetBase + "/" + ref }
323
324// ThemeID resolves a theme name to one this build has: a deck naming a
325// theme that was renamed out from under it renders as the default
326// rather than as nothing.
327//
328// Exported because the layout engine needs the same answer — it asks
329// internal/slides/fonts for the face that theme sets its headings in,
330// and asking with an unresolved name would measure a slide in a face
331// the browser is not using.
332func ThemeID(name string) string {
333 if _, ok := themeVars[name]; ok {
334 return name
335 }
336 return defaultThemeID
337}
338
339// themeID is ThemeID under the renderer's own hand.
340func (c *renderer) themeID(name string) string { return ThemeID(name) }
341
342// sectionStyle is the theme's custom properties, plus the three things
343// a deck may override: meta.accent, meta.fonts, and the slide's own
344// background. Each override is allowlisted before it is written, and a
345// value that does not pass is dropped — the theme's own value stands.
346//
347// Colour overrides pass a second test after the allowlist: the result
348// has to be readable. §8 takes WCAG 2.2 AA with no exemptions, and a
349// deck that sets a plum background on a theme whose text is near-black
350// would otherwise render an unreadable slide with nothing to say so. A
351// background colour therefore brings a foreground and accents that
352// clear the thresholds against it, and an accent a deck names is used
353// only if it clears 3:1 against the background it will actually sit on.
354func (c *renderer) sectionStyle(s deck.Slide) string {
355 out := slideVars(c.deck, s)
356
357 // The slide's own backdrop when it is a picture (§2.2): a custom
358 // property the stylesheet paints, pointing at THIS surface's asset
359 // base — which is why it is here and not in slideVars. A colour is
360 // the same on every surface; a URL is not.
361 //
362 // Unquoted url() because safeAssetID and safeRef between them have
363 // already ruled out everything that would need quoting.
364 var image string
365 if s.Background.Kind == "image" {
366 if ref := c.assetRef(safeAssetID(s.Background.Value)); ref != "" {
367 image = "--slides-bg-image:url(" + c.assetPath(ref) + ")"
368 }
369 }
370
371 parts := make([]string, 0, len(varOrder)+1)
372 for _, k := range varOrder {
373 parts = append(parts, k+":"+out[k])
374 }
375 if image != "" {
376 parts = append(parts, image)
377 }
378 return strings.Join(parts, ";")
379}
380
381// SlideVars is the palette d's slide at index is drawn in: the theme's
382// custom properties with the deck's and the slide's own overrides
383// already judged. It is what Slide writes on the section, so the
384// layout engine (internal/slides/layout, and through it the SVG and
385// the PDF) paints the slide the browser paints rather than forming a
386// second opinion about it. False for an index that is not a slide.
387//
388// Colours and font stacks only — a background IMAGE is not here,
389// because its URL depends on which surface is asking (Options).
390func SlideVars(d *deck.Deck, index int) (map[string]string, bool) {
391 if d == nil || index < 0 || index >= len(d.Slides) {
392 return nil, false
393 }
394 return slideVars(d, d.Slides[index]), true
395}
396
397// slideVars is sectionStyle's arithmetic without the serialising.
398func slideVars(d *deck.Deck, s deck.Slide) map[string]string {
399 vars := themeVars[ThemeID(d.Meta.Theme)]
400 out := make(map[string]string, len(vars)+1)
401 for k, v := range vars {
402 out[k] = v
403 }
404 if f := d.Meta.Fonts; f != nil {
405 if h := safeFontStack(f.Heading); h != "" {
406 out["--slides-font-heading"] = h
407 }
408 if b := safeFontStack(f.Body); b != "" {
409 out["--slides-font-body"] = b
410 }
411 }
412 // The slide's own backdrop (§2.2). A colour replaces the theme's
413 // background outright — replaces, rather than being appended as a
414 // second --slides-bg that happens to win, so the style attribute
415 // says one thing about the background and not two. Hex only: a
416 // colour keyword is a colour this package cannot measure, and an
417 // unmeasurable background cannot be given a readable foreground.
418 if s.Background.Kind == "color" {
419 if bg := safeHexColor(s.Background.Value); bg != "" && bg != out["--slides-bg"] {
420 out["--slides-bg"] = bg
421 // The theme's own text first, then the colour it was
422 // sitting on (the light half of a dark theme, and the
423 // other way round), then plain black or white.
424 out["--slides-fg"] = readableOn(bg, bodyContrast,
425 vars["--slides-fg"], vars["--slides-bg"], "#000000", "#ffffff")
426 // An accent that cannot be seen on the new background
427 // collapses to the foreground, so the slide reads even
428 // though it has lost its second colour. A deck that wants
429 // an accent back on a background of its own sets
430 // meta.accent, which is judged below.
431 for _, k := range []string{"--slides-accent", "--slides-accent-2"} {
432 out[k] = readableOn(bg, accentContrast, vars[k], out["--slides-fg"])
433 }
434 }
435 }
436
437 // The deck's accent, last, so it is judged against the background
438 // this slide actually has rather than against the theme's.
439 if accent := safeHexColor(d.Meta.Accent); accent != "" &&
440 contrastRatio(accent, out["--slides-bg"]) >= accentContrast {
441 out["--slides-accent"] = accent
442 }
443 return out
444}
445
446// body is the section's children: region wrappers on a flow slide,
447// bare blocks on a canvas one.
448func (c *renderer) body(s deck.Slide, reflowed bool) []template.HTML {
449 blocks := s.Blocks
450 if reflowed {
451 blocks = reflowOrder(blocks)
452 }
453 if c.phone {
454 blocks = phoneOrder(blocks)
455 }
456
457 // A columns block's children render inside it, in the order
458 // props.children names them, and nowhere else (§2.4).
459 byID := make(map[string]deck.Block, len(blocks))
460 claimed := make(map[string]bool)
461 for _, b := range blocks {
462 byID[b.ID] = b
463 }
464 for _, b := range blocks {
465 if b.Type != "columns" {
466 continue
467 }
468 for _, id := range childIDs(b) {
469 if _, ok := byID[id]; ok {
470 claimed[id] = true
471 }
472 }
473 }
474
475 // done is shared across the whole slide, so a block renders at most
476 // once however many columns blocks name it. claimed decides WHERE
477 // it renders; done makes sure that is the only place.
478 done := map[string]bool{}
479
480 // What no root reaches renders last, marked, rather than not at all
481 // (codex 7). The ops refuse a cycle and a shared child now, but two
482 // peers' concurrent assignments can still merge into one, and a
483 // document that arrived by another road than the ops can hold
484 // anything. Rendering from each unreached block in turn: a cycle's
485 // members each render once (done stops the loop), in array order.
486 late := unreached(blocks, byID, claimed)
487 for _, b := range late {
488 c.late[b.ID] = true
489 }
490
491 if c.canvas {
492 out := make([]template.HTML, 0, len(blocks))
493 for _, b := range blocks {
494 if claimed[b.ID] {
495 continue
496 }
497 if h := c.block(b, byID, done); h != "" {
498 out = append(out, h)
499 }
500 }
501 for _, b := range late {
502 if h := c.block(b, byID, done); h != "" {
503 out = append(out, h)
504 }
505 }
506 return out
507 }
508
509 // Flow: group into regions, canonical regions first, then any
510 // region name the core let through, in first-appearance order,
511 // then whatever nothing reached.
512 grouped := map[string][]template.HTML{}
513 var extra []string
514 for _, b := range blocks {
515 if claimed[b.ID] {
516 continue
517 }
518 name := b.Region
519 switch {
520 case name == "":
521 name = "body"
522 case !slices.Contains(regionOrder, name) && !slices.Contains(extra, name):
523 extra = append(extra, name)
524 }
525 if h := c.block(b, byID, done); h != "" {
526 grouped[name] = append(grouped[name], h)
527 }
528 }
529 for _, b := range late {
530 if h := c.block(b, byID, done); h != "" {
531 grouped[unreachedRegion] = append(grouped[unreachedRegion], h)
532 }
533 }
534
535 names := append(slices.Clone(regionOrder), extra...)
536 names = append(names, unreachedRegion)
537 out := make([]template.HTML, 0, len(names))
538 for _, name := range names {
539 if len(grouped[name]) == 0 {
540 continue
541 }
542 out = append(out, elBlock("div", []attr{
543 {name: "slides-region", bare: true},
544 {name: "data-region", value: name},
545 }, "", grouped[name]))
546 }
547 return out
548}
549
550// unreached is every block no traversal from the slide's roots — the
551// blocks no columns block claims — arrives at: the members of a cycle
552// of columns blocks and whatever hangs under them. Array order.
553func unreached(blocks []deck.Block, byID map[string]deck.Block, claimed map[string]bool) []deck.Block {
554 reached := map[string]bool{}
555 var visit func(b deck.Block)
556 visit = func(b deck.Block) {
557 if reached[b.ID] {
558 return
559 }
560 reached[b.ID] = true
561 for _, id := range childIDs(b) {
562 if child, ok := byID[id]; ok && b.Type == "columns" {
563 visit(child)
564 }
565 }
566 }
567 for _, b := range blocks {
568 if !claimed[b.ID] {
569 visit(b)
570 }
571 }
572 var out []deck.Block
573 for _, b := range blocks {
574 if !reached[b.ID] {
575 out = append(out, b)
576 }
577 }
578 return out
579}
580
581// phoneOrder is §2.5's `order` applied to the document itself (codex
582// 10): a stable sort by the phone layer's order, an unset order
583// counting as 0 — exactly the key the stylesheet's `order:
584// var(--slides-phone-order, 0)` sorts by, so the two agree and the CSS
585// is no longer load-bearing. Stable, so blocks with the same order keep
586// the sequence they had, region grouping included.
587func phoneOrder(blocks []deck.Block) []deck.Block {
588 out := slices.Clone(blocks)
589 slices.SortStableFunc(out, func(a, b deck.Block) int {
590 return phoneRank(a) - phoneRank(b)
591 })
592 return out
593}
594
595func phoneRank(b deck.Block) int {
596 if b.Phone.Order != nil {
597 return *b.Phone.Order
598 }
599 return 0
600}
601
602// reflowOrder is §2.3's ordering for a canvas slide reflowed onto a
603// phone: z, then top, then left. Stable, so two blocks stacked at the
604// same point keep the order the array had.
605func reflowOrder(blocks []deck.Block) []deck.Block {
606 out := slices.Clone(blocks)
607 slices.SortStableFunc(out, func(a, b deck.Block) int {
608 if a.Z != b.Z {
609 return a.Z - b.Z
610 }
611 ax, ay := corner(a.Box)
612 bx, by := corner(b.Box)
613 switch {
614 case ay < by:
615 return -1
616 case ay > by:
617 return 1
618 case ax < bx:
619 return -1
620 case ax > bx:
621 return 1
622 }
623 return 0
624 })
625 return out
626}
627
628// corner is a box's top-left, or the origin for a block that has none.
629func corner(b *deck.Box) (x, y float64) {
630 if b == nil {
631 return 0, 0
632 }
633 return b.X, b.Y
634}
635
636// block renders one block. done is the set already rendered on this
637// slide: it stops a block appearing twice when two columns blocks name
638// it, and it stops a columns block that names a columns block that
639// names it back. The core refuses both shapes now (codex 7), but a
640// merge of two peers' assignments can still produce either, and this
641// is what makes that a rendering rather than a stack overflow.
642func (c *renderer) block(b deck.Block, byID map[string]deck.Block, done map[string]bool) template.HTML {
643 if done[b.ID] {
644 return ""
645 }
646 done[b.ID] = true
647
648 switch b.Type {
649 case "heading":
650 return c.headingBlock(b)
651 case "text":
652 return c.textBlock(b)
653 case "list":
654 return c.listBlock(b)
655 case "quote":
656 return c.quoteBlock(b)
657 case "image":
658 return c.imageBlock(b)
659 case "columns":
660 return c.columnsBlock(b, byID, done)
661 case "code":
662 return c.codeBlock(b)
663 case "shape":
664 return c.shapeBlock(b)
665 case "table":
666 return c.tableBlock(b)
667 case "scene":
668 return c.sceneBlock(b)
669 case "clip":
670 return c.clipBlock(b)
671 case "divider":
672 return elVoid("hr", c.attrs(b), c.style(b))
673 case "qr":
674 return c.qrBlock(b)
675 case "spacer":
676 return elInline("div", c.attrs(b,
677 attr{name: "data-size", value: sizeProp(b.Props, "l")},
678 attr{name: "aria-hidden", value: "true"}), c.style(b), "")
679 }
680 // An unknown type is a block from a newer build of the core.
681 // Rendering nothing keeps the rest of the slide standing.
682 return ""
683}
684
685// attrs is the attribute set every block carries: the marker the
686// stylesheet selects on, the type, the id the editor addresses it by,
687// then whatever the caller adds, then the placement (region or z) and
688// the phone layer.
689func (c *renderer) attrs(b deck.Block, extra ...attr) []attr {
690 return c.blockAttrs(b, c.reveal.attrs(b.ID, -1), extra...)
691}
692
693// blockAttrs is attrs with the block's own press marks given: a clip
694// played on a press keeps them for a mark inside it (clipBlock).
695func (c *renderer) blockAttrs(b deck.Block, marks []attr, extra ...attr) []attr {
696 out := []attr{
697 {name: "slides-block", bare: true},
698 {name: "data-block", value: b.Type},
699 {name: "data-id", value: b.ID},
700 }
701 out = append(out, extra...)
702 out = append(out, marks...)
703 if c.editing && c.placeholders[b.Type] != "" {
704 out = append(out, attr{name: "data-placeholder", value: c.placeholders[b.Type]})
705 }
706 if c.canvas {
707 out = append(out, attr{name: "data-z", value: strconv.Itoa(b.Z)})
708 } else if b.Region != "" {
709 out = append(out, attr{name: "data-region", value: b.Region})
710 }
711 if c.late[b.ID] {
712 // Rendered in the unreached pass (body): on the slide, at the
713 // end, and saying so — the stylesheet outlines it and the
714 // editor can tell a person why it is where it is.
715 out = append(out, attr{name: "data-unreached", value: "true"})
716 }
717
718 // The phone layer, always emitted whichever viewport this is: the
719 // stylesheet honours it under the phone container query, and the
720 // editor's desktop/phone switcher (§3.2) reads it back.
721 p := b.Phone
722 if p.Hidden {
723 out = append(out, attr{name: "data-phone-hidden", value: "true"})
724 }
725 if p.Order != nil {
726 out = append(out, attr{name: "data-phone-order", value: strconv.Itoa(*p.Order)})
727 }
728 if p.Size != "" {
729 out = append(out, attr{name: "data-phone-size", value: sizeStep(p.Size, "m")})
730 }
731 if p.Box != nil && c.canvas {
732 out = append(out, attr{name: "data-phone-box", value: fracs(*p.Box)})
733 }
734 return out
735}
736
737// style is a block's inline style: nothing at all on a flow slide, and
738// on a canvas slide the box as percentages of the frame plus the z.
739// A phone box rides along as custom properties, which is what lets the
740// stylesheet move the block under its container query without this
741// package needing to know how wide the screen turned out to be.
742//
743// --slides-phone-order is here for the same reason: CSS cannot read an
744// integer out of a data attribute, so the order the phone layer asks
745// for has to arrive as a value. On a phone rendering it is redundant —
746// the blocks are already emitted in that order (phoneOrder) — and it
747// stays for a desktop rendering that a narrow screen opens anyway,
748// where the container query is the only ordering there is.
749func (c *renderer) style(b deck.Block) string {
750 var parts []string
751 if c.canvas && b.Box != nil {
752 parts = append(parts,
753 "left:"+pct(b.Box.X),
754 "top:"+pct(b.Box.Y),
755 "width:"+pct(b.Box.W),
756 "height:"+pct(b.Box.H),
757 "z-index:"+strconv.Itoa(b.Z),
758 )
759 if p := b.Phone.Box; p != nil {
760 parts = append(parts,
761 "--slides-phone-left:"+pct(p.X),
762 "--slides-phone-top:"+pct(p.Y),
763 "--slides-phone-width:"+pct(p.W),
764 "--slides-phone-height:"+pct(p.H),
765 )
766 }
767 }
768 if o := b.Phone.Order; o != nil {
769 parts = append(parts, "--slides-phone-order:"+strconv.Itoa(*o))
770 }
771 if r := numProp(b.Props, "radius", 0); b.Type == "image" && r > 0 {
772 parts = append(parts, "--slides-radius:"+num(r)+"px")
773 }
774 return strings.Join(parts, ";")
775}
776
777func (c *renderer) headingBlock(b deck.Block) template.HTML {
778 level := int(numProp(b.Props, "level", 1))
779 if level < 1 || level > 3 {
780 level = 1
781 }
782 // A heading is one line by the schema; a stray second paragraph
783 // becomes a line break rather than a second heading.
784 lines := make([]template.HTML, 0, len(b.Text))
785 for _, p := range b.Text {
786 lines = append(lines, inline(p))
787 }
788 body := joinWith("<br>", lines)
789 if c.editing {
790 body = editingParagraphs("div", b.Text)
791 }
792 return elInline("h"+strconv.Itoa(level), c.attrs(b,
793 attr{name: "data-level", value: strconv.Itoa(level)}),
794 c.style(b), body)
795}
796
797func (c *renderer) textBlock(b deck.Block) template.HTML {
798 extra := []attr{{name: "data-size", value: sizeProp(b.Props, "m")}}
799 if a := alignProp(b.Props); a != "" {
800 extra = append(extra, attr{name: "data-align", value: a})
801 }
802 if c.editing {
803 return elInline("div", c.attrs(b, extra...), c.style(b), editingParagraphs("p", b.Text))
804 }
805 paras := make([]template.HTML, 0, len(b.Text))
806 for _, p := range b.Text {
807 paras = append(paras, elInline("p", nil, "", inline(p)))
808 }
809 return elBlock("div", c.attrs(b, extra...), c.style(b), paras)
810}
811
812func (c *renderer) listBlock(b deck.Block) template.HTML {
813 style, tag := "bullet", "ul"
814 if s, _ := b.Props["style"].(string); s == "number" {
815 style, tag = "number", "ol"
816 }
817 extra := []attr{
818 {name: "data-style", value: style},
819 {name: "data-size", value: sizeProp(b.Props, "m")},
820 }
821 // A nested list is a second list block with indent 1 (§2.6), not a
822 // nested <ul>: the schema has no nesting, so neither does this.
823 if n := int(numProp(b.Props, "indent", 0)); n > 0 {
824 if n > 3 {
825 n = 3
826 }
827 extra = append(extra, attr{name: "data-indent", value: strconv.Itoa(n)})
828 }
829 if c.editing {
830 return elInline(tag, c.attrs(b, extra...), c.style(b), editingParagraphs("li", b.Text))
831 }
832 items := make([]template.HTML, 0, len(b.Text))
833 for i, p := range b.Text {
834 var li []attr
835 if b.Items == "each" {
836 li = c.reveal.attrs(b.ID, i)
837 }
838 items = append(items, elInline("li", li, "", inline(p)))
839 }
840 return elBlock(tag, c.attrs(b, extra...), c.style(b), items)
841}
842
843func (c *renderer) quoteBlock(b deck.Block) template.HTML {
844 paras := make([]template.HTML, 0, len(b.Text))
845 for _, p := range b.Text {
846 paras = append(paras, elInline("p", nil, "", inline(p)))
847 }
848 // figure + figcaption rather than a <cite> loose inside the
849 // blockquote: the attribution is about the quote, it is not part of
850 // what was said.
851 children := []template.HTML{elBlock("blockquote", nil, "", paras)}
852 if c.editing {
853 children = []template.HTML{elInline("blockquote", nil, "", editingParagraphs("p", b.Text))}
854 }
855 if cite, _ := b.Props["cite"].(string); cite != "" {
856 children = append(children, elInline("figcaption", nil, "",
857 elInline("cite", nil, "", esc(cite))))
858 }
859 return elBlock("figure", c.attrs(b), c.style(b), children)
860}
861
862func (c *renderer) imageBlock(b deck.Block) template.HTML {
863 id := safeAssetID(stringProp(b.Props, "asset"))
864 fit := "cover"
865 if f, _ := b.Props["fit"].(string); f == "contain" {
866 fit = "contain"
867 }
868 extra := []attr{{name: "data-fit", value: fit}}
869 ref := c.assetRef(id)
870 if ref == "" {
871 // No asset, an id that is not an id, or an id nothing in this
872 // deck's `assets` map ever registered: an empty frame the
873 // editor shows as unfinished, never a broken <img>.
874 return elInline("figure", append(c.attrs(b, extra...),
875 attr{name: "data-missing-asset", value: "true"}), c.style(b), "")
876 }
877
878 alt, missing := c.altFor(b, id)
879 img := []attr{
880 {name: "src", value: c.assetPath(ref)},
881 {name: "alt", value: alt},
882 }
883 if a, ok := c.deck.Assets[id]; ok && a.Width > 0 && a.Height > 0 {
884 img = append(img,
885 attr{name: "width", value: strconv.Itoa(a.Width)},
886 attr{name: "height", value: strconv.Itoa(a.Height)})
887 }
888 if missing {
889 // §2.4 makes alt required. The attribute is never omitted — an
890 // <img> with no alt is read out as its filename — so a missing
891 // one is an empty alt plus a mark the editor can surface.
892 img = append(img, attr{name: "data-missing-alt", value: "true"})
893 }
894 return elBlock("figure", c.attrs(b, extra...), c.style(b),
895 []template.HTML{elVoid("img", img, "")})
896}
897
898// sceneBlock draws a scene block as its stills (scenes and clips spec
899// §3, §8.3): one child per state the block passes through, from `from`
900// to `to` (deck.Scene.Shown), each the state's still with its
901// description as the text alternative, or, with no still, the panel
902// Slides draws in its place (plan call R4): the scene's name and the
903// state's description in the theme's colours. The states after `from`
904// arrive on presses as an `each` list's items do, so a slide drawn at
905// a press marks them data-press and data-waiting; slides.css shows the
906// newest that has arrived. A scene the deck no longer has is the panel
907// with nothing on it.
908//
909// Wherever scripts run, fixtures/scene-layer.mjs puts the scene's own
910// frame over the block (data-scene names the scene); the stills stay
911// underneath, as what a frame that is not ready shows and what
912// assistive technology reads.
913func (c *renderer) sceneBlock(b deck.Block) template.HTML {
914 id := stringProp(b.Props, "scene")
915 var extra []attr
916 if deck.SceneID(id) {
917 extra = append(extra, attr{name: "data-scene", value: id})
918 }
919 sc, ok := c.deck.Scenes[id]
920 shown := sc.Shown(stringProp(b.Props, "from"), stringProp(b.Props, "to"))
921 var states []template.HTML
922 for _, i := range shown {
923 states = append(states, c.sceneState(sc, sc.States[i], c.reveal.attrs(b.ID, i)))
924 }
925 if len(states) == 0 {
926 name := ""
927 if ok {
928 name = sc.Name
929 }
930 states = append(states, scenePanel("", name, ""))
931 }
932 return elBlock("div", c.attrs(b, extra...), c.style(b), states)
933}
934
935// sceneState is one state of a scene block: its still, or the panel.
936func (c *renderer) sceneState(sc deck.Scene, st deck.SceneState, marks []attr) template.HTML {
937 text := st.Description
938 if text == "" {
939 text = st.Name
940 }
941 _, a, ok := c.deck.StillOf(sc, st.ID)
942 ref := safeRef(a.Ref)
943 if !ok || ref == "" {
944 return scenePanel(st.ID, sc.Name, text, marks...)
945 }
946 img := []attr{
947 {name: "data-scene-state", value: st.ID},
948 {name: "src", value: c.assetPath(ref)},
949 {name: "alt", value: text},
950 }
951 if a.Width > 0 && a.Height > 0 {
952 img = append(img,
953 attr{name: "width", value: strconv.Itoa(a.Width)},
954 attr{name: "height", value: strconv.Itoa(a.Height)})
955 }
956 return elVoid("img", append(img, marks...), "")
957}
958
959// scenePanel is the placeholder for a state with no still: the scene's
960// name and the state's description, each only when there is one.
961func scenePanel(state, name, text string, marks ...attr) template.HTML {
962 attrs := append([]attr{
963 {name: "data-scene-state", value: state},
964 {name: "data-scene-placeholder", bare: true},
965 }, marks...)
966 var words []template.HTML
967 if name != "" {
968 words = append(words, elInline("strong", nil, "", esc(name)))
969 }
970 if text != "" {
971 words = append(words, elInline("span", nil, "", esc(text)))
972 }
973 return elBlock("div", attrs, "", words)
974}
975
976// clipBlock draws a clip block (scenes and clips spec §2) as its
977// poster, the picture of its video's first frame, described as an image
978// is (the block's description, or the video's): what a reader with scripts
979// off, a thumbnail, the PDF, the presenter's Next and the remote show.
980// data-clip-src is the video's address and data-clip how it plays, for
981// fixtures/clip.mjs, which puts the video over the poster wherever
982// scripts run. A clip played on a press takes that press as a list item
983// takes one, so a slide drawn at a press marks it on a child of its own
984// (data-clip-press), never on the block: the poster is there from the
985// slide's arrival, and the press starts the video. A clip that names no
986// video, or a video with no poster the deck holds, is an empty frame, as
987// an image with no asset is.
988func (c *renderer) clipBlock(b deck.Block) template.HTML {
989 id := safeAssetID(stringProp(b.Props, "asset"))
990 play := stringProp(b.Props, "play")
991 if play != "press" && play != "loop" {
992 play = "once"
993 }
994 marks := c.reveal.attrs(b.ID, -1)
995 own := marks
996 if play == "press" {
997 own = nil
998 }
999 video, ref := c.deck.Assets[id], c.assetRef(id)
1000 _, poster, ok := c.deck.PosterOf(id)
1001 if ref == "" || !ok || safeRef(poster.Ref) == "" {
1002 return elInline("figure", c.blockAttrs(b, own,
1003 attr{name: "data-clip", value: play},
1004 attr{name: "data-missing-asset", value: "true"}), c.style(b), "")
1005 }
1006 // Described as a picture is (altFor): the block's own description,
1007 // empty when it is marked decorative, else the video's.
1008 alt, missing := c.altFor(b, id)
1009 img := []attr{
1010 {name: "src", value: c.assetPath(safeRef(poster.Ref))},
1011 {name: "alt", value: alt},
1012 }
1013 if video.Width > 0 && video.Height > 0 {
1014 img = append(img,
1015 attr{name: "width", value: strconv.Itoa(video.Width)},
1016 attr{name: "height", value: strconv.Itoa(video.Height)})
1017 }
1018 if missing {
1019 img = append(img, attr{name: "data-missing-alt", value: "true"})
1020 }
1021 children := []template.HTML{elVoid("img", img, "")}
1022 if play == "press" && len(marks) > 0 {
1023 children = append(children, elInline("span", append([]attr{{name: "data-clip-press", bare: true}}, marks...), "", ""))
1024 }
1025 return elBlock("figure", c.blockAttrs(b, own,
1026 attr{name: "data-clip", value: play},
1027 attr{name: "data-clip-src", value: c.assetPath(ref)}), c.style(b), children)
1028}
1029
1030// altFor resolves an image's alternative text: the block's own alt, the
1031// asset's registered alt, or empty. Decorative means empty on purpose
1032// (§2.4) and is not reported as missing.
1033func (c *renderer) altFor(b deck.Block, id string) (alt string, missing bool) {
1034 if v, ok := b.Props["alt"].(string); ok && v != "" {
1035 return v, false
1036 }
1037 if dec, _ := b.Props["decorative"].(bool); dec {
1038 return "", false
1039 }
1040 if a, ok := c.deck.Assets[id]; ok && a.Alt != "" {
1041 return a.Alt, false
1042 }
1043 return "", true
1044}
1045
1046func (c *renderer) columnsBlock(b deck.Block, byID map[string]deck.Block, done map[string]bool) template.HTML {
1047 count := int(numProp(b.Props, "count", 2))
1048 if count != 3 {
1049 count = 2
1050 }
1051 kids := make([]deck.Block, 0, len(childIDs(b)))
1052 for _, id := range childIDs(b) {
1053 if child, ok := byID[id]; ok {
1054 kids = append(kids, child)
1055 }
1056 }
1057 // The phone layer's order applies among siblings, and a columns
1058 // block's children are siblings of each other (codex 10).
1059 if c.phone {
1060 kids = phoneOrder(kids)
1061 }
1062 var children []template.HTML
1063 for _, child := range kids {
1064 if h := c.block(child, byID, done); h != "" {
1065 children = append(children, h)
1066 }
1067 }
1068 return elBlock("div", c.attrs(b,
1069 attr{name: "data-count", value: strconv.Itoa(count)}), c.style(b), children)
1070}
1071
1072func (c *renderer) codeBlock(b deck.Block) template.HTML {
1073 extra := []attr{{name: "data-size", value: sizeProp(b.Props, "m")}}
1074 code := []attr{}
1075 if lang := stringProp(b.Props, "language"); langPattern.MatchString(lang) {
1076 extra = append(extra, attr{name: "data-language", value: lang})
1077 code = append(code, attr{name: "class", value: "language-" + lang})
1078 }
1079 // No highlighter: the text is the text, escaped, one paragraph per
1080 // line (§2.4). Nothing inside a <pre> gets extra whitespace.
1081 body := esc(b.Text.Plain())
1082 if c.editing {
1083 body = editingParagraphs("div", b.Text)
1084 }
1085 return elInline("pre", c.attrs(b, extra...), c.style(b),
1086 elInline("code", code, "", body))
1087}
1088
1089// shapeKinds is the §2.4 vocabulary. Anything else draws a rectangle,
1090// which is the shape that says least.
1091var shapeKinds = []string{"rect", "ellipse", "line", "arrow"}
1092
1093func (c *renderer) shapeBlock(b deck.Block) template.HTML {
1094 kind := stringProp(b.Props, "kind")
1095 if !slices.Contains(shapeKinds, kind) {
1096 kind = "rect"
1097 }
1098 fill := safeColor(stringProp(b.Props, "fill"))
1099 if fill == "" {
1100 fill = "none"
1101 }
1102 stroke := safeColor(stringProp(b.Props, "stroke"))
1103 if stroke == "" {
1104 stroke = "currentColor"
1105 }
1106 width := num(clamp(numProp(b.Props, "strokeWidth", 1), 0, 50))
1107 radius := num(clamp(numProp(b.Props, "radius", 0), 0, 50))
1108
1109 // A 0..100 viewBox stretched to the block's box, with non-scaling
1110 // strokes so a wide shape does not get a fat left edge and a thin
1111 // top one. Geometry only — the colours come from props, the size
1112 // from the box or the region.
1113 geom := []attr{{name: "fill", value: fill}, {name: "stroke", value: stroke},
1114 {name: "stroke-width", value: width}, {name: "vector-effect", value: "non-scaling-stroke"}}
1115 var shape template.HTML
1116 switch kind {
1117 case "ellipse":
1118 shape = elClosed("ellipse", append([]attr{
1119 {name: "cx", value: "50"}, {name: "cy", value: "50"},
1120 {name: "rx", value: "49"}, {name: "ry", value: "49"}}, geom...))
1121 case "line":
1122 shape = elClosed("line", append([]attr{
1123 {name: "x1", value: "1"}, {name: "y1", value: "50"},
1124 {name: "x2", value: "99"}, {name: "y2", value: "50"}}, geom...))
1125 case "arrow":
1126 line := elClosed("line", append([]attr{
1127 {name: "x1", value: "1"}, {name: "y1", value: "50"},
1128 {name: "x2", value: "88"}, {name: "y2", value: "50"}}, geom...))
1129 head := elClosed("path", []attr{
1130 {name: "d", value: "M99 50 L86 42 L86 58 Z"},
1131 {name: "fill", value: stroke}, {name: "stroke", value: "none"}})
1132 shape = join([]template.HTML{line, head})
1133 default:
1134 shape = elClosed("rect", append([]attr{
1135 {name: "x", value: "1"}, {name: "y", value: "1"},
1136 {name: "width", value: "98"}, {name: "height", value: "98"},
1137 {name: "rx", value: radius}}, geom...))
1138 }
1139
1140 extra := []attr{
1141 {name: "data-kind", value: kind},
1142 {name: "viewBox", value: "0 0 100 100"},
1143 {name: "preserveAspectRatio", value: "none"},
1144 {name: "focusable", value: "false"},
1145 }
1146 children := []template.HTML{shape}
1147 // A shape with a label is a picture with a name; one without is
1148 // decoration, and is kept out of the accessibility tree rather than
1149 // announced as "graphic".
1150 if label := b.Text.Plain(); label != "" {
1151 extra = append(extra, attr{name: "role", value: "img"})
1152 children = append([]template.HTML{elInline("title", nil, "", esc(label))}, children...)
1153 } else {
1154 extra = append(extra, attr{name: "aria-hidden", value: "true"})
1155 }
1156 return elBlock("svg", c.attrs(b, extra...), c.style(b), children)
1157}
1158
1159// qrBlock is a follow-along code: the code for the follow link the box
1160// holds, drawn in the slide's own text colour on its background
1161// (slides.css), with the short address printed under it for somebody
1162// whose camera will not read it. The path is one subpath per run of
1163// dark modules (qr.Runs), in module units, and the viewBox is the whole
1164// code with its quiet zone, so the picture scales to whatever the box
1165// gives it.
1166//
1167// What is drawn is Options.QR's address for the stored one, never the
1168// stored one as it stands: the document takes any follow-shaped
1169// address, and only the app knows which are this deck's live links
1170// and which link this reader holds. A box with no link yet, or one the
1171// app did not vouch for, is an empty frame on the editor's stage,
1172// waiting for its link, and nothing at all for a reader: a code that
1173// goes nowhere, or somewhere else, is worse than no code.
1174func (c *renderer) qrBlock(b deck.Block) template.HTML {
1175 url, ok := c.qr[stringProp(b.Props, "url")]
1176 address := ""
1177 if ok {
1178 address, ok = deck.FollowAddress(url)
1179 }
1180 var modules [][]bool
1181 if ok {
1182 var err error
1183 if modules, err = qr.Modules(url); err != nil {
1184 ok = false
1185 }
1186 }
1187 if !ok {
1188 if c.editing {
1189 return elInline("figure", c.attrs(b, attr{name: "data-missing-qr", value: "true"}), c.style(b), "")
1190 }
1191 return ""
1192 }
1193 var d strings.Builder
1194 for _, r := range qr.Runs(modules) {
1195 fmt.Fprintf(&d, "M%d %dh%dv1h-%dz", r.X, r.Y, r.N, r.N)
1196 }
1197 n := strconv.Itoa(len(modules))
1198 alt := address
1199 if c.qrAlt != "" {
1200 alt = strings.ReplaceAll(c.qrAlt, "{address}", address)
1201 }
1202 code := elBlock("svg", []attr{
1203 {name: "viewBox", value: "0 0 " + n + " " + n},
1204 {name: "role", value: "img"},
1205 {name: "aria-label", value: alt},
1206 {name: "focusable", value: "false"},
1207 }, "", []template.HTML{
1208 elClosed("rect", []attr{{name: "width", value: n}, {name: "height", value: n}}),
1209 elClosed("path", []attr{{name: "d", value: d.String()}}),
1210 })
1211 return elBlock("figure", c.attrs(b), c.style(b), []template.HTML{
1212 code,
1213 elInline("figcaption", nil, "", esc(address)),
1214 })
1215}
1216
1217func (c *renderer) tableBlock(b deck.Block) template.HTML {
1218 cells := cellsProp(b.Props)
1219 // A deck may also carry a "rows" prop; it is never read here, because
1220 // row count is derived below from len(cells) and cols.
1221 cols := int(numProp(b.Props, "cols", 0))
1222 if cols < 1 {
1223 cols = len(cells)
1224 }
1225 if cols < 1 {
1226 return elInline("table", c.attrs(b), c.style(b), "")
1227 }
1228 header, _ := b.Props["header"].(bool)
1229
1230 var rows [][]deck.Text
1231 for i := 0; i < len(cells); i += cols {
1232 end := min(i+cols, len(cells))
1233 rows = append(rows, cells[i:end])
1234 }
1235
1236 row := func(cs []deck.Text, head bool) template.HTML {
1237 out := make([]template.HTML, 0, len(cs))
1238 for _, cell := range cs {
1239 // A cell is the same text schema, but short: paragraphs
1240 // become line breaks rather than <p>, so a one-line cell is
1241 // one line high.
1242 lines := make([]template.HTML, 0, len(cell))
1243 for _, p := range cell {
1244 lines = append(lines, inline(p))
1245 }
1246 body := joinWith("<br>", lines)
1247 if c.editing {
1248 body = editingParagraphs("div", cell)
1249 }
1250 if head {
1251 out = append(out, elInline("th", []attr{{name: "scope", value: "col"}}, "", body))
1252 } else {
1253 out = append(out, elInline("td", nil, "", body))
1254 }
1255 }
1256 return elBlock("tr", nil, "", out)
1257 }
1258
1259 var children []template.HTML
1260 if header && len(rows) > 0 {
1261 children = append(children, elBlock("thead", nil, "", []template.HTML{row(rows[0], true)}))
1262 rows = rows[1:]
1263 }
1264 body := make([]template.HTML, 0, len(rows))
1265 for _, r := range rows {
1266 body = append(body, row(r, false))
1267 }
1268 if len(body) > 0 {
1269 children = append(children, elBlock("tbody", nil, "", body))
1270 }
1271 return elBlock("table", c.attrs(b), c.style(b), children)
1272}
1273
1274// ── Text ──────────────────────────────────────────────────────────────
1275
1276// runTemplate is the one real html/template in this package, and it
1277// covers the one place a deck's content decides markup: a run's marks
1278// and its link. The nesting is fixed — link outside, then strong, em,
1279// mark, code — so the same run always produces the same bytes.
1280//
1281// rel="noopener" on every link (§4.1's brief). No target: a slide is
1282// not a menu, and a link that opened a tab the reader did not ask for
1283// would take them out of a presentation mid-sentence.
1284var runTemplate = template.Must(template.New("run").Parse(
1285 `{{define "run"}}{{if .Link}}<a href="{{.Href}}" rel="noopener">{{template "marks" .}}</a>` +
1286 `{{else}}{{template "marks" .}}{{end}}{{end}}` +
1287 `{{define "marks"}}{{if .B}}<strong>{{end}}{{if .I}}<em>{{end}}{{if .H}}<mark>{{end}}{{if .C}}<code>{{end}}` +
1288 `{{.T}}` +
1289 `{{if .C}}</code>{{end}}{{if .H}}</mark>{{end}}{{if .I}}</em>{{end}}{{if .B}}</strong>{{end}}{{end}}`))
1290
1291// runView is one run as the template sees it: the marks, the text, and
1292// a href that has already passed safeHref.
1293type runView struct {
1294 T string
1295 B, I, C, H bool
1296 Href string
1297 Link bool
1298}
1299
1300// inline renders one paragraph's runs, with no wrapping element — the
1301// caller decides whether they sit in a <p>, an <li>, a <th> or a
1302// heading.
1303func inline(runs []deck.Run) template.HTML {
1304 var buf bytes.Buffer
1305 for _, r := range runs {
1306 href := safeHref(r.Href)
1307 v := runView{T: r.T, B: r.B, I: r.I, C: r.C, H: r.H, Href: href, Link: href != ""}
1308 if err := runTemplate.ExecuteTemplate(&buf, "run", v); err != nil {
1309 // Executing a template over a struct of strings and bools
1310 // has no failure mode; the fallback exists so a future one
1311 // degrades to plain escaped words rather than to markup.
1312 return esc(plainRuns(runs))
1313 }
1314 }
1315 return template.HTML(buf.String())
1316}
1317
1318func plainRuns(runs []deck.Run) string {
1319 var b strings.Builder
1320 for _, r := range runs {
1321 b.WriteString(r.T)
1322 }
1323 return b.String()
1324}
1325
1326// linkSchemes is what a link mark may point at. Everything else — a
1327// javascript: URL, a data: document, a bare relative path somebody
1328// pasted — renders as the text it was, with no anchor: a link that goes
1329// nowhere useful is worse than words, and a neutered href still looks
1330// clickable.
1331var linkSchemes = []string{"http", "https", "mailto"}
1332
1333func safeHref(raw string) string {
1334 if raw == "" || strings.TrimSpace(raw) != raw {
1335 return ""
1336 }
1337 u, err := url.Parse(raw)
1338 if err != nil {
1339 return ""
1340 }
1341 if !slices.Contains(linkSchemes, strings.ToLower(u.Scheme)) {
1342 return ""
1343 }
1344 return raw
1345}
1346
1347// ── Elements ──────────────────────────────────────────────────────────
1348
1349// attr is one attribute, in the order the renderer writes it. A bare
1350// attribute (slides-slide, slides-block, slides-region) is written with
1351// no value: it is a marker for a CSS selector, not data.
1352type attr struct {
1353 name string
1354 value string
1355 bare bool
1356}
1357
1358// openTag writes `<tag a="b" style="…">`. Names are literals from this
1359// file; values are escaped; style has already been assembled from
1360// allowlisted parts.
1361func openTag(tag string, attrs []attr, style string) string {
1362 var b strings.Builder
1363 b.WriteString("<")
1364 b.WriteString(tag)
1365 for _, a := range attrs {
1366 b.WriteString(" ")
1367 b.WriteString(a.name)
1368 if a.bare {
1369 continue
1370 }
1371 b.WriteString(`="`)
1372 b.WriteString(template.HTMLEscapeString(a.value))
1373 b.WriteString(`"`)
1374 }
1375 if style != "" {
1376 b.WriteString(` style="`)
1377 b.WriteString(template.HTMLEscapeString(style))
1378 b.WriteString(`"`)
1379 }
1380 b.WriteString(">")
1381 return b.String()
1382}
1383
1384// elInline writes an element whose content is inline: no whitespace is
1385// added, because inside a <p>, a <pre> or a heading it would be read.
1386func elInline(tag string, attrs []attr, style string, body template.HTML) template.HTML {
1387 return template.HTML(openTag(tag, attrs, style) + string(body) + "</" + tag + ">")
1388}
1389
1390// elBlock writes an element whose children are blocks, one per line —
1391// the newlines are what makes a golden file readable, and they are
1392// collapsed away wherever the stylesheet cares (grid and flex ignore
1393// whitespace between items).
1394func elBlock(tag string, attrs []attr, style string, children []template.HTML) template.HTML {
1395 open := openTag(tag, attrs, style)
1396 if len(children) == 0 {
1397 return template.HTML(open + "</" + tag + ">")
1398 }
1399 return template.HTML(open + "\n" + string(join(children)) + "\n</" + tag + ">")
1400}
1401
1402// elVoid writes an HTML void element: <img>, <hr>. There is no closing
1403// tag to write, and a trailing slash would be noise.
1404func elVoid(tag string, attrs []attr, style string) template.HTML {
1405 return template.HTML(openTag(tag, attrs, style))
1406}
1407
1408// elClosed writes a self-closing element: <rect …/>. Only for the SVG
1409// primitives, and the slash is load-bearing — inside <svg> the HTML
1410// parser is in foreign content, where nothing is void and `<line>` with
1411// no slash swallows whatever follows it as a child. An arrow drawn that
1412// way loses its head, because a shape element's children never paint.
1413func elClosed(tag string, attrs []attr) template.HTML {
1414 return template.HTML(strings.TrimSuffix(openTag(tag, attrs, ""), ">") + " />")
1415}
1416
1417func esc(s string) template.HTML { return template.HTML(template.HTMLEscapeString(s)) }
1418
1419func join(parts []template.HTML) template.HTML { return joinWith("\n", parts) }
1420
1421func joinWith(sep string, parts []template.HTML) template.HTML {
1422 ss := make([]string, len(parts))
1423 for i, p := range parts {
1424 ss[i] = string(p)
1425 }
1426 return template.HTML(strings.Join(ss, sep))
1427}
1428
1429// ── Props ─────────────────────────────────────────────────────────────
1430//
1431// props is free-form (deck.Block's own comment says why), so every read
1432// takes a default and every enumerated value is checked against its
1433// vocabulary. A prop of the wrong type is a peer mid-edit, not a bug to
1434// propagate.
1435
1436func stringProp(props map[string]any, key string) string {
1437 s, _ := props[key].(string)
1438 return s
1439}
1440
1441func numProp(props map[string]any, key string, def float64) float64 {
1442 switch v := props[key].(type) {
1443 case float64:
1444 return v
1445 case int:
1446 return float64(v)
1447 case json.Number:
1448 if f, err := v.Float64(); err == nil {
1449 return f
1450 }
1451 }
1452 return def
1453}
1454
1455// sizeProp reads props.size as a size step; sizeStep is the same check
1456// for a step that arrived somewhere else, like the phone layer's.
1457func sizeProp(props map[string]any, def string) string {
1458 s, _ := props["size"].(string)
1459 return sizeStep(s, def)
1460}
1461
1462// sizeStep is §2.4's s, m, l — defaulted rather than passed through, so
1463// an unknown step never reaches a CSS selector that has no rule for it
1464// and leaves a block at whatever size it inherited.
1465func sizeStep(s, def string) string {
1466 switch s {
1467 case "s", "m", "l":
1468 return s
1469 }
1470 return def
1471}
1472
1473func alignProp(props map[string]any) string {
1474 switch a, _ := props["align"].(string); a {
1475 case "start", "center", "end", "justify":
1476 return a
1477 }
1478 return ""
1479}
1480
1481// childIDs is a columns block's props.children (§2.4), as they arrive
1482// from JSON.
1483func childIDs(b deck.Block) []string {
1484 switch v := b.Props["children"].(type) {
1485 case []string:
1486 return v
1487 case []any:
1488 out := make([]string, 0, len(v))
1489 for _, c := range v {
1490 if s, ok := c.(string); ok {
1491 out = append(out, s)
1492 }
1493 }
1494 return out
1495 }
1496 return nil
1497}
1498
1499// cellsProp reads a table's props.cells: a row-major array of texts
1500// (core/src/view.rs). It goes back through JSON rather than being
1501// walked by hand — the view built it with encoding/json's shapes, and a
1502// round trip is both shorter and harder to get wrong than five type
1503// assertions deep.
1504func cellsProp(props map[string]any) []deck.Text {
1505 raw, ok := props["cells"]
1506 if !ok {
1507 return nil
1508 }
1509 b, err := json.Marshal(raw)
1510 if err != nil {
1511 return nil
1512 }
1513 var out []deck.Text
1514 if err := json.Unmarshal(b, &out); err != nil {
1515 return nil
1516 }
1517 return out
1518}
1519
1520// ── Values that land in CSS or a URL ──────────────────────────────────
1521
1522var (
1523 // colorPattern is a hex colour or a plain CSS colour keyword.
1524 // Deliberately no functions: oklch() and color-mix() are free in
1525 // this family's own stylesheets (rastrillo SKILL.md), but a value
1526 // somebody typed into a deck is not a stylesheet, and a syntax that
1527 // takes arbitrary nested tokens is a syntax to keep out of a style
1528 // attribute.
1529 colorPattern = regexp.MustCompile(`^(#[0-9a-fA-F]{3,8}|[a-zA-Z]{1,24})$`)
1530
1531 // fontPattern is a font-family list: names, quotes, commas, and the
1532 // generic families. No parentheses, so no url() and no expression().
1533 fontPattern = regexp.MustCompile(`^[A-Za-z0-9 ,'._-]{1,200}$`)
1534
1535 // idPattern is an asset id. The core mints them as 12 lowercase
1536 // base32 characters; this is wider so an id from a later scheme
1537 // still resolves, and narrow enough that no id can be a path.
1538 idPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
1539
1540 // refPattern is an object-store address (deck.Asset.Ref). One path
1541 // segment of unreserved characters: the store mints a hex SHA-256,
1542 // and this stays wide enough for a store that mints something else
1543 // without ever admitting a slash, a colon, or a character that
1544 // would have to be percent-encoded to survive a URL.
1545 refPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,128}$`)
1546
1547 // langPattern is a code block's language, which becomes a class.
1548 langPattern = regexp.MustCompile(`^[A-Za-z0-9+#._-]{1,32}$`)
1549)
1550
1551// safeColor takes a hex colour or a CSS colour keyword. It is for the
1552// values whose contrast nothing has to compute: a shape's fill and
1553// stroke, which sit on whatever the author put behind them.
1554func safeColor(v string) string {
1555 v = strings.TrimSpace(v)
1556 if !colorPattern.MatchString(v) {
1557 return ""
1558 }
1559 if strings.HasPrefix(v, "#") {
1560 switch len(v) {
1561 case 4, 5, 7, 9: // #rgb, #rgba, #rrggbb, #rrggbbaa
1562 default:
1563 return ""
1564 }
1565 }
1566 return v
1567}
1568
1569// safeHexColor is safeColor narrowed to opaque hex — #rgb or #rrggbb.
1570// It is for the two colours whose readability this package has to
1571// promise: a slide's background and a deck's accent. A keyword or an
1572// alpha channel is dropped rather than guessed at, because a colour
1573// with no measurable luminance cannot be checked against §8's floor.
1574func safeHexColor(v string) string {
1575 v = safeColor(v)
1576 if _, ok := parseHexColor(v); !ok {
1577 return ""
1578 }
1579 return v
1580}
1581
1582func safeFontStack(v string) string {
1583 v = strings.TrimSpace(v)
1584 if !fontPattern.MatchString(v) {
1585 return ""
1586 }
1587 return v
1588}
1589
1590func safeAssetID(v string) string {
1591 if !idPattern.MatchString(v) {
1592 return ""
1593 }
1594 return v
1595}
1596
1597// safeRef is an object-store address as it may appear in a URL path:
1598// one segment, no slash, no colon, nothing a URL would have to escape.
1599// rastrillo blobs mints a hex SHA-256, which passes; anything else is
1600// dropped rather than escaped — the rule every other value that lands
1601// in a URL in this file follows.
1602func safeRef(v string) string {
1603 if !refPattern.MatchString(v) {
1604 return ""
1605 }
1606 return v
1607}
1608
1609// ── Numbers ───────────────────────────────────────────────────────────
1610
1611// pct turns a box fraction into a percentage with no floating-point
1612// tail: 0.06 is "6%", not "6.000000000000001%".
1613func pct(v float64) string { return trimNum(strconv.FormatFloat(v*100, 'f', 4, 64)) + "%" }
1614
1615// fracs is a box as the four decimals §2.3 stores, for data-phone-box —
1616// a value the editor reads back, not one CSS uses. A zero of either
1617// sign, or what rounds to one, is written without a sign.
1618func fracs(b deck.Box) string {
1619 four := func(v float64) string {
1620 s := strconv.FormatFloat(v, 'f', 4, 64)
1621 if s == "-0.0000" {
1622 return "0.0000"
1623 }
1624 return s
1625 }
1626 return strings.Join([]string{four(b.X), four(b.Y), four(b.W), four(b.H)}, ",")
1627}
1628
1629// num is a prop number as CSS or SVG wants it.
1630func num(v float64) string { return trimNum(strconv.FormatFloat(v, 'f', 4, 64)) }
1631
1632func trimNum(s string) string {
1633 if strings.Contains(s, ".") {
1634 s = strings.TrimRight(s, "0")
1635 s = strings.TrimSuffix(s, ".")
1636 }
1637 if s == "" || s == "-" || s == "-0" {
1638 return "0"
1639 }
1640 return s
1641}
1642
1643func clamp(v, lo, hi float64) float64 {
1644 if v < lo {
1645 return lo
1646 }
1647 if v > hi {
1648 return hi
1649 }
1650 return v
1651}
1652
1653// AssetPaths is every asset the slide at index draws (its background,
1654// its image boxes, its scene blocks' stills and its clips' posters), as the URLs render writes for them under
1655// assetBase, each once, in block order. It reads the same ids the
1656// renderer does, so a window can fetch the pictures before the slide
1657// is shown.
1658func AssetPaths(d *deck.Deck, index int, assetBase string) []string {
1659 out := []string{}
1660 if d == nil || index < 0 || index >= len(d.Slides) {
1661 return out
1662 }
1663 c := &renderer{deck: d, assetBase: strings.TrimSuffix(strings.TrimSpace(assetBase), "/")}
1664 s := d.Slides[index]
1665 seen := map[string]bool{}
1666 add := func(id string) {
1667 ref := c.assetRef(safeAssetID(id))
1668 if ref == "" || seen[ref] {
1669 return
1670 }
1671 seen[ref] = true
1672 out = append(out, c.assetPath(ref))
1673 }
1674 if s.Background.Kind == "image" {
1675 add(s.Background.Value)
1676 }
1677 for _, b := range s.Blocks {
1678 switch b.Type {
1679 case "image":
1680 add(stringProp(b.Props, "asset"))
1681 case "clip":
1682 if id, _, ok := d.PosterOf(stringProp(b.Props, "asset")); ok {
1683 add(id)
1684 }
1685 case "scene":
1686 // Every still the block may show, as it shows them.
1687 sc := d.Scenes[stringProp(b.Props, "scene")]
1688 for _, i := range sc.Shown(stringProp(b.Props, "from"), stringProp(b.Props, "to")) {
1689 if id, _, ok := d.StillOf(sc, sc.States[i].ID); ok {
1690 add(id)
1691 }
1692 }
1693 }
1694 }
1695 return out
1696}
1697
1698// ClipPaths is the video of every clip on the slide at index, as the
1699// URLs render writes for them under assetBase (data-clip-src), each
1700// once, in block order: what a presenting window fetches with the talk
1701// so a press on one needs no network. A clip with no poster is drawn
1702// empty, and has none.
1703func ClipPaths(d *deck.Deck, index int, assetBase string) []string {
1704 var out []string
1705 if d == nil || index < 0 || index >= len(d.Slides) {
1706 return out
1707 }
1708 c := &renderer{deck: d, assetBase: strings.TrimSuffix(strings.TrimSpace(assetBase), "/")}
1709 seen := map[string]bool{}
1710 for _, b := range d.Slides[index].Blocks {
1711 id := safeAssetID(stringProp(b.Props, "asset"))
1712 ref := c.assetRef(id)
1713 if b.Type != "clip" || ref == "" || seen[ref] {
1714 continue
1715 }
1716 if _, _, ok := d.PosterOf(id); !ok {
1717 continue
1718 }
1719 seen[ref] = true
1720 out = append(out, c.assetPath(ref))
1721 }
1722 return out
1723}
1724