oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/strip.mjs — the slide strip: one item per slide, each a
2// server-drawn picture of it (`/d/{sqid}/slides/{id}.svg`, thumbs.go),
3// the slide's label, and the word "current" on the one on stage.
4//
5// An <img> of an SVG, not a scaled copy of the slide's HTML, which is
6// what this used to be: nine sections with every block and every run
7// live in the page, re-laid-out on every resize, and a second opinion
8// about what a slide looks like. One image each is smaller to send,
9// cheaper to paint, and is the same picture the PDF export is made of,
10// because both come off one paint list.
11//
12// The server renders the whole strip on the page; this keeps it in
13// line with the Y.Doc afterwards. sync() reconciles the items with the
14// deck's slide order (adding, dropping, reordering — never re-fetching
15// on its own), and marks anything it added as dirty; mark(id) marks a
16// slide whose content changed. flush() re-points every dirty
17// thumbnail's src at a URL carrying the deck's current seq — and the
18// caller decides when: after a remote change, straight away; after a
19// local one, once the save has landed, because until then the server
20// would draw the slide as it was (or, for a new slide, not at all).
21// The seq is what makes the browser ask again; the route's ETag is
22// what makes asking cheap for the slides that did not change.
23//
24// Navigation is the URL hash: every item's link is #<slide id>, and
25// editor-entry.js loads the stage on hashchange. No click handler for
26// it — the link is the control, for a pointer and a keyboard alike.
27// Each item also carries its menu (add after, duplicate, move, delete),
28// cloned with the item from the page's <template>, which a right-click
29// on the item opens too; reordering by drag and by Alt+arrows is
30// strip-reorder.mjs.
31//
32// Each item says too what the server says of it at the first paint
33// (steps and presenter spec §4): data-talk, full or parked, which
34// editor.css draws as a dashed edge or a slim bar, with the words for
35// it after the title; its count of presses in its picture's corner; and
36// its menu's two talk toggles pressed. relabel() keeps them current from
37// describe(), which is each slide's {talk, presses} by id.
38//
39// The <ol>'s last child is not a slide: li[slides-strip-new], New slide
40// and its layouts (spec §6.1). Every item this adds or moves goes
41// before it, and it is never one of items().
42import { slideIDs, slideHeading } from './stage.mjs'
43import { pressesWords } from './play-through.mjs'
44
45/**
46 * A thumbnail's label: the slide's first heading's words, or the
47 * numbered fallback ("Slide {n}").
48 *
49 * From the document, not from the picture: an <img> has no text to
50 * read, and the heading in the Y.Doc is current the moment it is typed
51 * rather than one fetch later.
52 */
53export function labelFor (ydoc, id, n, fallback) {
54 const words = ydoc ? slideHeading(ydoc, id) : ''
55 return words || fallback.replace('{n}', String(n))
56}
57
58/** What sync has to do to turn `have` (item ids in DOM order) into `want`. */
59export function plan (have, want) {
60 const has = new Set(have)
61 const wants = new Set(want)
62 return {
63 add: want.filter(id => !has.has(id)),
64 drop: have.filter(id => !wants.has(id)),
65 order: want.slice()
66 }
67}
68
69/**
70 * Mounts the strip over root (the <ol>). thumbURL(id) is the address
71 * of a slide's picture at the deck's current seq; template is the
72 * page's <template> of one item; slideLabel is the catalog's
73 * "Slide {n}"; onCommand(name, id) hears the item menu; describe() is
74 * a Map of each slide's {talk, presses}, and texts the catalog's words
75 * for them ({one, many, full, parked}). Returns
76 * {sync, mark, flush, relabel, setCurrent, destroy}.
77 */
78export function mountStrip ({ root, ydoc, thumbURL, template, slideLabel, onCommand = () => {}, describe = () => new Map(), texts = {} }) {
79 const dirty = new Set()
80 // The <ol> outlives any one Y.Doc: a resync mounts a second strip
81 // over the same element, and destroy() is how the first lets go.
82 const abort = new AbortController()
83
84 // The item menu: five commands, each handed to the entry with the
85 // slide's id, the menu closed first (rastrillo.js closes it on an
86 // outside click, not on a press inside).
87 root.addEventListener('click', e => {
88 const btn = e.target.closest('[data-slide-command]')
89 const li = btn && btn.closest('[slides-strip-item]')
90 if (!li) return
91 const menu = btn.closest('details')
92 if (menu) menu.open = false
93 onCommand(btn.dataset.slideCommand, li.dataset.slideId)
94 }, { signal: abort.signal })
95
96 // A right-click on an item opens its menu, as the ⋮ does: the
97 // trigger focused, as a press on it leaves it, so Escape and Tab
98 // behave the same. Anywhere else (the New slide row) the browser's
99 // own menu is left alone.
100 root.addEventListener('contextmenu', e => {
101 const li = e.target.closest('[slides-strip-item]')
102 const menu = li && li.querySelector('[slides-strip-menu]')
103 if (!menu) return
104 e.preventDefault()
105 // A <details>' first child is its <summary>, the ⋮.
106 const summary = menu.firstElementChild
107 if (summary) summary.focus()
108 menu.open = true
109 }, { signal: abort.signal })
110
111 function items () {
112 return Array.from(root.querySelectorAll('[slides-strip-item]'))
113 }
114
115 // Where an item at the end goes: before the New slide row, or last
116 // when the page has none.
117 function tail () {
118 return root.querySelector('[slides-strip-new]')
119 }
120
121 function itemFor (id) {
122 return items().find(li => li.dataset.slideId === id) || null
123 }
124
125 // A new item is the page's own <template> cloned, so its markup and
126 // its words (the menu's items, "Current slide") are the server's.
127 function makeItem (id) {
128 const li = template.content.firstElementChild.cloneNode(true)
129 li.dataset.slideId = id
130 li.querySelector('[slides-strip-link]').href = '#' + id
131 const img = li.querySelector('[slides-thumb-img]')
132 // The src is set by the flush sync() schedules, not here: a slide
133 // this tab has only just added does not exist on the server yet,
134 // and asking for its picture now would be one guaranteed 404 per
135 // new slide.
136 if (img) img.alt = ''
137 return li
138 }
139
140 // The number goes in two: the gutter's, drawn and hidden from a
141 // screen reader, and its hidden twin at the start of the link's name.
142 // Every change of order or count ends here (sync, flush), so a new
143 // item from the template, a drag, Alt+arrows or a colleague's move
144 // are all renumbered.
145 //
146 // The label goes in three places, and they are not the same place:
147 // the link's words, which a screen reader reads and the screen does
148 // not draw; its title, the tooltip; and the picture's alt, because a
149 // screen reader announces an image by its alt and never opens the
150 // file to read the <title> inside it.
151 function relabel () {
152 const said = describe()
153 items().forEach((li, i) => {
154 const n = String(i + 1)
155 for (const sel of ['[slides-strip-number]', '[slides-strip-number-said]']) {
156 const el = li.querySelector(sel)
157 if (el && el.textContent !== n) el.textContent = n
158 }
159 const words = labelFor(ydoc, li.dataset.slideId, i + 1, slideLabel)
160 const label = li.querySelector('[slides-strip-label]')
161 if (label && label.textContent !== words) label.textContent = words
162 const link = li.querySelector('[slides-strip-link]')
163 if (link && link.title !== words) link.title = words
164 const img = li.querySelector('[slides-thumb-img]')
165 if (img && img.alt !== words) img.alt = words
166 inTalk(li, said.get(li.dataset.slideId) || {})
167 })
168 }
169
170 // Each write only when it changes something: the server drew all of
171 // it, and the first relabel must leave its paint as it is.
172 function inTalk (li, { talk = '', presses = 0 }) {
173 if ((li.dataset.talk || '') !== talk) {
174 if (talk) li.dataset.talk = talk
175 else delete li.dataset.talk
176 }
177 const put = (sel, words) => {
178 const el = li.querySelector(sel)
179 if (el && el.textContent !== words) el.textContent = words
180 }
181 put('[slides-strip-talk]', talk === 'full' ? texts.full || '' : talk === 'parked' ? texts.parked || '' : '')
182 put('[slides-strip-presses]', pressesWords(texts, presses, 0))
183 for (const row of li.querySelectorAll('[aria-pressed][data-slide-command]')) {
184 const on = String(row.dataset.slideCommand === 'slide-talk-' + talk)
185 if (row.getAttribute('aria-pressed') !== on) row.setAttribute('aria-pressed', on)
186 }
187 }
188
189 function sync () {
190 const want = slideIDs(ydoc)
191 const { add, drop, order } = plan(items().map(li => li.dataset.slideId), want)
192 for (const id of drop) {
193 const li = itemFor(id)
194 if (li) li.remove()
195 dirty.delete(id)
196 }
197 for (const id of add) {
198 root.insertBefore(makeItem(id), tail())
199 dirty.add(id)
200 }
201 // Only the items out of place move, and focus is put back after.
202 // A browser blurs a node it moves, so re-appending every item to
203 // walk the order — as this once did — took focus off the strip
204 // whenever a colleague reordered slides, mid-keystroke.
205 const active = typeof document !== 'undefined' ? document.activeElement : null
206 order.forEach((id, i) => {
207 const li = itemFor(id)
208 if (!li) return
209 const at = items()[i] || tail()
210 if (at !== li) root.insertBefore(li, at)
211 })
212 if (active && root.contains(active) && document.activeElement !== active && typeof active.focus === 'function') {
213 active.focus()
214 }
215 relabel()
216 }
217
218 function mark (id) {
219 dirty.add(id)
220 }
221
222 // Re-point every dirty thumbnail. No fetch of our own and nothing to
223 // await: setting src is the request, the browser makes it, and a
224 // slide whose bytes did not change comes back 304 off the route's
225 // ETag. A picture that fails to load keeps the last one it had,
226 // which is a thumbnail a little behind rather than a hole in the
227 // strip — and not worth an error on screen either way.
228 function flush () {
229 const ids = Array.from(dirty)
230 dirty.clear()
231 for (const id of ids) {
232 const li = itemFor(id)
233 const img = li && li.querySelector('[slides-thumb-img]')
234 if (img) img.src = thumbURL(id)
235 }
236 relabel()
237 }
238
239 function setCurrent (id) {
240 for (const li of items()) {
241 const on = li.dataset.slideId === id
242 if (on) li.dataset.current = 'true'
243 else delete li.dataset.current
244 const a = li.querySelector('[slides-strip-link]')
245 if (a) {
246 if (on) a.setAttribute('aria-current', 'true')
247 else a.removeAttribute('aria-current')
248 }
249 }
250 }
251
252 return { sync, mark, flush, relabel, setCurrent, destroy: () => abort.abort() }
253}
254