slidev-theme-kotlin 0.13.2 → 0.14.1

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +38 -1
  2. package/README.md +396 -633
  3. package/assets/gutter/suspendCall@14x14.svg +6 -0
  4. package/assets/gutter/suspendCall@14x14_dark.svg +6 -0
  5. package/bin/present.mjs +296 -0
  6. package/components/DrawnAnnotation.vue +57 -9
  7. package/components/DrawnAnnotationEditorToolbar.vue +1 -1
  8. package/components/InlineCompilerError.vue +46 -15
  9. package/components/InlineValue.vue +3 -3
  10. package/components/MagicMoveBetween.vue +6 -4
  11. package/components/README.md +60 -2
  12. package/components/SmartCast.vue +3 -3
  13. package/components/SuspendGutter.vue +168 -0
  14. package/components/TypeHint.vue +3 -3
  15. package/components/Warning.vue +3 -3
  16. package/components/carried-layer.ts +29 -0
  17. package/components/code-highlight.ts +119 -5
  18. package/components/transition-ink.ts +27 -6
  19. package/docs/annotation-editor.png +0 -0
  20. package/docs/code-marks.md +76 -0
  21. package/docs/phone-remote.png +0 -0
  22. package/docs/presenting.md +122 -0
  23. package/docs/publishing.md +111 -0
  24. package/docs/snippets.md +84 -0
  25. package/global-top.vue +3 -8
  26. package/package.json +11 -4
  27. package/remote/RemoteControl.vue +278 -0
  28. package/remote/connection.ts +19 -0
  29. package/setup/code-imports.ts +3 -2
  30. package/setup/code-marks.ts +562 -0
  31. package/setup/kotlin-snippets.ts +4 -2
  32. package/setup/magic-move-between.ts +10 -2
  33. package/setup/main.ts +5 -1
  34. package/setup/remote-sync.ts +226 -0
  35. package/setup/routes.ts +21 -0
  36. package/setup/static-content.ts +39 -5
  37. package/setup/transformers.ts +16 -1
  38. package/styles/layout.css +17 -0
  39. package/assets/edit-3-svgrepo-com.svg +0 -5
  40. package/components/DrawnAnnotationEditorLauncher.vue +0 -59
@@ -0,0 +1,6 @@
1
+ <!-- Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
2
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
3
+ <path d="M5.50025 1.5C5.50025 1.5 3.24989 4 5.49994 6.5C7.74994 9 5.50026 11.5 5.50026 11.5" stroke="#208A3C" stroke-linecap="round"/>
4
+ <path d="M9.85355 2.14645C9.65829 1.95118 9.34171 1.95118 9.14645 2.14645C8.95118 2.34171 8.95118 2.65829 9.14645 2.85355L12.2929 6H7.02351C7.26532 6.33273 7.45493 6.66748 7.60006 7H12.2929L9.14645 10.1464C8.95118 10.3417 8.95118 10.6583 9.14645 10.8536C9.34171 11.0488 9.65829 11.0488 9.85355 10.8536L13.8536 6.85355C14.0488 6.65829 14.0488 6.34171 13.8536 6.14645L9.85355 2.14645Z" fill="#6C707E"/>
5
+ <path d="M3.97649 7C3.73468 6.66727 3.54507 6.33252 3.39994 6H0.5C0.223858 6 0 6.22386 0 6.5C0 6.77614 0.223858 7 0.5 7H3.97649Z" fill="#6C707E"/>
6
+ </svg>
@@ -0,0 +1,6 @@
1
+ <!-- Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
2
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
3
+ <path d="M5.50025 1.5C5.50025 1.5 3.24989 4 5.49994 6.5C7.74994 9 5.50026 11.5 5.50026 11.5" stroke="#57965C" stroke-linecap="round"/>
4
+ <path d="M9.85355 2.14645C9.65829 1.95118 9.34171 1.95118 9.14645 2.14645C8.95118 2.34171 8.95118 2.65829 9.14645 2.85355L12.2929 6H7.02351C7.26532 6.33273 7.45493 6.66748 7.60006 7H12.2929L9.14645 10.1464C8.95118 10.3417 8.95118 10.6583 9.14645 10.8536C9.34171 11.0488 9.65829 11.0488 9.85355 10.8536L13.8536 6.85355C14.0488 6.65829 14.0488 6.34171 13.8536 6.14645L9.85355 2.14645Z" fill="#CED0D6"/>
5
+ <path d="M3.97649 7C3.73468 6.66727 3.54507 6.33252 3.39994 6H0.5C0.223858 6 0 6.22386 0 6.5C0 6.77614 0.223858 7 0.5 7H3.97649Z" fill="#CED0D6"/>
6
+ </svg>
@@ -0,0 +1,296 @@
1
+ #!/usr/bin/env node
2
+ // Serves a built deck (`slidev build`) on the local network and relays
3
+ // navigation from a phone remote to every open display. No internet needed.
4
+ //
5
+ // Reading is open to whoever can reach the server: the slides, the speaker
6
+ // notes in the bundle, and the current slide number. Driving the deck needs
7
+ // the write secret, which only ever leaves this process inside the remote
8
+ // URL and QR code printed below.
9
+ import { randomBytes, timingSafeEqual } from 'node:crypto'
10
+ import { createReadStream } from 'node:fs'
11
+ import { mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises'
12
+ import { createServer } from 'node:http'
13
+ import { networkInterfaces } from 'node:os'
14
+ import { dirname, extname, resolve, sep } from 'node:path'
15
+ import process from 'node:process'
16
+ import { parseArgs } from 'node:util'
17
+ import { encode } from 'uqr'
18
+
19
+ const usage = `Usage: slidev-kotlin-present [dist] [--port 4174] [--new-secret]
20
+
21
+ dist the built deck to serve (default: ./dist)
22
+ --port, -p port to listen on (default: $PORT or 4174)
23
+ --new-secret replace the saved write secret, invalidating old remote links
24
+ `
25
+
26
+ const { values: flags, positionals } = parseArgs({
27
+ allowPositionals: true,
28
+ options: {
29
+ 'port': { type: 'string', short: 'p' },
30
+ 'new-secret': { type: 'boolean' },
31
+ 'help': { type: 'boolean', short: 'h' },
32
+ },
33
+ })
34
+ if (flags.help) {
35
+ process.stdout.write(usage)
36
+ process.exit(0)
37
+ }
38
+
39
+ function fail(message) {
40
+ process.stderr.write(`${message}\n`)
41
+ process.exit(1)
42
+ }
43
+
44
+ const dist = resolve(process.cwd(), positionals[0] ?? 'dist')
45
+ const root = await realpath(dist).catch(() => fail(`No built deck at ${dist}. Run \`slidev build\` first.`))
46
+ const indexFile = resolve(root, 'index.html')
47
+ const headTag = /<head[^>]*>/
48
+
49
+ /** The deck's Vite base, read from the entry script the build wrote. */
50
+ function baseOf(html) {
51
+ const base = /<script type="module"[^>]*\ssrc="([^"]*?)assets\//.exec(html)?.[1]
52
+ return base?.startsWith('/') ? base : '/'
53
+ }
54
+
55
+ const firstIndex = await readFile(indexFile, 'utf8').catch(() => fail(`No index.html in ${dist}. Run \`slidev build\` first.`))
56
+ if (!headTag.test(firstIndex))
57
+ fail(`${indexFile} has no <head>; cannot enable the remote.`)
58
+ const base = baseOf(firstIndex)
59
+
60
+ /**
61
+ * The write secret survives a restart, so a phone that is already connected
62
+ * keeps working after the server is restarted mid-rehearsal.
63
+ */
64
+ async function loadSecret() {
65
+ const file = resolve(process.cwd(), 'node_modules/.cache/slidev-kotlin-present/secret')
66
+ if (!flags['new-secret']) {
67
+ const saved = (await readFile(file, 'utf8').catch(() => '')).trim()
68
+ if (/^[\w-]{20,}$/.test(saved))
69
+ return saved
70
+ }
71
+ const secret = randomBytes(16).toString('base64url')
72
+ try {
73
+ await mkdir(dirname(file), { recursive: true })
74
+ await writeFile(file, `${secret}\n`, { mode: 0o600 })
75
+ }
76
+ catch {
77
+ process.stderr.write('Could not save the write secret; remote links will change on restart.\n')
78
+ }
79
+ return secret
80
+ }
81
+
82
+ const secret = Buffer.from(await loadSecret())
83
+ // Changes on every start: lets tests and clients tell a restart from a blip.
84
+ const instance = randomBytes(8).toString('hex')
85
+
86
+ function authorized(header) {
87
+ const given = Buffer.from(/^Bearer (.+)$/.exec(header ?? '')?.[1] ?? '')
88
+ return given.length === secret.length && timingSafeEqual(given, secret)
89
+ }
90
+
91
+ const roles = new Set(['remote', 'display', 'viewer'])
92
+ /** Open event streams and the role each one announced. */
93
+ const clients = new Map()
94
+ /** The last state a remote sent, replayed to displays that connect later. */
95
+ let latest
96
+
97
+ function broadcast(text) {
98
+ for (const client of clients.keys())
99
+ client.write(text)
100
+ }
101
+
102
+ function broadcastPeers() {
103
+ const count = role => [...clients.values()].filter(value => value === role).length
104
+ broadcast(`event: peers\ndata: ${JSON.stringify({ displays: count('display'), remotes: count('remote') })}\n\n`)
105
+ }
106
+
107
+ const types = {
108
+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript',
109
+ '.css': 'text/css', '.json': 'application/json', '.map': 'application/json',
110
+ '.webmanifest': 'application/manifest+json', '.xml': 'application/xml', '.txt': 'text/plain; charset=utf-8',
111
+ '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
112
+ '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif', '.ico': 'image/x-icon',
113
+ '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf',
114
+ '.mp4': 'video/mp4', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav',
115
+ '.pdf': 'application/pdf', '.wasm': 'application/wasm',
116
+ }
117
+
118
+ /** Safari only plays video from a server that answers byte-range requests. */
119
+ function rangeOf(header, size) {
120
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header ?? '')
121
+ if (!match || (!match[1] && !match[2]))
122
+ return undefined
123
+ const start = match[1] ? Number(match[1]) : Math.max(0, size - Number(match[2]))
124
+ const end = match[1] && match[2] ? Math.min(Number(match[2]), size - 1) : size - 1
125
+ return start <= end && start < size ? { start, end } : undefined
126
+ }
127
+
128
+ async function readBody(req, limit = 65536) {
129
+ let body = ''
130
+ for await (const chunk of req) {
131
+ body += chunk
132
+ if (body.length > limit)
133
+ return undefined
134
+ }
135
+ return body
136
+ }
137
+
138
+ function validState(state) {
139
+ return state !== null && typeof state === 'object'
140
+ && Number.isInteger(state.page) && state.page >= 1
141
+ && Number.isInteger(state.clicks) && state.clicks >= 0
142
+ }
143
+
144
+ const server = createServer(async (req, res) => {
145
+ try {
146
+ const url = new URL(req.url, 'http://localhost')
147
+ const pathname = decodeURIComponent(url.pathname)
148
+ res.setHeader('Cache-Control', 'no-store')
149
+
150
+ if (!pathname.startsWith(base)) {
151
+ if (pathname === '/' || `${pathname}/` === base)
152
+ res.writeHead(302, { Location: `${base}${url.search}` }).end()
153
+ else
154
+ res.writeHead(404).end()
155
+ return
156
+ }
157
+ const path = `/${pathname.slice(base.length)}`
158
+
159
+ if (path === '/__remote/session') {
160
+ if (req.method !== 'GET') { res.writeHead(405).end(); return }
161
+ res.writeHead(200, { 'Content-Type': 'application/json' })
162
+ res.end(JSON.stringify({ instance, state: latest ?? null }))
163
+ return
164
+ }
165
+ if (path === '/__remote/events') {
166
+ if (req.method !== 'GET') { res.writeHead(405).end(); return }
167
+ const role = url.searchParams.get('role')
168
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive' })
169
+ res.write(': connected\n\n')
170
+ clients.set(res, roles.has(role) ? role : 'viewer')
171
+ broadcastPeers()
172
+ if (latest)
173
+ res.write(`data: ${JSON.stringify(latest)}\n\n`)
174
+ const heartbeat = setInterval(() => res.write(': heartbeat\n\n'), 15000)
175
+ res.on('close', () => {
176
+ clients.delete(res)
177
+ clearInterval(heartbeat)
178
+ broadcastPeers()
179
+ })
180
+ return
181
+ }
182
+ if (path === '/__remote/state') {
183
+ if (req.method !== 'POST') { res.writeHead(405).end(); return }
184
+ if (!authorized(req.headers.authorization)) { res.writeHead(403).end(); return }
185
+ const body = await readBody(req)
186
+ if (body === undefined) { res.writeHead(413).end(); return }
187
+ const state = JSON.parse(body)
188
+ if (!validState(state)) { res.writeHead(400).end(); return }
189
+ latest = { page: state.page, clicks: state.clicks }
190
+ broadcast(`data: ${JSON.stringify(latest)}\n\n`)
191
+ res.writeHead(204).end()
192
+ return
193
+ }
194
+
195
+ if (!['GET', 'HEAD'].includes(req.method)) { res.writeHead(405).end(); return }
196
+ if (path === '/index.html' || !extname(path)) {
197
+ // Read per request: a rebuild replaces the hashed assets it points to.
198
+ const html = (await readFile(indexFile, 'utf8')).replace(headTag, head =>
199
+ `${head}<script>window.__slidevKotlinPresent=${JSON.stringify({ instance })}</script>`)
200
+ res.writeHead(200, { 'Content-Type': types['.html'] })
201
+ res.end(req.method === 'HEAD' ? undefined : html)
202
+ return
203
+ }
204
+ const file = await realpath(resolve(root, `.${path}`))
205
+ if (!file.startsWith(root + sep)) { res.writeHead(403).end(); return }
206
+ const info = await stat(file)
207
+ if (!info.isFile()) { res.writeHead(404).end(); return }
208
+ const headers = { 'Content-Type': types[extname(file).toLowerCase()] ?? 'application/octet-stream', 'Accept-Ranges': 'bytes' }
209
+ const range = rangeOf(req.headers.range, info.size)
210
+ if (range) {
211
+ headers['Content-Range'] = `bytes ${range.start}-${range.end}/${info.size}`
212
+ headers['Content-Length'] = range.end - range.start + 1
213
+ }
214
+ else {
215
+ headers['Content-Length'] = info.size
216
+ }
217
+ res.writeHead(range ? 206 : 200, headers)
218
+ if (req.method === 'HEAD')
219
+ res.end()
220
+ else
221
+ createReadStream(file, range).on('error', () => res.destroy()).pipe(res)
222
+ }
223
+ catch (error) {
224
+ if (!res.headersSent)
225
+ res.writeHead(error.code === 'ENOENT' ? 404 : 400)
226
+ res.end()
227
+ }
228
+ })
229
+
230
+ /**
231
+ * Two QR rows per terminal line, in fixed black on white so the code scans
232
+ * the same on a light and on a dark terminal theme.
233
+ */
234
+ function qr(text) {
235
+ const { data, size } = encode(text, { ecc: 'L', border: 2 })
236
+ const lines = []
237
+ for (let y = 0; y < size; y += 2) {
238
+ let line = ''
239
+ for (let x = 0; x < size; x++) {
240
+ const top = data[y][x]
241
+ const bottom = y + 1 < size && data[y + 1][x]
242
+ line += top && bottom ? '█' : top ? '▀' : bottom ? '▄' : ' '
243
+ }
244
+ lines.push(` \u001B[30;107m${line}\u001B[0m`)
245
+ }
246
+ return lines.join('\n')
247
+ }
248
+
249
+ // VPN tunnels, virtual machine bridges and Apple's peer-to-peer links have an
250
+ // address too, but a phone on the Wi-Fi cannot reach the laptop through them.
251
+ const virtualInterface = /^(?:utun|tun|tap|ppp|ipsec|wg|tailscale|zt|awdl|llw|bridge|docker|veth|vmnet|vboxnet|vEthernet)/i
252
+
253
+ function lanAddresses() {
254
+ const found = []
255
+ for (const [name, addresses] of Object.entries(networkInterfaces())) {
256
+ for (const address of addresses ?? []) {
257
+ if (address.family === 'IPv4' && !address.internal)
258
+ found.push({ name, address: address.address })
259
+ }
260
+ }
261
+ const physical = found.filter(({ name }) => !virtualInterface.test(name))
262
+ // Better a code that may not work than none, should the pattern be wrong.
263
+ return physical.length > 0 ? physical : found
264
+ }
265
+
266
+ const port = Number(flags.port ?? process.env.PORT ?? 4174)
267
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
268
+ fail(`Invalid port: ${flags.port ?? process.env.PORT}`)
269
+
270
+ server.on('error', (error) => {
271
+ fail(error.code === 'EADDRINUSE'
272
+ ? `Port ${port} is in use. Stop the other server or pass --port.`
273
+ : `Could not start the server: ${error.message}`)
274
+ })
275
+
276
+ server.listen(port, '0.0.0.0', () => {
277
+ const out = [`Display http://localhost:${port}${base}`, '']
278
+ const addresses = lanAddresses()
279
+ if (addresses.length === 0)
280
+ out.push('No network address found: connect to Wi-Fi or a phone hotspot, then restart.')
281
+ for (const { name, address } of addresses) {
282
+ const remote = `http://${address}:${port}${base}?k=${secret}`
283
+ out.push(`Remote ${remote} (${name})`, '', qr(remote), '')
284
+ }
285
+ out.push('Scan a code with the phone, on the same network. The link carries the write secret:',
286
+ 'whoever has it can drive the slides. `--new-secret` replaces it.')
287
+ process.stdout.write(`${out.join('\n')}\n`)
288
+ })
289
+
290
+ for (const signal of ['SIGINT', 'SIGTERM']) {
291
+ process.on(signal, () => {
292
+ for (const client of clients.keys())
293
+ client.destroy()
294
+ server.close(() => process.exit(0))
295
+ })
296
+ }
@@ -54,7 +54,8 @@ import { RoughGenerator } from 'roughjs/bin/generator'
54
54
  import { findTextInSegments } from './code-text-match'
55
55
  import type { TextSegment } from './code-text-match'
56
56
  import { normalizeAnnotationLineBreaks } from './annotation-line-breaks'
57
- import { rememberTransitionInk, takeTransitionInk } from './transition-ink'
57
+ import { useCarriedLayer } from './carried-layer'
58
+ import { handOverTransitionInk, rememberTransitionInk, takeTransitionInk } from './transition-ink'
58
59
  import type { TransitionInkBox } from './transition-ink'
59
60
  import { annotationLabelText, renderAnnotationLabel } from './annotation-label-markdown'
60
61
  import { localLabelWidthToSlideFraction, localPointToSlideFraction, nudgeConnector, nudgeLabelWidth, persistedGeometrySignature, quadraticControlForCubic, slideFractionPointToLocal, translateConnector, validateDrawnAnnotationGeometry } from './drawn-annotation/geometry'
@@ -476,6 +477,17 @@ const settled = ref(!props.wait)
476
477
  // Let the incoming SVG appear complete after the move, rather than replaying
477
478
  // its stroke-dash entrance from scratch.
478
479
  const skipEntranceAnimation = ref(false)
480
+ // Ink taken over from an equivalent annotation is on screen already, so it
481
+ // opens the entrance without waiting for the slide to settle: it stays put,
482
+ // or travels with its tokens, while the code around it is still moving.
483
+ const inkCarried = ref(false)
484
+ // The neighbouring page took this annotation's ink over. Its copy is the one
485
+ // on screen now, so this one goes at once instead of fading out beneath it.
486
+ const handedOver = ref(false)
487
+ // Under a view transition the strokes and the label each need a layer of
488
+ // their own to stay above the code window; see carried-layer.ts.
489
+ const inkLayer = useCarriedLayer(inkCarried)
490
+ const labelLayer = useCarriedLayer(inkCarried)
479
491
  // An annotation with `until` is only shown while the thing it points at is on
480
492
  // screen: past that click every stage hides again, in one step.
481
493
  // `on` is the same thing derived from the resolved clicks, so the shorthand
@@ -524,7 +536,7 @@ function entrance(isReached: ComputedRef<boolean>) {
524
536
  watchEffect(() => {
525
537
  if (!isReached.value)
526
538
  opened.value = false
527
- else if (settled.value)
539
+ else if (settled.value || inkCarried.value)
528
540
  opened.value = true
529
541
  })
530
542
  return computed(() => isReached.value && opened.value)
@@ -989,6 +1001,9 @@ let lastVisibleMarkTransitionBox: TransitionInkBox | undefined
989
1001
  // Ink left behind by an unmounted instance of this annotation is still to be
990
1002
  // taken back (see restoreTransitionInk).
991
1003
  let restorePending = false
1004
+ // The pending hand-off is from the neighbouring Magic Move page, whose code
1005
+ // is still moving: the ink is taken over, but nothing has settled yet.
1006
+ let restoreWhileMoving = false
992
1007
  // Animation frame during which handed-over ink is being revealed. `unsettle`
993
1008
  // leaves `skipEntranceAnimation` alone while it is set: a click that lands
994
1009
  // in the same frame would otherwise clear the skip before the browser has
@@ -1119,6 +1134,8 @@ function settleAfterMagicMove() {
1119
1134
  return
1120
1135
  magicMoveWasObserved = false
1121
1136
  settled.value = true
1137
+ // Carried only for the move it arrived with; the entrance stays open.
1138
+ inkCarried.value = false
1122
1139
  invalidateTextMatch()
1123
1140
  updateGeometry()
1124
1141
  inheritTransitionInk()
@@ -1131,8 +1148,10 @@ function settleAfterMagicMove() {
1131
1148
  function unsettle(grace = 0) {
1132
1149
  const run = ++settleRun
1133
1150
  magicMoveWasObserved = false
1134
- if (!restoreHold)
1151
+ if (!restoreHold) {
1135
1152
  skipEntranceAnimation.value = false
1153
+ inkCarried.value = false
1154
+ }
1136
1155
  // A click can restyle the slide, so measured label sizes and content
1137
1156
  // obstacles go stale here — once per click, which leaves them shared by
1138
1157
  // every frame of the animation.
@@ -1333,7 +1352,9 @@ function measureGeometry(root: HTMLElement, overlayBox: DOMRect, width: number,
1333
1352
  // click always recomputes, because other content can have moved around a
1334
1353
  // stationary mark.
1335
1354
  const markKey = `${width}x${height}|${shapeBoxes.map(box => `${box.left.toFixed(2)},${box.top.toFixed(2)},${box.right.toFixed(2)},${box.bottom.toFixed(2)}`).join(';')}`
1336
- if (!settled.value && geometry.ready && markKey === lastMarkKey)
1355
+ // A pending hand-off still has to compare this very box with the ink left
1356
+ // behind, which for a mark that stays is exactly the unchanged one.
1357
+ if (!settled.value && geometry.ready && markKey === lastMarkKey && !restorePending)
1337
1358
  return
1338
1359
  lastMarkKey = markKey
1339
1360
 
@@ -1348,7 +1369,9 @@ function measureGeometry(root: HTMLElement, overlayBox: DOMRect, width: number,
1348
1369
  && lastMarkTransitionBox && takeTransitionInk(transitionInkIdentity.value, slideContext.$page.value, lastMarkTransitionBox)) {
1349
1370
  restorePending = false
1350
1371
  skipEntranceAnimation.value = true
1351
- settled.value = true
1372
+ inkCarried.value = true
1373
+ if (!restoreWhileMoving)
1374
+ settled.value = true
1352
1375
  // Handed-over ink is complete from its first frame on, so it skips the
1353
1376
  // hidden first paint that a fresh entrance needs (see below).
1354
1377
  geometryPainted.value = true
@@ -1441,7 +1464,10 @@ function isCrossSlideMagicMove() {
1441
1464
  function inheritTransitionInk() {
1442
1465
  if (!isCurrentSlide.value || !withinRange.value || !lastMarkTransitionBox || !isCrossSlideMagicMove())
1443
1466
  return
1444
- skipEntranceAnimation.value = takeTransitionInk(transitionInkIdentity.value, slideContext.$page.value, lastMarkTransitionBox)
1467
+ // Ink carried on arrival has consumed its record; a miss here must not
1468
+ // take the skip away from it again.
1469
+ if (takeTransitionInk(transitionInkIdentity.value, slideContext.$page.value, lastMarkTransitionBox))
1470
+ skipEntranceAnimation.value = true
1445
1471
  }
1446
1472
 
1447
1473
  /**
@@ -1464,6 +1490,7 @@ function inheritTransitionInk() {
1464
1490
  */
1465
1491
  function restoreTransitionInk() {
1466
1492
  restorePending = true
1493
+ restoreWhileMoving = false
1467
1494
  invalidateTextMatch()
1468
1495
  updateGeometry()
1469
1496
  if (restorePending) {
@@ -2174,6 +2201,10 @@ function connectObservers() {
2174
2201
  invalidateTextMatch()
2175
2202
  if (isMagicMoveInProgress())
2176
2203
  magicMoveWasObserved = true
2204
+ // The neighbouring page's ink is taken over in the very frame the code
2205
+ // starts to move, measured where the tokens set off from.
2206
+ if (restorePending && restoreWhileMoving)
2207
+ updateGeometry()
2177
2208
  track()
2178
2209
  settleAfterMagicMove()
2179
2210
  })
@@ -2260,13 +2291,21 @@ watch($clicks, () => {
2260
2291
  watch(isCurrentSlide, (current) => {
2261
2292
  if (current) {
2262
2293
  lastVisibleMarkTransitionBox = undefined
2294
+ handedOver.value = false
2263
2295
  connectObservers()
2264
2296
  unsettle(VIEW_TRANSITION_START_GRACE)
2297
+ // Ink the neighbouring Magic Move page left behind is taken over by the
2298
+ // first measurement that finds the mark where that page had it, instead
2299
+ // of once the move is over: nothing that stays may disappear meanwhile.
2300
+ restoreWhileMoving = isCrossSlideMagicMove()
2301
+ restorePending = restoreWhileMoving
2265
2302
  track()
2266
2303
  }
2267
2304
  else {
2268
2305
  if (lastVisibleMarkTransitionBox && isCrossSlideMagicMove())
2269
- rememberTransitionInk(transitionInkIdentity.value, slideContext.$page.value, lastVisibleMarkTransitionBox)
2306
+ handOverTransitionInk(transitionInkIdentity.value, slideContext.$page.value, lastVisibleMarkTransitionBox, () => {
2307
+ handedOver.value = true
2308
+ })
2270
2309
  lastVisibleMarkTransitionBox = undefined
2271
2310
  disconnectObservers()
2272
2311
  // Cancel in-flight measurement too: a settle pass or tracking loop begun
@@ -2790,7 +2829,7 @@ if (isAnnotationEditorDevelopment) {
2790
2829
  <div
2791
2830
  ref="container"
2792
2831
  class="drawn-annotation"
2793
- :class="{ 'is-fading-out': fadingOut, 'is-edit-frozen': annotationEditMode, 'skip-entrance-animation': skipEntranceAnimation }"
2832
+ :class="{ 'is-fading-out': fadingOut, 'is-edit-frozen': annotationEditMode, 'skip-entrance-animation': skipEntranceAnimation, 'is-handed-over': handedOver }"
2794
2833
  >
2795
2834
  <!-- The marker takes part in Slidev's click ordering while component state
2796
2835
  drives the drawing. This avoids a mount-time v-click class race. -->
@@ -2799,12 +2838,14 @@ if (isAnnotationEditorDevelopment) {
2799
2838
  <svg
2800
2839
  ref="overlay"
2801
2840
  class="annotation-overlay annotation-ignore"
2841
+ :class="{ 'magic-move-carried': inkCarried }"
2802
2842
  :viewBox="`0 0 ${geometry.width} ${geometry.height}`"
2803
2843
  preserveAspectRatio="none"
2804
2844
  :aria-hidden="!(connectorEditable && annotationEditMode)"
2805
2845
  :role="connectorEditable && annotationEditMode ? 'group' : undefined"
2806
2846
  :aria-label="connectorEditable && annotationEditMode ? `Connector editor for ${locator}` : undefined"
2807
2847
  :style="{
2848
+ ...inkLayer,
2808
2849
  '--annotation-color': props.color,
2809
2850
  '--annotation-width': `${props.strokeWidth}px`,
2810
2851
  '--leader-delay': `${delays.leader}ms`,
@@ -2920,7 +2961,7 @@ if (isAnnotationEditorDevelopment) {
2920
2961
  v-if="hasLabel"
2921
2962
  ref="labelEl"
2922
2963
  class="annotation-label annotation-ignore"
2923
- :class="{ 'is-active': labelActive && geometry.ready, 'is-placed': geometry.labelPlaced, 'is-editable': editable && annotationEditMode, 'is-selected-for-editing': selectedForEditing }"
2964
+ :class="{ 'magic-move-carried': inkCarried, 'is-active': labelActive && geometry.ready, 'is-placed': geometry.labelPlaced, 'is-editable': editable && annotationEditMode, 'is-selected-for-editing': selectedForEditing }"
2924
2965
  :data-click="resolvedLabelClick"
2925
2966
  @pointerdown="beginLabelDrag($event)"
2926
2967
  @pointermove="moveLabelDrag"
@@ -2928,6 +2969,7 @@ if (isAnnotationEditorDevelopment) {
2928
2969
  @pointercancel="cancelLabelDrag"
2929
2970
  @click="stopEditorClick"
2930
2971
  :style="{
2972
+ ...labelLayer,
2931
2973
  '--annotation-color': props.color,
2932
2974
  '--label-delay': `${delays.label}ms`,
2933
2975
  '--label-fade': `${LABEL_FADE_DURATION}ms`,
@@ -3024,6 +3066,12 @@ if (isAnnotationEditorDevelopment) {
3024
3066
  transition-delay: 0ms !important;
3025
3067
  }
3026
3068
 
3069
+ /* The neighbouring Magic Move page shows this ink now (see `handedOver`). */
3070
+ .is-handed-over .annotation-overlay,
3071
+ .is-handed-over .annotation-label {
3072
+ visibility: hidden !important;
3073
+ }
3074
+
3027
3075
  .is-active .annotation-mark {
3028
3076
  stroke-dashoffset: 0;
3029
3077
  opacity: 1;
@@ -276,7 +276,7 @@ function cancelEditSessionOnEscape(event: KeyboardEvent) {
276
276
  * from firing; other window-level listeners (selection clearing, drag
277
277
  * handlers on captured pointers) are unaffected.
278
278
  */
279
- const EDITOR_UI_SELECTOR = '.drawn-annotation-toolbar, .drawn-annotation-editor-launcher, .annotation-label.is-editable, .annotation-connector-editor'
279
+ const EDITOR_UI_SELECTOR = '.drawn-annotation-toolbar, .annotation-label.is-editable, .annotation-connector-editor'
280
280
  function blockNavigationInput(event: Event) {
281
281
  if (!annotationEditMode.value)
282
282
  return
@@ -7,7 +7,8 @@ import { useMutationObserver, useResizeObserver } from '@vueuse/core'
7
7
  import { codeTextSegments, findTextInSegments, lineSpanMatch, mergeVisualLines, trimmedLineRange } from './code-text-match'
8
8
  import { normalizeAnnotationLineBreaks } from './annotation-line-breaks'
9
9
  import { annotationLabelText, renderAnnotationLabel } from './annotation-label-markdown'
10
- import { rememberTransitionInk, takeTransitionInk } from './transition-ink'
10
+ import { useCarriedLayer } from './carried-layer'
11
+ import { handOverTransitionInk, rememberTransitionInk, takeTransitionInk } from './transition-ink'
11
12
  import type { TransitionInkBox } from './transition-ink'
12
13
  import { clearAnnotationAuthoringProblems, reportAnnotationAuthoringProblem } from './drawn-annotation/editor-store'
13
14
 
@@ -99,6 +100,17 @@ const hasTarget = computed(() => !!targetRange.value)
99
100
  // True while Shiki Magic Move is transitioning between steps.
100
101
  const animating = ref(false)
101
102
  const skipEntranceAnimation = ref(false)
103
+ // The diagnostic was taken over from the neighbouring Magic Move slide, where
104
+ // it was on screen already: it keeps out of the slide's own fade.
105
+ const carried = ref(false)
106
+ // The neighbouring Magic Move slide took this diagnostic over. Its copy is
107
+ // the one on screen now, so this one goes at once instead of fading out
108
+ // beneath it, which thickens the squiggle for as long as the fade takes.
109
+ const handedOver = ref(false)
110
+ // Under a view transition the squiggle and the message each need a layer of
111
+ // their own to stay above the code window; see carried-layer.ts.
112
+ const underlinesLayer = useCarriedLayer(carried)
113
+ const messageLayer = useCarriedLayer(carried)
102
114
  const transitionInkIdentity = computed(() => JSON.stringify([
103
115
  props.line, props.text, props.occurrence, props.message,
104
116
  ]))
@@ -178,7 +190,6 @@ let warnedClassDrift = false
178
190
  // frame while Magic Move moves retained tokens, so an already-visible
179
191
  // diagnostic stays attached to its target rather than waiting for the final
180
192
  // mutation at the end of the transition.
181
- let magicMoveFrame: number | undefined
182
193
 
183
194
  // The wrapped code block renders in one of two shapes, discovered lazily
184
195
  // because Magic Move only renders after mount. The <pre>/<code> element
@@ -225,7 +236,10 @@ function isMagicMoveAnimating(host: HTMLElement) {
225
236
  function inheritTransitionInk(host: HTMLElement) {
226
237
  if (!visible.value || !lastTargetTransitionBox || !isCrossSlideMagicMove(host))
227
238
  return
228
- skipEntranceAnimation.value = takeTransitionInk(transitionInkIdentity.value, slideContext.$page.value, lastTargetTransitionBox)
239
+ // A diagnostic carried on arrival has consumed its record; a miss here
240
+ // must not take the skip away from it again.
241
+ if (takeTransitionInk(transitionInkIdentity.value, slideContext.$page.value, lastTargetTransitionBox))
242
+ skipEntranceAnimation.value = true
229
243
  }
230
244
 
231
245
  /**
@@ -256,6 +270,7 @@ function restoreTransitionInk() {
256
270
  restorePending = false
257
271
  clearTimeout(revealTimer)
258
272
  skipEntranceAnimation.value = true
273
+ carried.value = true
259
274
  revealed.value = true
260
275
  }
261
276
 
@@ -376,6 +391,8 @@ function sync() {
376
391
  const wasAnimating = animating.value
377
392
  animating.value = isMagicMoveAnimating(host)
378
393
  if (wasAnimating && !animating.value) {
394
+ // Carried only for the move it arrived with.
395
+ carried.value = false
379
396
  inheritTransitionInk(host)
380
397
  // A preloaded page's visibility watcher can run before Slidev commits the
381
398
  // incoming route, then be invalidated by that commit. This is the actual
@@ -461,12 +478,10 @@ function sync() {
461
478
  let pendingSync: number | undefined
462
479
 
463
480
  function trackMagicMove() {
464
- if (!animating.value || magicMoveFrame !== undefined)
465
- return
466
- magicMoveFrame = requestAnimationFrame(() => {
467
- magicMoveFrame = undefined
468
- sync()
469
- })
481
+ // Shares the frame with any observer-triggered sync: one measurement per
482
+ // frame follows the tokens just as well as two.
483
+ if (animating.value)
484
+ scheduleSync()
470
485
  }
471
486
  function scheduleSync() {
472
487
  pendingSync ??= requestAnimationFrame(() => {
@@ -484,7 +499,13 @@ function scheduleSync() {
484
499
  useMutationObserver(container, (records) => {
485
500
  if (records.some(record => record.type !== 'attributes'))
486
501
  invalidateTarget()
487
- scheduleSync()
502
+ // A diagnostic arriving from the neighbouring Magic Move slide is taken
503
+ // over in the very frame the code starts to move, measured where its tokens
504
+ // set off from; waiting for the next frame would paint one without it.
505
+ if (restorePending && isCurrentSlide.value)
506
+ sync()
507
+ else
508
+ scheduleSync()
488
509
  }, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['class'] })
489
510
  // The getter re-observes automatically whenever the line or text is retargeted.
490
511
  useResizeObserver(() => [container.value, ...targets.value], scheduleSync)
@@ -506,8 +527,6 @@ onBeforeUnmount(() => {
506
527
  $clicksContext?.unregister(id)
507
528
  if (pendingSync !== undefined)
508
529
  cancelAnimationFrame(pendingSync)
509
- if (magicMoveFrame !== undefined)
510
- cancelAnimationFrame(magicMoveFrame)
511
530
  clearTimeout(revealTimer)
512
531
  clearTimeout(missingTargetWarning)
513
532
  if (isDevelopment)
@@ -569,12 +588,21 @@ watch(isCurrentSlide, (current) => {
569
588
  if (current) {
570
589
  lastVisibleTargetTransitionBox = undefined
571
590
  skipEntranceAnimation.value = false
591
+ carried.value = false
592
+ handedOver.value = false
593
+ // What the neighbouring Magic Move slide left behind is taken over by
594
+ // the first measurement that finds the target where that slide had it,
595
+ // rather than once the move is over (see restoreTransitionInk).
596
+ const host = container.value
597
+ restorePending = !!host && isCrossSlideMagicMove(host)
572
598
  scheduleSync()
573
599
  return
574
600
  }
575
601
  const host = container.value
576
602
  if (host && lastVisibleTargetTransitionBox && isCrossSlideMagicMove(host))
577
- rememberTransitionInk(transitionInkIdentity.value, slideContext.$page.value, lastVisibleTargetTransitionBox)
603
+ handOverTransitionInk(transitionInkIdentity.value, slideContext.$page.value, lastVisibleTargetTransitionBox, () => {
604
+ handedOver.value = true
605
+ })
578
606
  lastVisibleTargetTransitionBox = undefined
579
607
  revealed.value = false
580
608
  }, { flush: 'sync' })
@@ -624,7 +652,7 @@ watch([visible, hasTarget, () => props.line, text, () => props.occurrence, textM
624
652
  </script>
625
653
 
626
654
  <template>
627
- <div ref="container" class="inline-compiler-error-host">
655
+ <div ref="container" class="inline-compiler-error-host" :data-magic-move-handed-over="handedOver || undefined">
628
656
  <slot />
629
657
  <!-- Screen readers only announce a live region reliably when its content
630
658
  changes while it is already mounted, so this one exists permanently
@@ -637,6 +665,8 @@ watch([visible, hasTarget, () => props.line, text, () => props.occurrence, textM
637
665
  <span
638
666
  v-if="revealed"
639
667
  class="inline-compiler-error-underlines"
668
+ :class="{ 'magic-move-carried': carried }"
669
+ :style="underlinesLayer"
640
670
  aria-hidden="true"
641
671
  >
642
672
  <span
@@ -651,7 +681,8 @@ watch([visible, hasTarget, () => props.line, text, () => props.occurrence, textM
651
681
  <span
652
682
  v-if="revealed"
653
683
  class="inline-compiler-error-message"
654
- :style="position"
684
+ :class="{ 'magic-move-carried': carried }"
685
+ :style="[position, messageLayer]"
655
686
  aria-hidden="true"
656
687
  ><i>●</i><span class="annotation-label-content" v-html="messageHtml" /></span>
657
688
  </Transition>