@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/profiles.mjs ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Reading and writing the per-speaker profile files.
3
+ *
4
+ * One file per speaker, never a shared one: two speakers changing their
5
+ * selection touch disjoint files, so git cannot put them in conflict. Arrays
6
+ * are written sorted so diffs stay minimal. There is deliberately no
7
+ * `updatedAt` field: it would be the one line that changes on every write and
8
+ * would turn "same person, two machines, different slides" into a guaranteed
9
+ * conflict carrying no information. Git already records the timestamp.
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
12
+ import { dirname, join } from 'node:path'
13
+
14
+ export const PROFILE_DIR = '.slidev-profiles'
15
+ export const SCHEMA_VERSION = 1
16
+
17
+ const RE_SAFE_NAME = /^[a-z0-9][a-z0-9_-]*$/i
18
+
19
+ /** Walk up from the deck root looking for the profile directory, then the repo root. */
20
+ export function findProfilesRoot(startDir) {
21
+ let dir = startDir
22
+ for (let i = 0; i < 6; i++) {
23
+ if (existsSync(join(dir, PROFILE_DIR)))
24
+ return dir
25
+ const parent = dirname(dir)
26
+ if (parent === dir)
27
+ break
28
+ dir = parent
29
+ }
30
+ dir = startDir
31
+ for (let i = 0; i < 6; i++) {
32
+ if (existsSync(join(dir, '.git')))
33
+ return dir
34
+ const parent = dirname(dir)
35
+ if (parent === dir)
36
+ break
37
+ dir = parent
38
+ }
39
+ return startDir
40
+ }
41
+
42
+ export function profilePath(root, speaker) {
43
+ return join(root, PROFILE_DIR, `${speaker}.json`)
44
+ }
45
+
46
+ export function listProfiles(root) {
47
+ const dir = join(root, PROFILE_DIR)
48
+ if (!existsSync(dir))
49
+ return []
50
+ return readdirSync(dir)
51
+ .filter(f => f.endsWith('.json'))
52
+ .map(f => f.slice(0, -5))
53
+ .sort()
54
+ }
55
+
56
+ /**
57
+ * Which speaker are we? `SLIDEV_PROFILE` wins so CI and one-off builds can be
58
+ * explicit. Otherwise a local, gitignored `.slidev-profiles/.current`.
59
+ * Deliberately NOT `git config user.name`: that is a GitHub handle here and it
60
+ * differs per machine.
61
+ */
62
+ export function resolveSpeaker(root, { allowCurrentFile = true } = {}) {
63
+ const fromEnv = process.env.SLIDEV_PROFILE?.trim()
64
+ // `none` switches the addon off for tools that drive the deck slide by slide
65
+ // (the validator, screenshot runs): the skip logic would navigate away from
66
+ // the slide they are waiting for and they would time out.
67
+ if (fromEnv === 'none')
68
+ return undefined
69
+ if (fromEnv)
70
+ return fromEnv
71
+ if (!allowCurrentFile)
72
+ return undefined
73
+ const currentFile = join(root, PROFILE_DIR, '.current')
74
+ if (existsSync(currentFile)) {
75
+ const name = readFileSync(currentFile, 'utf-8').trim()
76
+ if (name)
77
+ return name
78
+ }
79
+ return undefined
80
+ }
81
+
82
+ /** Is there a .current that we are deliberately ignoring? Used for a clear log line. */
83
+ export function hasCurrentFile(root) {
84
+ return existsSync(join(root, PROFILE_DIR, '.current'))
85
+ }
86
+
87
+ export function isValidName(name) {
88
+ return typeof name === 'string' && RE_SAFE_NAME.test(name) && name.length <= 64
89
+ }
90
+
91
+ export function readProfile(root, speaker) {
92
+ const file = profilePath(root, speaker)
93
+ if (!existsSync(file))
94
+ return { schemaVersion: SCHEMA_VERSION, speaker, hidden: [], order: null, knownIds: [] }
95
+ const raw = JSON.parse(readFileSync(file, 'utf-8'))
96
+ return {
97
+ schemaVersion: raw.schemaVersion ?? SCHEMA_VERSION,
98
+ speaker,
99
+ hidden: Array.isArray(raw.hidden) ? raw.hidden : [],
100
+ order: raw.order ?? null,
101
+ knownIds: Array.isArray(raw.knownIds) ? raw.knownIds : [],
102
+ }
103
+ }
104
+
105
+ export function writeProfile(root, speaker, profile) {
106
+ const dir = join(root, PROFILE_DIR)
107
+ if (!existsSync(dir))
108
+ mkdirSync(dir, { recursive: true })
109
+ const payload = {
110
+ schemaVersion: SCHEMA_VERSION,
111
+ speaker,
112
+ hidden: [...new Set(profile.hidden ?? [])].sort(),
113
+ order: profile.order ?? null,
114
+ knownIds: [...new Set(profile.knownIds ?? [])].sort(),
115
+ }
116
+ writeFileSync(profilePath(root, speaker), `${JSON.stringify(payload, null, 2)}\n`, 'utf-8')
117
+ return payload
118
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * One state, two uses: the profile file decides what the speaker presents and
3
+ * what the export contains.
4
+ *
5
+ * `hide: true` is evaluated while parsing, so a hidden slide never reaches the
6
+ * client. That is exactly what we want for build and export, and exactly what
7
+ * we do NOT want in dev, where the editor has to list the switched-off slides
8
+ * so they can be switched back on. So:
9
+ *
10
+ * dev -> inject `data-profile-off`, keep the slide. The runtime skips it.
11
+ * build -> set `hide: true`. The slide is gone from the bundle and the PDF.
12
+ *
13
+ * Author intent is untouchable: a slide that already carries `hide: true` in
14
+ * the markdown (a backup slide for the Q&A) is the author's decision, not the
15
+ * speaker's. The addon never lists it and never changes it. It does carry an
16
+ * id, though - `slide-ids --stamp` covers hidden slides as well, so that
17
+ * deleting the `hide: true` line one day brings the slide back with the
18
+ * identity it always had rather than as a new slide for everybody.
19
+ *
20
+ * Frontmatter keys are handed to the layout as props and unknown ones fall
21
+ * through onto the layout's root element, so the injected keys are named
22
+ * `data-*`: they land in the DOM as valid data attributes instead of stray
23
+ * ones, and they are handy when debugging a slide. An authored `id:` is read
24
+ * and then removed for the same reason.
25
+ */
26
+ import { createIdAssigner, indexMarkdownFiles } from '../identity.mjs'
27
+ import { findProfilesRoot, hasCurrentFile, readProfile, resolveSpeaker } from '../profiles.mjs'
28
+
29
+ export default function ({ filepath, mode }: { filepath: string, headmatter: Record<string, unknown>, mode?: string }) {
30
+ const userRoot = filepath.replace(/[\\/][^\\/]+$/, '')
31
+ const profilesRoot = findProfilesRoot(userRoot)
32
+ const isDev = mode === 'dev'
33
+
34
+ // A local `.current` picks the profile while working on the deck, but it must
35
+ // never quietly filter a build: someone would deploy a deck with slides
36
+ // missing and not notice. Build and export take SLIDEV_PROFILE and nothing
37
+ // else, so filtering a release is always a deliberate act.
38
+ const speaker = resolveSpeaker(profilesRoot, { allowCurrentFile: isDev })
39
+ if (!speaker && !isDev && hasCurrentFile(profilesRoot))
40
+ console.log('[speaker-profiles] .slidev-profiles/.current is ignored outside dev - pass SLIDEV_PROFILE=<name> to filter a build')
41
+
42
+ // Dev keeps every slide so the editor can show them. Build and export drop them.
43
+ const shouldHide = process.env.SLIDEV_PROFILE_HIDE === '1' || !isDev
44
+
45
+ const profile = speaker ? readProfile(profilesRoot, speaker) : undefined
46
+ const hidden = new Set<string>(profile?.hidden ?? [])
47
+
48
+ if (speaker)
49
+ console.log(`[speaker-profiles] profile "${speaker}": ${hidden.size} slide(s) off, ${shouldHide ? 'removed from this build' : 'skipped at runtime'}`)
50
+ else
51
+ console.log(`[speaker-profiles] no profile selected (${isDev ? 'set SLIDEV_PROFILE or .slidev-profiles/.current' : 'set SLIDEV_PROFILE'}) - showing the full deck`)
52
+
53
+ const assigner = createIdAssigner(indexMarkdownFiles(userRoot))
54
+
55
+ return [{
56
+ name: 'speaker-profiles',
57
+ transformRawLines(lines: string[]) {
58
+ assigner.startFile(lines)
59
+ },
60
+ transformSlide(content: string, frontmatter: any) {
61
+ // author intent, not ours to touch
62
+ if (frontmatter.hide === true || frontmatter.disabled === true)
63
+ return undefined
64
+
65
+ // A `src:` slide is an import wrapper, not a slide. Slidev merges its
66
+ // frontmatter over EVERY imported slide (`{...slide, ...override}`, the
67
+ // override wins), so anything injected here would clobber the ids of the
68
+ // whole chapter. Leave it alone and let the imported slides speak.
69
+ if (frontmatter.src)
70
+ return undefined
71
+
72
+ const id = assigner.next(content, frontmatter)
73
+ delete frontmatter.id
74
+ frontmatter['data-profile-id'] = id
75
+ // A stamped id says nothing about where the slide lives, so the chapter
76
+ // travels separately. The editor groups by it.
77
+ frontmatter['data-profile-chapter'] = assigner.file()
78
+
79
+ if (hidden.has(id)) {
80
+ if (shouldHide)
81
+ frontmatter.hide = true
82
+ else
83
+ frontmatter['data-profile-off'] = true
84
+ }
85
+ return undefined
86
+ },
87
+ }]
88
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Navigation that steps over the switched-off slides.
3
+ *
4
+ * Slidev's built-in shortcuts carry stable names, and a shortcuts setup gets
5
+ * the whole array and returns it. So we do not rebind keys and we do not
6
+ * rebuild the magicKeys combinations: we map over the array and swap `fn` on
7
+ * the ten navigation entries. Everything else, including the guard that warns
8
+ * when a setup drops the base shortcuts, keeps working.
9
+ *
10
+ * The click logic has to be rebuilt by hand: exhaust the current slide's
11
+ * `v-click` steps first, only then look for the next slide that is on.
12
+ */
13
+ import type { NavOperations, ShortcutOptions } from '@slidev/types'
14
+ import { useNav } from '@slidev/client'
15
+ import { editable, isSlideOff } from '../state'
16
+
17
+ export default function (context: NavOperations, shortcuts: ShortcutOptions[]) {
18
+ const nav = useNav()
19
+
20
+ // Editing keeps normal navigation, so a switched-off slide stays reachable
21
+ // and can be turned back on. That is the play view with the controls on
22
+ // screen only: the presenter window is presenting and keeps skipping.
23
+ const editing = () => editable.value && nav.isPlaying.value
24
+ const off = (no: number) => !editing() && isSlideOff(nav.slides.value, no)
25
+
26
+ const seek = (from: number, step: 1 | -1) => {
27
+ let no = from + step
28
+ while (no >= 1 && no <= nav.slides.value.length && off(no))
29
+ no += step
30
+ return no >= 1 && no <= nav.slides.value.length ? no : undefined
31
+ }
32
+
33
+ function next() {
34
+ // finish the clicks of the current slide first
35
+ if (nav.clicks.value < nav.clicksTotal.value)
36
+ return context.next()
37
+ const no = seek(nav.currentSlideNo.value, 1)
38
+ if (no)
39
+ nav.go(no)
40
+ }
41
+
42
+ function prev() {
43
+ if (nav.clicks.value > nav.clicksStart.value)
44
+ return context.prev()
45
+ const no = seek(nav.currentSlideNo.value, -1)
46
+ // land on the last click of the previous slide, like the built-in prev.
47
+ // `go` clamps the click count to what the target slide actually has.
48
+ if (no)
49
+ nav.go(no, Number.MAX_SAFE_INTEGER)
50
+ }
51
+
52
+ function nextSlide() {
53
+ const no = seek(nav.currentSlideNo.value, 1)
54
+ if (no)
55
+ nav.go(no)
56
+ }
57
+
58
+ function prevSlide() {
59
+ const no = seek(nav.currentSlideNo.value, -1)
60
+ if (no)
61
+ nav.go(no)
62
+ }
63
+
64
+ const replacements: Record<string, () => void> = {
65
+ next_space: next,
66
+ prev_space: prev,
67
+ next_right: next,
68
+ prev_left: prev,
69
+ next_page_key: next,
70
+ prev_page_key: prev,
71
+ next_down: nextSlide,
72
+ prev_up: prevSlide,
73
+ next_shift: nextSlide,
74
+ prev_shift: prevSlide,
75
+ }
76
+
77
+ return shortcuts.map(shortcut => (
78
+ shortcut.name && replacements[shortcut.name]
79
+ ? { ...shortcut, fn: replacements[shortcut.name] }
80
+ : shortcut
81
+ ))
82
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The dev-only half of the addon: the write path for the editor overlay, and
3
+ * giving new slides their ids.
4
+ *
5
+ * A built SPA has no file system, so the endpoint simply does not exist there
6
+ * and the overlay never turns editable. That is the gate: in the deployed deck
7
+ * and in the presentation itself there is no UI to mis-click, only the skip
8
+ * logic. Editing is unlocked with SLIDEV_PROFILE_EDIT=1.
9
+ *
10
+ * Stamping lives here rather than in an npm hook because a deck can have any
11
+ * number of ways to start a dev server - the two developer trainings have one
12
+ * script per chapter, eight and nine of them - and a `predev` hook would have to
13
+ * be repeated in each and would be forgotten in one. Every one of them boots
14
+ * this plugin.
15
+ */
16
+ import { findProfilesRoot, isValidName, listProfiles, readProfile, resolveSpeaker, writeProfile } from '../profiles.mjs'
17
+ import { hasProfilesDir, stampSlides } from '../stamp.mjs'
18
+
19
+ const BASE = '/@speaker-profiles'
20
+
21
+ function json(res: any, status: number, body: unknown) {
22
+ res.statusCode = status
23
+ res.setHeader('content-type', 'application/json')
24
+ res.setHeader('cache-control', 'no-store')
25
+ res.end(JSON.stringify(body))
26
+ }
27
+
28
+ function readBody(req: any): Promise<string> {
29
+ return new Promise((resolve, reject) => {
30
+ let body = ''
31
+ req.on('data', (chunk: any) => {
32
+ body += chunk
33
+ if (body.length > 1_000_000)
34
+ reject(new Error('payload too large'))
35
+ })
36
+ req.on('end', () => resolve(body))
37
+ req.on('error', reject)
38
+ })
39
+ }
40
+
41
+ /**
42
+ * Give the slides that have none an id, once, when the server starts.
43
+ *
44
+ * Deliberately quiet about the cases where it must not act:
45
+ *
46
+ * - `SLIDEV_PROFILE=none` switches the addon off, and tools that boot a dev
47
+ * server to drive the deck (the validator, a screenshot run) set it. They must
48
+ * not come back to a modified working tree.
49
+ * - `SLIDEV_SPEAKER_PROFILES_NO_STAMP=1` is the opt-out for anyone who wants the
50
+ * dev server to keep its hands off the sources. `slide-ids --stamp` still does
51
+ * it on demand.
52
+ * - No `.slidev-profiles/` directory means nobody is using profiles here.
53
+ *
54
+ * It never throws. A read-only checkout or a lost race is worth a warning, not a
55
+ * dev server that refuses to start - and `slide-ids --check` in CI is what
56
+ * actually guarantees the deck on main is stamped.
57
+ *
58
+ * The ids land a moment after the first parse, so Vite reloads once. That only
59
+ * happens when there is something to stamp, which is the run right after
60
+ * somebody wrote a slide.
61
+ */
62
+ async function stampOnce(entry: string, profilesRoot: string) {
63
+ if (process.env.SLIDEV_PROFILE?.trim() === 'none')
64
+ return
65
+ if (process.env.SLIDEV_SPEAKER_PROFILES_NO_STAMP === '1')
66
+ return
67
+ if (!hasProfilesDir(profilesRoot))
68
+ return
69
+ try {
70
+ const { stamped, unwritable, skipped } = await stampSlides({ entry })
71
+ if (unwritable.length)
72
+ console.warn(`[speaker-profiles] ${unwritable.length} slide(s) have no writable frontmatter block and stay unstamped`)
73
+ else if (stamped.length)
74
+ console.log(`[speaker-profiles] stamped ${stamped.length} new slide(s) with an id`)
75
+ else if (skipped)
76
+ console.log('[speaker-profiles] another run is stamping, skipped')
77
+ }
78
+ catch (error: any) {
79
+ console.warn(`[speaker-profiles] could not stamp slide ids: ${error?.message ?? error}`)
80
+ }
81
+ }
82
+
83
+ export default function (options: any) {
84
+ const userRoot = options.userRoot as string
85
+ const profilesRoot = findProfilesRoot(userRoot)
86
+ const editable = process.env.SLIDEV_PROFILE_EDIT === '1'
87
+
88
+ return {
89
+ name: 'speaker-profiles:server',
90
+ apply: 'serve' as const,
91
+ configureServer(server: any) {
92
+ // Not awaited: the server must come up regardless, and the file writes
93
+ // reach the client through Vite's watcher like any other edit.
94
+ void stampOnce(options.entry as string, profilesRoot)
95
+
96
+ server.middlewares.use(`${BASE}/state`, (_req: any, res: any) => {
97
+ const speaker = resolveSpeaker(profilesRoot)
98
+ json(res, 200, {
99
+ editable,
100
+ speaker: speaker ?? null,
101
+ profiles: listProfiles(profilesRoot),
102
+ profile: speaker ? readProfile(profilesRoot, speaker) : null,
103
+ })
104
+ })
105
+
106
+ server.middlewares.use(`${BASE}/save`, async (req: any, res: any) => {
107
+ if (req.method !== 'POST')
108
+ return json(res, 405, { error: 'POST only' })
109
+ if (!editable)
110
+ return json(res, 403, { error: 'editing is locked. Restart with SLIDEV_PROFILE_EDIT=1' })
111
+ try {
112
+ const payload = JSON.parse(await readBody(req))
113
+ const speaker = String(payload.speaker ?? '').trim()
114
+ if (!isValidName(speaker))
115
+ return json(res, 400, { error: `invalid profile name "${speaker}"` })
116
+ const written = writeProfile(profilesRoot, speaker, {
117
+ hidden: payload.hidden ?? [],
118
+ order: payload.order ?? null,
119
+ knownIds: payload.knownIds ?? [],
120
+ })
121
+ console.log(`[speaker-profiles] saved ${speaker}.json (${written.hidden.length} off)`)
122
+ return json(res, 200, { ok: true, profile: written })
123
+ }
124
+ catch (error: any) {
125
+ return json(res, 400, { error: String(error?.message ?? error) })
126
+ }
127
+ })
128
+ },
129
+ }
130
+ }
package/slide-top.vue ADDED
@@ -0,0 +1,58 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * Greying out inside Slidev's OWN overview.
4
+ *
5
+ * `SlideWrapper` renders `<SlideTop />` and the built-in overview uses
6
+ * `SlideWrapper` with `render-context="overview"`, so this layer reaches every
7
+ * card there and in the presenter's next-slide preview. That is why the addon
8
+ * does not ship its own thumbnail grid: pressing `o` shows the real slides with
9
+ * the switched-off ones dimmed, and the checkbox list lives in the editor panel.
10
+ *
11
+ * Interaction is not possible here: the overview wraps each card in
12
+ * `pointer-events: none` and puts its own click handler on the parent.
13
+ */
14
+ import { useSlideContext } from '@slidev/client'
15
+ import { computed } from 'vue'
16
+ import { ensureLoaded, isHidden } from './state'
17
+
18
+ const { $renderContext, $frontmatter } = useSlideContext()
19
+
20
+ // the standalone /overview/ page renders these without a GlobalTop above them
21
+ ensureLoaded()
22
+
23
+ const id = computed(() => ($frontmatter as any)?.['data-profile-id'] as string | undefined)
24
+ const show = computed(() =>
25
+ (['overview', 'previewNext'].includes($renderContext.value))
26
+ && isHidden(id.value),
27
+ )
28
+ </script>
29
+
30
+ <template>
31
+ <div v-if="show" class="speaker-profiles-dim" data-testid="speaker-profiles-dim">
32
+ <div class="speaker-profiles-dim-label">
33
+ OFF
34
+ </div>
35
+ </div>
36
+ </template>
37
+
38
+ <style>
39
+ .speaker-profiles-dim {
40
+ position: absolute;
41
+ inset: 0;
42
+ z-index: 400;
43
+ display: flex;
44
+ align-items: center;
45
+ justify-content: center;
46
+ background: rgba(17, 17, 24, 0.66);
47
+ backdrop-filter: saturate(0.2);
48
+ }
49
+
50
+ .speaker-profiles-dim-label {
51
+ font: 700 2.4rem/1 ui-sans-serif, system-ui, sans-serif;
52
+ letter-spacing: 0.18em;
53
+ color: rgba(255, 255, 255, 0.92);
54
+ border: 3px solid rgba(255, 255, 255, 0.75);
55
+ border-radius: 0.5rem;
56
+ padding: 0.5rem 1.1rem;
57
+ }
58
+ </style>