@miragon/slidev-speaker-profiles 0.2.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/stamp.mjs ADDED
@@ -0,0 +1,253 @@
1
+ /**
2
+ * Giving slides their ids: the part the CLI and the dev server share.
3
+ *
4
+ * A profile addresses slides by the `id:` in their frontmatter, so the id has
5
+ * to hold still. An id derived from a slide's title or position moves the
6
+ * moment somebody retitles a slide, inserts one above it or renumbers a chapter
7
+ * file, and the speaker's selection then points at a slide they never chose.
8
+ *
9
+ * `bin/slide-ids.mjs` calls this from a script; `setup/vite-plugins.ts` calls it
10
+ * once when a dev server starts, so that a deck needs no npm wiring at all to
11
+ * keep new slides stamped - which matters for the decks that have one dev script
12
+ * per chapter, where a `predev` hook would have to be repeated eight times and
13
+ * would be forgotten once.
14
+ */
15
+ import { randomBytes } from 'node:crypto'
16
+ import { closeSync, existsSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
17
+ import path from 'node:path'
18
+ import { injectPreparserExtensionLoader, load } from '@slidev/parser/fs'
19
+ import { walkMarkdownFiles } from './identity.mjs'
20
+ import { PROFILE_DIR, findProfilesRoot, listProfiles, readProfile } from './profiles.mjs'
21
+
22
+ export const ID_PREFIX = 's-'
23
+ export const RE_ID = /^s-[0-9a-f]{8}$/
24
+
25
+ /** `chapter/*` and `chapter/**\/*.md` style patterns. Only `*` and `**` are special. */
26
+ export function globToRegExp(pattern) {
27
+ let body = ''
28
+ for (let i = 0; i < pattern.length; i++) {
29
+ const char = pattern[i]
30
+ if (char === '*') {
31
+ if (pattern[i + 1] === '*') {
32
+ i++
33
+ if (pattern[i + 1] === '/') {
34
+ i++
35
+ body += '(?:.*/)?'
36
+ }
37
+ else {
38
+ body += '.*'
39
+ }
40
+ }
41
+ else {
42
+ body += '[^/]*'
43
+ }
44
+ }
45
+ else if ('.+^${}()|[]\\'.includes(char)) {
46
+ body += `\\${char}`
47
+ }
48
+ else {
49
+ body += char
50
+ }
51
+ }
52
+ return new RegExp(`^${body}$`)
53
+ }
54
+
55
+ /**
56
+ * The entry, plus whatever `also` asks for.
57
+ *
58
+ * A deck can park a chapter by taking its `src:` line out, and then no entry
59
+ * reaches the file any more. Parsing only what the entry imports would leave
60
+ * those slides unstamped, and the day the chapter comes back every speaker who
61
+ * had made a selection in it loses it. A parked file is loaded as its own entry:
62
+ * Slidev reads its first frontmatter block as headmatter, which changes nothing
63
+ * about where its slides start.
64
+ */
65
+ function deckEntries(entry, userRoot, also) {
66
+ if (!also.length)
67
+ return [entry]
68
+ const patterns = also.map(globToRegExp)
69
+ const extra = walkMarkdownFiles(userRoot).filter((file) => {
70
+ const relative = path.relative(userRoot, file).split(path.sep).join('/')
71
+ return file !== entry && patterns.some(re => re.test(relative))
72
+ })
73
+ return [entry, ...extra]
74
+ }
75
+
76
+ /**
77
+ * Every slide of the deck, anchored to where it really lives.
78
+ *
79
+ * `slide.source` is the slide as written; `slide.frontmatter` is that merged
80
+ * with the frontmatter of the `src:` wrapper that imported it. The wrapper is an
81
+ * import instruction, not a slide, so it is the source we read and the source we
82
+ * write - an `id:` on a wrapper would merge over every slide of the imported
83
+ * file and give them all the same one. `source.start` is the line index of the
84
+ * `---` that opens the slide's frontmatter, which is exactly where a new `id:`
85
+ * line goes.
86
+ *
87
+ * The deck's own preparsers are deliberately not loaded, and one of ours is.
88
+ * Not loaded: this addon's preparser, because here the frontmatter IS the
89
+ * question and its fallback id derivation would paper over the gap; nor any
90
+ * preparser the deck installs, so a slide that a variant switch would drop is
91
+ * stamped too instead of depending on the environment this runs in. Loaded: an
92
+ * extension that strips `hide` before Slidev acts on it, because Slidev drops a
93
+ * hidden slide while parsing and `hide` is how a deck parks content it means to
94
+ * bring back. Stripping it is in-memory only: the file keeps its `hide: true`
95
+ * and simply also gets an `id:`.
96
+ */
97
+ export async function collectSlides({ entry, also = [] }) {
98
+ const userRoot = path.dirname(entry)
99
+ const profilesRoot = findProfilesRoot(userRoot)
100
+
101
+ injectPreparserExtensionLoader(async () => [{
102
+ name: 'slide-ids:reveal-hidden',
103
+ transformSlide(_content, frontmatter) {
104
+ delete frontmatter.hide
105
+ delete frontmatter.disabled
106
+ return undefined
107
+ },
108
+ }])
109
+
110
+ const rows = []
111
+ const seenAnchor = new Set()
112
+ for (const file of deckEntries(entry, userRoot, also)) {
113
+ const data = await load(
114
+ { userRoot, roots: [userRoot], allowedRoots: [profilesRoot, userRoot] },
115
+ file,
116
+ undefined,
117
+ 'dev',
118
+ )
119
+ for (const slide of data.slides) {
120
+ const source = slide.source ?? slide
121
+ if (!source.filepath)
122
+ continue
123
+ // A file can be reached twice, once through the entry and once as its own.
124
+ // File plus starting line is what makes a slide one slide.
125
+ const anchor = `${source.filepath}:${source.start}`
126
+ if (seenAnchor.has(anchor))
127
+ continue
128
+ seenAnchor.add(anchor)
129
+ const frontmatter = source.frontmatter ?? slide.frontmatter ?? {}
130
+ rows.push({
131
+ file: source.filepath,
132
+ start: source.start,
133
+ style: source.frontmatterStyle,
134
+ title: (slide.title ?? '').trim(),
135
+ id: typeof frontmatter.id === 'string' ? frontmatter.id.trim() : '',
136
+ })
137
+ }
138
+ }
139
+ rows.sort((a, b) => a.file === b.file ? a.start - b.start : a.file.localeCompare(b.file))
140
+ return { rows, userRoot, profilesRoot }
141
+ }
142
+
143
+ function mintId(taken) {
144
+ for (let attempt = 0; attempt < 1000; attempt++) {
145
+ const candidate = ID_PREFIX + randomBytes(4).toString('hex')
146
+ if (!taken.has(candidate)) {
147
+ taken.add(candidate)
148
+ return candidate
149
+ }
150
+ }
151
+ throw new Error('could not mint a free slide id')
152
+ }
153
+
154
+ /**
155
+ * Ids already spoken for. The deck is the obvious half; the profiles are the
156
+ * other one. A slide that was deleted still lives on in some speaker's `hidden`
157
+ * list (deliberately, it may come back on another branch), and handing its id to
158
+ * a new slide would switch that slide off for them out of nowhere.
159
+ */
160
+ function takenIds(rows, profilesRoot) {
161
+ const taken = new Set(rows.map(row => row.id).filter(Boolean))
162
+ for (const speaker of listProfiles(profilesRoot)) {
163
+ const profile = readProfile(profilesRoot, speaker)
164
+ for (const id of [...profile.hidden, ...profile.knownIds])
165
+ taken.add(id)
166
+ }
167
+ return taken
168
+ }
169
+
170
+ const LOCK_NAME = '.stamp.lock'
171
+ const LOCK_STALE_MS = 60_000
172
+
173
+ /**
174
+ * One stamping run at a time.
175
+ *
176
+ * Decks with a dev script per chapter are meant to be run several at once, and
177
+ * two servers starting together on a deck that has unstamped slides would both
178
+ * mint ids and both write. The loser of that race would hold ids in memory that
179
+ * are not the ones on disk. Whoever does not get the lock skips: by the time it
180
+ * matters the other run has written the ids, and stamping is idempotent anyway.
181
+ */
182
+ function withLock(profilesRoot, fn) {
183
+ const lock = path.join(profilesRoot, PROFILE_DIR, LOCK_NAME)
184
+ let handle
185
+ try {
186
+ handle = openSync(lock, 'wx')
187
+ }
188
+ catch {
189
+ // A lock left behind by a killed process must not block the deck forever.
190
+ try {
191
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS)
192
+ unlinkSync(lock)
193
+ handle = openSync(lock, 'wx')
194
+ }
195
+ catch {
196
+ return { skipped: true, stamped: [], total: 0 }
197
+ }
198
+ }
199
+ try {
200
+ return fn()
201
+ }
202
+ finally {
203
+ try {
204
+ closeSync(handle)
205
+ unlinkSync(lock)
206
+ }
207
+ catch {
208
+ // best effort: a stale lock is cleared by the next run
209
+ }
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Write an id into every slide that has none.
215
+ *
216
+ * Returns what it did rather than printing, so the CLI can be chatty and the dev
217
+ * server can be a single line.
218
+ */
219
+ export async function stampSlides({ entry, also = [] }) {
220
+ const { rows, profilesRoot } = await collectSlides({ entry, also })
221
+ const todo = rows.filter(row => !row.id)
222
+ const unwritable = todo.filter(row => row.style !== 'frontmatter')
223
+ if (unwritable.length)
224
+ return { rows, stamped: [], unwritable, total: rows.length }
225
+ if (!todo.length)
226
+ return { rows, stamped: [], unwritable: [], total: rows.length }
227
+
228
+ const result = withLock(profilesRoot, () => {
229
+ const taken = takenIds(rows, profilesRoot)
230
+ // Bottom up per file: every insertion shifts the line numbers below it.
231
+ const byFile = new Map()
232
+ for (const row of todo)
233
+ byFile.set(row.file, [...(byFile.get(row.file) ?? []), row])
234
+ for (const [file, slides] of byFile) {
235
+ const raw = readFileSync(file, 'utf-8')
236
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n'
237
+ const lines = raw.split(/\r?\n/)
238
+ for (const row of [...slides].sort((a, b) => b.start - a.start)) {
239
+ row.id = mintId(taken)
240
+ lines.splice(row.start + 1, 0, `id: ${row.id}`)
241
+ }
242
+ writeFileSync(file, lines.join(eol), 'utf-8')
243
+ }
244
+ return { skipped: false, stamped: todo, files: byFile.size }
245
+ })
246
+
247
+ return { rows, unwritable: [], total: rows.length, ...result }
248
+ }
249
+
250
+ /** Is there a profile directory at all? Nothing here makes sense without one. */
251
+ export function hasProfilesDir(profilesRoot) {
252
+ return existsSync(path.join(profilesRoot, PROFILE_DIR))
253
+ }
package/state.ts ADDED
@@ -0,0 +1,186 @@
1
+ /**
2
+ * The client-side truth while presenting and while editing.
3
+ *
4
+ * Initialised from the `data-profile-off` keys the preparser injected, then
5
+ * owned by the editor: a toggle takes effect immediately (skip logic, greying
6
+ * out) and is persisted to the profile file separately. That way editing does
7
+ * not need a server restart per click, and the file stays the thing git tracks.
8
+ */
9
+ import type { SlideRoute } from '@slidev/types'
10
+ import { computed, ref } from 'vue'
11
+
12
+ export const hiddenIds = ref<Set<string>>(new Set())
13
+ export const knownIds = ref<string[]>([])
14
+ export const speaker = ref<string | null>(null)
15
+ export const editable = ref(false)
16
+ export const editorOpen = ref(false)
17
+ export const saveState = ref<'idle' | 'saving' | 'saved' | 'error'>('idle')
18
+ /** Toggled but not written to the profile file yet. */
19
+ export const dirty = ref(false)
20
+ /**
21
+ * True once we know where the selection comes from.
22
+ *
23
+ * `data-profile-off` is a snapshot from when the dev server parsed the deck, and
24
+ * saving does not re-parse. So on a reload the frontmatter can be minutes out of
25
+ * date, and the navigation watcher would skip slides the speaker has already
26
+ * switched back on. Nothing navigates until the state endpoint has answered (or
27
+ * failed, which is the built deck, where the selection is baked in anyway).
28
+ */
29
+ export const ready = ref(false)
30
+ export const saveError = ref('')
31
+
32
+ let initialised = false
33
+
34
+ export function slideId(route?: SlideRoute): string | undefined {
35
+ const value = (route?.meta?.slide?.frontmatter as any)?.['data-profile-id']
36
+ return typeof value === 'string' ? value : undefined
37
+ }
38
+
39
+ export function slideTitle(route?: SlideRoute): string {
40
+ return route?.meta?.slide?.title?.trim() || '(untitled)'
41
+ }
42
+
43
+ /**
44
+ * Which chapter file a slide came from, for the editor's grouping.
45
+ *
46
+ * A stamped id (`s-29076475`) carries no chapter, so the preparser sends it
47
+ * along separately. The slash form is the fallback id of a slide written since
48
+ * the last stamp run.
49
+ */
50
+ export function slideChapter(route?: SlideRoute): string {
51
+ const frontmatter = route?.meta?.slide?.frontmatter as any
52
+ const chapter = frontmatter?.['data-profile-chapter']
53
+ if (typeof chapter === 'string' && chapter)
54
+ return chapter
55
+ const id = slideId(route)
56
+ const slash = id?.indexOf('/') ?? -1
57
+ return slash === -1 ? 'unknown' : id!.slice(0, slash)
58
+ }
59
+
60
+ export function initFromSlides(slides: SlideRoute[]) {
61
+ if (initialised)
62
+ return
63
+ initialised = true
64
+ const off = new Set<string>()
65
+ for (const route of slides) {
66
+ const id = slideId(route)
67
+ if (id && (route.meta?.slide?.frontmatter as any)?.['data-profile-off'])
68
+ off.add(id)
69
+ }
70
+ hiddenIds.value = off
71
+ dirty.value = false
72
+ }
73
+
74
+ export function isHidden(id: string | undefined) {
75
+ return !!id && hiddenIds.value.has(id)
76
+ }
77
+
78
+ export function isSlideOff(slides: SlideRoute[], no: number) {
79
+ return isHidden(slideId(slides[no - 1]))
80
+ }
81
+
82
+ export function toggle(id: string) {
83
+ const next = new Set(hiddenIds.value)
84
+ if (next.has(id))
85
+ next.delete(id)
86
+ else
87
+ next.add(id)
88
+ hiddenIds.value = next
89
+ dirty.value = true
90
+ }
91
+
92
+ export const hiddenCount = computed(() => hiddenIds.value.size)
93
+
94
+ /**
95
+ * Drift against the profile's `knownIds`: unknown means visible, so a slide
96
+ * added on main shows up for every speaker instead of silently disappearing.
97
+ *
98
+ * Only additions. A deck can be run in pieces - the developer trainings have a
99
+ * separate entry per chapter - and "gone" would then mean "not in this chapter",
100
+ * which is true and useless. Ids that vanished are never dropped from `hidden`
101
+ * either: the slide may come back on another branch.
102
+ */
103
+ export function drift(currentIds: string[]) {
104
+ if (!knownIds.value.length)
105
+ return { added: [] }
106
+ const known = new Set(knownIds.value)
107
+ return { added: currentIds.filter(id => !known.has(id)) }
108
+ }
109
+
110
+ /**
111
+ * In dev the profile FILE is the truth, not the frontmatter.
112
+ *
113
+ * `data-profile-off` is decided while parsing, so it is a snapshot from the
114
+ * moment the dev server started. Saving changes the file but does not re-parse
115
+ * the deck, so after a reload the frontmatter is stale. Seeding the client from
116
+ * it would show slides as on that were switched off minutes ago - and the next
117
+ * save would write that stale picture back and quietly undo the earlier work.
118
+ * So whenever the endpoint answers, its profile wins over the frontmatter.
119
+ */
120
+ export async function loadServerState() {
121
+ try {
122
+ const res = await fetch('/@speaker-profiles/state')
123
+ if (!res.ok)
124
+ return
125
+ const data = await res.json()
126
+ editable.value = !!data.editable
127
+ speaker.value = data.speaker ?? null
128
+ knownIds.value = data.profile?.knownIds ?? []
129
+ if (data.profile) {
130
+ hiddenIds.value = new Set<string>(data.profile.hidden ?? [])
131
+ dirty.value = false
132
+ }
133
+ }
134
+ catch {
135
+ // built deck: no dev server, no editing. The selection is already baked in,
136
+ // and the frontmatter seeded by initFromSlides is all there is.
137
+ }
138
+ finally {
139
+ ready.value = true
140
+ }
141
+ }
142
+
143
+ let loading: Promise<void> | undefined
144
+
145
+ /**
146
+ * `/overview/` is its own page and does not render GlobalTop, so nothing there
147
+ * would ever fetch the profile and every card would look switched on. Any
148
+ * consumer can call this; the fetch happens once per window.
149
+ */
150
+ export function ensureLoaded() {
151
+ loading ??= loadServerState()
152
+ return loading
153
+ }
154
+
155
+ export async function save(currentIds: string[]) {
156
+ if (!speaker.value)
157
+ return
158
+ saveState.value = 'saving'
159
+ saveError.value = ''
160
+ try {
161
+ const res = await fetch('/@speaker-profiles/save', {
162
+ method: 'POST',
163
+ headers: { 'content-type': 'application/json' },
164
+ body: JSON.stringify({
165
+ speaker: speaker.value,
166
+ hidden: [...hiddenIds.value],
167
+ order: null,
168
+ // Additive, never a replacement. Saving from a single-chapter run must
169
+ // not shrink what this profile has already seen, or every slide of the
170
+ // other chapters would count as new the next time the whole deck runs.
171
+ knownIds: [...new Set([...knownIds.value, ...currentIds])],
172
+ }),
173
+ })
174
+ const data = await res.json()
175
+ if (!res.ok)
176
+ throw new Error(data?.error ?? `HTTP ${res.status}`)
177
+ knownIds.value = data.profile.knownIds
178
+ dirty.value = false
179
+ saveState.value = 'saved'
180
+ setTimeout(() => { if (saveState.value === 'saved') saveState.value = 'idle' }, 2000)
181
+ }
182
+ catch (error: any) {
183
+ saveState.value = 'error'
184
+ saveError.value = String(error?.message ?? error)
185
+ }
186
+ }