oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/notes-card.mjs — the speaker notes as a card at the foot of
2// the desk (the editor tidied, spec §5; editor.html's
3// [slides-notes-pane]).
4//
5// Open, the card is the stage pane's last child, in the flow, so the
6// stages give up its height by layout: it has an × that closes it, a
7// top edge that resizes it ([slides-notes-resize], a separator: drag
8// it, or ArrowUp/ArrowDown 16px at a time, Home and End to the limits),
9// and the notes themselves — the same [slides-notes] field as before,
10// which stage.mjs binds; nothing here touches it but focus. No heading:
11// the field's placeholder names it (the quieter editor, spec §6.2).
12// Closed, the card is display: none and the tab [slides-notes-open]
13// shows in the pane's bottom start corner: its text is the word for
14// notes, with the count of the slide's words when it has any
15// (refresh, from the server's data-label and data-label-words).
16//
17// Open or closed, and the height in px, are remembered in cookies the
18// server reads (NOTES_COOKIE: open or closed; NOTES_HEIGHT_COOKIE: whole
19// px; pref-cookie.mjs), as the inspector card's state is: the server
20// renders the card's data-state and its --slides-notes-block-size, so
21// the first paint is final and nothing here changes it on mount (ruling
22// R21: a card that closed or changed height under a slow bundle was a
23// flash). A preference from before the cookies, in localStorage under
24// NOTES_KEY ('on', 'off') and NOTES_HEIGHT_KEY, is honoured once where
25// there is no cookie yet, written to the cookies and removed. Where
26// cookies are blocked the card still opens, closes and resizes, for the
27// page. A per-person convenience, never document state.
28//
29// mountNotesCard({root, storage, words, onChange}) → {open, close,
30// toggle, isOpen, refresh}. root holds the card and the tab (the stage
31// pane); storage is where the old preference may be; words() is how
32// many words the slide on stage has in its notes (countWords);
33// onChange(open) hears every open or close (the View menu's check).
34import { readCookie, writeCookie } from './pref-cookie.mjs'
35
36export const NOTES_KEY = 'slides.editor.notes'
37export const NOTES_HEIGHT_KEY = 'slides.editor.notes.height'
38export const NOTES_COOKIE = 'slides-notes'
39export const NOTES_HEIGHT_COOKIE = 'slides-notes-height'
40/** The card's height before anybody has changed it, in px. */
41export const DEFAULT_HEIGHT = 144
42/** What one arrow key moves the top edge by, in px. */
43export const STEP = 16
44/**
45 * The card less its body, in px: its hairline (1 + 1) and its padding
46 * (12 + 12); there is no head row, the × sits in the padding's corner.
47 * editor.css's "The notes card" draws exactly this, and editor.go's
48 * notesMinHeight is this and two lines.
49 */
50export const HEAD_PX = 26
51
52/**
53 * The height the card may have: at least the head and two lines of
54 * notes, at most half the desk (deskPx). Where the desk is too short
55 * for both, the two lines win; with no desk measured (0) there is no
56 * upper bound. Whole px.
57 */
58export function clampHeight (px, deskPx, lineHeightPx) {
59 const min = Math.ceil(HEAD_PX + 2 * lineHeightPx)
60 const max = deskPx > 0 ? Math.floor(deskPx / 2) : Infinity
61 const want = Number.isFinite(px) ? Math.round(px) : DEFAULT_HEIGHT
62 return Math.max(min, Math.min(want, max))
63}
64
65// What Go's unicode.IsSpace says is a space, which is what the
66// server's strings.Fields splits on: not JavaScript's \s, which
67// counts U+FEFF and not U+0085.
68const SPACES = /[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/
69
70// A node's plain text: a run's inserts (its marks dropped, an embed
71// nothing), or its children's, side by side.
72function plain (node) {
73 if (!node) return ''
74 if (typeof node.toDelta === 'function') {
75 return node.toDelta().map(op => typeof op.insert === 'string' ? op.insert : '').join('')
76 }
77 if (typeof node.toArray === 'function') return node.toArray().map(plain).join('')
78 return ''
79}
80
81/**
82 * How many words a notes fragment (Y.XmlFragment of paragraphs, or
83 * anything with toArray() of elements and toDelta() of text) holds:
84 * the count the tab says. The server counts the first slide's the same
85 * way, len(strings.Fields(notes.Plain())): runs side by side in a
86 * paragraph, paragraphs joined by a line break, split on whitespace.
87 */
88export function countWords (fragment) {
89 if (!fragment || typeof fragment.toArray !== 'function') return 0
90 const text = fragment.toArray().map(plain).join('\n')
91 return text.split(SPACES).filter(w => w !== '').length
92}
93
94function read (storage, key) {
95 try { return storage ? storage.getItem(key) : null } catch { return null }
96}
97function forget (storage, key) {
98 try { if (storage) storage.removeItem(key) } catch { /* nothing to move */ }
99}
100
101export function mountNotesCard ({ root, storage = globalThis.localStorage, words = () => 0, onChange = () => {} }) {
102 const pane = root.querySelector('[slides-notes-pane]')
103 const openBtn = root.querySelector('[slides-notes-open]')
104 const closeBtn = root.querySelector('[slides-notes-close]')
105 const edge = root.querySelector('[slides-notes-resize]')
106 const notesEl = root.querySelector('[slides-notes]')
107
108 // The server's first paint is the cookie's state.
109 let open = !pane || pane.dataset.state !== 'closed'
110 // Two heights: the preferred one, the person's own, which is what is
111 // remembered; and the shown one, the preferred one clamped to the
112 // desk as it is now (a smaller window narrows the card for the visit,
113 // and the person's height comes back with the room). Every change —
114 // a key, a drag — starts from what is shown, and its result becomes
115 // the new preferred height.
116 let preferred = Number(readCookie(NOTES_HEIGHT_COOKIE)) || DEFAULT_HEIGHT
117 let shown = 0
118
119 // The desk the card may take half of: the pane, which from 1100px is
120 // the desk's height, and never more than the window (narrower, the
121 // page scrolls and the pane is as tall as what is in it).
122 function deskPx () {
123 const h = root.clientHeight || 0
124 const win = Number(globalThis.innerHeight) || 0
125 return win > 0 && h > 0 ? Math.min(h, win) : (h || win)
126 }
127 function lineHeightPx () {
128 const lh = notesEl && typeof globalThis.getComputedStyle === 'function'
129 ? parseFloat(globalThis.getComputedStyle(notesEl).lineHeight)
130 : NaN
131 return Number.isFinite(lh) && lh > 0 ? lh : 24
132 }
133 function limits () {
134 const desk = deskPx()
135 const line = lineHeightPx()
136 const min = clampHeight(0, desk, line)
137 return { min, max: desk > 0 ? Math.max(min, Math.floor(desk / 2)) : Infinity, desk, line }
138 }
139
140 // Draws a height, clamped to the desk as it is now, and returns what
141 // was drawn. Remembers nothing.
142 function draw (px) {
143 const { min, max, desk, line } = limits()
144 const h = clampHeight(px, desk, line)
145 if (pane) pane.style.setProperty('--slides-notes-block-size', h + 'px')
146 if (edge) {
147 edge.setAttribute('aria-valuemin', String(min))
148 edge.setAttribute('aria-valuemax', String(Number.isFinite(max) ? max : Math.max(h, min)))
149 edge.setAttribute('aria-valuenow', String(h))
150 }
151 return h
152 }
153 // The preferred height, drawn inside today's limits: what is shown.
154 function redraw () {
155 shown = draw(preferred)
156 return shown
157 }
158 // A new height from a key or a drag: shown, and preferred from now on.
159 function prefer (px) {
160 preferred = shown = draw(px)
161 writeCookie(NOTES_HEIGHT_COOKIE, String(preferred))
162 }
163
164 function show (on, { focus = false } = {}) {
165 open = on
166 if (pane) pane.dataset.state = on ? 'open' : 'closed'
167 writeCookie(NOTES_COOKIE, on ? 'open' : 'closed')
168 if (on) redraw()
169 if (focus) {
170 const target = on ? notesEl : openBtn
171 if (target) target.focus()
172 }
173 onChange(on)
174 }
175
176 // The tab's text, from the strings the server gave it: the word for
177 // notes, or that and the count. Written only when it changes, so the
178 // server's first paint is kept as it is.
179 function refresh () {
180 if (!openBtn) return
181 const n = Math.max(0, Math.floor(Number(words()) || 0))
182 const label = n > 0
183 ? (openBtn.getAttribute('data-label-words') || '').replace('{n}', String(n))
184 : openBtn.getAttribute('data-label')
185 if (label && openBtn.textContent !== label) openBtn.textContent = label
186 }
187
188 // The old localStorage preference, once: applied where no cookie says
189 // otherwise yet, moved to the cookies, and removed either way.
190 const oldOpen = read(storage, NOTES_KEY)
191 if (oldOpen !== null) {
192 if (readCookie(NOTES_COOKIE) === null && (oldOpen === 'on' || oldOpen === 'off')) {
193 open = oldOpen === 'on'
194 writeCookie(NOTES_COOKIE, open ? 'open' : 'closed')
195 }
196 forget(storage, NOTES_KEY)
197 }
198 const oldHeight = read(storage, NOTES_HEIGHT_KEY)
199 if (oldHeight !== null) {
200 const px = Number(oldHeight)
201 if (readCookie(NOTES_HEIGHT_COOKIE) === null && Number.isFinite(px) && px > 0) {
202 preferred = Math.round(px)
203 writeCookie(NOTES_HEIGHT_COOKIE, String(preferred))
204 }
205 forget(storage, NOTES_HEIGHT_KEY)
206 }
207
208 if (pane) pane.dataset.state = open ? 'open' : 'closed'
209 redraw()
210
211 closeBtn?.addEventListener('click', () => show(false, { focus: true }))
212 openBtn?.addEventListener('click', () => show(true, { focus: true }))
213
214 if (edge) {
215 edge.addEventListener('keydown', e => {
216 if (e.altKey || e.ctrlKey || e.metaKey) return
217 if (!['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(e.key)) return
218 e.preventDefault()
219 // From what is shown now: the desk may have changed since the
220 // last draw.
221 const from = redraw()
222 const { min, max } = limits()
223 if (e.key === 'ArrowUp') prefer(from + STEP)
224 else if (e.key === 'ArrowDown') prefer(from - STEP)
225 else if (e.key === 'Home') prefer(min)
226 else prefer(Number.isFinite(max) ? max : from)
227 })
228 // The top edge follows the pointer: up is taller. The pointer is
229 // captured, so a drag that leaves the edge still drives it, and the
230 // height is remembered once, on release.
231 let drag = null
232 edge.addEventListener('pointerdown', e => {
233 if (e.button !== undefined && e.button !== 0) return
234 e.preventDefault()
235 drag = { id: e.pointerId, y: e.clientY, from: redraw() }
236 edge.setPointerCapture(e.pointerId)
237 })
238 edge.addEventListener('pointermove', e => {
239 if (!drag || e.pointerId !== drag.id) return
240 shown = draw(drag.from + (drag.y - e.clientY))
241 })
242 const end = e => {
243 if (!drag || e.pointerId !== drag.id) return
244 drag = null
245 if (edge.hasPointerCapture(e.pointerId)) edge.releasePointerCapture(e.pointerId)
246 prefer(shown)
247 }
248 edge.addEventListener('pointerup', end)
249 edge.addEventListener('pointercancel', end)
250 }
251
252 // The window, and with it the desk, changed size: the height is drawn
253 // again inside the new limits.
254 if (typeof globalThis.addEventListener === 'function') {
255 globalThis.addEventListener('resize', () => { if (open) redraw() })
256 }
257
258 return {
259 open: () => show(true, { focus: true }),
260 close: () => show(false),
261 toggle () { show(!open, { focus: !open }) },
262 isOpen: () => open,
263 refresh
264 }
265}
266