@lintje/slides 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/slides.js ADDED
@@ -0,0 +1,427 @@
1
+ // Turns a page of <section class="slide" data-layout="…"> into a deck: scaling, paging, the
2
+ // foot, the emblem, and the check of every slide against its layout. It loads lintje.js
3
+ // itself: core.js beside it would be a second copy of the module's state. Lintje lives at one
4
+ // URL, from the root of the project, where lintje-slides serves the copy it was installed with.
5
+ import { setIconSource } from '/node_modules/lintje/dist-elements/lintje.js'
6
+ import { LAYOUTS } from './layouts.js'
7
+
8
+ setIconSource({ base: new URL('/node_modules/lintje/dist-icons/', location.href).href })
9
+
10
+ const params = new URLSearchParams(location.search)
11
+ if (params.get('mode') === 'dark' || params.get('mode') === 'light') document.documentElement.dataset.mode = params.get('mode')
12
+ if (params.has('theme')) document.documentElement.dataset.theme = params.get('theme')
13
+
14
+ const slides = [...document.querySelectorAll('.slide')]
15
+ const deck = document.title
16
+ const organisations = {
17
+ rijksoverheid: 'Rijksoverheid',
18
+ marechaussee: 'Koninklijke Marechaussee',
19
+ defensie: 'Ministerie van Defensie',
20
+ landmacht: 'Koninklijke Landmacht',
21
+ marine: 'Koninklijke Marine',
22
+ luchtmacht: 'Koninklijke Luchtmacht',
23
+ }
24
+
25
+ // --- Building ----------------------------------------------------------------------------------
26
+
27
+ function build() {
28
+ const theme = document.documentElement.dataset.theme ?? 'rijksoverheid'
29
+ const emblem = document.body.dataset.emblem ?? `embleem-${theme}`
30
+ const organisation = document.body.dataset.organisation ?? organisations[theme] ?? ''
31
+ const date = document.body.dataset.date ?? ''
32
+ let chapter = ''
33
+ slides.forEach((slide, index) => {
34
+ const layout = LAYOUTS[slide.dataset.layout]
35
+ if (slide.dataset.chapter !== undefined) chapter = slide.dataset.chapter
36
+ for (const img of slide.querySelectorAll('img[data-focus]')) {
37
+ const [x, y] = img.dataset.focus.split(/\s+/)
38
+ img.style.objectPosition = `${x}% ${y ?? 50}%`
39
+ }
40
+ // A table's column of figures aligns right: every body cell in it is a number.
41
+ for (const table of slide.querySelectorAll('[data-field] table')) markFigures(table)
42
+ // The slide's number, shown only in the overview; the tile's label already says it aloud.
43
+ const number = document.createElement('span')
44
+ number.className = 'slide__number'
45
+ number.setAttribute('aria-hidden', 'true')
46
+ number.textContent = String(index + 1)
47
+ slide.append(number)
48
+ if (!layout) return
49
+ if (layout.logo) {
50
+ const logo = document.createElement('lintje-logo')
51
+ logo.className = 'slide__logo'
52
+ logo.setAttribute('name', emblem)
53
+ logo.setAttribute('alt', organisation)
54
+ logo.setAttribute('width', '48')
55
+ logo.toggleAttribute('open', true)
56
+ slide.append(logo)
57
+ }
58
+ if (layout.footer !== false) {
59
+ const foot = document.createElement('footer')
60
+ foot.className = 'slide__footer'
61
+ const left = document.createElement('span')
62
+ left.textContent = [deck, chapter].filter(Boolean).join(' · ')
63
+ const right = document.createElement('span')
64
+ right.textContent = [date, String(index + 1)].filter(Boolean).join(' · ')
65
+ foot.append(left, right)
66
+ slide.append(foot)
67
+ }
68
+ })
69
+ }
70
+
71
+ function markFigures(table) {
72
+ const rows = [...table.rows]
73
+ const body = [...table.tBodies].flatMap((tbody) => [...tbody.rows])
74
+ const columns = Math.max(...rows.map((row) => row.cells.length))
75
+ for (let column = 0; column < columns; column++) {
76
+ const cells = body.map((row) => row.cells[column]).filter(Boolean)
77
+ if (!cells.length || !cells.every((cell) => /^[−\-+€$%\d.,\s]+$/.test(cell.textContent.trim()))) continue
78
+ for (const row of rows) row.cells[column]?.setAttribute('data-numeric', '')
79
+ }
80
+ }
81
+
82
+ // --- Checking ----------------------------------------------------------------------------------
83
+
84
+ const TEXT_TAGS = new Set(['P', 'UL', 'OL', 'LI', 'H3', 'H4', 'STRONG', 'EM', 'B', 'I', 'BR', 'A', 'MARK', 'SPAN', 'BLOCKQUOTE'])
85
+
86
+ function words(element) {
87
+ return element.textContent.trim().split(/\s+/).filter(Boolean).length
88
+ }
89
+
90
+ function checkField(name, field, element, report) {
91
+ const where = `veld "${name}"`
92
+ const lists = element.matches('ul, ol') ? [element] : [...element.querySelectorAll(':scope > ul, :scope > ol')]
93
+ if (field.kind === 'photo') {
94
+ if (!element.matches('img')) report(`${where} is een <img>`)
95
+ else checkImage(element, where, report)
96
+ } else if (field.kind === 'photos') {
97
+ const images = [...element.querySelectorAll('img')]
98
+ if (images.length !== field.count) report(`${where} heeft ${field.count} foto's, nu ${images.length}`)
99
+ images.forEach((img) => checkImage(img, where, report))
100
+ } else if (field.kind === 'chart') {
101
+ if (!element.querySelector('lintje-chart') && !element.matches('lintje-chart')) report(`${where} is een <lintje-chart>`)
102
+ } else if (field.kind === 'table') {
103
+ const table = element.matches('table') ? element : element.querySelector('table')
104
+ if (!table) report(`${where} is een <table>`)
105
+ else {
106
+ if (!table.querySelector('caption')?.textContent.trim()) report(`${where}: de tabel heeft een <caption>`)
107
+ const rows = table.querySelectorAll('tbody tr').length
108
+ if (field.items && rows > field.items[1]) report(`${where}: hoogstens ${field.items[1]} rijen, nu ${rows}`)
109
+ }
110
+ } else {
111
+ for (const node of element.querySelectorAll('*')) {
112
+ if (!TEXT_TAGS.has(node.tagName)) report(`${where}: <${node.tagName.toLowerCase()}> hoort niet in tekst`)
113
+ }
114
+ if (field.items) {
115
+ const count = lists.reduce((sum, list) => sum + list.children.length, 0)
116
+ const [min, max] = field.items
117
+ if (count < min || count > max) {
118
+ report(min === max ? `${where} heeft ${min} punten, nu ${count}` : `${where} heeft ${min} tot ${max} punten, nu ${count}`)
119
+ }
120
+ }
121
+ }
122
+ if (field.words && words(element) > field.words) report(`${where}: hoogstens ${field.words} woorden, nu ${words(element)}`)
123
+ }
124
+
125
+ function checkImage(img, where, report) {
126
+ if (!img.getAttribute('alt')?.trim()) report(`${where}: de foto heeft een alt-tekst`)
127
+ if (img.complete && img.naturalWidth === 0) report(`${where}: de foto ${img.getAttribute('src')} laadt niet`)
128
+ }
129
+
130
+ // An element that holds more than its box shows it in its scroll size. A tight line height lets
131
+ // the glyphs stand a little outside their lines, so a part of the font size is allowed.
132
+ function overflows(element) {
133
+ const style = getComputedStyle(element)
134
+ if (style.clipPath !== 'none') return false
135
+ const slack = Math.max(2, Number.parseFloat(style.fontSize) * 0.15)
136
+ return element.scrollHeight > element.clientHeight + slack || element.scrollWidth > element.clientWidth + slack
137
+ }
138
+
139
+ function checkSlide(slide) {
140
+ const findings = []
141
+ const report = (message, element) => findings.push({ message, element })
142
+ const name = slide.dataset.layout
143
+ const layout = LAYOUTS[name]
144
+ if (!layout) {
145
+ report(name ? `onbekende indeling "${name}"` : 'de dia heeft geen data-layout')
146
+ return findings
147
+ }
148
+ const titles = slide.querySelectorAll(':scope > h1')
149
+ if (titles.length !== 1) report('de dia heeft precies één <h1> als titel')
150
+ else if (!titles[0].textContent.trim()) report('de titel is leeg')
151
+ else if (words(titles[0]) > (layout.titleWords ?? 16)) {
152
+ report(`de titel heeft hoogstens ${layout.titleWords ?? 16} woorden, nu ${words(titles[0])}`, titles[0])
153
+ }
154
+
155
+ const seen = new Set()
156
+ for (const child of slide.children) {
157
+ if (child.matches('h1, .slide__footer, .slide__logo, .slide__finding, .slide__number')) continue
158
+ const field = child.dataset.field
159
+ if (field === undefined) report(`<${child.tagName.toLowerCase()}> zonder data-field: alles op een dia staat in een veld`, child)
160
+ else if (!layout.fields[field]) report(`"${field}" is geen veld van ${name}; wel: ${Object.keys(layout.fields).join(', ')}`, child)
161
+ else if (seen.has(field)) report(`veld "${field}" staat er twee keer`, child)
162
+ else seen.add(field)
163
+ }
164
+ for (const [field, spec] of Object.entries(layout.fields)) {
165
+ const element = slide.querySelector(`:scope > [data-field="${field}"]`)
166
+ if (!element) {
167
+ if (spec.required) report(`veld "${field}" ontbreekt`)
168
+ continue
169
+ }
170
+ checkField(field, spec, element, (message) => report(message, element))
171
+ }
172
+ // Styling belongs to the layout: a style or class in the content is a way around it.
173
+ for (const node of slide.querySelectorAll('[style], [class]')) {
174
+ if (node.closest('lintje-chart, .slide__footer, .slide__logo, .slide__finding, .slide__number') || node === slide) continue
175
+ if (node.hasAttribute('class')) report(`<${node.tagName.toLowerCase()} class>: de opmaak komt uit de indeling`, node)
176
+ if (node.hasAttribute('style') && !node.matches('img[data-focus]')) report(`<${node.tagName.toLowerCase()} style>: de opmaak komt uit de indeling`, node)
177
+ }
178
+ // What does not fit: a box that overflows, or a field past the frame.
179
+ const wasCurrent = slide.classList.contains('is-current')
180
+ slide.classList.add('is-current')
181
+ const frame = slide.getBoundingClientRect()
182
+ const scale = frame.width / 1280
183
+ const bottom = frame.top + (layout.footer === false ? 720 : 672) * scale
184
+ for (const element of slide.querySelectorAll(':scope > h1, :scope > [data-field], [data-field] li, [data-field] figure')) {
185
+ const field = element.closest('[data-field]')?.dataset.field
186
+ if (field && !layout.fields[field]) continue
187
+ const box = element.getBoundingClientRect()
188
+ const label = element.matches('h1') ? 'de titel' : element.dataset.field ? `veld "${element.dataset.field}"` : `een punt in "${field}"`
189
+ if (overflows(element) || box.right > frame.right - 24 * scale + 1) report(`${label} past niet: maak de tekst korter`, element)
190
+ // A field that fits its own box but stands past the frame was pushed there by the text above it.
191
+ else if (box.bottom > bottom + 1) report(`${label} valt van de dia: de titel of de tekst erboven is te lang`, element)
192
+ }
193
+ if (!wasCurrent) slide.classList.remove('is-current')
194
+ return findings
195
+ }
196
+
197
+ /** Every finding in the deck, for scripts/check.mjs and the console. */
198
+ export function check() {
199
+ return slides.flatMap((slide, index) =>
200
+ checkSlide(slide).map(({ message, element }) => ({ slide: index + 1, layout: slide.dataset.layout ?? '', message, element })),
201
+ )
202
+ }
203
+
204
+ function showFindings(findings) {
205
+ for (const old of document.querySelectorAll('.slide__finding')) old.remove()
206
+ for (const old of document.querySelectorAll('.is-error')) old.classList.remove('is-error')
207
+ for (const { slide, message, element } of findings) {
208
+ element?.classList.add('is-error')
209
+ const note = document.createElement('p')
210
+ note.className = 'slide__finding'
211
+ note.textContent = message
212
+ const host = slides[slide - 1]
213
+ const previous = host.querySelectorAll('.slide__finding').length
214
+ note.style.bottom = `${32 + previous * 40}px`
215
+ host.append(note)
216
+ }
217
+ }
218
+
219
+ // --- Presenting --------------------------------------------------------------------------------
220
+
221
+ const width = 1280
222
+ const height = 720
223
+
224
+ // The slide number lives in the URL (#3), so a reload or a link lands on the same slide.
225
+ function current() {
226
+ const number = Number.parseInt(location.hash.slice(1), 10)
227
+ return Number.isInteger(number) ? Math.min(Math.max(number, 1), slides.length) : 1
228
+ }
229
+
230
+ const nav = document.createElement('nav')
231
+ nav.className = 'slides-nav'
232
+ nav.setAttribute('aria-label', "Dia's")
233
+ nav.innerHTML = `
234
+ <lintje-icon-button class="slides-nav__previous" icon="functioneel-delta-naar-links" label="Vorige dia"></lintje-icon-button>
235
+ <span class="slides-nav__count" aria-live="polite"></span>
236
+ <lintje-icon-button class="slides-nav__next" icon="functioneel-delta-naar-rechts" label="Volgende dia"></lintje-icon-button>
237
+ <lintje-icon-button class="slides-nav__mode" icon="functioneel-darkmode" label="Donker"></lintje-icon-button>
238
+ <lintje-icon-button class="slides-nav__overview" icon="functioneel-tegelweergave" label="Alle dia's"></lintje-icon-button>
239
+ <lintje-icon-button class="slides-nav__fullscreen" icon="multimedia-player-full-screen" label="Volledig scherm"></lintje-icon-button>`
240
+ document.body.append(nav)
241
+
242
+ const count = nav.querySelector('.slides-nav__count')
243
+ const previous = nav.querySelector('.slides-nav__previous')
244
+ const next = nav.querySelector('.slides-nav__next')
245
+ const overviewButton = nav.querySelector('.slides-nav__overview')
246
+ const fullscreenButton = nav.querySelector('.slides-nav__fullscreen')
247
+ const modeButton = nav.querySelector('.slides-nav__mode')
248
+ const root = document.documentElement
249
+
250
+ function show(number) {
251
+ slides.forEach((slide, index) => slide.classList.toggle('is-current', index === number - 1))
252
+ count.textContent = `${number} / ${slides.length}`
253
+ previous.disabled = number === 1
254
+ next.disabled = number === slides.length
255
+ const title = slides[number - 1]?.querySelector(':scope > h1')?.textContent.trim()
256
+ document.title = `${title ?? deck} (${number}/${slides.length})`
257
+ }
258
+
259
+ function go(number) {
260
+ const target = Math.min(Math.max(number, 1), slides.length)
261
+ if (target !== current()) location.hash = String(target)
262
+ }
263
+
264
+ function scale() {
265
+ const factor = Math.min(innerWidth / width, innerHeight / height)
266
+ document.documentElement.style.setProperty('--slide-scale', String(factor))
267
+ }
268
+
269
+ function fullscreen() {
270
+ return document.fullscreenElement ? document.exitFullscreen() : root.requestFullscreen()
271
+ }
272
+
273
+ // Light or dark lives in the URL (?mode=dark) like the slide number, so a link keeps it.
274
+ function mode(dark = root.dataset.mode !== 'dark') {
275
+ root.dataset.mode = dark ? 'dark' : 'light'
276
+ modeButton.pressed = dark
277
+ const url = new URL(location.href)
278
+ url.searchParams.set('mode', dark ? 'dark' : 'light')
279
+ history.replaceState(null, '', url)
280
+ }
281
+
282
+ function fullscreenChanged() {
283
+ const on = Boolean(document.fullscreenElement)
284
+ fullscreenButton.icon = on ? 'multimedia-player-full-screen-uitgaan' : 'multimedia-player-full-screen'
285
+ fullscreenButton.label = on ? 'Volledig scherm verlaten' : 'Volledig scherm'
286
+ }
287
+
288
+ // The overview lays every slide out small, in a grid: pick one to go there. The slides are the
289
+ // same elements, zoomed, so a chart or a photo looks as it does on the slide.
290
+ function overviewOpen() {
291
+ return root.classList.contains('slides-overview')
292
+ }
293
+
294
+ function overviewSize() {
295
+ const columns = innerWidth >= 1100 ? 4 : innerWidth >= 700 ? 3 : 2
296
+ const room = root.clientWidth - 2 * 40 - (columns - 1) * 32
297
+ root.style.setProperty('--slide-overview-columns', String(columns))
298
+ root.style.setProperty('--slide-overview-zoom', String(room / columns / width))
299
+ return columns
300
+ }
301
+
302
+ function overview(open = !overviewOpen()) {
303
+ root.classList.toggle('slides-overview', open)
304
+ overviewButton.icon = open ? 'functioneel-kruis' : 'functioneel-tegelweergave'
305
+ overviewButton.label = open ? 'Overzicht sluiten' : "Alle dia's"
306
+ slides.forEach((slide, index) => {
307
+ const title = slide.querySelector(':scope > h1')?.textContent.trim()
308
+ for (const child of slide.children) child.inert = open
309
+ if (open) {
310
+ slide.tabIndex = 0
311
+ slide.setAttribute('role', 'button')
312
+ slide.setAttribute('aria-label', `Dia ${index + 1}${title ? `: ${title}` : ''}`)
313
+ } else {
314
+ for (const name of ['tabindex', 'role', 'aria-label']) slide.removeAttribute(name)
315
+ }
316
+ })
317
+ if (open) {
318
+ overviewSize()
319
+ wake()
320
+ const slide = slides[current() - 1]
321
+ slide.focus({ preventScroll: true })
322
+ slide.scrollIntoView({ block: 'center' })
323
+ } else {
324
+ scrollTo(0, 0)
325
+ }
326
+ }
327
+
328
+ function choose(slide) {
329
+ overview(false)
330
+ go(slides.indexOf(slide) + 1)
331
+ }
332
+
333
+ for (const slide of slides) {
334
+ slide.addEventListener('click', () => overviewOpen() && choose(slide))
335
+ }
336
+
337
+ addEventListener('hashchange', () => show(current()))
338
+ addEventListener('resize', () => {
339
+ scale()
340
+ if (overviewOpen()) overviewSize()
341
+ })
342
+ addEventListener('fullscreenchange', fullscreenChanged)
343
+ overviewButton.addEventListener('click', () => overview())
344
+ modeButton.addEventListener('click', () => mode())
345
+ modeButton.pressed = root.dataset.mode === 'dark'
346
+ previous.addEventListener('click', () => go(current() - 1))
347
+ next.addEventListener('click', () => go(current() + 1))
348
+ fullscreenButton.addEventListener('click', fullscreen)
349
+
350
+ addEventListener('keydown', (event) => {
351
+ // A key a Lintje element already handled (a chart's marks) or one typed into a field stays there.
352
+ const target = event.composedPath()[0]
353
+ const typing = target instanceof HTMLElement && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName))
354
+ if (event.defaultPrevented || typing || event.metaKey || event.ctrlKey || event.altKey) return
355
+ // Space on a focused button presses that button.
356
+ if (event.key === ' ' && target instanceof HTMLButtonElement) return
357
+ if (overviewOpen()) return overviewKey(event)
358
+ const keys = {
359
+ ArrowRight: () => go(current() + 1),
360
+ ArrowDown: () => go(current() + 1),
361
+ PageDown: () => go(current() + 1),
362
+ ' ': () => go(current() + (event.shiftKey ? -1 : 1)),
363
+ ArrowLeft: () => go(current() - 1),
364
+ ArrowUp: () => go(current() - 1),
365
+ PageUp: () => go(current() - 1),
366
+ Home: () => go(1),
367
+ End: () => go(slides.length),
368
+ f: fullscreen,
369
+ o: () => overview(true),
370
+ d: () => mode(),
371
+ }
372
+ const action = keys[event.key]
373
+ if (!action) return
374
+ event.preventDefault()
375
+ action()
376
+ // Presenting with the keys or a clicker: the controls step aside at once.
377
+ rest()
378
+ })
379
+
380
+ // In the overview the keys move between the slides; Enter goes to one, Escape or o goes back.
381
+ function overviewKey(event) {
382
+ const index = Math.max(slides.indexOf(document.activeElement), 0)
383
+ const columns = overviewSize()
384
+ const moves = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: columns, ArrowUp: -columns }
385
+ let target
386
+ if (event.key in moves) target = index + moves[event.key]
387
+ else if (event.key === 'Home') target = 0
388
+ else if (event.key === 'End') target = slides.length - 1
389
+ else if (event.key === 'Enter' || event.key === ' ') {
390
+ event.preventDefault()
391
+ return choose(slides[index])
392
+ } else if (event.key === 'Escape' || event.key === 'o') {
393
+ event.preventDefault()
394
+ return overview(false)
395
+ } else return
396
+ event.preventDefault()
397
+ const slide = slides[Math.min(Math.max(target, 0), slides.length - 1)]
398
+ slide.focus({ preventScroll: true })
399
+ slide.scrollIntoView({ block: 'nearest' })
400
+ }
401
+
402
+ // The controls stand over the slide's corner: they show when the mouse moves, and go after a
403
+ // short rest, also right after the deck opens.
404
+ let idle
405
+ function rest() {
406
+ clearTimeout(idle)
407
+ nav.classList.add('is-idle')
408
+ }
409
+ function wake() {
410
+ nav.classList.remove('is-idle')
411
+ clearTimeout(idle)
412
+ idle = setTimeout(rest, 2500)
413
+ }
414
+ addEventListener('pointermove', wake)
415
+
416
+ build()
417
+ scale()
418
+ show(current())
419
+ wake()
420
+
421
+ // The check runs once the fonts and photos are in, since both change what fits.
422
+ await Promise.all([document.fonts.ready, ...[...document.images].map((img) => img.decode().catch(() => {}))])
423
+ const findings = check()
424
+ for (const { slide, layout, message } of findings) console.warn(`Dia ${slide} (${layout}): ${message}`)
425
+ if (params.has('check')) showFindings(findings)
426
+ window.slidesCheck = () => check().map(({ slide, layout, message }) => ({ slide, layout, message }))
427
+ document.documentElement.dataset.slidesReady = ''