slidev-theme-kotlin 0.10.0 → 0.12.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +240 -14
  3. package/annotation-editor.d.ts +2 -0
  4. package/annotation-editor.mjs +5 -0
  5. package/assets/edit-3-svgrepo-com.svg +5 -0
  6. package/components/DrawnAnnotation.vue +1362 -433
  7. package/components/DrawnAnnotationEditorLauncher.vue +50 -0
  8. package/components/DrawnAnnotationEditorToolbar.vue +264 -0
  9. package/components/InlineCompilerError.vue +608 -0
  10. package/components/Kodee.vue +79 -84
  11. package/components/KodeeWrapper.vue +11 -27
  12. package/components/MagicMoveBetween.vue +276 -0
  13. package/components/README.md +181 -40
  14. package/components/annotation-label-markdown.test.ts +22 -0
  15. package/components/annotation-label-markdown.ts +34 -0
  16. package/components/code-text-match.ts +78 -0
  17. package/components/drawn-annotation/editor-store.test.ts +141 -0
  18. package/components/drawn-annotation/editor-store.ts +137 -0
  19. package/components/drawn-annotation/geometry.test.ts +88 -0
  20. package/components/drawn-annotation/geometry.ts +239 -0
  21. package/components/drawn-annotation/writer-client.ts +81 -0
  22. package/components/kodee-props.ts +16 -0
  23. package/global-top.vue +26 -0
  24. package/package.json +35 -10
  25. package/plugins/drawn-annotation-editor.d.ts +30 -0
  26. package/plugins/drawn-annotation-editor.mjs +391 -0
  27. package/plugins/drawn-annotation-editor.test.ts +386 -0
  28. package/public/Postgresql_elephant.svg +22 -0
  29. package/public/amper-icon.svg +9 -0
  30. package/public/gradle.svg +7 -0
  31. package/public/gradle_dark.svg +7 -0
  32. package/public/java.svg +6 -0
  33. package/public/java_dark.svg +6 -0
  34. package/public/kotlin.svg +5 -0
  35. package/public/kotlin_dark.svg +5 -0
  36. package/public/maven.svg +4 -0
  37. package/public/maven_dark.svg +4 -0
  38. package/public/terminal.svg +6 -0
  39. package/public/terminal_dark.svg +6 -0
  40. package/setup/code-window-icon.ts +22 -0
  41. package/setup/magic-move-between.ts +191 -0
  42. package/setup/preparser.ts +24 -0
  43. package/setup/shiki.ts +277 -327
  44. package/setup/transformers.ts +239 -0
  45. package/styles/fonts.css +59 -0
  46. package/styles/index.ts +2 -0
  47. package/styles/layout.css +262 -2
@@ -1,14 +1,53 @@
1
+ <script lang="ts">
2
+ /**
3
+ * Labels already placed on the current slide, in concrete-slide fractions,
4
+ * shared by every annotation instance. Automatic placement treats the labels
5
+ * of annotations that registered earlier (mount order, which follows document
6
+ * order) as obstacles; an earlier label never reacts to a later one, so the
7
+ * avoidance is deterministic and cannot oscillate.
8
+ */
9
+ interface PlacedLabelRecord {
10
+ order: number
11
+ click: number
12
+ root: HTMLElement
13
+ box: { left: number, top: number, right: number, bottom: number }
14
+ active: boolean
15
+ }
16
+ const placedLabelRegistry = new Map<symbol, PlacedLabelRecord>()
17
+ let nextPlacementOrder = 0
18
+ </script>
19
+
1
20
  <script setup lang="ts">
2
21
  import type { Options as RoughOptions } from 'roughjs/bin/core'
3
22
  import type { ClicksContext } from '@slidev/types'
4
23
  import type { ComputedRef, InjectionKey, Ref } from 'vue'
5
24
  import { injectLocal } from '@vueuse/core'
6
- import { useSlideContext } from '@slidev/client'
25
+ import { useIsSlideActive, useSlideContext } from '@slidev/client'
7
26
  // The explicit `.ts` extension is required: Slidev's client ships bare TypeScript
8
27
  // sources, and the bundler resolves this subpath literally.
9
28
  import { injectionClicksContext } from '@slidev/client/constants.ts'
10
29
  import rough from 'roughjs'
11
- import { computed, nextTick, onBeforeUnmount, onMounted, provide, reactive, ref, shallowRef, toRef, watch, watchEffect } from 'vue'
30
+ import { findTextInSegments } from './code-text-match'
31
+ import type { TextSegment } from './code-text-match'
32
+ import { annotationLabelText, renderAnnotationLabel } from './annotation-label-markdown'
33
+ import { localLabelWidthToSlideFraction, localPointToSlideFraction, nudgeConnector, nudgeLabelWidth, slideFractionPointToLocal, translateConnector, validateDrawnAnnotationGeometry } from './drawn-annotation/geometry'
34
+ import type { DrawnAnnotationGeometry, PersistedAnnotationGeometry } from './drawn-annotation/geometry'
35
+ import { annotationDraftChange, annotationEditMode, annotationEditorStatus, annotationDrafts, annotationLabelLayoutChange, beginAnnotationDraftGesture, claimAnnotationSelection, clearAnnotationSelection, clearLabelDraft, endAnnotationDraftGesture, migrateAnnotationLocator, recordAnnotationUndo, recordAnnotationUndoOnce, registerAnnotationEditorActions, releaseAnnotationSelection, selectAnnotation, selectedAnnotationId, selectedAnnotationPart, setLabelDraft } from './drawn-annotation/editor-store'
36
+ import type { AnnotationUndoSession } from './drawn-annotation/editor-store'
37
+ import { computed, nextTick, onBeforeUnmount, onMounted, provide, reactive, ref, shallowRef, toRef, useSlots, watch, watchEffect } from 'vue'
38
+
39
+ // Slidev's build renderer can leave `import.meta.env.DEV` true. Restrict
40
+ // development-only editing to Vite's explicit serve mode so published decks
41
+ // never carry interactive controls or a browser write client.
42
+ const isAnnotationEditorDevelopment = import.meta.env.MODE === 'development'
43
+
44
+ // Do not let the optional browser writer become a production chunk. Vite
45
+ // serves this explicit TypeScript module during development; production cannot
46
+ // reach it because every caller is guarded by `isAnnotationEditorDevelopment`.
47
+ const writerClientModule = './drawn-annotation/writer-client.ts'
48
+ function loadWriterClient() {
49
+ return import(/* @vite-ignore */ writerClientModule)
50
+ }
12
51
 
13
52
  /**
14
53
  * Hand-drawn annotation for anything on a slide.
@@ -19,10 +58,15 @@ import { computed, nextTick, onBeforeUnmount, onMounted, provide, reactive, ref,
19
58
  * to a second element on the slide or to a text label.
20
59
  *
21
60
  * A label is placed out of the slide's normal flow: its position is searched at
22
- * runtime so it never overlaps other content — nor the labels other annotations
23
- * wrote on earlier clicks — preferring downwards for marks in the upper half of
24
- * the slide and upwards for marks in the lower half. Pass
25
- * `label-x` / `label-y` (percentages of the slide) to place it by hand instead.
61
+ * runtime near its source — preferring downwards for marks in the upper half
62
+ * of the slide and upwards for marks in the lower half — while staying clear
63
+ * of the slide's laid-out content, of its own mark, of labels placed by
64
+ * earlier annotations on the slide, and of anything matched by
65
+ * `avoid-selector`, kept at `clearance` distance. Laid-out but still-hidden
66
+ * v-click content counts too, so a label never sits where the slide is about
67
+ * to grow; nothing is guessed, so placement stays deterministic.
68
+ * Source-authored `geometry.label` gives authors the final say and is never
69
+ * moved by obstacles.
26
70
  *
27
71
  * Annotations nest, and two that share a click draw one after the other: the
28
72
  * inner one starts when the one around it has finished, so "point at it, then
@@ -41,6 +85,10 @@ import { computed, nextTick, onBeforeUnmount, onMounted, provide, reactive, ref,
41
85
  type MarkType = 'circle' | 'underline' | 'box' | 'strike-through' | 'none'
42
86
 
43
87
  const props = withDefaults(defineProps<{
88
+ /** Source-authored normalized label and connector geometry. */
89
+ geometry?: DrawnAnnotationGeometry
90
+ /** Opaque, serve-only locator injected by the Vite source transform. */
91
+ __drawnAnnotationLocator?: string
44
92
  /** Shape drawn on the source. Kept as the short form of `sourceType`. */
45
93
  type?: MarkType
46
94
  /** Shape drawn on the source. Overrides `type` when supplied. */
@@ -49,8 +97,8 @@ const props = withDefaults(defineProps<{
49
97
  selector?: string
50
98
  /** Exact text to annotate inside the slot. Works inside Shiki and Magic Move. */
51
99
  text?: string
52
- /** Which occurrence of `text` to annotate, 1-based. */
53
- occurrence?: number
100
+ /** Which occurrence of `text` to annotate, 1-based. Markdown attributes arrive as strings. */
101
+ occurrence?: number | string
54
102
  /** Mark every visual line of a wrapped or multi-line match. */
55
103
  multiline?: boolean
56
104
  /** Extra space between the annotated box and the mark, in slide pixels. */
@@ -66,26 +114,21 @@ const props = withDefaults(defineProps<{
66
114
  targetType?: MarkType
67
115
  /** Show the default target circle when `targetType` is omitted. */
68
116
  targetMark?: boolean
69
- /** Text label. Placed automatically unless `labelX` / `labelY` are given. */
117
+ /** Markdown text label. Placed automatically unless geometry supplies a position. */
70
118
  label?: string
71
- /** Label centre, as a percentage of the slide. Disables automatic placement. */
72
- labelX?: number
73
- labelY?: number
74
- /** Optional maximum label width in slide pixels, before it wraps. */
75
- labelWidth?: number
76
119
  /** Preferred side for automatic placement. `auto` picks by vertical position. */
77
120
  placement?: 'auto' | 'up' | 'down' | 'left' | 'right'
78
121
  /** Smallest distance between the mark and the label, in slide pixels. */
79
122
  gap?: number
80
- /** Space the label keeps from everything else on the slide. */
123
+ /** Space an automatically placed label keeps from its obstacles, in slide pixels. */
81
124
  clearance?: number
82
- /** Extra elements the label must not cover. */
125
+ /** Extra elements an automatically placed label must not cover. */
83
126
  avoidSelector?: string
84
127
  /** Draw the leader line between the mark and the label or target. */
85
128
  connect?: boolean
86
129
  /** Arrow head at the end of the leader line. */
87
130
  arrow?: boolean
88
- /** Curvature of the leader line, as a fraction of its length. */
131
+ /** Sideways bow of the leader line, as a fraction of its length (capped at 40 slide pixels). */
89
132
  curve?: number
90
133
  /**
91
134
  * Passed straight to rough.js, which draws every stroke, so everything it
@@ -109,13 +152,19 @@ const props = withDefaults(defineProps<{
109
152
  /** How long drawing one stage takes, in milliseconds. */
110
153
  duration?: number
111
154
  at?: number | string
155
+ /**
156
+ * Observe an existing slide click without registering another click marker.
157
+ * Use this beside a `v-click` / `v-clicks` reveal that already owns `at`,
158
+ * when the annotation should draw after that reveal has settled.
159
+ */
160
+ passive?: boolean | string
112
161
  /**
113
162
  * Start drawing only once the annotation this one sits inside has finished,
114
163
  * when the two share a click. That is what turns "point at it, then circle
115
164
  * it" into a single reveal instead of two clicks, without anyone having to
116
165
  * time it by hand. Turn off to draw both at once.
117
166
  */
118
- sequential?: boolean
167
+ sequential?: boolean | string
119
168
  /**
120
169
  * Click that takes the annotation away again, so it only belongs to the
121
170
  * steps it describes. Exclusive, like the end of a `v-click` range: with
@@ -150,6 +199,8 @@ const props = withDefaults(defineProps<{
150
199
  /** Follow the annotated element while Magic Move or a transition animates it. */
151
200
  track?: boolean
152
201
  }>(), {
202
+ geometry: undefined,
203
+ __drawnAnnotationLocator: undefined,
153
204
  type: 'underline',
154
205
  sourceType: undefined,
155
206
  selector: '[data-annotate]',
@@ -164,9 +215,6 @@ const props = withDefaults(defineProps<{
164
215
  targetType: undefined,
165
216
  targetMark: true,
166
217
  label: undefined,
167
- labelX: undefined,
168
- labelY: undefined,
169
- labelWidth: undefined,
170
218
  placement: 'auto',
171
219
  gap: 28,
172
220
  clearance: 16,
@@ -180,9 +228,11 @@ const props = withDefaults(defineProps<{
180
228
  // bindings. Anything that needs an actual colour cannot read this raw.
181
229
  color: 'var(--drawn-annotation-color, currentColor)',
182
230
  strokeWidth: 2,
183
- duration: 800,
231
+ // Keep the hand-drawn stage aligned with Magic Move and page transitions.
232
+ duration: 500,
184
233
  sequential: true,
185
234
  at: undefined,
235
+ passive: false,
186
236
  until: undefined,
187
237
  on: undefined,
188
238
  insert: false,
@@ -264,7 +314,12 @@ const resolvedPlacement = computed(() => {
264
314
  // The label and the target each drive several stages, so their presence is
265
315
  // decided once, and an empty string counts as absent everywhere.
266
316
  const hasLabel = computed(() => !!props.label)
317
+ const labelHtml = computed(() => renderAnnotationLabel(props.label ?? ''))
318
+ const labelText = computed(() => annotationLabelText(props.label ?? ''))
267
319
  const hasTarget = computed(() => !!props.target)
320
+ // A source-only mark exposes no visual-editor operation. It remains valid:
321
+ // only labels and connectors have geometry that an editor can manipulate.
322
+ const editorRelevant = computed(() => hasLabel.value || (props.connect && hasTarget.value))
268
323
 
269
324
  if (props.on !== undefined && (props.at !== undefined || props.until !== undefined))
270
325
  warn('`on` is `at` and `until` in one, so the separate `at` / `until` given here are ignored. Use either `on` alone, or `at` and `until`.')
@@ -277,6 +332,27 @@ const labelMarker = ref<HTMLElement>()
277
332
  const overlay = ref<SVGSVGElement>()
278
333
  const labelEl = ref<HTMLElement>()
279
334
 
335
+ // Wrapped annotations only search their own slot. A self-closing annotation
336
+ // intentionally searches the remaining slide so it can point at following
337
+ // Markdown without adding a wrapper around it.
338
+ const slots = useSlots()
339
+ function searchRoot() {
340
+ const root = container.value
341
+ if (slots.default || !root)
342
+ return root
343
+ return root.closest<HTMLElement>('.slidev-layout') ?? root.parentElement ?? root
344
+ }
345
+ const searchScope = () => slots.default ? 'the slot' : 'the content below this annotation on the slide'
346
+ // The self-closing search root is the whole layout, so occurrence counting and
347
+ // selector matches are narrowed here to what actually follows the tag —
348
+ // content above it (a slide title, say) is outside the promised scope.
349
+ function followsAnnotation(node: Node) {
350
+ const anchor = container.value
351
+ if (slots.default || !anchor)
352
+ return true
353
+ return !!(anchor.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING) && !anchor.contains(node)
354
+ }
355
+
280
356
  // The mark and the label can share one click or be spread over two, which is
281
357
  // what makes "mark it, then name it" possible from Markdown.
282
358
  const resolvedClick = ref(Number.POSITIVE_INFINITY)
@@ -291,20 +367,30 @@ const showImmediately = ref(false)
291
367
  // renders the slot provided, which plain `inject` walks straight past. Slidev's
292
368
  // own clicks context reaches nested components the same way.
293
369
  const outerClicksContext = injectLocal(realClicksKey, null)
294
- const $clicksContext = outerClicksContext ?? useSlideContext().$clicksContext
370
+ const slideContext = useSlideContext()
371
+ const $clicksContext = outerClicksContext ?? slideContext.$clicksContext
295
372
  const $clicks = toRef($clicksContext, 'current')
373
+ // Slidev mounts the previous and next slides ahead of time. An annotation on
374
+ // one of those hidden slides must not paint before that slide becomes current,
375
+ // otherwise the view-transition snapshot captures the finished mark.
376
+ const isCurrentSlide = useIsSlideActive()
296
377
  provide(realClicksKey, $clicksContext)
378
+ // An annotation without `at` or `on` belongs to the slide's initial state.
379
+ // It must not render a bare `v-click` marker: Slidev treats that as the next
380
+ // automatic click, adding a reveal the author did not ask for.
381
+ const hasExplicitStartClick = computed(() => props.at !== undefined || props.on !== undefined)
297
382
  // Slidev's click ordering runs in the context the markers are rendered in, and
298
383
  // that one is shifted here. So these annotations resolve and register their
299
384
  // clicks themselves, from the numbers on the props.
300
385
  // Slidev deliberately normalizes `v-click="0"` to click 1. Resolve an
301
386
  // annotation on click 0 ourselves so it can be present before the first click.
302
- const startsOnInitialSlide = computed(() => Number(atClick.value) === 0)
303
- const manualClicks = computed(() => props.insert || !!outerClicksContext || startsOnInitialSlide.value)
387
+ const startsOnInitialSlide = computed(() => hasExplicitStartClick.value && Number(atClick.value) === 0)
388
+ const passive = computed(() => props.passive === true || props.passive === 'true' || props.passive === '')
389
+ const manualClicks = computed(() => passive.value || props.insert || !!outerClicksContext || startsOnInitialSlide.value)
304
390
  const painted = computed(() => geometryPainted.value || showImmediately.value)
305
- // True once the annotated element has held still for a few frames. Drawing is
306
- // held back until then, so a mark never appears on top of a Magic Move step or
307
- // a slide transition that is still travelling.
391
+ // True once the animations triggered by the current click have finished.
392
+ // Drawing is held back until then, so a mark never appears on top of a Magic
393
+ // Move step or a slide transition that is still travelling.
308
394
  const settled = ref(!props.wait)
309
395
  // An annotation with `until` is only shown while the thing it points at is on
310
396
  // screen: past that click every stage hides again, in one step.
@@ -331,7 +417,7 @@ const withinRange = computed(() => $clicks.value < rangeEnd.value)
331
417
  // slide would inherit the delay too.
332
418
  const fadingOut = ref(false)
333
419
  /** How long the strokes' exit fade takes, mirrored into CSS as `--exit-fade`. */
334
- const EXIT_FADE_DURATION = 280
420
+ const EXIT_FADE_DURATION = 300
335
421
  let exitFadeTimer: ReturnType<typeof setTimeout> | undefined
336
422
  watch(withinRange, (inside, wasInside) => {
337
423
  clearTimeout(exitFadeTimer)
@@ -339,7 +425,10 @@ watch(withinRange, (inside, wasInside) => {
339
425
  if (fadingOut.value)
340
426
  exitFadeTimer = setTimeout(() => fadingOut.value = false, EXIT_FADE_DURATION)
341
427
  })
342
- const reached = (click: Ref<number>) => computed(() => $clicks.value >= click.value && withinRange.value && painted.value)
428
+ const reached = (click: Ref<number>) => computed(() => isCurrentSlide.value
429
+ && $clicks.value >= click.value
430
+ && withinRange.value
431
+ && painted.value)
343
432
 
344
433
  /**
345
434
  * Holds a stage back until everything has stopped moving, and then keeps it
@@ -400,7 +489,10 @@ const outerSequence = injectLocal(sequenceKey, null)
400
489
  // annotation sharing the enclosing one's click waits for it: one that has a
401
490
  // click of its own is already a step later, and starts straight away.
402
491
  const sequenceStart = computed(() => {
403
- if (!props.sequential || !outerSequence)
492
+ // Static HTML attributes are strings, so support both `sequential="false"`
493
+ // and Vue's `:sequential="false"`.
494
+ const sequential = props.sequential !== false && props.sequential !== 'false'
495
+ if (!sequential || !outerSequence)
404
496
  return 0
405
497
  return outerSequence.click.value === resolvedClick.value ? outerSequence.end.value : 0
406
498
  })
@@ -413,7 +505,7 @@ const ARROW_FRACTION = 0.2
413
505
  const TARGET_FRACTION = 0.5
414
506
  const LABEL_HEAD_START = 0.1
415
507
  /** How long the label's opacity fade takes, mirrored into CSS as `--label-fade`. */
416
- const LABEL_FADE_DURATION = 240
508
+ const LABEL_FADE_DURATION = 250
417
509
 
418
510
  // Whether a leader line is drawn at all: it needs somewhere to go.
419
511
  const connectsLine = computed(() => props.connect && (hasTarget.value || hasLabel.value))
@@ -475,9 +567,25 @@ const geometry = reactive({
475
567
  // assigned only when fitting it on the slide requires wrapping.
476
568
  labelWidth: undefined as number | undefined,
477
569
  labelPlaced: false,
570
+ /** Resolved leader endpoints, used to materialize automatic lines on first edit. */
571
+ connectorStart: undefined as Point | undefined,
572
+ connectorEnd: undefined as Point | undefined,
478
573
  ready: false,
479
574
  })
480
575
 
576
+ /**
577
+ * Replaces one of the path lists only when it actually changed. Geometry is
578
+ * re-measured on animation frames, and an unconditional assignment would be a
579
+ * new array every time — re-rendering and re-patching every <path> element
580
+ * even in a frame where nothing moved.
581
+ */
582
+ function assignPaths(key: 'mark' | 'leader' | 'arrow' | 'targetMark', next: string[]) {
583
+ const previous = geometry[key]
584
+ if (previous.length === next.length && previous.every((d, index) => d === next[index]))
585
+ return
586
+ geometry[key] = next
587
+ }
588
+
481
589
  // Identity of this annotation's own clicks in the slide's click count, used
482
590
  // when it resolves them itself instead of leaving that to the `v-click` marker.
483
591
  const ownClicks = Symbol('drawn-annotation-clicks') as unknown as HTMLElement
@@ -597,7 +705,7 @@ function padBox(box: Box, padding: number) {
597
705
  * starts and ends in different nodes. The number of matches is reported either
598
706
  * way, so a miss can be explained rather than silently swallowed.
599
707
  */
600
- function textRange(root: HTMLElement, needle: string, occurrence: number): { range?: Range, matches: number } {
708
+ function textRange(root: HTMLElement, needle: string, occurrence: number | string): { range?: Range, matches: number } {
601
709
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
602
710
  acceptNode(node) {
603
711
  const parent = node.nodeType === Node.TEXT_NODE ? node.parentElement : node as HTMLElement
@@ -605,68 +713,30 @@ function textRange(root: HTMLElement, needle: string, occurrence: number): { ran
605
713
  // a match is never made against text that is on its way off the slide.
606
714
  if (!parent || parent.closest('svg, .annotation-ignore, .shiki-magic-move-leave, .shiki-magic-move-leave-to'))
607
715
  return NodeFilter.FILTER_REJECT
716
+ // Only leaves are position-filtered: an element that merely precedes or
717
+ // contains the annotation must still be descended into (FILTER_SKIP),
718
+ // because content following the tag can live inside it.
608
719
  if (node.nodeType === Node.ELEMENT_NODE)
609
- return (node as HTMLElement).tagName === 'BR' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP
610
- return NodeFilter.FILTER_ACCEPT
720
+ return (node as HTMLElement).tagName === 'BR' && followsAnnotation(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP
721
+ return followsAnnotation(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT
611
722
  },
612
723
  })
613
724
 
614
725
  // Magic Move renders line breaks as <br> instead of newline characters, so
615
726
  // they are folded back into the searched text to keep line-aware matches
616
727
  // working in both kinds of code block.
617
- const segments: { node?: Text, text: string }[] = []
618
- let value = ''
728
+ const segments: TextSegment[] = []
619
729
  let node: Node | null
620
730
  // eslint-disable-next-line no-cond-assign
621
731
  while ((node = walker.nextNode())) {
622
- const segment = node.nodeType === Node.TEXT_NODE
732
+ segments.push(node.nodeType === Node.TEXT_NODE
623
733
  ? { node: node as Text, text: (node as Text).data }
624
- : { text: '\n' }
625
- segments.push(segment)
626
- value += segment.text
627
- }
628
-
629
- const starts: number[] = []
630
- for (let index = value.indexOf(needle); index >= 0; index = value.indexOf(needle, index + 1))
631
- starts.push(index)
632
- const start = starts[Math.max(1, occurrence) - 1]
633
- if (start === undefined)
634
- return { matches: starts.length }
635
-
636
- const end = start + needle.length
637
- let offset = 0
638
- let startNode: Text | undefined
639
- let endNode: Text | undefined
640
- let startOffset = 0
641
- let endOffset = 0
642
- for (const segment of segments) {
643
- const next = offset + segment.text.length
644
- if (segment.node) {
645
- if (!startNode && start >= offset && start < next) {
646
- startNode = segment.node
647
- startOffset = start - offset
648
- }
649
- if (startNode && end > offset && end <= next) {
650
- endNode = segment.node
651
- endOffset = end - offset
652
- break
653
- }
654
- // A match that ends on a line break ends inside a <br>, which cannot hold
655
- // a range boundary. Trail the last real node the match covered instead.
656
- if (startNode && end > next) {
657
- endNode = segment.node
658
- endOffset = segment.text.length
659
- }
660
- }
661
- offset = next
734
+ : { text: '\n' })
662
735
  }
663
- if (!startNode || !endNode)
664
- return { matches: starts.length }
665
736
 
666
- const range = document.createRange()
667
- range.setStart(startNode, startOffset)
668
- range.setEnd(endNode, endOffset)
669
- return { range, matches: starts.length }
737
+ const requestedOccurrence = Number(occurrence)
738
+ const match = findTextInSegments(segments, needle, Number.isFinite(requestedOccurrence) ? requestedOccurrence : 1)
739
+ return { range: match.range ?? undefined, matches: match.matches }
670
740
  }
671
741
 
672
742
  function slideRoot() {
@@ -680,54 +750,129 @@ let paintFrame = 0
680
750
  let trackFrame = 0
681
751
  let trackUntil = 0
682
752
  let mounted = false
753
+ let unregisterEditorActions: (() => void) | undefined
754
+ // Fingerprint of the mark's last measured boxes. While the slide animates, a
755
+ // frame in which the mark has not moved recomputes nothing.
756
+ let lastMarkKey = ''
757
+ // Content boxes an automatic label avoids, in local SVG coordinates. The DOM
758
+ // scan is refreshed on discrete re-measures (click settles, resizes, prop or
759
+ // draft changes) and reused by the per-frame tracking passes, which must not
760
+ // re-walk and re-measure the whole slide.
761
+ let contentObstacleCache: Box[] | undefined
683
762
  // The images whose load re-measures geometry, kept so unmount removes exactly
684
763
  // the listeners that were added.
685
764
  const watchedImages: HTMLImageElement[] = []
686
- // How long the geometry has to hold still before it counts as settled, and how
687
- // long we are willing to wait for that. The cap matters for anything that never
688
- // stops moving, so an annotation is never lost to it.
689
- const SETTLE_FRAMES = 3
690
- const SETTLE_TIMEOUT = 3000
691
- let settleDeadline = 0
692
- let stableFrames = 0
693
- let lastSignature = ''
765
+ // Each wait gets an identity so a completion from the previous click cannot
766
+ // release the next one. The Web Animations API covers CSS transitions, CSS
767
+ // animations and Magic Move's generated animations with the same `finished`
768
+ // promise, including their real delay and duration.
769
+ let settleRun = 0
694
770
 
695
- /**
696
- * Whether something in the slot is still animating. Geometry alone does not
697
- * catch everything: a Magic Move step fades new tokens in where they already
698
- * belong, so the boxes sit still while the code is visibly still arriving.
699
- */
700
- function inMotion() {
771
+ function relevantAnimations() {
701
772
  const root = container.value
702
773
  if (!root?.getAnimations)
703
- return false
704
- return root.getAnimations({ subtree: true }).some((animation) => {
705
- if (animation.playState !== 'running')
774
+ return []
775
+
776
+ // A view transition is owned by the document, not by the incoming slide's
777
+ // slot. Its pseudo-elements therefore never appear in the annotation
778
+ // container's subtree, even though they are exactly the animation we must
779
+ // wait for before drawing on the new slide.
780
+ const viewTransitionAnimations = typeof document !== 'undefined'
781
+ ? document.getAnimations().filter((animation) => {
782
+ const pseudo = (animation.effect as KeyframeEffect | null)?.pseudoElement
783
+ return typeof pseudo === 'string' && pseudo.startsWith('::view-transition-')
784
+ })
785
+ : []
786
+ const animations = [...root.getAnimations({ subtree: true }), ...viewTransitionAnimations]
787
+
788
+ return [...new Set(animations)].filter((animation) => {
789
+ if (animation.playState !== 'running' && !animation.pending)
706
790
  return false
707
- const target = (animation.effect as KeyframeEffect | null)?.target ?? null
708
- // The annotation's own strokes and label are not what it waits for.
709
- return !target?.closest('.annotation-ignore')
791
+ const target = (animation.effect as KeyframeEffect | null)?.target
792
+ const pseudo = (animation.effect as KeyframeEffect | null)?.pseudoElement
793
+ // Pseudo-elements belong to the page transition and are intentionally
794
+ // included. For regular elements, never wait for our own strokes or label:
795
+ // they only start after `settled` opens the annotation.
796
+ const belongsToPageTransition = typeof pseudo === 'string' && pseudo.startsWith('::view-transition-')
797
+ const belongsToSlot = target instanceof Element && !target.closest('.annotation-ignore')
798
+ return (belongsToPageTransition || belongsToSlot)
799
+ && Number.isFinite(animation.effect?.getComputedTiming().endTime)
710
800
  })
711
801
  }
712
802
 
803
+ function nextFrame() {
804
+ return new Promise<void>(resolve => requestAnimationFrame(() => resolve()))
805
+ }
806
+
807
+ /**
808
+ * Release the entrance when the animations that actually started for this
809
+ * click finish. Re-check after each batch because Magic Move can create the
810
+ * next transition while completing the previous one. A final frame lets the
811
+ * browser commit the finished layout before it is measured for drawing.
812
+ */
813
+ const VIEW_TRANSITION_START_GRACE = 100
814
+
815
+ async function settleAfterAnimations(run: number, grace = 0) {
816
+ // Slidev starts document.startViewTransition() after a short timeout. A
817
+ // preloaded annotation can therefore observe the route change before the
818
+ // browser has created the view-transition pseudo-elements. Give that start
819
+ // callback time to run instead of concluding that there is nothing to wait
820
+ // for.
821
+ if (grace > 0)
822
+ await new Promise<void>(resolve => setTimeout(resolve, grace))
823
+ await nextTick()
824
+ await nextFrame()
825
+ while (mounted && run === settleRun) {
826
+ const animations = relevantAnimations()
827
+ if (!animations.length) {
828
+ await nextFrame()
829
+ if (mounted && run === settleRun && !relevantAnimations().length) {
830
+ // Settle before measuring: the settled pass is the one full
831
+ // recomputation per click that the animation-frame passes lean on.
832
+ settled.value = true
833
+ updateGeometry()
834
+ }
835
+ return
836
+ }
837
+ await Promise.allSettled(animations.map(animation => animation.finished))
838
+ await nextFrame()
839
+ }
840
+ }
841
+
713
842
  /**
714
843
  * Marks the annotation as moving again and keeps measuring until it stops.
715
844
  * Called on every click, because that is what starts a Magic Move step.
716
845
  */
717
- function unsettle() {
846
+ function unsettle(grace = 0) {
847
+ const run = ++settleRun
848
+ // A click can restyle the slide, so measured label sizes and content
849
+ // obstacles go stale here — once per click, which leaves them shared by
850
+ // every frame of the animation.
851
+ labelSizeCache.clear()
852
+ contentObstacleCache = undefined
718
853
  if (!props.wait || !props.track) {
719
854
  settled.value = true
720
855
  return
721
856
  }
722
857
  settled.value = false
723
- stableFrames = 0
724
- settleDeadline = performance.now() + SETTLE_TIMEOUT
725
858
  track(0)
859
+ void settleAfterAnimations(run, grace)
726
860
  }
727
861
 
728
862
  function scheduleUpdate() {
729
863
  // Late asynchronous callers — a font that finishes loading, an image that
730
864
  // decodes — must not schedule work on an annotation that is already gone.
865
+ if (!mounted)
866
+ return
867
+ // Discrete events land here (per-frame tracking calls updateGeometry
868
+ // directly): the slide may have reflowed, so re-scan content obstacles.
869
+ contentObstacleCache = undefined
870
+ cancelAnimationFrame(frame)
871
+ frame = requestAnimationFrame(updateGeometry)
872
+ }
873
+
874
+ /** Repaint one editing annotation without invalidating the slide obstacle scan. */
875
+ function scheduleDraftUpdate() {
731
876
  if (!mounted)
732
877
  return
733
878
  cancelAnimationFrame(frame)
@@ -735,20 +880,28 @@ function scheduleUpdate() {
735
880
  }
736
881
 
737
882
  /**
738
- * Keeps re-measuring for a short while. Magic Move and click transitions move
739
- * the annotated tokens over several hundred milliseconds, and there is no
740
- * single event that reliably marks the end of that movement.
883
+ * Keeps re-measuring while an animation moves the annotated content. The
884
+ * animation's `finished` promise controls the entrance; this loop only keeps
885
+ * the geometry attached to the moving element until then.
741
886
  */
887
+ // A plain click has no moving geometry. Keep a short tracking window for Vue to
888
+ // apply that click, while mutations from Magic Move retain the longer window.
889
+ const CLICK_TRACK_DURATION = 120
890
+
742
891
  function track(duration = 700) {
743
892
  if (!props.track)
744
893
  return
894
+ // A still-hidden (or already-ended) annotation has nothing on screen that
895
+ // must glide with the animation. Its geometry is refreshed once per click by
896
+ // the settled measurement instead of on every frame — including the strokes
897
+ // other annotations route around while it waits for its click.
898
+ if (!withinRange.value || $clicks.value < Math.min(resolvedClick.value, resolvedLabelClick.value))
899
+ return
745
900
  trackUntil = Math.max(trackUntil, performance.now() + duration)
746
901
  if (trackFrame)
747
902
  return
748
903
  const step = () => {
749
904
  updateGeometry()
750
- if (!settled.value && performance.now() > settleDeadline)
751
- settled.value = true
752
905
  if (mounted && (performance.now() < trackUntil || !settled.value)) {
753
906
  trackFrame = requestAnimationFrame(step)
754
907
  }
@@ -770,24 +923,24 @@ let everFound = false
770
923
  // click has been reached and the slide has stopped moving; before that, it may
771
924
  // simply not have arrived yet.
772
925
  const missingIsAnError = computed(() =>
773
- settled.value && $clicks.value >= resolvedClick.value && withinRange.value)
926
+ isCurrentSlide.value && settled.value && $clicks.value >= resolvedClick.value && withinRange.value)
774
927
 
775
928
  /** Explains why nothing was drawn, once something should have been. */
776
929
  function explainMissing(match?: { range?: Range, matches: number }) {
777
930
  if (everFound || !missingIsAnError.value)
778
931
  return
779
932
  if (!props.text)
780
- warn(`Selector "${props.selector}" matched nothing inside the slot. Put the attribute on the element to annotate, or use \`text\` to mark code.`)
933
+ warn(`Selector "${props.selector}" matched nothing inside ${searchScope()}. Put the attribute on the element to annotate, or use \`text\` to mark code.`)
781
934
  else if (!match || match.matches === 0)
782
- warn(`Text "${props.text}" was not found in the slot. It has to match the rendered text exactly — and inside a Magic Move block, be part of the step the annotation is drawn on.`)
783
- else if (match.matches < Math.max(1, props.occurrence))
935
+ warn(`Text "${props.text}" was not found in ${searchScope()}. It has to match the rendered text exactly — and inside a Magic Move block, be part of the step the annotation is drawn on.`)
936
+ else if (match.matches < Math.max(1, Number(props.occurrence)))
784
937
  warn(`Text "${props.text}" ${match.matches === 1 ? 'matches only once' : `matches only ${match.matches} times`}, but \`occurrence\` asks for match ${props.occurrence}.`)
785
938
  else
786
939
  warn(`Text "${props.text}" was found, but has no size on screen right now, so there is nothing to draw around.`)
787
940
  }
788
941
 
789
942
  function updateGeometry() {
790
- const root = container.value
943
+ const root = searchRoot()
791
944
  const svg = overlay.value
792
945
  if (!root || !svg)
793
946
  return
@@ -817,7 +970,9 @@ function updateGeometry() {
817
970
  )
818
971
 
819
972
  const match = props.text ? textRange(root, props.text, props.occurrence) : undefined
820
- const source = props.text ? undefined : root.querySelector<HTMLElement>(props.selector)
973
+ const source = props.text
974
+ ? undefined
975
+ : Array.from(root.querySelectorAll<HTMLElement>(props.selector)).find(followsAnnotation) ?? null
821
976
  const rects = match?.range
822
977
  ? Array.from(match.range.getClientRects()).filter(rect => rect.width > 0.5 && rect.height > 0.5)
823
978
  : source
@@ -847,29 +1002,21 @@ function updateGeometry() {
847
1002
  const multiline = props.multiline ?? (sourceMarkType.value === 'underline' || sourceMarkType.value === 'strike-through')
848
1003
  const shapeBoxes = multiline ? boxes : [marked]
849
1004
 
1005
+ // While the slide is still animating, a mark that has not moved since the
1006
+ // previous frame needs nothing recomputed: the paths, the leader and the
1007
+ // label placement all derive from it. The settled pass at the end of every
1008
+ // click always recomputes, because other content can have moved around a
1009
+ // stationary mark.
1010
+ 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(';')}`
1011
+ if (!settled.value && geometry.ready && markKey === lastMarkKey)
1012
+ return
1013
+ lastMarkKey = markKey
1014
+
850
1015
  geometry.width = width
851
1016
  geometry.height = height
852
- geometry.mark = shapeBoxes.flatMap(box => markPaths(box, sourceMarkType.value))
853
-
854
- paintDestination(root, toLocal, marked, width, height)
855
-
856
- // Two measurements that come out identical mean the element has come to rest.
857
- const signature = [
858
- geometry.mark.join(''),
859
- geometry.leader.join(''),
860
- geometry.arrow.join(''),
861
- geometry.targetMark.join(''),
862
- Math.round(geometry.labelLeft),
863
- Math.round(geometry.labelTop),
864
- ].join('|')
865
- if (signature === lastSignature && !inMotion()) {
866
- if (++stableFrames >= SETTLE_FRAMES)
867
- settled.value = true
868
- }
869
- else {
870
- lastSignature = signature
871
- stableFrames = 0
872
- }
1017
+ assignPaths('mark', shapeBoxes.flatMap(box => markPaths(box, sourceMarkType.value)))
1018
+
1019
+ paintDestination(root, toLocal, marked)
873
1020
 
874
1021
  const firstMeasurement = !geometry.ready
875
1022
  geometry.ready = true
@@ -927,13 +1074,25 @@ function paintDestination(
927
1074
  root: HTMLElement,
928
1075
  toLocal: (rect: DOMRect) => Box,
929
1076
  marked: Box,
930
- width: number,
931
- height: number,
932
1077
  ) {
933
- geometry.leader = []
934
- geometry.arrow = []
935
- geometry.targetMark = []
1078
+ geometry.connectorStart = undefined
1079
+ geometry.connectorEnd = undefined
1080
+ // Computed into locals first: the stable rough.js seed makes an unchanged
1081
+ // layout produce identical path strings, which assignPaths then drops
1082
+ // instead of re-patching the SVG.
1083
+ const paths = { leader: [] as string[], arrow: [] as string[], targetMark: [] as string[] }
1084
+ paintDestinationInto(paths, root, toLocal, marked)
1085
+ assignPaths('leader', paths.leader)
1086
+ assignPaths('arrow', paths.arrow)
1087
+ assignPaths('targetMark', paths.targetMark)
1088
+ }
936
1089
 
1090
+ function paintDestinationInto(
1091
+ paths: { leader: string[], arrow: string[], targetMark: string[] },
1092
+ root: HTMLElement,
1093
+ toLocal: (rect: DOMRect) => Box,
1094
+ marked: Box,
1095
+ ) {
937
1096
  const markBox = padBox(marked, sourceMarkType.value === 'none' ? 4 : props.padding + 6)
938
1097
  const targetEl = props.target ? (root.querySelector<HTMLElement>(props.target) ?? document.querySelector<HTMLElement>(props.target)) : undefined
939
1098
  if (props.target && !targetEl && missingIsAnError.value)
@@ -951,18 +1110,24 @@ function paintDestination(
951
1110
  endPoint = { x, y }
952
1111
  // The target is its own stage after the connection. A zero padding keeps
953
1112
  // target-radius the exact outer size authors position over screenshots.
954
- geometry.targetMark = markPaths(destination, targetMarkType.value, 0)
1113
+ paths.targetMark = markPaths(destination, targetMarkType.value, 0)
955
1114
  }
956
1115
 
957
1116
  if (hasLabel.value) {
958
1117
  // Start with the label's natural width, which is a single line. Only give
959
1118
  // it a maximum width when that line cannot stay on the slide or cannot be
960
1119
  // placed clear of the slide's content.
961
- const label = fitLabel(root, toLocal, destination ?? markBox, width, height)
1120
+ // An annotation nested in a positioned component (for example
1121
+ // InlineCompilerError) has an SVG canvas limited to that component. The
1122
+ // label is allowed to leave that canvas, so constrain it to the slide,
1123
+ // expressed in the SVG's local coordinates, rather than to the canvas.
1124
+ const slide = slideRoot() ?? root
1125
+ const label = fitLabel(root, toLocal, destination ?? markBox, toLocal(slide.getBoundingClientRect()))
962
1126
  geometry.labelLeft = label.box.cx
963
1127
  geometry.labelTop = label.box.cy
964
1128
  geometry.labelWidth = label.width
965
1129
  geometry.labelPlaced = true
1130
+ publishPlacedLabel(label.box)
966
1131
  if (!destination) {
967
1132
  destination = label.box
968
1133
  endPoint = undefined
@@ -970,19 +1135,56 @@ function paintDestination(
970
1135
  }
971
1136
  else {
972
1137
  geometry.labelPlaced = false
1138
+ placedLabelRegistry.delete(placementToken)
973
1139
  }
974
1140
 
975
1141
  if (!destination || !props.connect)
976
1142
  return
977
1143
 
978
- const route = routeLeader(root, toLocal, markBox, destination, endPoint)
979
- if (!route)
980
- return
981
- const { start, end, c1x, c1y, c2x, c2y } = route
982
- geometry.leader = toPaths(generator.path(
983
- `M ${start.x} ${start.y} C ${c1x} ${c1y}, ${c2x} ${c2y}, ${end.x} ${end.y}`,
984
- roughOptions(),
985
- ))
1144
+ const savedConnector = manualConnector()
1145
+ let start: Point
1146
+ let end: Point
1147
+ let c2x: number
1148
+ let c2y: number
1149
+ if (savedConnector && overlay.value) {
1150
+ // Saved fractions always use the concrete slide root, even if this SVG is
1151
+ // nested in a positioned component.
1152
+ const slide = slideRoot()
1153
+ if (!slide)
1154
+ return
1155
+ const slideBox = slide.getBoundingClientRect()
1156
+ const overlayBox = overlay.value.getBoundingClientRect()
1157
+ start = slideFractionPointToLocal({ x: savedConnector.x1, y: savedConnector.y1 }, slideBox, overlayBox, geometry)
1158
+ end = slideFractionPointToLocal({ x: savedConnector.x2, y: savedConnector.y2 }, slideBox, overlayBox, geometry)
1159
+ if (savedConnector.cx !== undefined && savedConnector.cy !== undefined) {
1160
+ const control = slideFractionPointToLocal({ x: savedConnector.cx, y: savedConnector.cy }, slideBox, overlayBox, geometry)
1161
+ // The authored control point is a genuine quadratic Bézier control, not
1162
+ // merely legacy metadata. Rough.js retains the curve's hand-drawn look.
1163
+ c2x = control.x
1164
+ c2y = control.y
1165
+ paths.leader = toPaths(generator.path(`M ${start.x} ${start.y} Q ${control.x} ${control.y}, ${end.x} ${end.y}`, roughOptions()))
1166
+ }
1167
+ else {
1168
+ c2x = start.x
1169
+ c2y = start.y
1170
+ paths.leader = toPaths(generator.line(start.x, start.y, end.x, end.y, roughOptions()))
1171
+ }
1172
+ }
1173
+ else {
1174
+ const route = routeLeader(markBox, destination, endPoint)
1175
+ if (!route)
1176
+ return
1177
+ start = route.start
1178
+ end = route.end
1179
+ c2x = route.c2x
1180
+ c2y = route.c2y
1181
+ paths.leader = toPaths(generator.path(
1182
+ `M ${start.x} ${start.y} C ${route.c1x} ${route.c1y}, ${route.c2x} ${route.c2y}, ${end.x} ${end.y}`,
1183
+ roughOptions(),
1184
+ ))
1185
+ }
1186
+ geometry.connectorStart = start
1187
+ geometry.connectorEnd = end
986
1188
 
987
1189
  if (props.arrow) {
988
1190
  // Aim the head along the tangent of the curve, not along the chord.
@@ -992,7 +1194,7 @@ function paintDestination(
992
1194
  end.x - Math.cos(angle + spread) * size,
993
1195
  end.y - Math.sin(angle + spread) * size,
994
1196
  ] as [number, number]
995
- geometry.arrow = [
1197
+ paths.arrow = [
996
1198
  ...toPaths(generator.linearPath([wing(0.42), [end.x, end.y]], roughOptions())),
997
1199
  ...toPaths(generator.linearPath([wing(-0.42), [end.x, end.y]], roughOptions())),
998
1200
  ]
@@ -1001,154 +1203,68 @@ function paintDestination(
1001
1203
 
1002
1204
  interface Point { x: number, y: number }
1003
1205
 
1004
- /** The leader's bezier between two points, bowed to one side or the other. */
1005
- function leaderCurve(start: Point, end: Point, side: 1 | -1) {
1206
+ function unitVector(x: number, y: number): Point | undefined {
1207
+ const length = Math.hypot(x, y)
1208
+ return length > 0.001 ? { x: x / length, y: y / length } : undefined
1209
+ }
1210
+
1211
+ // The bow of a leader is capped in slide pixels: proportional to length alone,
1212
+ // a long leader turns into a swooping gesture instead of a connection.
1213
+ const LEADER_MAX_BOW = 40
1214
+
1215
+ /**
1216
+ * The leader's bezier between two points. `out` is the direction the line
1217
+ * leaves the mark and `into` the direction it arrives at its destination; the
1218
+ * curve turns smoothly from one to the other, and `side` adds a gentle bow.
1219
+ * The arrival tangent stays aimed at the destination — that is what makes the
1220
+ * line read as pointing at the label rather than curling flat and sweeping
1221
+ * past it.
1222
+ */
1223
+ function leaderCurve(start: Point, end: Point, side: 1 | -1, out?: Point, into?: Point) {
1006
1224
  const dx = end.x - start.x
1007
1225
  const dy = end.y - start.y
1008
1226
  const distance = Math.hypot(dx, dy)
1009
- const bend = distance * props.curve * side
1010
- const perpX = -dy / (distance || 1) * bend
1011
- const perpY = dx / (distance || 1) * bend
1227
+ const along = unitVector(dx, dy) ?? { x: 1, y: 0 }
1228
+ const bend = Math.min(distance * props.curve, LEADER_MAX_BOW) * side
1229
+ const perpX = -along.y * bend
1230
+ const perpY = along.x * bend
1231
+ const reach = distance * 0.38
1232
+ const outDir = out ?? along
1233
+ const inDir = into ?? along
1012
1234
  return {
1013
1235
  start,
1014
1236
  end,
1015
1237
  distance,
1016
- c1x: start.x + dx * 0.34 + perpX,
1017
- c1y: start.y + dy * 0.34 + perpY,
1018
- c2x: start.x + dx * 0.72 + perpX,
1019
- c2y: start.y + dy * 0.72 + perpY,
1238
+ c1x: start.x + outDir.x * reach + perpX,
1239
+ c1y: start.y + outDir.y * reach + perpY,
1240
+ // Most of the bow sits near the exit; the arrival keeps pointing where it
1241
+ // is going, so the line lands on the label instead of flattening out.
1242
+ c2x: end.x - inDir.x * reach + perpX * 0.35,
1243
+ c2y: end.y - inDir.y * reach + perpY * 0.35,
1020
1244
  }
1021
1245
  }
1022
1246
 
1023
1247
  type Curve = ReturnType<typeof leaderCurve>
1024
1248
 
1025
- /** Roughly how much of the curve runs through the given boxes, in slide pixels. */
1026
- function curveCrossing(curve: Curve, obstacles: Box[]) {
1027
- const samples = 24
1028
- let inside = 0
1029
- for (let i = 0; i <= samples; i++) {
1030
- const t = i / samples
1031
- const u = 1 - t
1032
- const x = u ** 3 * curve.start.x + 3 * u ** 2 * t * curve.c1x + 3 * u * t ** 2 * curve.c2x + t ** 3 * curve.end.x
1033
- const y = u ** 3 * curve.start.y + 3 * u ** 2 * t * curve.c1y + 3 * u * t ** 2 * curve.c2y + t ** 3 * curve.end.y
1034
- if (obstacles.some(box => x >= box.left && x <= box.right && y >= box.top && y <= box.bottom))
1035
- inside++
1036
- }
1037
- return inside / (samples + 1) * curve.distance
1038
- }
1039
-
1040
1249
  /**
1041
- * Chooses where the leader leaves the mark and which way it bows. The obvious
1042
- * straight exit towards the destination regularly runs through the rest of the
1043
- * sentence the mark sits in, which reads as a strike-through of text the
1044
- * annotation has nothing to do with. So candidate exits along the mark's
1045
- * border are tried, bowing to either side, against the rendered text of the
1046
- * slide. The straight exit is only given up when another exit saves a
1047
- * substantial amount of crossing: brushing past a neighbouring line is part of
1048
- * the hand-drawn look, and a leader that trades it for a detour reads as
1049
- * starting from the wrong place.
1250
+ * Uses the shortest direct leader as the stable automatic fallback. Complex
1251
+ * routing is intentionally an editor operation: inspecting arbitrary future
1252
+ * slide content made an automatic line change as clicks progressed.
1050
1253
  */
1051
- function routeLeader(root: HTMLElement, toLocal: (rect: DOMRect) => Box, markBox: Box, destination: Box, endPoint?: Point): Curve | undefined {
1052
- const contains = (box: Box, x: number, y: number) => x >= box.left && x <= box.right && y >= box.top && y <= box.bottom
1053
- // Only text near the line's own neighbourhood matters, and never the words
1054
- // being marked or the destination itself.
1055
- const region = padBox(unionBox([markBox, destination]), 120)
1056
- const obstacles = collectTextObstacles(root, toLocal).filter(box =>
1057
- overlapArea(box, region) > 0
1058
- && !contains(markBox, box.cx, box.cy)
1059
- && !contains(destination, box.cx, box.cy))
1060
-
1061
- const defaultStart = edgePoint(markBox, destination.cx, destination.cy)
1062
- const exits: Point[] = [
1063
- { x: markBox.cx, y: markBox.top },
1064
- { x: markBox.cx, y: markBox.bottom },
1065
- { x: markBox.left, y: markBox.cy },
1066
- { x: markBox.right, y: markBox.cy },
1067
- { x: markBox.left, y: markBox.top },
1068
- { x: markBox.right, y: markBox.top },
1069
- { x: markBox.left, y: markBox.bottom },
1070
- { x: markBox.right, y: markBox.bottom },
1071
- ].sort((a, b) =>
1072
- Math.hypot(a.x - defaultStart.x, a.y - defaultStart.y)
1073
- - Math.hypot(b.x - defaultStart.x, b.y - defaultStart.y))
1074
-
1075
- let straight: { curve: Curve, crossing: number, cost: number } | undefined
1076
- let best: { curve: Curve, crossing: number, cost: number } | undefined
1077
- for (const [index, start] of [defaultStart, ...exits].entries()) {
1078
- const end = endPoint
1079
- ? backOff(endPoint, start, targetMarkType.value !== 'none' ? destination.width / 2 : 6)
1080
- : edgePoint(destination, start.x, start.y, 6)
1081
- for (const side of [1, -1] as const) {
1082
- const curve = leaderCurve(start, end, side)
1083
- if (curve.distance < 4)
1084
- continue
1085
- // Crossing text costs its length; the small terms only break ties.
1086
- const crossing = curveCrossing(curve, obstacles)
1087
- const cost = crossing + index * 2 + (side < 0 ? 1 : 0)
1088
- if (index === 0 && (!straight || cost < straight.cost))
1089
- straight = { curve, crossing, cost }
1090
- if (!best || cost < best.cost)
1091
- best = { curve, crossing, cost }
1092
- }
1093
- }
1094
- if (!straight)
1095
- return best?.curve
1096
- if (best && best.crossing < straight.crossing * 0.5 && straight.crossing - best.crossing > 24)
1097
- return best.curve
1098
- return straight.curve
1099
- }
1100
-
1101
- // Elements considered while measuring obstacles, capped: the collectors run on
1102
- // animation frames while the slide moves, and a slide with more elements than
1103
- // this has no room for an automatic label anyway.
1104
- const OBSTACLE_ELEMENT_CAP = 600
1105
- const MEDIA_TAGS = ['IMG', 'VIDEO', 'CANVAS', 'SVG']
1106
-
1107
- function isMedia(element: HTMLElement) {
1108
- return MEDIA_TAGS.includes(element.tagName.toUpperCase())
1109
- }
1110
-
1111
- /**
1112
- * The slide elements obstacle collection looks at. Excludes this component's
1113
- * own strokes and labels, content still hidden behind a later click, and the
1114
- * internals of inline SVGs — parts of an illustration do not count on their
1115
- * own; the whole graphic does.
1116
- */
1117
- function obstacleCandidates(slide: HTMLElement): HTMLElement[] {
1118
- return Array.from(slide.querySelectorAll<HTMLElement>('*'))
1119
- .slice(0, OBSTACLE_ELEMENT_CAP)
1120
- .filter(element => !element.closest('.annotation-ignore, .slidev-vclick-hidden')
1121
- && !element.parentElement?.closest('svg'))
1122
- }
1123
-
1124
- /**
1125
- * The slide's text and media, as the tight boxes of the rendered lines rather
1126
- * than the elements around them. This is what a leader line must not strike
1127
- * through: crossing a card's padding looks deliberate, crossing its words
1128
- * reads as marking text the annotation has nothing to do with.
1129
- */
1130
- function collectTextObstacles(root: HTMLElement, toLocal: (rect: DOMRect) => Box): Box[] {
1131
- const slide = slideRoot() ?? root
1132
- const boxes: Box[] = []
1133
- for (const element of obstacleCandidates(slide)) {
1134
- if (isMedia(element)) {
1135
- const rect = element.getBoundingClientRect()
1136
- if (rect.width >= 6 && rect.height >= 6)
1137
- boxes.push(toLocal(rect))
1138
- continue
1139
- }
1140
- for (const node of Array.from(element.childNodes)) {
1141
- if (node.nodeType !== Node.TEXT_NODE || !node.nodeValue?.trim())
1142
- continue
1143
- const range = document.createRange()
1144
- range.selectNodeContents(node)
1145
- for (const rect of Array.from(range.getClientRects())) {
1146
- if (rect.width >= 4 && rect.height >= 4)
1147
- boxes.push(toLocal(rect))
1254
+ function routeLeader(markBox: Box, destination: Box, endPoint?: Point): Curve | undefined {
1255
+ const start = edgePoint(markBox, destination.cx, destination.cy)
1256
+ const end = endPoint
1257
+ ? backOff(endPoint, start, targetMarkType.value !== 'none' ? destination.width / 2 : 6)
1258
+ : {
1259
+ x: clamp(start.x, destination.left, destination.right),
1260
+ y: clamp(start.y, destination.top, destination.bottom),
1148
1261
  }
1149
- }
1150
- }
1151
- return boxes
1262
+ const chord = unitVector(end.x - start.x, end.y - start.y)
1263
+ if (!chord)
1264
+ return undefined
1265
+ const outward = unitVector(start.x - markBox.cx, start.y - markBox.cy) ?? chord
1266
+ const into = endPoint ? unitVector(endPoint.x - end.x, endPoint.y - end.y) ?? chord : chord
1267
+ return leaderCurve(start, end, 1, unitVector(outward.x + chord.x, outward.y + chord.y) ?? chord, into)
1152
1268
  }
1153
1269
 
1154
1270
  // Stands in for a label that cannot be measured yet, so placement still has a
@@ -1158,15 +1274,84 @@ const FALLBACK_LABEL_HEIGHT = 40
1158
1274
  // The label never sits closer to a slide edge than this, in slide pixels.
1159
1275
  const SLIDE_MARGIN = 24
1160
1276
 
1161
- // Sideways nudges tried for each gap while placing the label, nearest first.
1162
- const LATERAL_OFFSETS = (() => {
1163
- const offsets = [0]
1164
- for (let step = 40; step <= 400; step += 40)
1165
- offsets.push(step, -step)
1166
- return offsets
1167
- })()
1277
+ // Measured label sizes per width cap. Writing a candidate max-width and
1278
+ // reading the resulting box back forces a synchronous layout, and the answer
1279
+ // only changes with the label's text or font — never from frame to frame while
1280
+ // the slide animates. Sizes are in slide coordinates, so they survive window
1281
+ // resizes too. Cleared on every click and whenever the props or fonts change.
1282
+ const labelSizeCache = new Map<number | 'natural', { width: number, height: number }>()
1283
+
1284
+ // This instance's slot in the shared placed-label registry (module scope, see
1285
+ // the plain `<script>` block above). Mount order approximates document order.
1286
+ const placementToken = Symbol('drawn-annotation-label')
1287
+ const placementOrder = nextPlacementOrder++
1288
+
1289
+ const locator = computed(() => props.__drawnAnnotationLocator)
1290
+ if (isAnnotationEditorDevelopment) {
1291
+ // A save remounts the slide. The locator survives the writer's own edits,
1292
+ // so this instance can take over the selection the unmounting one released.
1293
+ if (locator.value)
1294
+ claimAnnotationSelection(locator.value)
1295
+ // A write elsewhere in the file can still move this tag to another line.
1296
+ // Should Vue patch the prop in place, the editor state keyed by the old
1297
+ // locator has to follow it.
1298
+ watch(locator, (next, previous) => {
1299
+ if (!previous)
1300
+ return
1301
+ if (next)
1302
+ migrateAnnotationLocator(previous, next)
1303
+ else
1304
+ clearAnnotationSelection(previous)
1305
+ })
1306
+ }
1307
+ /**
1308
+ * The `geometry` binding, checked once per change. A hand-edited binding in
1309
+ * the wrong unit (`{ x: 70, y: 18 }` in percent) would otherwise place the
1310
+ * label off the slide without a word; it is ignored with a warning instead.
1311
+ */
1312
+ const sourceGeometry = computed<DrawnAnnotationGeometry | undefined>(() => {
1313
+ if (props.geometry === undefined)
1314
+ return undefined
1315
+ try {
1316
+ return validateDrawnAnnotationGeometry(props.geometry)
1317
+ }
1318
+ catch (error) {
1319
+ warn(`Ignoring \`geometry\`: ${error instanceof Error ? error.message : String(error)}. Every value is a fraction of the slide from 0 to 1, for example \`:geometry="{ label: { x: 0.7, y: 0.18 } }"\`.`)
1320
+ return undefined
1321
+ }
1322
+ })
1323
+ /** Source geometry is the persisted state; editor drafts remain visible through HMR. */
1324
+ function persistedLabelGeometry(): PersistedAnnotationGeometry {
1325
+ const value = sourceGeometry.value
1326
+ return {
1327
+ x: value?.label?.x, y: value?.label?.y, width: value?.label?.width,
1328
+ x1: value?.connector?.start.x, y1: value?.connector?.start.y,
1329
+ x2: value?.connector?.end.x, y2: value?.connector?.end.y,
1330
+ cx: value?.connector?.control?.x, cy: value?.connector?.control?.y,
1331
+ }
1332
+ }
1333
+ function draftLabelGeometry() { return locator.value ? annotationDrafts.get(locator.value) : undefined }
1334
+ function effectiveLabelX() { return draftLabelGeometry()?.x ?? persistedLabelGeometry().x }
1335
+ function effectiveLabelY() { return draftLabelGeometry()?.y ?? persistedLabelGeometry().y }
1336
+ function effectiveLabelWidth(bounds: Box) { const width = draftLabelGeometry()?.width ?? persistedLabelGeometry().width; return width === undefined ? undefined : bounds.width * width }
1337
+ /** A connector becomes manual only once all four endpoints are present. */
1338
+ function manualConnector() {
1339
+ const draft = draftLabelGeometry()
1340
+ const saved = persistedLabelGeometry()
1341
+ const x1 = draft?.x1 ?? saved.x1
1342
+ const y1 = draft?.y1 ?? saved.y1
1343
+ const x2 = draft?.x2 ?? saved.x2
1344
+ const y2 = draft?.y2 ?? saved.y2
1345
+ return x1 === undefined || y1 === undefined || x2 === undefined || y2 === undefined
1346
+ ? undefined
1347
+ : { x1, y1, x2, y2, cx: draft?.cx ?? saved.cx, cy: draft?.cy ?? saved.cy }
1348
+ }
1168
1349
 
1169
1350
  function measureLabel(toLocal: (rect: DOMRect) => Box, maxWidth?: number) {
1351
+ const cached = labelSizeCache.get(maxWidth ?? 'natural')
1352
+ if (cached)
1353
+ return cached
1354
+
1170
1355
  const label = labelEl.value
1171
1356
  if (!label)
1172
1357
  return { width: maxWidth ?? 0, height: FALLBACK_LABEL_HEIGHT }
@@ -1181,36 +1366,47 @@ function measureLabel(toLocal: (rect: DOMRect) => Box, maxWidth?: number) {
1181
1366
  const rect = label.getBoundingClientRect()
1182
1367
  label.style.maxWidth = previousMaxWidth
1183
1368
 
1369
+ // Only a real measurement is worth remembering; the fallbacks stand in for a
1370
+ // label that cannot be measured yet.
1184
1371
  if (!rect.width)
1185
1372
  return { width: maxWidth ?? 0, height: FALLBACK_LABEL_HEIGHT }
1186
1373
  const box = toLocal(rect)
1187
- return { width: box.width, height: box.height }
1374
+ const size = { width: box.width, height: box.height }
1375
+ labelSizeCache.set(maxWidth ?? 'natural', size)
1376
+ return size
1188
1377
  }
1189
1378
 
1190
1379
  /**
1191
- * Finds the widest label that can stay inside the slide and clear its
1192
- * obstacles. The unbounded measurement is always tried first, so ordinary
1193
- * labels remain a single, readable line instead of inheriting an arbitrary
1194
- * short line length.
1380
+ * Finds a bounded default label position. The unbounded measurement is always
1381
+ * tried first, so ordinary labels remain a single, readable line instead of
1382
+ * inheriting an arbitrary short line length. When the natural width cannot be
1383
+ * placed clear of the obstacles, narrower candidates let the label wrap into
1384
+ * the free space instead.
1195
1385
  */
1196
1386
  function fitLabel(
1197
1387
  root: HTMLElement,
1198
1388
  toLocal: (rect: DOMRect) => Box,
1199
1389
  anchor: Box,
1200
- width: number,
1201
- height: number,
1390
+ bounds: Box,
1202
1391
  ): { box: Box, width: number | undefined } {
1392
+ // Collected once for every width candidate tried below: the obstacles do not
1393
+ // depend on how the label wraps. An explicitly positioned label ignores
1394
+ // obstacles entirely — authored geometry is the final say.
1395
+ const explicitX = effectiveLabelX()
1396
+ const explicitY = effectiveLabelY()
1397
+ const maximumWidth = effectiveLabelWidth(bounds)
1398
+ const obstacles = explicitX !== undefined || explicitY !== undefined ? [] : collectLabelObstacles(toLocal)
1203
1399
  const natural = measureLabel(toLocal)
1204
- const unwrapped = placeLabel(root, toLocal, anchor, natural, width, height)
1205
- const fitsSlide = natural.width <= width - SLIDE_MARGIN * 2 && natural.height <= height - SLIDE_MARGIN * 2
1206
- const respectsExplicitMaximum = props.labelWidth === undefined || natural.width <= props.labelWidth
1400
+ const unwrapped = placeLabel(anchor, natural, bounds, obstacles)
1401
+ const fitsSlide = natural.width <= bounds.width - SLIDE_MARGIN * 2 && natural.height <= bounds.height - SLIDE_MARGIN * 2
1402
+ const respectsExplicitMaximum = maximumWidth === undefined || natural.width <= maximumWidth
1207
1403
 
1208
1404
  if (fitsSlide && unwrapped.overlap === 0 && respectsExplicitMaximum)
1209
1405
  return { box: unwrapped.box, width: undefined }
1210
1406
 
1211
- // An explicit `label-width` remains a useful author override. Without one,
1212
- // the slide edges are the only width limit.
1213
- const maximum = Math.min(natural.width, props.labelWidth ?? natural.width, width - SLIDE_MARGIN * 2)
1407
+ // An explicit normalized geometry width remains a useful author override.
1408
+ // Without one, the slide edges are the only width limit.
1409
+ const maximum = Math.min(natural.width, maximumWidth ?? natural.width, bounds.width - SLIDE_MARGIN * 2)
1214
1410
  const minimum = Math.min(maximum, 160)
1215
1411
  let best: { box: Box, width: number, overlap: number } | undefined
1216
1412
 
@@ -1219,7 +1415,7 @@ function fitLabel(
1219
1415
  // Magic Move animations.
1220
1416
  for (let cap = maximum; cap >= minimum; cap -= 48) {
1221
1417
  const size = measureLabel(toLocal, cap)
1222
- const placed = placeLabel(root, toLocal, anchor, size, width, height)
1418
+ const placed = placeLabel(anchor, size, bounds, obstacles)
1223
1419
  if (placed.overlap === 0)
1224
1420
  return { box: placed.box, width: cap }
1225
1421
  if (!best || placed.overlap < best.overlap)
@@ -1229,7 +1425,7 @@ function fitLabel(
1229
1425
  // Include the lower bound when the step above did not land on it.
1230
1426
  if (!best || best.width !== minimum) {
1231
1427
  const size = measureLabel(toLocal, minimum)
1232
- const placed = placeLabel(root, toLocal, anchor, size, width, height)
1428
+ const placed = placeLabel(anchor, size, bounds, obstacles)
1233
1429
  if (placed.overlap === 0)
1234
1430
  return { box: placed.box, width: minimum }
1235
1431
  if (!best || placed.overlap < best.overlap)
@@ -1240,132 +1436,168 @@ function fitLabel(
1240
1436
  }
1241
1437
 
1242
1438
  function placeLabel(
1243
- root: HTMLElement,
1244
- toLocal: (rect: DOMRect) => Box,
1245
1439
  anchor: Box,
1246
1440
  size: { width: number, height: number },
1247
- width: number,
1248
- height: number,
1441
+ bounds: Box,
1442
+ obstacles: Box[] = [],
1249
1443
  ): { box: Box, overlap: number } {
1250
1444
  const halfW = size.width / 2
1251
1445
  const halfH = size.height / 2
1252
1446
  const centred = (cx: number, cy: number) => makeBox(cx - halfW, cy - halfH, cx + halfW, cy + halfH)
1447
+ const explicitX = effectiveLabelX()
1448
+ const explicitY = effectiveLabelY()
1449
+ if (explicitX !== undefined || explicitY !== undefined) {
1450
+ // Authored geometry is the final say; it is never moved by obstacles.
1451
+ return { box: centred(
1452
+ explicitX !== undefined ? bounds.left + bounds.width * explicitX : anchor.cx,
1453
+ explicitY !== undefined ? bounds.top + bounds.height * explicitY : anchor.cy,
1454
+ ), overlap: 0 }
1455
+ }
1253
1456
 
1254
- if (props.labelX !== undefined || props.labelY !== undefined) {
1255
- return {
1256
- box: centred(
1257
- props.labelX !== undefined ? width * props.labelX / 100 : anchor.cx,
1258
- props.labelY !== undefined ? height * props.labelY / 100 : anchor.cy,
1259
- ),
1260
- overlap: 0,
1261
- }
1457
+ type Direction = 'up' | 'down' | 'left' | 'right'
1458
+ const preferred: Direction = resolvedPlacement.value === 'auto'
1459
+ ? (anchor.cy < bounds.cy ? 'down' : 'up')
1460
+ : resolvedPlacement.value
1461
+ // `auto` may fall back to the other sides. An explicit side is a contract:
1462
+ // the label wraps or stays put rather than drifting to another side.
1463
+ const directions: Direction[] = resolvedPlacement.value === 'auto'
1464
+ ? [preferred, preferred === 'down' ? 'up' : 'down', 'right', 'left']
1465
+ : [preferred]
1466
+
1467
+ const candidate = (direction: Direction, shift: number, extra: number) => {
1468
+ const cx = direction === 'left' ? anchor.left - props.gap - extra - halfW
1469
+ : direction === 'right' ? anchor.right + props.gap + extra + halfW : anchor.cx + shift
1470
+ const cy = direction === 'up' ? anchor.top - props.gap - extra - halfH
1471
+ : direction === 'down' ? anchor.bottom + props.gap + extra + halfH : anchor.cy + shift
1472
+ const box = centred(
1473
+ clamp(cx, bounds.left + SLIDE_MARGIN + halfW, bounds.right - SLIDE_MARGIN - halfW),
1474
+ clamp(cy, bounds.top + SLIDE_MARGIN + halfH, bounds.bottom - SLIDE_MARGIN - halfH),
1475
+ )
1476
+ // The clearance keeps the label breathing: a label flush against the
1477
+ // bottom of a code block reads as part of it. The anchor is an obstacle
1478
+ // too, so a clamped candidate never covers its own mark unnoticed.
1479
+ const inflated = padBox(box, props.clearance)
1480
+ let overlap = overlapArea(inflated, anchor)
1481
+ for (const obstacle of obstacles)
1482
+ overlap += overlapArea(inflated, obstacle)
1483
+ return { box, overlap }
1262
1484
  }
1263
1485
 
1264
- // Obstacles are inflated so the label breathes: a label that ends up flush
1265
- // against the bottom of a code block reads as part of it.
1266
- const obstacles = collectObstacles(root, toLocal)
1267
- .map(box => padBox(box, props.clearance))
1268
- .concat(padBox(anchor, 8))
1269
- const placement = resolvedPlacement.value
1270
- const preferred = placement === 'auto'
1271
- ? (anchor.cy < height / 2 ? 'down' : 'up')
1272
- : placement
1273
- const directions = placement === 'auto'
1274
- ? [preferred, preferred === 'down' ? 'up' : 'down', 'right', 'left'] as const
1275
- : [preferred] as const
1276
-
1277
- let best: { box: Box, overlap: number, score: number } | undefined
1278
-
1279
- for (const [order, direction] of directions.entries()) {
1280
- for (let gap = props.gap; gap <= props.gap + 260; gap += 20) {
1281
- for (const lateral of LATERAL_OFFSETS) {
1282
- const vertical = direction === 'up' || direction === 'down'
1283
- const cx = vertical
1284
- ? anchor.cx + lateral
1285
- : direction === 'right' ? anchor.right + gap + halfW : anchor.left - gap - halfW
1286
- const cy = vertical
1287
- ? (direction === 'down' ? anchor.bottom + gap + halfH : anchor.top - gap - halfH)
1288
- : anchor.cy + lateral
1289
-
1290
- const box = centred(
1291
- clamp(cx, SLIDE_MARGIN + halfW, width - SLIDE_MARGIN - halfW),
1292
- clamp(cy, SLIDE_MARGIN + halfH, height - SLIDE_MARGIN - halfH),
1293
- )
1294
- const overlap = obstacles.reduce((total, obstacle) => total + overlapArea(box, obstacle), 0)
1295
- const score = overlap * 6 + gap + Math.abs(lateral) * 0.6 + order * 400
1296
- // A clear spot always beats an overlapping one, and among clear spots
1297
- // the best-scoring one wins: taking the first found would let a small
1298
- // gap with a long drift along the mark beat a slightly larger gap that
1299
- // stays level with it, which reads as belonging to something else.
1300
- const better = !best
1301
- || (overlap === 0 && best.overlap > 0)
1302
- || ((overlap === 0) === (best.overlap === 0) && score < best.score)
1303
- if (better)
1304
- best = { box, overlap, score }
1486
+ let best: { box: Box, overlap: number } | undefined
1487
+ for (const direction of directions) {
1488
+ // Nearest first: step further out along the side to clear an occupied
1489
+ // row, and slide along it to step out from under an obstacle — both
1490
+ // without leaving the requested side.
1491
+ const lateral = direction === 'up' || direction === 'down' ? halfW + props.gap : halfH + props.gap
1492
+ for (const extra of [0, 70, 150]) {
1493
+ for (const shift of [0, -lateral, lateral]) {
1494
+ const placed = candidate(direction, shift, extra)
1495
+ if (placed.overlap === 0)
1496
+ return placed
1497
+ if (!best || placed.overlap < best.overlap)
1498
+ best = placed
1305
1499
  }
1306
1500
  }
1307
1501
  }
1502
+ return best!
1503
+ }
1308
1504
 
1309
- // The loops above always run at least once, so `best` is always set; the
1310
- // fallback only satisfies the types.
1311
- return best ?? { box: centred(anchor.cx, anchor.cy), overlap: Number.POSITIVE_INFINITY }
1505
+ /** The intersection area of two boxes, 0 when they do not touch. */
1506
+ function overlapArea(a: Box, b: Box) {
1507
+ const width = Math.min(a.right, b.right) - Math.max(a.left, b.left)
1508
+ const height = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)
1509
+ return width > 0 && height > 0 ? width * height : 0
1312
1510
  }
1313
1511
 
1314
1512
  /**
1315
- * Everything the label has to stay clear of: the leaf elements of the slide,
1316
- * which is what actually carries text and images, plus anything the slide opted
1317
- * in through `avoid-selector`. `.card` and `.kodee-character` are the Kotlin
1318
- * theme's callouts and mascot.
1513
+ * Everything an automatically placed label must stay clear of, in local SVG
1514
+ * coordinates: the slide's laid-out content (text lines, images, code blocks
1515
+ * — including v-click content that is laid out but still hidden, so a label
1516
+ * never sits where the slide is about to grow), elements matched by
1517
+ * `avoid-selector`, and the labels that annotations on an earlier click (or
1518
+ * the same click and earlier in mount order) have placed on this slide. Only
1519
+ * what the browser has laid out is measured — deterministic by construction,
1520
+ * never guessed.
1319
1521
  */
1320
- const BLOCK_OBSTACLES = 'pre, .slidev-code, .slidev-code-wrapper, .card, table, blockquote, .kodee-character'
1321
-
1322
- function collectObstacles(root: HTMLElement, toLocal: (rect: DOMRect) => Box): Box[] {
1323
- const slide = slideRoot() ?? root
1324
- const boxes: Box[] = []
1325
- for (const element of obstacleCandidates(slide)) {
1326
- // Empty leaves are spacers and other invisible layout helpers, which the
1327
- // label is free to cover.
1328
- const leaf = element.childElementCount === 0 && !!element.textContent?.trim()
1329
- // Blocks are added whole, so a label never lands in the padding of a code
1330
- // block or a card, which their leaf elements alone would leave free.
1331
- const block = element.matches(BLOCK_OBSTACLES)
1332
- if (!leaf && !block && !isMedia(element))
1522
+ function collectLabelObstacles(toLocal: (rect: DOMRect) => Box): Box[] {
1523
+ const obstacles: Box[] = []
1524
+ const slide = slideRoot()
1525
+ const svg = overlay.value
1526
+ if (!slide || !svg)
1527
+ return obstacles
1528
+ obstacles.push(...contentObstacles(slide, toLocal))
1529
+ if (props.avoidSelector) {
1530
+ for (const element of Array.from(slide.querySelectorAll<HTMLElement>(props.avoidSelector))) {
1531
+ if (element.closest('.annotation-ignore'))
1532
+ continue
1533
+ const rect = element.getBoundingClientRect()
1534
+ if (rect.width && rect.height)
1535
+ obstacles.push(toLocal(rect))
1536
+ }
1537
+ }
1538
+ const slideBox = slide.getBoundingClientRect()
1539
+ const overlayBox = svg.getBoundingClientRect()
1540
+ const ourClick = resolvedLabelClick.value
1541
+ for (const record of placedLabelRegistry.values()) {
1542
+ if (record.root !== slide || !record.active)
1333
1543
  continue
1334
- const rect = element.getBoundingClientRect()
1335
- if (rect.width < 6 || rect.height < 6)
1544
+ // A later label avoids an earlier one, never the other way round, so two
1545
+ // labels can never chase each other. Earlier means an earlier click first
1546
+ // — a click-1 label is already on screen when a click-3 label is placed,
1547
+ // whatever their markup order — with mount order breaking the tie.
1548
+ if (!(record.click < ourClick || (record.click === ourClick && record.order < placementOrder)))
1336
1549
  continue
1337
- boxes.push(toLocal(rect))
1550
+ const topLeft = slideFractionPointToLocal({ x: record.box.left, y: record.box.top }, slideBox, overlayBox, geometry)
1551
+ const bottomRight = slideFractionPointToLocal({ x: record.box.right, y: record.box.bottom }, slideBox, overlayBox, geometry)
1552
+ obstacles.push(makeBox(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y))
1338
1553
  }
1339
- if (props.avoidSelector) {
1340
- for (const element of Array.from(slide.querySelectorAll<HTMLElement>(props.avoidSelector)))
1341
- boxes.push(toLocal(element.getBoundingClientRect()))
1342
- }
1343
- // The labels other annotations have already written. Only the ones from an
1344
- // earlier click count — a later label avoids an earlier one, never the other
1345
- // way round — so two labels can never chase each other across the slide.
1346
- const ourLabel = labelEl.value
1347
- for (const other of Array.from(slide.querySelectorAll<HTMLElement>('.annotation-label.is-placed'))) {
1348
- if (other === ourLabel)
1554
+ return obstacles
1555
+ }
1556
+
1557
+ /** The slide's own laid-out content, scanned once per discrete re-measure. */
1558
+ function contentObstacles(slide: HTMLElement, toLocal: (rect: DOMRect) => Box): Box[] {
1559
+ if (contentObstacleCache)
1560
+ return contentObstacleCache
1561
+ const boxes: Box[] = []
1562
+ for (const element of Array.from(slide.querySelectorAll<HTMLElement>('*'))) {
1563
+ if (element.closest('.annotation-ignore'))
1349
1564
  continue
1350
- const click = Number(other.dataset.click ?? Number.NaN)
1351
- if (!Number.isFinite(click))
1565
+ // A code block or an SVG drawing counts as one opaque box.
1566
+ const aggregate = element.closest('pre, svg')
1567
+ if (aggregate && aggregate !== element)
1352
1568
  continue
1353
- const ours = resolvedLabelClick.value
1354
- const earlier = click < ours
1355
- || (click === ours && !!ourLabel && !!(other.compareDocumentPosition(ourLabel) & Node.DOCUMENT_POSITION_FOLLOWING))
1356
- if (!earlier)
1569
+ const tag = element.tagName.toLowerCase()
1570
+ const isMedia = tag === 'img' || tag === 'video' || tag === 'canvas' || tag === 'svg' || tag === 'pre'
1571
+ // Only leaf-ish boxes obstruct: an element with text of its own keeps its
1572
+ // line, while pure layout containers leave their free space usable.
1573
+ if (!isMedia && !Array.from(element.childNodes).some(node => node.nodeType === Node.TEXT_NODE && node.textContent?.trim()))
1357
1574
  continue
1358
- const rect = other.getBoundingClientRect()
1359
- if (rect.width >= 6 && rect.height >= 6)
1360
- boxes.push(toLocal(rect))
1575
+ const rect = element.getBoundingClientRect()
1576
+ if (rect.width < 2 || rect.height < 2)
1577
+ continue
1578
+ boxes.push(toLocal(rect))
1361
1579
  }
1580
+ contentObstacleCache = boxes
1362
1581
  return boxes
1363
1582
  }
1364
1583
 
1365
- function overlapArea(a: Box, b: Box) {
1366
- const w = Math.min(a.right, b.right) - Math.max(a.left, b.left)
1367
- const h = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)
1368
- return w > 0 && h > 0 ? w * h : 0
1584
+ /** Record this label's placed box for later annotations on the same slide. */
1585
+ function publishPlacedLabel(box: Box) {
1586
+ const slide = slideRoot()
1587
+ const svg = overlay.value
1588
+ if (!slide || !svg)
1589
+ return
1590
+ const slideBox = slide.getBoundingClientRect()
1591
+ const overlayBox = svg.getBoundingClientRect()
1592
+ const topLeft = localPointToSlideFraction({ x: box.left, y: box.top }, slideBox, overlayBox, geometry)
1593
+ const bottomRight = localPointToSlideFraction({ x: box.right, y: box.bottom }, slideBox, overlayBox, geometry)
1594
+ placedLabelRegistry.set(placementToken, {
1595
+ order: placementOrder,
1596
+ click: resolvedLabelClick.value,
1597
+ root: slide,
1598
+ box: { left: topLeft.x, top: topLeft.y, right: bottomRight.x, bottom: bottomRight.y },
1599
+ active: withinRange.value,
1600
+ })
1369
1601
  }
1370
1602
 
1371
1603
  function clamp(value: number, min: number, max: number) {
@@ -1396,20 +1628,37 @@ function backOff(point: { x: number, y: number }, from: { x: number, y: number }
1396
1628
 
1397
1629
  onMounted(async () => {
1398
1630
  mounted = true
1631
+ if (isAnnotationEditorDevelopment && editorRelevant.value && locator.value) {
1632
+ unregisterEditorActions = registerAnnotationEditorActions(locator.value, {
1633
+ isManualConnector: () => !!manualConnector(),
1634
+ toggleConnectorAttachment,
1635
+ persistedGeometry: persistedLabelGeometry,
1636
+ })
1637
+ }
1399
1638
  // Registered synchronously, while the clicks context still accepts it.
1400
1639
  if (manualClicks.value) {
1401
- resolvedClick.value = manualClick(atClick.value, props.on !== undefined ? 'on' : 'at')
1640
+ // No start prop means the annotation is already present at click 0, even
1641
+ // when an enclosing annotation makes its click handling manual.
1642
+ resolvedClick.value = hasExplicitStartClick.value
1643
+ ? manualClick(atClick.value, props.on !== undefined ? 'on' : 'at')
1644
+ : 0
1402
1645
  resolvedLabelClick.value = props.labelAt === undefined
1403
1646
  ? resolvedClick.value
1404
1647
  : manualClick(props.labelAt, 'label-at')
1405
- $clicksContext.register(ownClicks, { delta: 0, max: Math.max(resolvedClick.value, resolvedLabelClick.value) })
1648
+ // A passive annotation observes the click owned by neighbouring Slidev
1649
+ // content. Registering here would make that content's automatic click
1650
+ // sequence advance one extra step.
1651
+ if (!passive.value)
1652
+ $clicksContext.register(ownClicks, { delta: 0, max: Math.max(resolvedClick.value, resolvedLabelClick.value) })
1406
1653
  }
1407
1654
  await nextTick()
1408
1655
  if (!manualClicks.value) {
1409
- // Slidev resolves automatic click ordering in the directive and stores the
1410
- // result on the marker. Reading it here keeps the first painted state
1411
- // unambiguously hidden, unlike styling a v-click element directly.
1412
- resolvedClick.value = markerClick(clickMarker.value)
1656
+ // An unqualified annotation is initial content, not a bare `v-click`.
1657
+ // Explicit `at`/`on` values deliberately retain Slidev's native v-click
1658
+ // parsing and automatic-ordering semantics.
1659
+ resolvedClick.value = hasExplicitStartClick.value
1660
+ ? markerClick(clickMarker.value)
1661
+ : 0
1413
1662
  // A label without a click of its own follows the mark, rather than taking
1414
1663
  // the next click in the slide's automatic ordering.
1415
1664
  resolvedLabelClick.value = props.labelAt === undefined
@@ -1418,10 +1667,35 @@ onMounted(async () => {
1418
1667
  }
1419
1668
  // Navigating backwards remounts the slide. If this click was already reached,
1420
1669
  // render the final state instead of replaying the entrance animation.
1421
- showImmediately.value = $clicks.value >= resolvedClick.value && withinRange.value
1670
+ showImmediately.value = isCurrentSlide.value
1671
+ && $clicks.value >= resolvedClick.value
1672
+ && withinRange.value
1422
1673
  unsettle()
1423
1674
  scheduleUpdate()
1424
1675
 
1676
+ if (isCurrentSlide.value)
1677
+ connectObservers()
1678
+
1679
+ document.fonts?.ready.then(() => {
1680
+ labelSizeCache.clear()
1681
+ scheduleUpdate()
1682
+ })
1683
+ })
1684
+
1685
+ /**
1686
+ * The observers only run while this annotation's slide is current. Every
1687
+ * slide of the deck stays mounted, so without the gate a deck full of
1688
+ * annotations would keep reacting to layout changes on slides nobody is
1689
+ * looking at. Nothing goes stale from being disconnected: becoming current
1690
+ * re-measures everything anyway, in the `isCurrentSlide` watch below.
1691
+ */
1692
+ let observersConnected = false
1693
+
1694
+ function connectObservers() {
1695
+ if (observersConnected || !mounted)
1696
+ return
1697
+ observersConnected = true
1698
+
1425
1699
  resizeObserver = new ResizeObserver(scheduleUpdate)
1426
1700
  if (container.value)
1427
1701
  resizeObserver.observe(container.value)
@@ -1444,48 +1718,575 @@ onMounted(async () => {
1444
1718
  mutationObserver.observe(element, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['style', 'class'] })
1445
1719
  }
1446
1720
 
1447
- document.fonts?.ready.then(scheduleUpdate)
1448
1721
  window.addEventListener('resize', scheduleUpdate)
1449
- })
1722
+ }
1723
+
1724
+ function disconnectObservers() {
1725
+ if (!observersConnected)
1726
+ return
1727
+ observersConnected = false
1728
+ resizeObserver?.disconnect()
1729
+ resizeObserver = undefined
1730
+ mutationObserver?.disconnect()
1731
+ mutationObserver = undefined
1732
+ for (const image of watchedImages.splice(0))
1733
+ image.removeEventListener('load', scheduleUpdate)
1734
+ window.removeEventListener('resize', scheduleUpdate)
1735
+ }
1450
1736
 
1451
1737
  onBeforeUnmount(() => {
1452
1738
  mounted = false
1739
+ unregisterEditorActions?.()
1740
+ unregisterEditorActions = undefined
1741
+ if (locator.value)
1742
+ releaseAnnotationSelection(locator.value)
1743
+ placedLabelRegistry.delete(placementToken)
1744
+ settleRun++
1453
1745
  clearTimeout(exitFadeTimer)
1454
1746
  $clicksContext.unregister(ownClicks)
1455
1747
  cancelAnimationFrame(frame)
1456
1748
  cancelAnimationFrame(paintFrame)
1457
1749
  cancelAnimationFrame(trackFrame)
1458
- resizeObserver?.disconnect()
1459
- mutationObserver?.disconnect()
1460
- for (const image of watchedImages.splice(0))
1461
- image.removeEventListener('load', scheduleUpdate)
1462
- window.removeEventListener('resize', scheduleUpdate)
1750
+ disconnectObservers()
1463
1751
  })
1464
1752
 
1465
1753
  // Magic Move and click transitions are driven by the click count, and both move
1466
1754
  // the annotated element for a while after it changes.
1467
1755
  watch($clicks, () => {
1756
+ // A hidden slide's clicks can move while it is preloaded. Nothing of it is
1757
+ // on screen, and becoming current re-measures everything in the
1758
+ // `isCurrentSlide` watch below, so skip the per-click measurement work.
1759
+ if (!isCurrentSlide.value)
1760
+ return
1468
1761
  unsettle()
1469
- track()
1470
- })
1762
+ track(CLICK_TRACK_DURATION)
1763
+ }, { flush: 'sync' })
1764
+
1765
+ // Preloaded slides can already contain their annotations before navigation
1766
+ // starts, so mount-time detection alone is not enough. Watching this annotation's
1767
+ // active-slide state also covers a preloaded component becoming visible inside
1768
+ // document.startViewTransition(); the grace period lets the browser create the
1769
+ // document-level pseudo-elements before the first animation scan.
1770
+ watch(isCurrentSlide, (current) => {
1771
+ if (current) {
1772
+ connectObservers()
1773
+ unsettle(VIEW_TRANSITION_START_GRACE)
1774
+ track()
1775
+ }
1776
+ else {
1777
+ disconnectObservers()
1778
+ // Cancel in-flight measurement too: a settle pass or tracking loop begun
1779
+ // before navigating away would keep calling updateGeometry on a slide
1780
+ // that is no longer visible. During a transition the outgoing slide moves
1781
+ // (or is snapshotted) as a whole, so its frozen geometry stays correct.
1782
+ settleRun++
1783
+ trackUntil = 0
1784
+ cancelAnimationFrame(trackFrame)
1785
+ trackFrame = 0
1786
+ cancelAnimationFrame(frame)
1787
+ }
1788
+ }, { flush: 'sync' })
1471
1789
 
1472
1790
  // Any prop can change what is drawn or where the label may go, so re-measure
1473
1791
  // on all of them instead of maintaining a list that can silently go stale.
1474
- watch(props, scheduleUpdate)
1792
+ // The caches assume unchanged props, so they are dropped along the way.
1793
+ watch(props, () => {
1794
+ labelSizeCache.clear()
1795
+ lastMarkKey = ''
1796
+ scheduleUpdate()
1797
+ })
1798
+
1799
+ // A draft is applied immediately instead of waiting for source HMR after save.
1800
+ // Connector drags affect only their owning SVG. Label drags also affect labels
1801
+ // that avoid one another, but their shared placement is published only at the
1802
+ // start and end of the gesture rather than once per pointer frame.
1803
+ watch(annotationDraftChange, (change) => {
1804
+ if (change?.locator !== locator.value)
1805
+ return
1806
+ if (change.kind === 'clear') {
1807
+ labelSizeCache.clear()
1808
+ lastMarkKey = ''
1809
+ }
1810
+ scheduleDraftUpdate()
1811
+ })
1812
+ watch(annotationLabelLayoutChange, (change) => {
1813
+ // The dragged label already has its exact on-screen geometry. Re-measuring it
1814
+ // on release would briefly reset it; only dependent labels need a full pass.
1815
+ if (change?.locator === locator.value) {
1816
+ scheduleDraftUpdate()
1817
+ return
1818
+ }
1819
+ labelSizeCache.clear()
1820
+ lastMarkKey = ''
1821
+ scheduleUpdate()
1822
+ })
1823
+
1824
+ const editable = computed(() => isAnnotationEditorDevelopment && !!locator.value && hasLabel.value && labelActive.value && geometry.ready)
1825
+ const connectorEditable = computed(() => isAnnotationEditorDevelopment && !!locator.value && connectsLine.value && active.value && !!geometry.connectorStart && !!geometry.connectorEnd)
1826
+ const selectedForEditing = computed(() => (editable.value || connectorEditable.value) && annotationEditMode.value && selectedAnnotationId.value === locator.value)
1827
+ interface DragSaveSession extends AnnotationUndoSession {
1828
+ /** The source geometry before this gesture's first autosave. */
1829
+ persistedCaptured: boolean
1830
+ persistedBefore?: PersistedAnnotationGeometry | null
1831
+ }
1832
+
1833
+ let labelDrag: ({ pointerId: number, width: boolean, centerX: number, rightOffsetX: number, offsetX: number, offsetY: number, previous?: PersistedAnnotationGeometry } & DragSaveSession) | undefined
1834
+
1835
+ function fraction(value: number) {
1836
+ return Math.max(0, Math.min(1, value))
1837
+ }
1838
+
1839
+ // Labels only suppress Slidev navigation while they are real editor controls.
1840
+ // Outside edit mode they are presentation-only (`pointer-events: none`), but
1841
+ // retaining that boundary here also keeps a transient/stale DOM state from
1842
+ // swallowing an ordinary slide click.
1843
+ function stopEditorClick(event: MouseEvent) {
1844
+ if (annotationEditMode.value && editable.value)
1845
+ event.stopPropagation()
1846
+ }
1847
+
1848
+ function beginLabelDrag(event: PointerEvent, width = false) {
1849
+ if (!editable.value || !annotationEditMode.value || !locator.value)
1850
+ return
1851
+ event.preventDefault()
1852
+ event.stopPropagation()
1853
+ // Keep the selected control in sync with the gesture. In particular, a
1854
+ // width-handle drag must leave the width handle selected so follow-up arrow
1855
+ // presses resize instead of unexpectedly moving the label.
1856
+ selectAnnotation(locator.value, width ? 'width' : 'label')
1857
+ const slide = slideRoot()
1858
+ const label = labelEl.value
1859
+ if (!slide || !label)
1860
+ return
1861
+ const slideBox = slide.getBoundingClientRect()
1862
+ const labelBox = label.getBoundingClientRect()
1863
+ labelDrag = {
1864
+ pointerId: event.pointerId,
1865
+ width,
1866
+ // The label is centre-anchored and a width drag leaves x untouched, so
1867
+ // the centre is the fixed point a new width is measured from; the right
1868
+ // edge moves at half the width change.
1869
+ centerX: labelBox.left + labelBox.width / 2,
1870
+ rightOffsetX: event.clientX - labelBox.right,
1871
+ // Preserve the grab point rather than snapping the label centre to the
1872
+ // pointer on its first move.
1873
+ offsetX: event.clientX - (labelBox.left + labelBox.width / 2),
1874
+ offsetY: event.clientY - (labelBox.top + labelBox.height / 2),
1875
+ previous: annotationDrafts.get(locator.value) ? { ...annotationDrafts.get(locator.value) } : undefined,
1876
+ persistedCaptured: false,
1877
+ }
1878
+ beginAnnotationDraftGesture(locator.value, 'label')
1879
+ ;(event.currentTarget as HTMLElement).setPointerCapture?.(event.pointerId)
1880
+ }
1881
+
1882
+ function moveLabelDrag(event: PointerEvent) {
1883
+ if (!labelDrag || labelDrag.pointerId !== event.pointerId || !locator.value)
1884
+ return
1885
+ event.preventDefault()
1886
+ event.stopPropagation()
1887
+ const slide = slideRoot()
1888
+ if (!slide)
1889
+ return
1890
+ const box = slide.getBoundingClientRect()
1891
+ if (labelDrag.width) {
1892
+ // Keep the handle under the pointer: the grabbed right edge follows the
1893
+ // cursor and the width doubles its distance from the fixed centre.
1894
+ const edge = event.clientX - labelDrag.rightOffsetX
1895
+ setLabelDraft(locator.value, { ...labelPositionSeed(), width: Math.max(.02, Math.min(1, 2 * (edge - labelDrag.centerX) / box.width)) })
1896
+ }
1897
+ else {
1898
+ setLabelDraft(locator.value, {
1899
+ x: fraction((event.clientX - labelDrag.offsetX - box.left) / box.width),
1900
+ y: fraction((event.clientY - labelDrag.offsetY - box.top) / box.height),
1901
+ })
1902
+ }
1903
+ scheduleDraftSave(labelDrag)
1904
+ }
1905
+
1906
+ /** Source HMR updates `geometry`; drafts intentionally remain until the save response is reconciled. */
1907
+
1908
+ let draftSaveTimer: ReturnType<typeof setTimeout> | undefined
1909
+ const savingDraftSignatures = new Set<string>()
1910
+ /** Independent of key order, so a draft compares equal to the same geometry read back from the source. */
1911
+ function draftSignature(geometry: PersistedAnnotationGeometry) {
1912
+ return JSON.stringify([geometry.x, geometry.y, geometry.width, geometry.x1, geometry.y1, geometry.x2, geometry.y2, geometry.cx, geometry.cy].map(value => value ?? null))
1913
+ }
1914
+
1915
+ /** Save during a pause in a long drag as well as on pointer release. */
1916
+ function scheduleDraftSave(session?: DragSaveSession) {
1917
+ clearTimeout(draftSaveTimer)
1918
+ draftSaveTimer = setTimeout(() => {
1919
+ if (locator.value)
1920
+ void saveDraft(locator.value, session)
1921
+ }, 350)
1922
+ }
1923
+
1924
+ async function saveDraft(id: string, session?: DragSaveSession) {
1925
+ const draft = annotationDrafts.get(id)
1926
+ if (!draft)
1927
+ return
1928
+ // This import stays behind a compile-time development guard. Production
1929
+ // decks neither render controls nor include browser write-client code.
1930
+ if (!isAnnotationEditorDevelopment)
1931
+ return
1932
+ const { cachedAnnotationGeometry, saveLabelGeometry } = await loadWriterClient()
1933
+ // Undo must return to what the source holds now: the geometry this tab
1934
+ // last saved (HMR may not have delivered it as a prop yet), otherwise the
1935
+ // authored binding. Store it before replacing it with the new geometry.
1936
+ const previous = cachedAnnotationGeometry(id) ?? persistedLabelGeometry()
1937
+ // The writer replaces the whole binding with what it is sent. A first drag
1938
+ // drafts only the label, so complete it from the source baseline rather than
1939
+ // letting a label move erase the connector or width the source holds.
1940
+ const savedDraft = { ...previous, ...draft }
1941
+ const signature = draftSignature(savedDraft)
1942
+ // There is nothing to write when the source already holds this geometry:
1943
+ // after a completed save, or when a drag ends where it started. Comparing
1944
+ // with the source rather than with the last request keeps a position that
1945
+ // Undo or Reset removed from the source saveable again.
1946
+ if (signature === draftSignature(previous) || savingDraftSignatures.has(signature))
1947
+ return
1948
+ savingDraftSignatures.add(signature)
1949
+ annotationEditorStatus.value = 'Saving annotation…'
1950
+ try {
1951
+ // A long drag may autosave before the pointer is released. Remember the
1952
+ // pre-drag rule before that first request, so Escape can truly cancel the
1953
+ // whole gesture instead of merely hiding a value that HMR has saved.
1954
+ if (session && !session.persistedCaptured) {
1955
+ session.persistedBefore = previous
1956
+ session.persistedCaptured = true
1957
+ }
1958
+ const saved = await saveLabelGeometry(id, savedDraft)
1959
+ // A debounced save and the release save belong to the same pointer
1960
+ // gesture. Record the pre-gesture snapshot once, rather than making Undo
1961
+ // stop at every intermediate autosave position.
1962
+ if (session)
1963
+ recordAnnotationUndoOnce(session, id, session.persistedBefore ?? previous)
1964
+ else
1965
+ recordAnnotationUndo(id, previous)
1966
+ // The writer returns its fixed-four-decimal source snapshot. Keep that
1967
+ // draft visible until Slidev recompiles the rewritten Markdown.
1968
+ const persisted = saved.geometry[id]
1969
+ if (persisted) setLabelDraft(id, persisted)
1970
+ annotationEditorStatus.value = 'Annotation saved'
1971
+ }
1972
+ catch (error) {
1973
+ annotationEditorStatus.value = error instanceof Error ? error.message : 'Unable to save annotation geometry'
1974
+ }
1975
+ finally {
1976
+ savingDraftSignatures.delete(signature)
1977
+ }
1978
+ }
1979
+
1980
+ /**
1981
+ * Switch explicitly between the attached route and a frozen two-endpoint
1982
+ * route. Unlike dragging, this makes the connector state discoverable from
1983
+ * the global toolbar without making the toolbar depend on annotation DOM.
1984
+ */
1985
+ async function toggleConnectorAttachment() {
1986
+ if (!locator.value || !connectorEditable.value)
1987
+ return
1988
+ if (manualConnector()) {
1989
+ annotationEditorStatus.value = 'Restoring automatic connector…'
1990
+ try {
1991
+ const { cachedAnnotationGeometry, resetAnnotationGeometry } = await loadWriterClient()
1992
+ const previous = cachedAnnotationGeometry(locator.value) ?? persistedLabelGeometry()
1993
+ await resetAnnotationGeometry(locator.value, 'connector', previous)
1994
+ recordAnnotationUndo(locator.value, previous)
1995
+ clearLabelDraft(locator.value)
1996
+ annotationEditorStatus.value = 'Connector now follows its source and label'
1997
+ }
1998
+ catch (error) {
1999
+ annotationEditorStatus.value = error instanceof Error ? error.message : 'Unable to restore automatic connector'
2000
+ }
2001
+ return
2002
+ }
2003
+
2004
+ const start = geometry.connectorStart && localConnectorFraction(geometry.connectorStart)
2005
+ const end = geometry.connectorEnd && localConnectorFraction(geometry.connectorEnd)
2006
+ if (!start || !end)
2007
+ return
2008
+ setLabelDraft(locator.value, { x1: start.x, y1: start.y, x2: end.x, y2: end.y })
2009
+ await saveDraft(locator.value)
2010
+ }
2011
+
2012
+ async function endLabelDrag(event: PointerEvent) {
2013
+ if (!labelDrag || labelDrag.pointerId !== event.pointerId || !locator.value)
2014
+ return
2015
+ event.preventDefault()
2016
+ event.stopPropagation()
2017
+ const session = labelDrag
2018
+ labelDrag = undefined
2019
+ endAnnotationDraftGesture(locator.value, 'label')
2020
+ clearTimeout(draftSaveTimer)
2021
+ await saveDraft(locator.value, session)
2022
+ }
2023
+
2024
+ // A pointer cancellation means the browser interrupted the gesture (for
2025
+ // example, a window focus change), not that the author released it. Never turn
2026
+ // that partial movement into a persisted edit.
2027
+ function restoreCancelledDrag(id: string, previous: PersistedAnnotationGeometry | undefined, session: DragSaveSession) {
2028
+ if (previous)
2029
+ setLabelDraft(id, previous)
2030
+ else
2031
+ clearLabelDraft(id)
2032
+ // No request has started, so reverting the local preview is sufficient.
2033
+ if (!session.persistedCaptured) {
2034
+ annotationEditorStatus.value = 'Annotation drag cancelled'
2035
+ return
2036
+ }
2037
+ annotationEditorStatus.value = 'Cancelling annotation drag…'
2038
+ // Keep this dynamic import behind the explicit serve-mode boundary. Slidev's
2039
+ // build renderer can still set DEV, but a published deck must not ship a
2040
+ // browser client capable of reaching the local writer endpoint.
2041
+ if (!isAnnotationEditorDevelopment)
2042
+ return
2043
+ // Writer-client writes are serialized. This restore runs after any autosave
2044
+ // already in flight, preventing source HMR from resurrecting a cancelled drag.
2045
+ void loadWriterClient().then(({ restoreAnnotationGeometry }) =>
2046
+ restoreAnnotationGeometry(id, session.persistedBefore ?? null),
2047
+ ).then(() => {
2048
+ clearLabelDraft(id)
2049
+ annotationEditorStatus.value = 'Annotation drag cancelled'
2050
+ }).catch((error) => {
2051
+ annotationEditorStatus.value = error instanceof Error ? error.message : 'Unable to cancel saved annotation geometry'
2052
+ })
2053
+ }
2054
+
2055
+ function cancelLabelDrag(event: PointerEvent) {
2056
+ if (!labelDrag || labelDrag.pointerId !== event.pointerId || !locator.value)
2057
+ return
2058
+ event.preventDefault()
2059
+ event.stopPropagation()
2060
+ const drag = labelDrag
2061
+ labelDrag = undefined
2062
+ endAnnotationDraftGesture(locator.value, 'label')
2063
+ clearTimeout(draftSaveTimer)
2064
+ restoreCancelledDrag(locator.value, drag.previous, drag)
2065
+ }
2066
+
2067
+ type ConnectorDragKind = 'start' | 'end' | 'body'
2068
+ let connectorDrag: ({ pointerId: number, kind: ConnectorDragKind, startX: number, startY: number, slideBox: DOMRect, connector: { x1: number, y1: number, x2: number, y2: number, cx?: number, cy?: number }, previous?: PersistedAnnotationGeometry } & DragSaveSession) | undefined
2069
+
2070
+ function localConnectorFraction(point: Point) {
2071
+ const slide = slideRoot()
2072
+ const svg = overlay.value
2073
+ if (!slide || !svg)
2074
+ return undefined
2075
+ const local = localPointToSlideFraction(point, slide.getBoundingClientRect(), svg.getBoundingClientRect(), geometry)
2076
+ return { x: fraction(local.x), y: fraction(local.y) }
2077
+ }
2078
+
2079
+ /**
2080
+ * A width-only draft cannot be persisted: the writer's document shape stores
2081
+ * `width` inside `label`, which requires a position. When no position is
2082
+ * known yet, the first width edit materializes the label's current on-screen
2083
+ * position, so the edit survives the save instead of being silently dropped
2084
+ * and snapped back while the status still reports "Annotation saved".
2085
+ */
2086
+ function labelPositionSeed(): PersistedAnnotationGeometry {
2087
+ const draft = draftLabelGeometry()
2088
+ const saved = persistedLabelGeometry()
2089
+ if ((draft?.x ?? saved.x) !== undefined && (draft?.y ?? saved.y) !== undefined)
2090
+ return {}
2091
+ const current = localConnectorFraction({ x: geometry.labelLeft, y: geometry.labelTop })
2092
+ return current ? { x: current.x, y: current.y } : {}
2093
+ }
2094
+
2095
+ function beginConnectorDrag(event: PointerEvent, kind: ConnectorDragKind) {
2096
+ if (!connectorEditable.value || !annotationEditMode.value || !locator.value || !geometry.connectorStart || !geometry.connectorEnd)
2097
+ return
2098
+ const slide = slideRoot()
2099
+ const start = localConnectorFraction(geometry.connectorStart)
2100
+ const end = localConnectorFraction(geometry.connectorEnd)
2101
+ if (!slide || !start || !end)
2102
+ return
2103
+ event.preventDefault()
2104
+ event.stopPropagation()
2105
+ selectAnnotation(locator.value, kind)
2106
+ const saved = manualConnector()
2107
+ connectorDrag = { pointerId: event.pointerId, kind, startX: event.clientX, startY: event.clientY, slideBox: slide.getBoundingClientRect(), connector: { x1: start.x, y1: start.y, x2: end.x, y2: end.y, cx: saved?.cx, cy: saved?.cy }, previous: annotationDrafts.get(locator.value) ? { ...annotationDrafts.get(locator.value) } : undefined, persistedCaptured: false }
2108
+ beginAnnotationDraftGesture(locator.value, 'connector')
2109
+ ;(event.currentTarget as Element).setPointerCapture?.(event.pointerId)
2110
+ }
2111
+
2112
+ function moveConnectorDrag(event: PointerEvent) {
2113
+ if (!connectorDrag || connectorDrag.pointerId !== event.pointerId || !locator.value)
2114
+ return
2115
+ event.preventDefault()
2116
+ event.stopPropagation()
2117
+ const box = connectorDrag.slideBox
2118
+ const dx = (event.clientX - connectorDrag.startX) / box.width
2119
+ const dy = (event.clientY - connectorDrag.startY) / box.height
2120
+ const next = { ...connectorDrag.connector }
2121
+ if (connectorDrag.kind === 'start') {
2122
+ next.x1 = fraction(next.x1 + dx); next.y1 = fraction(next.y1 + dy)
2123
+ }
2124
+ else if (connectorDrag.kind === 'end') {
2125
+ next.x2 = fraction(next.x2 + dx); next.y2 = fraction(next.y2 + dy)
2126
+ }
2127
+ else {
2128
+ // Translate as one rigid line. Constrain the delta rather than its two
2129
+ // endpoints, otherwise a line against a slide edge would shrink as the
2130
+ // pointer kept moving.
2131
+ Object.assign(next, translateConnector(next, dx, dy))
2132
+ }
2133
+ setLabelDraft(locator.value, next)
2134
+ scheduleDraftSave(connectorDrag)
2135
+ }
2136
+
2137
+ async function endConnectorDrag(event: PointerEvent) {
2138
+ if (!connectorDrag || connectorDrag.pointerId !== event.pointerId || !locator.value)
2139
+ return
2140
+ event.preventDefault()
2141
+ event.stopPropagation()
2142
+ const session = connectorDrag
2143
+ connectorDrag = undefined
2144
+ endAnnotationDraftGesture(locator.value, 'connector')
2145
+ clearTimeout(draftSaveTimer)
2146
+ await saveDraft(locator.value, session)
2147
+ }
2148
+
2149
+ function cancelConnectorDrag(event: PointerEvent) {
2150
+ if (!connectorDrag || connectorDrag.pointerId !== event.pointerId || !locator.value)
2151
+ return
2152
+ event.preventDefault()
2153
+ event.stopPropagation()
2154
+ const drag = connectorDrag
2155
+ connectorDrag = undefined
2156
+ endAnnotationDraftGesture(locator.value, 'connector')
2157
+ clearTimeout(draftSaveTimer)
2158
+ restoreCancelledDrag(locator.value, drag.previous, drag)
2159
+ }
2160
+
2161
+ let keyboardSaveTimer: ReturnType<typeof setTimeout> | undefined
2162
+
2163
+ /** Arrow keys nudge the selected label or connector in slide fractions. */
2164
+ function nudgeSelectedAnnotation(event: KeyboardEvent) {
2165
+ if (!annotationEditMode.value || selectedAnnotationId.value !== locator.value || labelDrag || connectorDrag || !locator.value)
2166
+ return
2167
+ if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key))
2168
+ return
2169
+ // Do not steal arrow keys from toolbar controls or a deck's editable text.
2170
+ // The width handle is deliberately a real button for accessibility, but it
2171
+ // is also an annotation control: its focused arrow keys must resize rather
2172
+ // than being discarded by the generic form-control guard.
2173
+ const target = event.target instanceof Element ? event.target : undefined
2174
+ const annotationControl = target?.closest('.annotation-width-handle, .annotation-connector-handle')
2175
+ if (!annotationControl && target?.closest('button, input, textarea, select, [contenteditable="true"]'))
2176
+ return
2177
+
2178
+ const step = event.shiftKey ? .01 : .002
2179
+ const dx = event.key === 'ArrowLeft' ? -step : event.key === 'ArrowRight' ? step : 0
2180
+ const dy = event.key === 'ArrowUp' ? -step : event.key === 'ArrowDown' ? step : 0
2181
+ const part = selectedAnnotationPart.value
2182
+
2183
+ if ((part === 'label' || part === 'width') && editable.value) {
2184
+ if (part === 'width') {
2185
+ // Width is a horizontal dimension. Do not make Up/Down silently resize
2186
+ // a label just because they have no horizontal delta.
2187
+ if (!dx) {
2188
+ event.preventDefault()
2189
+ event.stopPropagation()
2190
+ return
2191
+ }
2192
+ const slide = slideRoot()
2193
+ const label = labelEl.value
2194
+ if (!slide || !label)
2195
+ return
2196
+ // An unbounded label has no saved maximum yet. Materialize the width it
2197
+ // occupies now, so the first key press changes the visible label rather
2198
+ // than jumping to an unrelated default cap.
2199
+ const slideWidth = slide.getBoundingClientRect().width
2200
+ const overlayWidth = overlay.value?.getBoundingClientRect().width
2201
+ if (!overlayWidth)
2202
+ return
2203
+ const currentFraction = geometry.labelWidth === undefined
2204
+ ? label.getBoundingClientRect().width / slideWidth
2205
+ : localLabelWidthToSlideFraction(geometry.labelWidth, geometry.width, overlayWidth, slideWidth)
2206
+ setLabelDraft(locator.value, { ...labelPositionSeed(), width: nudgeLabelWidth(currentFraction, dx) })
2207
+ }
2208
+ else {
2209
+ const current = localConnectorFraction({ x: geometry.labelLeft, y: geometry.labelTop })
2210
+ if (!current)
2211
+ return
2212
+ setLabelDraft(locator.value, { x: fraction(current.x + dx), y: fraction(current.y + dy) })
2213
+ }
2214
+ }
2215
+ else if ((part === 'start' || part === 'end' || part === 'body') && connectorEditable.value && geometry.connectorStart && geometry.connectorEnd) {
2216
+ const start = localConnectorFraction(geometry.connectorStart)
2217
+ const end = localConnectorFraction(geometry.connectorEnd)
2218
+ if (!start || !end)
2219
+ return
2220
+ // Keep arrow-key body movement identical to dragging the line itself:
2221
+ // translation is constrained as one rigid segment at slide edges.
2222
+ const saved = manualConnector()
2223
+ const base = {
2224
+ x1: start.x,
2225
+ y1: start.y,
2226
+ x2: end.x,
2227
+ y2: end.y,
2228
+ ...(saved?.cx !== undefined && saved.cy !== undefined ? { cx: saved.cx, cy: saved.cy } : {}),
2229
+ }
2230
+ const translated = nudgeConnector(base, part, dx, dy)
2231
+ setLabelDraft(locator.value, { ...translated } satisfies PersistedAnnotationGeometry)
2232
+ }
2233
+ else {
2234
+ return
2235
+ }
2236
+
2237
+ event.preventDefault()
2238
+ event.stopPropagation()
2239
+ // One debounce is intentional. Reusing the pointer-drag timer here creates
2240
+ // two writes for one key press; after a 409 the second would adopt the
2241
+ // conflict response's revision and overwrite the other author's geometry.
2242
+ clearTimeout(keyboardSaveTimer)
2243
+ keyboardSaveTimer = setTimeout(() => void saveDraft(locator.value!), 250)
2244
+ }
2245
+
2246
+ function cancelActiveDrag(event: KeyboardEvent) {
2247
+ if (event.key !== 'Escape' || (!labelDrag && !connectorDrag) || !locator.value)
2248
+ return
2249
+ event.preventDefault()
2250
+ event.stopPropagation()
2251
+ const drag = labelDrag ?? connectorDrag
2252
+ const dragKind = labelDrag ? 'label' as const : 'connector' as const
2253
+ labelDrag = undefined
2254
+ connectorDrag = undefined
2255
+ endAnnotationDraftGesture(locator.value, dragKind)
2256
+ clearTimeout(draftSaveTimer)
2257
+ restoreCancelledDrag(locator.value, drag?.previous, drag!)
2258
+ }
2259
+
2260
+ onMounted(() => {
2261
+ window.addEventListener('keydown', cancelActiveDrag, true)
2262
+ window.addEventListener('keydown', nudgeSelectedAnnotation, true)
2263
+ })
2264
+ onBeforeUnmount(() => {
2265
+ window.removeEventListener('keydown', cancelActiveDrag, true)
2266
+ window.removeEventListener('keydown', nudgeSelectedAnnotation, true)
2267
+ clearTimeout(keyboardSaveTimer)
2268
+ clearTimeout(draftSaveTimer)
2269
+ })
1475
2270
  </script>
1476
2271
 
1477
2272
  <template>
1478
- <div ref="container" class="drawn-annotation" :class="{ 'is-fading-out': fadingOut }">
2273
+ <div
2274
+ ref="container"
2275
+ class="drawn-annotation"
2276
+ :class="{ 'is-fading-out': fadingOut }"
2277
+ >
1479
2278
  <!-- The marker takes part in Slidev's click ordering while component state
1480
2279
  drives the drawing. This avoids a mount-time v-click class race. -->
1481
- <span ref="clickMarker" v-click="manualClicks ? false : atClick" class="click-marker annotation-ignore" />
2280
+ <span ref="clickMarker" v-click="manualClicks || !hasExplicitStartClick ? false : atClick" class="click-marker annotation-ignore" />
1482
2281
  <span v-if="props.labelAt !== undefined" ref="labelMarker" v-click="manualClicks ? false : props.labelAt" class="click-marker annotation-ignore" />
1483
2282
  <svg
1484
2283
  ref="overlay"
1485
2284
  class="annotation-overlay annotation-ignore"
1486
2285
  :viewBox="`0 0 ${geometry.width} ${geometry.height}`"
1487
2286
  preserveAspectRatio="none"
1488
- aria-hidden="true"
2287
+ :aria-hidden="!(connectorEditable && annotationEditMode)"
2288
+ :role="connectorEditable && annotationEditMode ? 'group' : undefined"
2289
+ :aria-label="connectorEditable && annotationEditMode ? `Connector editor for ${locator}` : undefined"
1489
2290
  :style="{
1490
2291
  '--annotation-color': props.color,
1491
2292
  '--annotation-width': `${props.strokeWidth}px`,
@@ -1538,13 +2339,58 @@ watch(props, scheduleUpdate)
1538
2339
  />
1539
2340
  </g>
1540
2341
  </template>
2342
+ <!-- Development-only hit targets deliberately live in the shared SVG
2343
+ canvas, so their coordinates match the persisted connector. -->
2344
+ <g
2345
+ v-if="connectorEditable && annotationEditMode && geometry.connectorStart && geometry.connectorEnd"
2346
+ class="annotation-connector-editor"
2347
+ @click.stop
2348
+ >
2349
+ <line
2350
+ class="annotation-connector-hit"
2351
+ :x1="geometry.connectorStart.x" :y1="geometry.connectorStart.y"
2352
+ :x2="geometry.connectorEnd.x" :y2="geometry.connectorEnd.y"
2353
+ role="button"
2354
+ tabindex="0"
2355
+ aria-label="Move connector"
2356
+ @focus="selectAnnotation(locator!, 'body')"
2357
+ @pointerdown="beginConnectorDrag($event, 'body')"
2358
+ @pointermove="moveConnectorDrag"
2359
+ @pointerup="endConnectorDrag"
2360
+ @pointercancel="cancelConnectorDrag"
2361
+ />
2362
+ <circle
2363
+ v-for="(point, index) in [geometry.connectorStart, geometry.connectorEnd]"
2364
+ :key="index"
2365
+ class="annotation-connector-handle"
2366
+ :cx="point.x" :cy="point.y" r="9"
2367
+ :aria-label="index ? 'Move connector end' : 'Move connector start'"
2368
+ role="button"
2369
+ tabindex="0"
2370
+ @focus="selectAnnotation(locator!, index ? 'end' : 'start')"
2371
+ @pointerdown.stop="beginConnectorDrag($event, index ? 'end' : 'start')"
2372
+ @pointermove="moveConnectorDrag"
2373
+ @pointerup="endConnectorDrag"
2374
+ @pointercancel="cancelConnectorDrag"
2375
+ />
2376
+ </g>
1541
2377
  </svg>
2378
+ <!-- In authoring mode the label itself is the keyboard target for moving
2379
+ it. It must not remain aria-hidden: otherwise the selected width
2380
+ handle nested below is invisible to assistive technology. Outside
2381
+ that development-only mode the positioned copy stays presentation
2382
+ only; the live region after the slot announces its text instead. -->
1542
2383
  <div
1543
2384
  v-if="hasLabel"
1544
2385
  ref="labelEl"
1545
2386
  class="annotation-label annotation-ignore"
1546
- :class="{ 'is-active': labelActive && geometry.ready, 'is-placed': geometry.labelPlaced }"
2387
+ :class="{ 'is-active': labelActive && geometry.ready, 'is-placed': geometry.labelPlaced, 'is-editable': editable && annotationEditMode, 'is-selected-for-editing': selectedForEditing }"
1547
2388
  :data-click="resolvedLabelClick"
2389
+ @pointerdown="beginLabelDrag($event)"
2390
+ @pointermove="moveLabelDrag"
2391
+ @pointerup="endLabelDrag"
2392
+ @pointercancel="cancelLabelDrag"
2393
+ @click="stopEditorClick"
1548
2394
  :style="{
1549
2395
  '--annotation-color': props.color,
1550
2396
  '--label-delay': `${delays.label}ms`,
@@ -1553,11 +2399,36 @@ watch(props, scheduleUpdate)
1553
2399
  'top': `${geometry.labelTop}px`,
1554
2400
  'maxWidth': geometry.labelWidth === undefined ? undefined : `${geometry.labelWidth}px`,
1555
2401
  }"
1556
- aria-hidden="true"
2402
+ :tabindex="editable && annotationEditMode ? 0 : undefined"
2403
+ :aria-label="editable && annotationEditMode ? `Move annotation label ${locator}` : undefined"
2404
+ :aria-hidden="!(editable && annotationEditMode)"
2405
+ @focus="selectAnnotation(locator!, 'label')"
1557
2406
  >
1558
- {{ props.label }}
2407
+ <!-- MarkdownIt has HTML disabled in `labelHtml`, so this remains safe
2408
+ while allowing authored inline code and block quotes. -->
2409
+ <div class="annotation-label-content" v-html="labelHtml" />
2410
+ <button
2411
+ v-if="selectedForEditing"
2412
+ class="annotation-width-handle"
2413
+ type="button"
2414
+ aria-label="Resize annotation label"
2415
+ title="Drag to resize label"
2416
+ @pointerdown.stop="beginLabelDrag($event, true)"
2417
+ @pointermove="moveLabelDrag"
2418
+ @pointerup="endLabelDrag"
2419
+ @pointercancel="cancelLabelDrag"
2420
+ @focus.stop="selectAnnotation(locator!, 'width')"
2421
+ />
1559
2422
  </div>
1560
2423
  <slot />
2424
+ <!-- Keep the live region mounted so screen readers announce the label when
2425
+ its click is reached. The positioned copy is presentation-only. -->
2426
+ <span
2427
+ class="annotation-label-status annotation-ignore"
2428
+ role="status"
2429
+ aria-live="polite"
2430
+ aria-atomic="true"
2431
+ >{{ labelActive && geometry.ready ? labelText : '' }}</span>
1561
2432
  </div>
1562
2433
  </template>
1563
2434
 
@@ -1572,6 +2443,14 @@ watch(props, scheduleUpdate)
1572
2443
  Slidev hides them when no annotation is in the way. */
1573
2444
  .drawn-annotation.slidev-vclick-hidden { visibility: hidden; }
1574
2445
  .click-marker { position: absolute; width: 0; height: 0; overflow: hidden; }
2446
+ .annotation-label-status {
2447
+ position: absolute;
2448
+ width: 1px;
2449
+ height: 1px;
2450
+ overflow: hidden;
2451
+ clip-path: inset(50%);
2452
+ white-space: nowrap;
2453
+ }
1575
2454
 
1576
2455
  .annotation-overlay {
1577
2456
  position: absolute;
@@ -1599,8 +2478,8 @@ watch(props, scheduleUpdate)
1599
2478
  made them disappear much more harshly than the content around them.
1600
2479
  `--exit-fade` mirrors the EXIT_FADE_DURATION constant in the script. */
1601
2480
  transition:
1602
- stroke-dashoffset 1ms linear var(--exit-fade, 280ms),
1603
- opacity var(--exit-fade, 280ms) ease-out;
2481
+ stroke-dashoffset 1ms linear var(--exit-fade, 300ms),
2482
+ opacity var(--exit-fade, 300ms) ease-out;
1604
2483
  }
1605
2484
 
1606
2485
  .is-active .annotation-mark {
@@ -1648,9 +2527,26 @@ watch(props, scheduleUpdate)
1648
2527
  pointer-events: none;
1649
2528
  opacity: 0;
1650
2529
  visibility: hidden;
1651
- transition: opacity var(--label-fade, 240ms) ease-out;
2530
+ transition: opacity var(--label-fade, 250ms) ease-out;
1652
2531
  }
1653
2532
 
2533
+ /* MarkdownIt wraps ordinary text in a paragraph. Reset the layout defaults
2534
+ inherited from `.slidev-layout`, otherwise its margins distort label
2535
+ measurement and placement. `v-html` children do not receive Vue's scoped
2536
+ attribute, so the descendant selectors intentionally remain deep. */
2537
+ .annotation-label-content > :first-child { margin-top: 0; }
2538
+ .annotation-label-content > :last-child { margin-bottom: 0; }
2539
+ .annotation-label-content :deep(p) { margin: 0; }
2540
+ .annotation-label-content :deep(code),
2541
+ .annotation-label-content :deep(pre),
2542
+ .annotation-label-content :deep(blockquote) {
2543
+ font-family: var(--drawn-annotation-code-font, var(--slidev-code-font-family, 'JetBrains Mono Local', 'JetBrains Mono', ui-monospace, monospace));
2544
+ }
2545
+
2546
+ /* Inline Markdown code should read as part of the handwritten label, rather
2547
+ than carrying the code-chip background supplied by the slide theme. */
2548
+ .annotation-label-content :deep(code) { background: transparent; }
2549
+
1654
2550
  /* Measured before it is placed, so keep it laid out but invisible until then. */
1655
2551
  .annotation-label.is-placed { visibility: visible; }
1656
2552
 
@@ -1659,6 +2555,39 @@ watch(props, scheduleUpdate)
1659
2555
  transition-delay: var(--label-delay);
1660
2556
  }
1661
2557
 
2558
+ /* Enabled only in Vite development by Alt+Shift+A. */
2559
+ .annotation-label.is-editable { pointer-events: auto; cursor: grab; }
2560
+ .annotation-label.is-editable:active { cursor: grabbing; }
2561
+ .annotation-label.is-selected-for-editing { outline: 1px dashed currentColor; outline-offset: 6px; }
2562
+ .annotation-width-handle {
2563
+ position: absolute;
2564
+ right: -12px;
2565
+ top: 50%;
2566
+ width: 12px;
2567
+ height: 28px;
2568
+ transform: translateY(-50%);
2569
+ padding: 0;
2570
+ border: 2px solid currentColor;
2571
+ border-radius: 3px;
2572
+ background: Canvas;
2573
+ cursor: ew-resize;
2574
+ }
2575
+ .annotation-connector-editor { pointer-events: auto; }
2576
+ .annotation-connector-hit {
2577
+ stroke: transparent;
2578
+ stroke-width: 24px;
2579
+ cursor: move;
2580
+ }
2581
+ .annotation-connector-handle {
2582
+ fill: Canvas;
2583
+ stroke: currentColor;
2584
+ stroke-width: 2px;
2585
+ cursor: crosshair;
2586
+ }
2587
+ @media print {
2588
+ .annotation-width-handle { display: none; }
2589
+ }
2590
+
1662
2591
  @media (prefers-reduced-motion: reduce) {
1663
2592
  .annotation-stroke,
1664
2593
  .annotation-label {