slidev-theme-kotlin 0.11.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 (34) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +87 -10
  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 +1106 -456
  7. package/components/DrawnAnnotationEditorLauncher.vue +50 -0
  8. package/components/DrawnAnnotationEditorToolbar.vue +264 -0
  9. package/components/InlineCompilerError.vue +57 -67
  10. package/components/Kodee.vue +60 -77
  11. package/components/KodeeWrapper.vue +11 -27
  12. package/components/MagicMoveBetween.vue +276 -0
  13. package/components/README.md +126 -46
  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 +22 -5
  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/setup/code-window-icon.ts +4 -0
  29. package/setup/magic-move-between.ts +191 -0
  30. package/setup/preparser.ts +24 -0
  31. package/setup/transformers.ts +190 -2
  32. package/styles/fonts.css +59 -0
  33. package/styles/index.ts +2 -0
  34. package/styles/layout.css +56 -0
@@ -1,97 +1,20 @@
1
1
  <script lang="ts">
2
- // Module scope, shared by every annotation instance. Several annotations on
3
- // one slide all measure the same content on the same animation frame while a
4
- // Magic Move step or a transition is travelling; scanning the slide once per
5
- // frame and letting each instance convert the shared viewport rects into its
6
- // own coordinates removes the most expensive duplicated work.
7
-
8
- // Elements considered while measuring obstacles, capped: the collectors run on
9
- // animation frames while the slide moves, and a slide with more elements than
10
- // this has no room for an automatic label anyway.
11
- const OBSTACLE_ELEMENT_CAP = 600
12
- const MEDIA_TAGS = ['IMG', 'VIDEO', 'CANVAS', 'SVG']
13
-
14
2
  /**
15
- * Elements whose whole box matters to label placement, not just their rendered
16
- * text: a label must not land in the padding of a card or in code-window
17
- * chrome. `.card` and `.kodee-character` are the Kotlin theme's callouts and
18
- * mascot.
19
- *
20
- * Code surfaces deliberately are not in this list. Their rendered code lines
21
- * are still text obstacles, but their unused body is a useful, readable place
22
- * for a short explanation. The title/tab strip remains a whole-box obstacle:
23
- * a label in that chrome looks like a broken window title rather than a note.
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.
24
8
  */
25
- const BLOCK_OBSTACLES = '.slidev-code-block-title, .slidev-code-group-tabs, .card, table, blockquote, .kodee-character'
26
-
27
- function isMedia(element: HTMLElement) {
28
- return MEDIA_TAGS.includes(element.tagName.toUpperCase())
29
- }
30
-
31
- /**
32
- * The slide elements obstacle collection looks at. Excludes annotation
33
- * strokes and labels, content still hidden behind a later click, and the
34
- * internals of inline SVGs — parts of an illustration do not count on their
35
- * own; the whole graphic does.
36
- */
37
- function obstacleCandidates(slide: HTMLElement): HTMLElement[] {
38
- return Array.from(slide.querySelectorAll<HTMLElement>('*'))
39
- .slice(0, OBSTACLE_ELEMENT_CAP)
40
- .filter(element => !element.closest('.annotation-ignore, .slidev-vclick-hidden')
41
- && !element.parentElement?.closest('svg'))
42
- }
43
-
44
- /** One slide scan, in viewport coordinates, valid for the current frame. */
45
- interface ObstacleScan {
46
- /** Whole boxes of images, videos, canvases and inline SVG roots. */
47
- media: DOMRect[]
48
- /** Whole boxes of BLOCK_OBSTACLES elements, padding included. */
49
- blocks: DOMRect[]
50
- /** Tight boxes of the rendered text lines. */
51
- texts: DOMRect[]
52
- }
53
-
54
- const scanCache = new Map<HTMLElement, ObstacleScan>()
55
-
56
- function scanObstacles(slide: HTMLElement): ObstacleScan {
57
- const cached = scanCache.get(slide)
58
- if (cached)
59
- return cached
60
-
61
- const scan: ObstacleScan = { media: [], blocks: [], texts: [] }
62
- for (const element of obstacleCandidates(slide)) {
63
- if (isMedia(element)) {
64
- const rect = element.getBoundingClientRect()
65
- if (rect.width >= 6 && rect.height >= 6)
66
- scan.media.push(rect)
67
- continue
68
- }
69
- if (element.matches(BLOCK_OBSTACLES)) {
70
- const rect = element.getBoundingClientRect()
71
- if (rect.width >= 6 && rect.height >= 6)
72
- scan.blocks.push(rect)
73
- }
74
- // Read direct text nodes from every element rather than only using leaf
75
- // element boxes. A list item commonly contains both plain text and a <b>
76
- // target; its plain text otherwise disappears from the obstacle map.
77
- for (const node of Array.from(element.childNodes)) {
78
- if (node.nodeType !== Node.TEXT_NODE || !node.nodeValue?.trim())
79
- continue
80
- const range = document.createRange()
81
- range.selectNodeContents(node)
82
- for (const rect of Array.from(range.getClientRects())) {
83
- if (rect.width >= 4 && rect.height >= 4)
84
- scan.texts.push(rect)
85
- }
86
- }
87
- }
88
-
89
- scanCache.set(slide, scan)
90
- // The scan stays valid until the next frame paints: annotations measuring in
91
- // the same frame reuse it, and nothing they draw is part of it.
92
- requestAnimationFrame(() => scanCache.delete(slide))
93
- return scan
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
94
15
  }
16
+ const placedLabelRegistry = new Map<symbol, PlacedLabelRecord>()
17
+ let nextPlacementOrder = 0
95
18
  </script>
96
19
 
97
20
  <script setup lang="ts">
@@ -99,12 +22,32 @@ import type { Options as RoughOptions } from 'roughjs/bin/core'
99
22
  import type { ClicksContext } from '@slidev/types'
100
23
  import type { ComputedRef, InjectionKey, Ref } from 'vue'
101
24
  import { injectLocal } from '@vueuse/core'
102
- import { useSlideContext } from '@slidev/client'
25
+ import { useIsSlideActive, useSlideContext } from '@slidev/client'
103
26
  // The explicit `.ts` extension is required: Slidev's client ships bare TypeScript
104
27
  // sources, and the bundler resolves this subpath literally.
105
28
  import { injectionClicksContext } from '@slidev/client/constants.ts'
106
29
  import rough from 'roughjs'
107
- 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
+ }
108
51
 
109
52
  /**
110
53
  * Hand-drawn annotation for anything on a slide.
@@ -115,10 +58,15 @@ import { computed, nextTick, onBeforeUnmount, onMounted, provide, reactive, ref,
115
58
  * to a second element on the slide or to a text label.
116
59
  *
117
60
  * A label is placed out of the slide's normal flow: its position is searched at
118
- * runtime so it never overlaps other content — nor the labels other annotations
119
- * wrote on earlier clicks — preferring downwards for marks in the upper half of
120
- * the slide and upwards for marks in the lower half. Pass
121
- * `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.
122
70
  *
123
71
  * Annotations nest, and two that share a click draw one after the other: the
124
72
  * inner one starts when the one around it has finished, so "point at it, then
@@ -137,6 +85,10 @@ import { computed, nextTick, onBeforeUnmount, onMounted, provide, reactive, ref,
137
85
  type MarkType = 'circle' | 'underline' | 'box' | 'strike-through' | 'none'
138
86
 
139
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
140
92
  /** Shape drawn on the source. Kept as the short form of `sourceType`. */
141
93
  type?: MarkType
142
94
  /** Shape drawn on the source. Overrides `type` when supplied. */
@@ -145,8 +97,8 @@ const props = withDefaults(defineProps<{
145
97
  selector?: string
146
98
  /** Exact text to annotate inside the slot. Works inside Shiki and Magic Move. */
147
99
  text?: string
148
- /** Which occurrence of `text` to annotate, 1-based. */
149
- occurrence?: number
100
+ /** Which occurrence of `text` to annotate, 1-based. Markdown attributes arrive as strings. */
101
+ occurrence?: number | string
150
102
  /** Mark every visual line of a wrapped or multi-line match. */
151
103
  multiline?: boolean
152
104
  /** Extra space between the annotated box and the mark, in slide pixels. */
@@ -162,20 +114,15 @@ const props = withDefaults(defineProps<{
162
114
  targetType?: MarkType
163
115
  /** Show the default target circle when `targetType` is omitted. */
164
116
  targetMark?: boolean
165
- /** Text label. Placed automatically unless `labelX` / `labelY` are given. */
117
+ /** Markdown text label. Placed automatically unless geometry supplies a position. */
166
118
  label?: string
167
- /** Label centre, as a percentage of the slide. Disables automatic placement. */
168
- labelX?: number
169
- labelY?: number
170
- /** Optional maximum label width in slide pixels, before it wraps. */
171
- labelWidth?: number
172
119
  /** Preferred side for automatic placement. `auto` picks by vertical position. */
173
120
  placement?: 'auto' | 'up' | 'down' | 'left' | 'right'
174
121
  /** Smallest distance between the mark and the label, in slide pixels. */
175
122
  gap?: number
176
- /** Space the label keeps from everything else on the slide. */
123
+ /** Space an automatically placed label keeps from its obstacles, in slide pixels. */
177
124
  clearance?: number
178
- /** Extra elements the label must not cover. */
125
+ /** Extra elements an automatically placed label must not cover. */
179
126
  avoidSelector?: string
180
127
  /** Draw the leader line between the mark and the label or target. */
181
128
  connect?: boolean
@@ -205,13 +152,19 @@ const props = withDefaults(defineProps<{
205
152
  /** How long drawing one stage takes, in milliseconds. */
206
153
  duration?: number
207
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
208
161
  /**
209
162
  * Start drawing only once the annotation this one sits inside has finished,
210
163
  * when the two share a click. That is what turns "point at it, then circle
211
164
  * it" into a single reveal instead of two clicks, without anyone having to
212
165
  * time it by hand. Turn off to draw both at once.
213
166
  */
214
- sequential?: boolean
167
+ sequential?: boolean | string
215
168
  /**
216
169
  * Click that takes the annotation away again, so it only belongs to the
217
170
  * steps it describes. Exclusive, like the end of a `v-click` range: with
@@ -246,6 +199,8 @@ const props = withDefaults(defineProps<{
246
199
  /** Follow the annotated element while Magic Move or a transition animates it. */
247
200
  track?: boolean
248
201
  }>(), {
202
+ geometry: undefined,
203
+ __drawnAnnotationLocator: undefined,
249
204
  type: 'underline',
250
205
  sourceType: undefined,
251
206
  selector: '[data-annotate]',
@@ -260,9 +215,6 @@ const props = withDefaults(defineProps<{
260
215
  targetType: undefined,
261
216
  targetMark: true,
262
217
  label: undefined,
263
- labelX: undefined,
264
- labelY: undefined,
265
- labelWidth: undefined,
266
218
  placement: 'auto',
267
219
  gap: 28,
268
220
  clearance: 16,
@@ -280,6 +232,7 @@ const props = withDefaults(defineProps<{
280
232
  duration: 500,
281
233
  sequential: true,
282
234
  at: undefined,
235
+ passive: false,
283
236
  until: undefined,
284
237
  on: undefined,
285
238
  insert: false,
@@ -361,7 +314,12 @@ const resolvedPlacement = computed(() => {
361
314
  // The label and the target each drive several stages, so their presence is
362
315
  // decided once, and an empty string counts as absent everywhere.
363
316
  const hasLabel = computed(() => !!props.label)
317
+ const labelHtml = computed(() => renderAnnotationLabel(props.label ?? ''))
318
+ const labelText = computed(() => annotationLabelText(props.label ?? ''))
364
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))
365
323
 
366
324
  if (props.on !== undefined && (props.at !== undefined || props.until !== undefined))
367
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`.')
@@ -374,6 +332,27 @@ const labelMarker = ref<HTMLElement>()
374
332
  const overlay = ref<SVGSVGElement>()
375
333
  const labelEl = ref<HTMLElement>()
376
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
+
377
356
  // The mark and the label can share one click or be spread over two, which is
378
357
  // what makes "mark it, then name it" possible from Markdown.
379
358
  const resolvedClick = ref(Number.POSITIVE_INFINITY)
@@ -389,21 +368,25 @@ const showImmediately = ref(false)
389
368
  // own clicks context reaches nested components the same way.
390
369
  const outerClicksContext = injectLocal(realClicksKey, null)
391
370
  const slideContext = useSlideContext()
392
- const $nav = slideContext.$nav
393
371
  const $clicksContext = outerClicksContext ?? slideContext.$clicksContext
394
372
  const $clicks = toRef($clicksContext, 'current')
395
373
  // Slidev mounts the previous and next slides ahead of time. An annotation on
396
374
  // one of those hidden slides must not paint before that slide becomes current,
397
375
  // otherwise the view-transition snapshot captures the finished mark.
398
- const isCurrentSlide = computed(() => slideContext.$page.value === $nav.value.currentSlideNo)
376
+ const isCurrentSlide = useIsSlideActive()
399
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)
400
382
  // Slidev's click ordering runs in the context the markers are rendered in, and
401
383
  // that one is shifted here. So these annotations resolve and register their
402
384
  // clicks themselves, from the numbers on the props.
403
385
  // Slidev deliberately normalizes `v-click="0"` to click 1. Resolve an
404
386
  // annotation on click 0 ourselves so it can be present before the first click.
405
- const startsOnInitialSlide = computed(() => Number(atClick.value) === 0)
406
- 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)
407
390
  const painted = computed(() => geometryPainted.value || showImmediately.value)
408
391
  // True once the animations triggered by the current click have finished.
409
392
  // Drawing is held back until then, so a mark never appears on top of a Magic
@@ -506,7 +489,10 @@ const outerSequence = injectLocal(sequenceKey, null)
506
489
  // annotation sharing the enclosing one's click waits for it: one that has a
507
490
  // click of its own is already a step later, and starts straight away.
508
491
  const sequenceStart = computed(() => {
509
- 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)
510
496
  return 0
511
497
  return outerSequence.click.value === resolvedClick.value ? outerSequence.end.value : 0
512
498
  })
@@ -581,6 +567,9 @@ const geometry = reactive({
581
567
  // assigned only when fitting it on the slide requires wrapping.
582
568
  labelWidth: undefined as number | undefined,
583
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,
584
573
  ready: false,
585
574
  })
586
575
 
@@ -716,7 +705,7 @@ function padBox(box: Box, padding: number) {
716
705
  * starts and ends in different nodes. The number of matches is reported either
717
706
  * way, so a miss can be explained rather than silently swallowed.
718
707
  */
719
- 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 } {
720
709
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
721
710
  acceptNode(node) {
722
711
  const parent = node.nodeType === Node.TEXT_NODE ? node.parentElement : node as HTMLElement
@@ -724,68 +713,30 @@ function textRange(root: HTMLElement, needle: string, occurrence: number): { ran
724
713
  // a match is never made against text that is on its way off the slide.
725
714
  if (!parent || parent.closest('svg, .annotation-ignore, .shiki-magic-move-leave, .shiki-magic-move-leave-to'))
726
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.
727
719
  if (node.nodeType === Node.ELEMENT_NODE)
728
- return (node as HTMLElement).tagName === 'BR' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP
729
- 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
730
722
  },
731
723
  })
732
724
 
733
725
  // Magic Move renders line breaks as <br> instead of newline characters, so
734
726
  // they are folded back into the searched text to keep line-aware matches
735
727
  // working in both kinds of code block.
736
- const segments: { node?: Text, text: string }[] = []
737
- let value = ''
728
+ const segments: TextSegment[] = []
738
729
  let node: Node | null
739
730
  // eslint-disable-next-line no-cond-assign
740
731
  while ((node = walker.nextNode())) {
741
- const segment = node.nodeType === Node.TEXT_NODE
732
+ segments.push(node.nodeType === Node.TEXT_NODE
742
733
  ? { node: node as Text, text: (node as Text).data }
743
- : { text: '\n' }
744
- segments.push(segment)
745
- value += segment.text
734
+ : { text: '\n' })
746
735
  }
747
736
 
748
- const starts: number[] = []
749
- for (let index = value.indexOf(needle); index >= 0; index = value.indexOf(needle, index + 1))
750
- starts.push(index)
751
- const start = starts[Math.max(1, occurrence) - 1]
752
- if (start === undefined)
753
- return { matches: starts.length }
754
-
755
- const end = start + needle.length
756
- let offset = 0
757
- let startNode: Text | undefined
758
- let endNode: Text | undefined
759
- let startOffset = 0
760
- let endOffset = 0
761
- for (const segment of segments) {
762
- const next = offset + segment.text.length
763
- if (segment.node) {
764
- if (!startNode && start >= offset && start < next) {
765
- startNode = segment.node
766
- startOffset = start - offset
767
- }
768
- if (startNode && end > offset && end <= next) {
769
- endNode = segment.node
770
- endOffset = end - offset
771
- break
772
- }
773
- // A match that ends on a line break ends inside a <br>, which cannot hold
774
- // a range boundary. Trail the last real node the match covered instead.
775
- if (startNode && end > next) {
776
- endNode = segment.node
777
- endOffset = segment.text.length
778
- }
779
- }
780
- offset = next
781
- }
782
- if (!startNode || !endNode)
783
- return { matches: starts.length }
784
-
785
- const range = document.createRange()
786
- range.setStart(startNode, startOffset)
787
- range.setEnd(endNode, endOffset)
788
- 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 }
789
740
  }
790
741
 
791
742
  function slideRoot() {
@@ -799,9 +750,15 @@ let paintFrame = 0
799
750
  let trackFrame = 0
800
751
  let trackUntil = 0
801
752
  let mounted = false
753
+ let unregisterEditorActions: (() => void) | undefined
802
754
  // Fingerprint of the mark's last measured boxes. While the slide animates, a
803
755
  // frame in which the mark has not moved recomputes nothing.
804
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
805
762
  // The images whose load re-measures geometry, kept so unmount removes exactly
806
763
  // the listeners that were added.
807
764
  const watchedImages: HTMLImageElement[] = []
@@ -888,9 +845,11 @@ async function settleAfterAnimations(run: number, grace = 0) {
888
845
  */
889
846
  function unsettle(grace = 0) {
890
847
  const run = ++settleRun
891
- // A click can restyle the slide, so measured label sizes go stale here —
892
- // once per click, which leaves them shared by every frame of the animation.
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.
893
851
  labelSizeCache.clear()
852
+ contentObstacleCache = undefined
894
853
  if (!props.wait || !props.track) {
895
854
  settled.value = true
896
855
  return
@@ -903,6 +862,17 @@ function unsettle(grace = 0) {
903
862
  function scheduleUpdate() {
904
863
  // Late asynchronous callers — a font that finishes loading, an image that
905
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() {
906
876
  if (!mounted)
907
877
  return
908
878
  cancelAnimationFrame(frame)
@@ -960,17 +930,17 @@ function explainMissing(match?: { range?: Range, matches: number }) {
960
930
  if (everFound || !missingIsAnError.value)
961
931
  return
962
932
  if (!props.text)
963
- 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.`)
964
934
  else if (!match || match.matches === 0)
965
- 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.`)
966
- 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)))
967
937
  warn(`Text "${props.text}" ${match.matches === 1 ? 'matches only once' : `matches only ${match.matches} times`}, but \`occurrence\` asks for match ${props.occurrence}.`)
968
938
  else
969
939
  warn(`Text "${props.text}" was found, but has no size on screen right now, so there is nothing to draw around.`)
970
940
  }
971
941
 
972
942
  function updateGeometry() {
973
- const root = container.value
943
+ const root = searchRoot()
974
944
  const svg = overlay.value
975
945
  if (!root || !svg)
976
946
  return
@@ -1000,7 +970,9 @@ function updateGeometry() {
1000
970
  )
1001
971
 
1002
972
  const match = props.text ? textRange(root, props.text, props.occurrence) : undefined
1003
- 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
1004
976
  const rects = match?.range
1005
977
  ? Array.from(match.range.getClientRects()).filter(rect => rect.width > 0.5 && rect.height > 0.5)
1006
978
  : source
@@ -1103,6 +1075,8 @@ function paintDestination(
1103
1075
  toLocal: (rect: DOMRect) => Box,
1104
1076
  marked: Box,
1105
1077
  ) {
1078
+ geometry.connectorStart = undefined
1079
+ geometry.connectorEnd = undefined
1106
1080
  // Computed into locals first: the stable rough.js seed makes an unchanged
1107
1081
  // layout produce identical path strings, which assignPaths then drops
1108
1082
  // instead of re-patching the SVG.
@@ -1153,6 +1127,7 @@ function paintDestinationInto(
1153
1127
  geometry.labelTop = label.box.cy
1154
1128
  geometry.labelWidth = label.width
1155
1129
  geometry.labelPlaced = true
1130
+ publishPlacedLabel(label.box)
1156
1131
  if (!destination) {
1157
1132
  destination = label.box
1158
1133
  endPoint = undefined
@@ -1160,19 +1135,56 @@ function paintDestinationInto(
1160
1135
  }
1161
1136
  else {
1162
1137
  geometry.labelPlaced = false
1138
+ placedLabelRegistry.delete(placementToken)
1163
1139
  }
1164
1140
 
1165
1141
  if (!destination || !props.connect)
1166
1142
  return
1167
1143
 
1168
- const route = routeLeader(root, toLocal, markBox, destination, endPoint)
1169
- if (!route)
1170
- return
1171
- const { start, end, c1x, c1y, c2x, c2y } = route
1172
- paths.leader = toPaths(generator.path(
1173
- `M ${start.x} ${start.y} C ${c1x} ${c1y}, ${c2x} ${c2y}, ${end.x} ${end.y}`,
1174
- roughOptions(),
1175
- ))
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
1176
1188
 
1177
1189
  if (props.arrow) {
1178
1190
  // Aim the head along the tangent of the curve, not along the chord.
@@ -1235,157 +1247,24 @@ function leaderCurve(start: Point, end: Point, side: 1 | -1, out?: Point, into?:
1235
1247
  type Curve = ReturnType<typeof leaderCurve>
1236
1248
 
1237
1249
  /**
1238
- * How much of the curve runs through the given boxes, and how much ink it
1239
- * spends overall, both in slide pixels and both sampled from the same points.
1240
- * The arc length is what prices a detour: a route that dodges text is only
1241
- * worth taking when it saves more crossing than the extra line it draws.
1242
- */
1243
- function measureCurve(curve: Curve, obstacles: Box[]) {
1244
- const samples = 24
1245
- let inside = 0
1246
- let length = 0
1247
- let px = 0
1248
- let py = 0
1249
- for (let i = 0; i <= samples; i++) {
1250
- const t = i / samples
1251
- const u = 1 - t
1252
- const x = u ** 3 * curve.start.x + 3 * u ** 2 * t * curve.c1x + 3 * u * t ** 2 * curve.c2x + t ** 3 * curve.end.x
1253
- const y = u ** 3 * curve.start.y + 3 * u ** 2 * t * curve.c1y + 3 * u * t ** 2 * curve.c2y + t ** 3 * curve.end.y
1254
- if (obstacles.some(box => x >= box.left && x <= box.right && y >= box.top && y <= box.bottom))
1255
- inside++
1256
- if (i)
1257
- length += Math.hypot(x - px, y - py)
1258
- px = x
1259
- py = y
1260
- }
1261
- return { crossing: inside / (samples + 1) * curve.distance, length }
1262
- }
1263
-
1264
- /**
1265
- * Chooses where the leader leaves the mark and which way it bows. The obvious
1266
- * straight exit towards the destination regularly runs through the rest of the
1267
- * sentence the mark sits in, which reads as a strike-through of text the
1268
- * annotation has nothing to do with. So candidate exits along the mark's
1269
- * border are tried, bowing to either side, against the rendered text of the
1270
- * slide — with the extra ink of a detour priced in, so a route that dodges
1271
- * text is only chosen when it saves more crossing than the line it adds. The
1272
- * straight exit is also only given up when another exit saves a substantial
1273
- * amount of crossing: brushing past a neighbouring line is part of the
1274
- * hand-drawn look, and a leader that trades it for a wide swing reads as
1275
- * starting from the wrong place.
1276
- */
1277
- function routeLeader(root: HTMLElement, toLocal: (rect: DOMRect) => Box, markBox: Box, destination: Box, endPoint?: Point): Curve | undefined {
1278
- const contains = (box: Box, x: number, y: number) => x >= box.left && x <= box.right && y >= box.top && y <= box.bottom
1279
- // Only text near the line's own neighbourhood matters, and never the words
1280
- // being marked or the destination itself.
1281
- const region = padBox(unionBox([markBox, destination]), 120)
1282
- const obstacles = collectTextObstacles(root, toLocal).filter(box =>
1283
- overlapArea(box, region) > 0
1284
- && !contains(markBox, box.cx, box.cy)
1285
- && !contains(destination, box.cx, box.cy))
1286
-
1287
- const defaultStart = edgePoint(markBox, destination.cx, destination.cy)
1288
- const exits: Point[] = [
1289
- { x: markBox.cx, y: markBox.top },
1290
- { x: markBox.cx, y: markBox.bottom },
1291
- { x: markBox.left, y: markBox.cy },
1292
- { x: markBox.right, y: markBox.cy },
1293
- { x: markBox.left, y: markBox.top },
1294
- { x: markBox.right, y: markBox.top },
1295
- { x: markBox.left, y: markBox.bottom },
1296
- { x: markBox.right, y: markBox.bottom },
1297
- ].sort((a, b) =>
1298
- Math.hypot(a.x - defaultStart.x, a.y - defaultStart.y)
1299
- - Math.hypot(b.x - defaultStart.x, b.y - defaultStart.y))
1300
-
1301
- // Where a route from `start` ends, and the direction it arrives in. A target
1302
- // is met at the given point; a label is met at its nearest edge — a drawn
1303
- // leader stops at the edge of the words it points at, it does not travel on
1304
- // towards their centre.
1305
- const endFor = (start: Point) => {
1306
- if (endPoint) {
1307
- const end = backOff(endPoint, start, targetMarkType.value !== 'none' ? destination.width / 2 : 6)
1308
- return { end, into: unitVector(endPoint.x - end.x, endPoint.y - end.y) }
1309
- }
1310
- const nearest = {
1311
- x: clamp(start.x, destination.left, destination.right),
1312
- y: clamp(start.y, destination.top, destination.bottom),
1313
- }
1314
- const into = unitVector(nearest.x - start.x, nearest.y - start.y)
1315
- const end = into ? { x: nearest.x - into.x * 6, y: nearest.y - into.y * 6 } : nearest
1316
- return { end, into }
1317
- }
1318
-
1319
- let straight: { curve: Curve, crossing: number, cost: number } | undefined
1320
- let best: { curve: Curve, crossing: number, cost: number } | undefined
1321
- // What the shortest reasonable route spends; anything beyond it is detour.
1322
- const defaultEnd = endFor(defaultStart).end
1323
- const directLength = Math.hypot(defaultEnd.x - defaultStart.x, defaultEnd.y - defaultStart.y)
1324
- for (const [index, start] of [defaultStart, ...exits].entries()) {
1325
- const { end, into: arrival } = endFor(start)
1326
- const chord = unitVector(end.x - start.x, end.y - start.y)
1327
- if (!chord)
1328
- continue
1329
- // Leave the mark outward through the chosen exit, leaning toward the
1330
- // destination so the curve can never double back around the mark, and
1331
- // arrive pointing into the destination.
1332
- const outward = unitVector(start.x - markBox.cx, start.y - markBox.cy) ?? chord
1333
- const out = unitVector(outward.x + chord.x, outward.y + chord.y) ?? chord
1334
- const into = arrival ?? chord
1335
- for (const side of [1, -1] as const) {
1336
- const curve = leaderCurve(start, end, side, out, into)
1337
- if (curve.distance < 4)
1338
- continue
1339
- // Crossing text costs its length, a detour costs part of the extra ink
1340
- // it spends; the small terms only break ties.
1341
- const { crossing, length } = measureCurve(curve, obstacles)
1342
- const detour = Math.max(0, length - directLength)
1343
- const cost = crossing + detour * 0.4 + index * 2 + (side < 0 ? 1 : 0)
1344
- if (index === 0 && (!straight || cost < straight.cost))
1345
- straight = { curve, crossing, cost }
1346
- if (!best || cost < best.cost)
1347
- best = { curve, crossing, cost }
1348
- }
1349
- }
1350
- if (!straight)
1351
- return best?.curve
1352
- if (best && best.crossing < straight.crossing * 0.5 && straight.crossing - best.crossing > 24)
1353
- return best.curve
1354
- return straight.curve
1355
- }
1356
-
1357
- /**
1358
- * The slide's text and media, as the tight boxes of the rendered lines rather
1359
- * than the elements around them. This is what a leader line must not strike
1360
- * through: crossing a card's padding looks deliberate, crossing its words
1361
- * reads as marking text the annotation has nothing to do with.
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.
1362
1253
  */
1363
- function collectTextObstacles(root: HTMLElement, toLocal: (rect: DOMRect) => Box): Box[] {
1364
- const slide = slideRoot() ?? root
1365
- const scan = scanObstacles(slide)
1366
- const boxes: Box[] = [...scan.media, ...scan.texts].map(toLocal)
1367
- // The marks and labels of the other annotations on the slide. A leader that
1368
- // dives through a circled word or a written label reads as marking it. Their
1369
- // paths are in the DOM from the first measurement — merely hidden until
1370
- // their click — so routing around them is stable rather than a jump on the
1371
- // click that reveals them.
1372
- for (const svg of Array.from(slide.querySelectorAll<SVGSVGElement>('svg.annotation-overlay'))) {
1373
- if (svg === overlay.value)
1374
- continue
1375
- for (const path of Array.from(svg.querySelectorAll<SVGPathElement>('.annotation-mark, .annotation-target'))) {
1376
- const rect = path.getBoundingClientRect()
1377
- if (rect.width >= 4 || rect.height >= 4)
1378
- boxes.push(toLocal(rect))
1379
- }
1380
- }
1381
- for (const label of Array.from(slide.querySelectorAll<HTMLElement>('.annotation-label.is-placed'))) {
1382
- if (label === labelEl.value)
1383
- continue
1384
- const rect = label.getBoundingClientRect()
1385
- if (rect.width >= 6 && rect.height >= 6)
1386
- boxes.push(toLocal(rect))
1387
- }
1388
- return boxes
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),
1261
+ }
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)
1389
1268
  }
1390
1269
 
1391
1270
  // Stands in for a label that cannot be measured yet, so placement still has a
@@ -1395,14 +1274,6 @@ const FALLBACK_LABEL_HEIGHT = 40
1395
1274
  // The label never sits closer to a slide edge than this, in slide pixels.
1396
1275
  const SLIDE_MARGIN = 24
1397
1276
 
1398
- // Sideways nudges tried for each gap while placing the label, nearest first.
1399
- const LATERAL_OFFSETS = (() => {
1400
- const offsets = [0]
1401
- for (let step = 40; step <= 400; step += 40)
1402
- offsets.push(step, -step)
1403
- return offsets
1404
- })()
1405
-
1406
1277
  // Measured label sizes per width cap. Writing a candidate max-width and
1407
1278
  // reading the resulting box back forces a synchronous layout, and the answer
1408
1279
  // only changes with the label's text or font — never from frame to frame while
@@ -1410,6 +1281,72 @@ const LATERAL_OFFSETS = (() => {
1410
1281
  // resizes too. Cleared on every click and whenever the props or fonts change.
1411
1282
  const labelSizeCache = new Map<number | 'natural', { width: number, height: number }>()
1412
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
+ }
1349
+
1413
1350
  function measureLabel(toLocal: (rect: DOMRect) => Box, maxWidth?: number) {
1414
1351
  const cached = labelSizeCache.get(maxWidth ?? 'natural')
1415
1352
  if (cached)
@@ -1440,10 +1377,11 @@ function measureLabel(toLocal: (rect: DOMRect) => Box, maxWidth?: number) {
1440
1377
  }
1441
1378
 
1442
1379
  /**
1443
- * Finds the widest label that can stay inside the slide and clear its
1444
- * obstacles. The unbounded measurement is always tried first, so ordinary
1445
- * labels remain a single, readable line instead of inheriting an arbitrary
1446
- * 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.
1447
1385
  */
1448
1386
  function fitLabel(
1449
1387
  root: HTMLElement,
@@ -1452,25 +1390,23 @@ function fitLabel(
1452
1390
  bounds: Box,
1453
1391
  ): { box: Box, width: number | undefined } {
1454
1392
  // Collected once for every width candidate tried below: the obstacles do not
1455
- // depend on how the label wraps. Inflated so the label breathes — a label
1456
- // that ends up flush against the bottom of a code block reads as part of it.
1457
- // An explicitly positioned label ignores obstacles entirely.
1458
- const obstacles = props.labelX !== undefined || props.labelY !== undefined
1459
- ? []
1460
- : collectObstacles(root, toLocal)
1461
- .map(box => padBox(box, props.clearance))
1462
- .concat(padBox(anchor, 8))
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)
1463
1399
  const natural = measureLabel(toLocal)
1464
1400
  const unwrapped = placeLabel(anchor, natural, bounds, obstacles)
1465
1401
  const fitsSlide = natural.width <= bounds.width - SLIDE_MARGIN * 2 && natural.height <= bounds.height - SLIDE_MARGIN * 2
1466
- const respectsExplicitMaximum = props.labelWidth === undefined || natural.width <= props.labelWidth
1402
+ const respectsExplicitMaximum = maximumWidth === undefined || natural.width <= maximumWidth
1467
1403
 
1468
1404
  if (fitsSlide && unwrapped.overlap === 0 && respectsExplicitMaximum)
1469
1405
  return { box: unwrapped.box, width: undefined }
1470
1406
 
1471
- // An explicit `label-width` remains a useful author override. Without one,
1472
- // the slide edges are the only width limit.
1473
- const maximum = Math.min(natural.width, props.labelWidth ?? natural.width, bounds.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)
1474
1410
  const minimum = Math.min(maximum, 160)
1475
1411
  let best: { box: Box, width: number, overlap: number } | undefined
1476
1412
 
@@ -1503,109 +1439,165 @@ function placeLabel(
1503
1439
  anchor: Box,
1504
1440
  size: { width: number, height: number },
1505
1441
  bounds: Box,
1506
- obstacles: Box[],
1442
+ obstacles: Box[] = [],
1507
1443
  ): { box: Box, overlap: number } {
1508
1444
  const halfW = size.width / 2
1509
1445
  const halfH = size.height / 2
1510
1446
  const centred = (cx: number, cy: number) => makeBox(cx - halfW, cy - halfH, cx + halfW, cy + halfH)
1511
-
1512
- if (props.labelX !== undefined || props.labelY !== undefined) {
1513
- return {
1514
- box: centred(
1515
- props.labelX !== undefined ? bounds.left + bounds.width * props.labelX / 100 : anchor.cx,
1516
- props.labelY !== undefined ? bounds.top + bounds.height * props.labelY / 100 : anchor.cy,
1517
- ),
1518
- overlap: 0,
1519
- }
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 }
1520
1455
  }
1521
1456
 
1522
- const placement = resolvedPlacement.value
1523
- const preferred = placement === 'auto'
1457
+ type Direction = 'up' | 'down' | 'left' | 'right'
1458
+ const preferred: Direction = resolvedPlacement.value === 'auto'
1524
1459
  ? (anchor.cy < bounds.cy ? 'down' : 'up')
1525
- : placement
1526
- const directions = placement === 'auto'
1527
- ? [preferred, preferred === 'down' ? 'up' : 'down', 'right', 'left'] as const
1528
- : [preferred] as const
1529
-
1530
- let best: { box: Box, overlap: number, score: number } | undefined
1531
-
1532
- for (const [order, direction] of directions.entries()) {
1533
- for (let gap = props.gap; gap <= props.gap + 260; gap += 20) {
1534
- for (const lateral of LATERAL_OFFSETS) {
1535
- const vertical = direction === 'up' || direction === 'down'
1536
- const cx = vertical
1537
- ? anchor.cx + lateral
1538
- : direction === 'right' ? anchor.right + gap + halfW : anchor.left - gap - halfW
1539
- const cy = vertical
1540
- ? (direction === 'down' ? anchor.bottom + gap + halfH : anchor.top - gap - halfH)
1541
- : anchor.cy + lateral
1542
-
1543
- const box = centred(
1544
- clamp(cx, bounds.left + SLIDE_MARGIN + halfW, bounds.right - SLIDE_MARGIN - halfW),
1545
- clamp(cy, bounds.top + SLIDE_MARGIN + halfH, bounds.bottom - SLIDE_MARGIN - halfH),
1546
- )
1547
- const overlap = obstacles.reduce((total, obstacle) => total + overlapArea(box, obstacle), 0)
1548
- const score = overlap * 6 + gap + Math.abs(lateral) * 0.6 + order * 400
1549
- // A clear spot always beats an overlapping one, and among clear spots
1550
- // the best-scoring one wins: taking the first found would let a small
1551
- // gap with a long drift along the mark beat a slightly larger gap that
1552
- // stays level with it, which reads as belonging to something else.
1553
- const better = !best
1554
- || (overlap === 0 && best.overlap > 0)
1555
- || ((overlap === 0) === (best.overlap === 0) && score < best.score)
1556
- if (better)
1557
- best = { box, overlap, score }
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 }
1484
+ }
1485
+
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
1558
1499
  }
1559
1500
  }
1560
1501
  }
1502
+ return best!
1503
+ }
1561
1504
 
1562
- // The loops above always run at least once, so `best` is always set; the
1563
- // fallback only satisfies the types.
1564
- 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
1565
1510
  }
1566
1511
 
1567
1512
  /**
1568
- * Everything the label has to stay clear of: every rendered text fragment and
1569
- * image on the slide, plus whole boxes for content whose padding also matters
1570
- * and anything the slide opted in through `avoid-selector`. Cards and similar
1571
- * blocks remain solid obstacles, but a code block's body is intentionally not:
1572
- * its blank area is a good label surface. Its title/tab strip is a block
1573
- * obstacle, so annotations can never be placed in window chrome.
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.
1574
1521
  */
1575
- function collectObstacles(root: HTMLElement, toLocal: (rect: DOMRect) => Box): Box[] {
1576
- const slide = slideRoot() ?? root
1577
- const scan = scanObstacles(slide)
1578
- const boxes: Box[] = [...scan.blocks, ...scan.media, ...scan.texts].map(toLocal)
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))
1579
1529
  if (props.avoidSelector) {
1580
- for (const element of Array.from(slide.querySelectorAll<HTMLElement>(props.avoidSelector)))
1581
- boxes.push(toLocal(element.getBoundingClientRect()))
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)
1543
+ continue
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)))
1549
+ continue
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))
1582
1553
  }
1583
- // The labels other annotations have already written. Only the ones from an
1584
- // earlier click count — a later label avoids an earlier one, never the other
1585
- // way round — so two labels can never chase each other across the slide.
1586
- const ourLabel = labelEl.value
1587
- for (const other of Array.from(slide.querySelectorAll<HTMLElement>('.annotation-label.is-placed'))) {
1588
- 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'))
1589
1564
  continue
1590
- const click = Number(other.dataset.click ?? Number.NaN)
1591
- 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)
1592
1568
  continue
1593
- const ours = resolvedLabelClick.value
1594
- const earlier = click < ours
1595
- || (click === ours && !!ourLabel && !!(other.compareDocumentPosition(ourLabel) & Node.DOCUMENT_POSITION_FOLLOWING))
1596
- 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()))
1597
1574
  continue
1598
- const rect = other.getBoundingClientRect()
1599
- if (rect.width >= 6 && rect.height >= 6)
1600
- boxes.push(toLocal(rect))
1575
+ const rect = element.getBoundingClientRect()
1576
+ if (rect.width < 2 || rect.height < 2)
1577
+ continue
1578
+ boxes.push(toLocal(rect))
1601
1579
  }
1580
+ contentObstacleCache = boxes
1602
1581
  return boxes
1603
1582
  }
1604
1583
 
1605
- function overlapArea(a: Box, b: Box) {
1606
- const w = Math.min(a.right, b.right) - Math.max(a.left, b.left)
1607
- const h = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)
1608
- 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
+ })
1609
1601
  }
1610
1602
 
1611
1603
  function clamp(value: number, min: number, max: number) {
@@ -1636,20 +1628,37 @@ function backOff(point: { x: number, y: number }, from: { x: number, y: number }
1636
1628
 
1637
1629
  onMounted(async () => {
1638
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
+ }
1639
1638
  // Registered synchronously, while the clicks context still accepts it.
1640
1639
  if (manualClicks.value) {
1641
- 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
1642
1645
  resolvedLabelClick.value = props.labelAt === undefined
1643
1646
  ? resolvedClick.value
1644
1647
  : manualClick(props.labelAt, 'label-at')
1645
- $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) })
1646
1653
  }
1647
1654
  await nextTick()
1648
1655
  if (!manualClicks.value) {
1649
- // Slidev resolves automatic click ordering in the directive and stores the
1650
- // result on the marker. Reading it here keeps the first painted state
1651
- // unambiguously hidden, unlike styling a v-click element directly.
1652
- 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
1653
1662
  // A label without a click of its own follows the mark, rather than taking
1654
1663
  // the next click in the slide's automatic ordering.
1655
1664
  resolvedLabelClick.value = props.labelAt === undefined
@@ -1664,6 +1673,29 @@ onMounted(async () => {
1664
1673
  unsettle()
1665
1674
  scheduleUpdate()
1666
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
+
1667
1699
  resizeObserver = new ResizeObserver(scheduleUpdate)
1668
1700
  if (container.value)
1669
1701
  resizeObserver.observe(container.value)
@@ -1686,31 +1718,46 @@ onMounted(async () => {
1686
1718
  mutationObserver.observe(element, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['style', 'class'] })
1687
1719
  }
1688
1720
 
1689
- document.fonts?.ready.then(() => {
1690
- labelSizeCache.clear()
1691
- scheduleUpdate()
1692
- })
1693
1721
  window.addEventListener('resize', scheduleUpdate)
1694
- })
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
+ }
1695
1736
 
1696
1737
  onBeforeUnmount(() => {
1697
1738
  mounted = false
1739
+ unregisterEditorActions?.()
1740
+ unregisterEditorActions = undefined
1741
+ if (locator.value)
1742
+ releaseAnnotationSelection(locator.value)
1743
+ placedLabelRegistry.delete(placementToken)
1698
1744
  settleRun++
1699
1745
  clearTimeout(exitFadeTimer)
1700
1746
  $clicksContext.unregister(ownClicks)
1701
1747
  cancelAnimationFrame(frame)
1702
1748
  cancelAnimationFrame(paintFrame)
1703
1749
  cancelAnimationFrame(trackFrame)
1704
- resizeObserver?.disconnect()
1705
- mutationObserver?.disconnect()
1706
- for (const image of watchedImages.splice(0))
1707
- image.removeEventListener('load', scheduleUpdate)
1708
- window.removeEventListener('resize', scheduleUpdate)
1750
+ disconnectObservers()
1709
1751
  })
1710
1752
 
1711
1753
  // Magic Move and click transitions are driven by the click count, and both move
1712
1754
  // the annotated element for a while after it changes.
1713
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
1714
1761
  unsettle()
1715
1762
  track(CLICK_TRACK_DURATION)
1716
1763
  }, { flush: 'sync' })
@@ -1722,9 +1769,22 @@ watch($clicks, () => {
1722
1769
  // document-level pseudo-elements before the first animation scan.
1723
1770
  watch(isCurrentSlide, (current) => {
1724
1771
  if (current) {
1772
+ connectObservers()
1725
1773
  unsettle(VIEW_TRANSITION_START_GRACE)
1726
1774
  track()
1727
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
+ }
1728
1788
  }, { flush: 'sync' })
1729
1789
 
1730
1790
  // Any prop can change what is drawn or where the label may go, so re-measure
@@ -1735,20 +1795,498 @@ watch(props, () => {
1735
1795
  lastMarkKey = ''
1736
1796
  scheduleUpdate()
1737
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
+ })
1738
2270
  </script>
1739
2271
 
1740
2272
  <template>
1741
- <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
+ >
1742
2278
  <!-- The marker takes part in Slidev's click ordering while component state
1743
2279
  drives the drawing. This avoids a mount-time v-click class race. -->
1744
- <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" />
1745
2281
  <span v-if="props.labelAt !== undefined" ref="labelMarker" v-click="manualClicks ? false : props.labelAt" class="click-marker annotation-ignore" />
1746
2282
  <svg
1747
2283
  ref="overlay"
1748
2284
  class="annotation-overlay annotation-ignore"
1749
2285
  :viewBox="`0 0 ${geometry.width} ${geometry.height}`"
1750
2286
  preserveAspectRatio="none"
1751
- aria-hidden="true"
2287
+ :aria-hidden="!(connectorEditable && annotationEditMode)"
2288
+ :role="connectorEditable && annotationEditMode ? 'group' : undefined"
2289
+ :aria-label="connectorEditable && annotationEditMode ? `Connector editor for ${locator}` : undefined"
1752
2290
  :style="{
1753
2291
  '--annotation-color': props.color,
1754
2292
  '--annotation-width': `${props.strokeWidth}px`,
@@ -1801,13 +2339,58 @@ watch(props, () => {
1801
2339
  />
1802
2340
  </g>
1803
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>
1804
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. -->
1805
2383
  <div
1806
2384
  v-if="hasLabel"
1807
2385
  ref="labelEl"
1808
2386
  class="annotation-label annotation-ignore"
1809
- :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 }"
1810
2388
  :data-click="resolvedLabelClick"
2389
+ @pointerdown="beginLabelDrag($event)"
2390
+ @pointermove="moveLabelDrag"
2391
+ @pointerup="endLabelDrag"
2392
+ @pointercancel="cancelLabelDrag"
2393
+ @click="stopEditorClick"
1811
2394
  :style="{
1812
2395
  '--annotation-color': props.color,
1813
2396
  '--label-delay': `${delays.label}ms`,
@@ -1816,9 +2399,26 @@ watch(props, () => {
1816
2399
  'top': `${geometry.labelTop}px`,
1817
2400
  'maxWidth': geometry.labelWidth === undefined ? undefined : `${geometry.labelWidth}px`,
1818
2401
  }"
1819
- 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')"
1820
2406
  >
1821
- {{ 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
+ />
1822
2422
  </div>
1823
2423
  <slot />
1824
2424
  <!-- Keep the live region mounted so screen readers announce the label when
@@ -1828,7 +2428,7 @@ watch(props, () => {
1828
2428
  role="status"
1829
2429
  aria-live="polite"
1830
2430
  aria-atomic="true"
1831
- >{{ labelActive && geometry.ready ? props.label : '' }}</span>
2431
+ >{{ labelActive && geometry.ready ? labelText : '' }}</span>
1832
2432
  </div>
1833
2433
  </template>
1834
2434
 
@@ -1930,6 +2530,23 @@ watch(props, () => {
1930
2530
  transition: opacity var(--label-fade, 250ms) ease-out;
1931
2531
  }
1932
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
+
1933
2550
  /* Measured before it is placed, so keep it laid out but invisible until then. */
1934
2551
  .annotation-label.is-placed { visibility: visible; }
1935
2552
 
@@ -1938,6 +2555,39 @@ watch(props, () => {
1938
2555
  transition-delay: var(--label-delay);
1939
2556
  }
1940
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
+
1941
2591
  @media (prefers-reduced-motion: reduce) {
1942
2592
  .annotation-stroke,
1943
2593
  .annotation-label {