slidev-theme-kotlin 0.10.0 → 0.11.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.
@@ -1,3 +1,99 @@
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
+ /**
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.
24
+ */
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
94
+ }
95
+ </script>
96
+
1
97
  <script setup lang="ts">
2
98
  import type { Options as RoughOptions } from 'roughjs/bin/core'
3
99
  import type { ClicksContext } from '@slidev/types'
@@ -85,7 +181,7 @@ const props = withDefaults(defineProps<{
85
181
  connect?: boolean
86
182
  /** Arrow head at the end of the leader line. */
87
183
  arrow?: boolean
88
- /** Curvature of the leader line, as a fraction of its length. */
184
+ /** Sideways bow of the leader line, as a fraction of its length (capped at 40 slide pixels). */
89
185
  curve?: number
90
186
  /**
91
187
  * Passed straight to rough.js, which draws every stroke, so everything it
@@ -180,7 +276,8 @@ const props = withDefaults(defineProps<{
180
276
  // bindings. Anything that needs an actual colour cannot read this raw.
181
277
  color: 'var(--drawn-annotation-color, currentColor)',
182
278
  strokeWidth: 2,
183
- duration: 800,
279
+ // Keep the hand-drawn stage aligned with Magic Move and page transitions.
280
+ duration: 500,
184
281
  sequential: true,
185
282
  at: undefined,
186
283
  until: undefined,
@@ -291,8 +388,14 @@ const showImmediately = ref(false)
291
388
  // renders the slot provided, which plain `inject` walks straight past. Slidev's
292
389
  // own clicks context reaches nested components the same way.
293
390
  const outerClicksContext = injectLocal(realClicksKey, null)
294
- const $clicksContext = outerClicksContext ?? useSlideContext().$clicksContext
391
+ const slideContext = useSlideContext()
392
+ const $nav = slideContext.$nav
393
+ const $clicksContext = outerClicksContext ?? slideContext.$clicksContext
295
394
  const $clicks = toRef($clicksContext, 'current')
395
+ // Slidev mounts the previous and next slides ahead of time. An annotation on
396
+ // one of those hidden slides must not paint before that slide becomes current,
397
+ // otherwise the view-transition snapshot captures the finished mark.
398
+ const isCurrentSlide = computed(() => slideContext.$page.value === $nav.value.currentSlideNo)
296
399
  provide(realClicksKey, $clicksContext)
297
400
  // Slidev's click ordering runs in the context the markers are rendered in, and
298
401
  // that one is shifted here. So these annotations resolve and register their
@@ -302,9 +405,9 @@ provide(realClicksKey, $clicksContext)
302
405
  const startsOnInitialSlide = computed(() => Number(atClick.value) === 0)
303
406
  const manualClicks = computed(() => props.insert || !!outerClicksContext || startsOnInitialSlide.value)
304
407
  const painted = computed(() => geometryPainted.value || showImmediately.value)
305
- // True once the annotated element has held still for a few frames. Drawing is
306
- // held back until then, so a mark never appears on top of a Magic Move step or
307
- // a slide transition that is still travelling.
408
+ // True once the animations triggered by the current click have finished.
409
+ // Drawing is held back until then, so a mark never appears on top of a Magic
410
+ // Move step or a slide transition that is still travelling.
308
411
  const settled = ref(!props.wait)
309
412
  // An annotation with `until` is only shown while the thing it points at is on
310
413
  // screen: past that click every stage hides again, in one step.
@@ -331,7 +434,7 @@ const withinRange = computed(() => $clicks.value < rangeEnd.value)
331
434
  // slide would inherit the delay too.
332
435
  const fadingOut = ref(false)
333
436
  /** How long the strokes' exit fade takes, mirrored into CSS as `--exit-fade`. */
334
- const EXIT_FADE_DURATION = 280
437
+ const EXIT_FADE_DURATION = 300
335
438
  let exitFadeTimer: ReturnType<typeof setTimeout> | undefined
336
439
  watch(withinRange, (inside, wasInside) => {
337
440
  clearTimeout(exitFadeTimer)
@@ -339,7 +442,10 @@ watch(withinRange, (inside, wasInside) => {
339
442
  if (fadingOut.value)
340
443
  exitFadeTimer = setTimeout(() => fadingOut.value = false, EXIT_FADE_DURATION)
341
444
  })
342
- const reached = (click: Ref<number>) => computed(() => $clicks.value >= click.value && withinRange.value && painted.value)
445
+ const reached = (click: Ref<number>) => computed(() => isCurrentSlide.value
446
+ && $clicks.value >= click.value
447
+ && withinRange.value
448
+ && painted.value)
343
449
 
344
450
  /**
345
451
  * Holds a stage back until everything has stopped moving, and then keeps it
@@ -413,7 +519,7 @@ const ARROW_FRACTION = 0.2
413
519
  const TARGET_FRACTION = 0.5
414
520
  const LABEL_HEAD_START = 0.1
415
521
  /** How long the label's opacity fade takes, mirrored into CSS as `--label-fade`. */
416
- const LABEL_FADE_DURATION = 240
522
+ const LABEL_FADE_DURATION = 250
417
523
 
418
524
  // Whether a leader line is drawn at all: it needs somewhere to go.
419
525
  const connectsLine = computed(() => props.connect && (hasTarget.value || hasLabel.value))
@@ -478,6 +584,19 @@ const geometry = reactive({
478
584
  ready: false,
479
585
  })
480
586
 
587
+ /**
588
+ * Replaces one of the path lists only when it actually changed. Geometry is
589
+ * re-measured on animation frames, and an unconditional assignment would be a
590
+ * new array every time — re-rendering and re-patching every <path> element
591
+ * even in a frame where nothing moved.
592
+ */
593
+ function assignPaths(key: 'mark' | 'leader' | 'arrow' | 'targetMark', next: string[]) {
594
+ const previous = geometry[key]
595
+ if (previous.length === next.length && previous.every((d, index) => d === next[index]))
596
+ return
597
+ geometry[key] = next
598
+ }
599
+
481
600
  // Identity of this annotation's own clicks in the slide's click count, used
482
601
  // when it resolves them itself instead of leaving that to the `v-click` marker.
483
602
  const ownClicks = Symbol('drawn-annotation-clicks') as unknown as HTMLElement
@@ -680,49 +799,105 @@ let paintFrame = 0
680
799
  let trackFrame = 0
681
800
  let trackUntil = 0
682
801
  let mounted = false
802
+ // Fingerprint of the mark's last measured boxes. While the slide animates, a
803
+ // frame in which the mark has not moved recomputes nothing.
804
+ let lastMarkKey = ''
683
805
  // The images whose load re-measures geometry, kept so unmount removes exactly
684
806
  // the listeners that were added.
685
807
  const watchedImages: HTMLImageElement[] = []
686
- // How long the geometry has to hold still before it counts as settled, and how
687
- // long we are willing to wait for that. The cap matters for anything that never
688
- // stops moving, so an annotation is never lost to it.
689
- const SETTLE_FRAMES = 3
690
- const SETTLE_TIMEOUT = 3000
691
- let settleDeadline = 0
692
- let stableFrames = 0
693
- let lastSignature = ''
808
+ // Each wait gets an identity so a completion from the previous click cannot
809
+ // release the next one. The Web Animations API covers CSS transitions, CSS
810
+ // animations and Magic Move's generated animations with the same `finished`
811
+ // promise, including their real delay and duration.
812
+ let settleRun = 0
694
813
 
695
- /**
696
- * Whether something in the slot is still animating. Geometry alone does not
697
- * catch everything: a Magic Move step fades new tokens in where they already
698
- * belong, so the boxes sit still while the code is visibly still arriving.
699
- */
700
- function inMotion() {
814
+ function relevantAnimations() {
701
815
  const root = container.value
702
816
  if (!root?.getAnimations)
703
- return false
704
- return root.getAnimations({ subtree: true }).some((animation) => {
705
- if (animation.playState !== 'running')
817
+ return []
818
+
819
+ // A view transition is owned by the document, not by the incoming slide's
820
+ // slot. Its pseudo-elements therefore never appear in the annotation
821
+ // container's subtree, even though they are exactly the animation we must
822
+ // wait for before drawing on the new slide.
823
+ const viewTransitionAnimations = typeof document !== 'undefined'
824
+ ? document.getAnimations().filter((animation) => {
825
+ const pseudo = (animation.effect as KeyframeEffect | null)?.pseudoElement
826
+ return typeof pseudo === 'string' && pseudo.startsWith('::view-transition-')
827
+ })
828
+ : []
829
+ const animations = [...root.getAnimations({ subtree: true }), ...viewTransitionAnimations]
830
+
831
+ return [...new Set(animations)].filter((animation) => {
832
+ if (animation.playState !== 'running' && !animation.pending)
706
833
  return false
707
- const target = (animation.effect as KeyframeEffect | null)?.target ?? null
708
- // The annotation's own strokes and label are not what it waits for.
709
- return !target?.closest('.annotation-ignore')
834
+ const target = (animation.effect as KeyframeEffect | null)?.target
835
+ const pseudo = (animation.effect as KeyframeEffect | null)?.pseudoElement
836
+ // Pseudo-elements belong to the page transition and are intentionally
837
+ // included. For regular elements, never wait for our own strokes or label:
838
+ // they only start after `settled` opens the annotation.
839
+ const belongsToPageTransition = typeof pseudo === 'string' && pseudo.startsWith('::view-transition-')
840
+ const belongsToSlot = target instanceof Element && !target.closest('.annotation-ignore')
841
+ return (belongsToPageTransition || belongsToSlot)
842
+ && Number.isFinite(animation.effect?.getComputedTiming().endTime)
710
843
  })
711
844
  }
712
845
 
846
+ function nextFrame() {
847
+ return new Promise<void>(resolve => requestAnimationFrame(() => resolve()))
848
+ }
849
+
850
+ /**
851
+ * Release the entrance when the animations that actually started for this
852
+ * click finish. Re-check after each batch because Magic Move can create the
853
+ * next transition while completing the previous one. A final frame lets the
854
+ * browser commit the finished layout before it is measured for drawing.
855
+ */
856
+ const VIEW_TRANSITION_START_GRACE = 100
857
+
858
+ async function settleAfterAnimations(run: number, grace = 0) {
859
+ // Slidev starts document.startViewTransition() after a short timeout. A
860
+ // preloaded annotation can therefore observe the route change before the
861
+ // browser has created the view-transition pseudo-elements. Give that start
862
+ // callback time to run instead of concluding that there is nothing to wait
863
+ // for.
864
+ if (grace > 0)
865
+ await new Promise<void>(resolve => setTimeout(resolve, grace))
866
+ await nextTick()
867
+ await nextFrame()
868
+ while (mounted && run === settleRun) {
869
+ const animations = relevantAnimations()
870
+ if (!animations.length) {
871
+ await nextFrame()
872
+ if (mounted && run === settleRun && !relevantAnimations().length) {
873
+ // Settle before measuring: the settled pass is the one full
874
+ // recomputation per click that the animation-frame passes lean on.
875
+ settled.value = true
876
+ updateGeometry()
877
+ }
878
+ return
879
+ }
880
+ await Promise.allSettled(animations.map(animation => animation.finished))
881
+ await nextFrame()
882
+ }
883
+ }
884
+
713
885
  /**
714
886
  * Marks the annotation as moving again and keeps measuring until it stops.
715
887
  * Called on every click, because that is what starts a Magic Move step.
716
888
  */
717
- function unsettle() {
889
+ function unsettle(grace = 0) {
890
+ 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.
893
+ labelSizeCache.clear()
718
894
  if (!props.wait || !props.track) {
719
895
  settled.value = true
720
896
  return
721
897
  }
722
898
  settled.value = false
723
- stableFrames = 0
724
- settleDeadline = performance.now() + SETTLE_TIMEOUT
725
899
  track(0)
900
+ void settleAfterAnimations(run, grace)
726
901
  }
727
902
 
728
903
  function scheduleUpdate() {
@@ -735,20 +910,28 @@ function scheduleUpdate() {
735
910
  }
736
911
 
737
912
  /**
738
- * Keeps re-measuring for a short while. Magic Move and click transitions move
739
- * the annotated tokens over several hundred milliseconds, and there is no
740
- * single event that reliably marks the end of that movement.
913
+ * Keeps re-measuring while an animation moves the annotated content. The
914
+ * animation's `finished` promise controls the entrance; this loop only keeps
915
+ * the geometry attached to the moving element until then.
741
916
  */
917
+ // A plain click has no moving geometry. Keep a short tracking window for Vue to
918
+ // apply that click, while mutations from Magic Move retain the longer window.
919
+ const CLICK_TRACK_DURATION = 120
920
+
742
921
  function track(duration = 700) {
743
922
  if (!props.track)
744
923
  return
924
+ // A still-hidden (or already-ended) annotation has nothing on screen that
925
+ // must glide with the animation. Its geometry is refreshed once per click by
926
+ // the settled measurement instead of on every frame — including the strokes
927
+ // other annotations route around while it waits for its click.
928
+ if (!withinRange.value || $clicks.value < Math.min(resolvedClick.value, resolvedLabelClick.value))
929
+ return
745
930
  trackUntil = Math.max(trackUntil, performance.now() + duration)
746
931
  if (trackFrame)
747
932
  return
748
933
  const step = () => {
749
934
  updateGeometry()
750
- if (!settled.value && performance.now() > settleDeadline)
751
- settled.value = true
752
935
  if (mounted && (performance.now() < trackUntil || !settled.value)) {
753
936
  trackFrame = requestAnimationFrame(step)
754
937
  }
@@ -770,7 +953,7 @@ let everFound = false
770
953
  // click has been reached and the slide has stopped moving; before that, it may
771
954
  // simply not have arrived yet.
772
955
  const missingIsAnError = computed(() =>
773
- settled.value && $clicks.value >= resolvedClick.value && withinRange.value)
956
+ isCurrentSlide.value && settled.value && $clicks.value >= resolvedClick.value && withinRange.value)
774
957
 
775
958
  /** Explains why nothing was drawn, once something should have been. */
776
959
  function explainMissing(match?: { range?: Range, matches: number }) {
@@ -847,29 +1030,21 @@ function updateGeometry() {
847
1030
  const multiline = props.multiline ?? (sourceMarkType.value === 'underline' || sourceMarkType.value === 'strike-through')
848
1031
  const shapeBoxes = multiline ? boxes : [marked]
849
1032
 
1033
+ // While the slide is still animating, a mark that has not moved since the
1034
+ // previous frame needs nothing recomputed: the paths, the leader and the
1035
+ // label placement all derive from it. The settled pass at the end of every
1036
+ // click always recomputes, because other content can have moved around a
1037
+ // stationary mark.
1038
+ const markKey = `${width}x${height}|${shapeBoxes.map(box => `${box.left.toFixed(2)},${box.top.toFixed(2)},${box.right.toFixed(2)},${box.bottom.toFixed(2)}`).join(';')}`
1039
+ if (!settled.value && geometry.ready && markKey === lastMarkKey)
1040
+ return
1041
+ lastMarkKey = markKey
1042
+
850
1043
  geometry.width = width
851
1044
  geometry.height = height
852
- geometry.mark = shapeBoxes.flatMap(box => markPaths(box, sourceMarkType.value))
853
-
854
- paintDestination(root, toLocal, marked, width, height)
855
-
856
- // Two measurements that come out identical mean the element has come to rest.
857
- const signature = [
858
- geometry.mark.join(''),
859
- geometry.leader.join(''),
860
- geometry.arrow.join(''),
861
- geometry.targetMark.join(''),
862
- Math.round(geometry.labelLeft),
863
- Math.round(geometry.labelTop),
864
- ].join('|')
865
- if (signature === lastSignature && !inMotion()) {
866
- if (++stableFrames >= SETTLE_FRAMES)
867
- settled.value = true
868
- }
869
- else {
870
- lastSignature = signature
871
- stableFrames = 0
872
- }
1045
+ assignPaths('mark', shapeBoxes.flatMap(box => markPaths(box, sourceMarkType.value)))
1046
+
1047
+ paintDestination(root, toLocal, marked)
873
1048
 
874
1049
  const firstMeasurement = !geometry.ready
875
1050
  geometry.ready = true
@@ -927,13 +1102,23 @@ function paintDestination(
927
1102
  root: HTMLElement,
928
1103
  toLocal: (rect: DOMRect) => Box,
929
1104
  marked: Box,
930
- width: number,
931
- height: number,
932
1105
  ) {
933
- geometry.leader = []
934
- geometry.arrow = []
935
- geometry.targetMark = []
1106
+ // Computed into locals first: the stable rough.js seed makes an unchanged
1107
+ // layout produce identical path strings, which assignPaths then drops
1108
+ // instead of re-patching the SVG.
1109
+ const paths = { leader: [] as string[], arrow: [] as string[], targetMark: [] as string[] }
1110
+ paintDestinationInto(paths, root, toLocal, marked)
1111
+ assignPaths('leader', paths.leader)
1112
+ assignPaths('arrow', paths.arrow)
1113
+ assignPaths('targetMark', paths.targetMark)
1114
+ }
936
1115
 
1116
+ function paintDestinationInto(
1117
+ paths: { leader: string[], arrow: string[], targetMark: string[] },
1118
+ root: HTMLElement,
1119
+ toLocal: (rect: DOMRect) => Box,
1120
+ marked: Box,
1121
+ ) {
937
1122
  const markBox = padBox(marked, sourceMarkType.value === 'none' ? 4 : props.padding + 6)
938
1123
  const targetEl = props.target ? (root.querySelector<HTMLElement>(props.target) ?? document.querySelector<HTMLElement>(props.target)) : undefined
939
1124
  if (props.target && !targetEl && missingIsAnError.value)
@@ -951,14 +1136,19 @@ function paintDestination(
951
1136
  endPoint = { x, y }
952
1137
  // The target is its own stage after the connection. A zero padding keeps
953
1138
  // target-radius the exact outer size authors position over screenshots.
954
- geometry.targetMark = markPaths(destination, targetMarkType.value, 0)
1139
+ paths.targetMark = markPaths(destination, targetMarkType.value, 0)
955
1140
  }
956
1141
 
957
1142
  if (hasLabel.value) {
958
1143
  // Start with the label's natural width, which is a single line. Only give
959
1144
  // it a maximum width when that line cannot stay on the slide or cannot be
960
1145
  // placed clear of the slide's content.
961
- const label = fitLabel(root, toLocal, destination ?? markBox, width, height)
1146
+ // An annotation nested in a positioned component (for example
1147
+ // InlineCompilerError) has an SVG canvas limited to that component. The
1148
+ // label is allowed to leave that canvas, so constrain it to the slide,
1149
+ // expressed in the SVG's local coordinates, rather than to the canvas.
1150
+ const slide = slideRoot() ?? root
1151
+ const label = fitLabel(root, toLocal, destination ?? markBox, toLocal(slide.getBoundingClientRect()))
962
1152
  geometry.labelLeft = label.box.cx
963
1153
  geometry.labelTop = label.box.cy
964
1154
  geometry.labelWidth = label.width
@@ -979,7 +1169,7 @@ function paintDestination(
979
1169
  if (!route)
980
1170
  return
981
1171
  const { start, end, c1x, c1y, c2x, c2y } = route
982
- geometry.leader = toPaths(generator.path(
1172
+ paths.leader = toPaths(generator.path(
983
1173
  `M ${start.x} ${start.y} C ${c1x} ${c1y}, ${c2x} ${c2y}, ${end.x} ${end.y}`,
984
1174
  roughOptions(),
985
1175
  ))
@@ -992,7 +1182,7 @@ function paintDestination(
992
1182
  end.x - Math.cos(angle + spread) * size,
993
1183
  end.y - Math.sin(angle + spread) * size,
994
1184
  ] as [number, number]
995
- geometry.arrow = [
1185
+ paths.arrow = [
996
1186
  ...toPaths(generator.linearPath([wing(0.42), [end.x, end.y]], roughOptions())),
997
1187
  ...toPaths(generator.linearPath([wing(-0.42), [end.x, end.y]], roughOptions())),
998
1188
  ]
@@ -1001,31 +1191,61 @@ function paintDestination(
1001
1191
 
1002
1192
  interface Point { x: number, y: number }
1003
1193
 
1004
- /** The leader's bezier between two points, bowed to one side or the other. */
1005
- function leaderCurve(start: Point, end: Point, side: 1 | -1) {
1194
+ function unitVector(x: number, y: number): Point | undefined {
1195
+ const length = Math.hypot(x, y)
1196
+ return length > 0.001 ? { x: x / length, y: y / length } : undefined
1197
+ }
1198
+
1199
+ // The bow of a leader is capped in slide pixels: proportional to length alone,
1200
+ // a long leader turns into a swooping gesture instead of a connection.
1201
+ const LEADER_MAX_BOW = 40
1202
+
1203
+ /**
1204
+ * The leader's bezier between two points. `out` is the direction the line
1205
+ * leaves the mark and `into` the direction it arrives at its destination; the
1206
+ * curve turns smoothly from one to the other, and `side` adds a gentle bow.
1207
+ * The arrival tangent stays aimed at the destination — that is what makes the
1208
+ * line read as pointing at the label rather than curling flat and sweeping
1209
+ * past it.
1210
+ */
1211
+ function leaderCurve(start: Point, end: Point, side: 1 | -1, out?: Point, into?: Point) {
1006
1212
  const dx = end.x - start.x
1007
1213
  const dy = end.y - start.y
1008
1214
  const distance = Math.hypot(dx, dy)
1009
- const bend = distance * props.curve * side
1010
- const perpX = -dy / (distance || 1) * bend
1011
- const perpY = dx / (distance || 1) * bend
1215
+ const along = unitVector(dx, dy) ?? { x: 1, y: 0 }
1216
+ const bend = Math.min(distance * props.curve, LEADER_MAX_BOW) * side
1217
+ const perpX = -along.y * bend
1218
+ const perpY = along.x * bend
1219
+ const reach = distance * 0.38
1220
+ const outDir = out ?? along
1221
+ const inDir = into ?? along
1012
1222
  return {
1013
1223
  start,
1014
1224
  end,
1015
1225
  distance,
1016
- c1x: start.x + dx * 0.34 + perpX,
1017
- c1y: start.y + dy * 0.34 + perpY,
1018
- c2x: start.x + dx * 0.72 + perpX,
1019
- c2y: start.y + dy * 0.72 + perpY,
1226
+ c1x: start.x + outDir.x * reach + perpX,
1227
+ c1y: start.y + outDir.y * reach + perpY,
1228
+ // Most of the bow sits near the exit; the arrival keeps pointing where it
1229
+ // is going, so the line lands on the label instead of flattening out.
1230
+ c2x: end.x - inDir.x * reach + perpX * 0.35,
1231
+ c2y: end.y - inDir.y * reach + perpY * 0.35,
1020
1232
  }
1021
1233
  }
1022
1234
 
1023
1235
  type Curve = ReturnType<typeof leaderCurve>
1024
1236
 
1025
- /** Roughly how much of the curve runs through the given boxes, in slide pixels. */
1026
- function curveCrossing(curve: Curve, obstacles: Box[]) {
1237
+ /**
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[]) {
1027
1244
  const samples = 24
1028
1245
  let inside = 0
1246
+ let length = 0
1247
+ let px = 0
1248
+ let py = 0
1029
1249
  for (let i = 0; i <= samples; i++) {
1030
1250
  const t = i / samples
1031
1251
  const u = 1 - t
@@ -1033,8 +1253,12 @@ function curveCrossing(curve: Curve, obstacles: Box[]) {
1033
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
1034
1254
  if (obstacles.some(box => x >= box.left && x <= box.right && y >= box.top && y <= box.bottom))
1035
1255
  inside++
1256
+ if (i)
1257
+ length += Math.hypot(x - px, y - py)
1258
+ px = x
1259
+ py = y
1036
1260
  }
1037
- return inside / (samples + 1) * curve.distance
1261
+ return { crossing: inside / (samples + 1) * curve.distance, length }
1038
1262
  }
1039
1263
 
1040
1264
  /**
@@ -1043,9 +1267,11 @@ function curveCrossing(curve: Curve, obstacles: Box[]) {
1043
1267
  * sentence the mark sits in, which reads as a strike-through of text the
1044
1268
  * annotation has nothing to do with. So candidate exits along the mark's
1045
1269
  * border are tried, bowing to either side, against the rendered text of the
1046
- * slide. The straight exit is only given up when another exit saves a
1047
- * substantial amount of crossing: brushing past a neighbouring line is part of
1048
- * the hand-drawn look, and a leader that trades it for a detour reads as
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
1049
1275
  * starting from the wrong place.
1050
1276
  */
1051
1277
  function routeLeader(root: HTMLElement, toLocal: (rect: DOMRect) => Box, markBox: Box, destination: Box, endPoint?: Point): Curve | undefined {
@@ -1072,19 +1298,49 @@ function routeLeader(root: HTMLElement, toLocal: (rect: DOMRect) => Box, markBox
1072
1298
  Math.hypot(a.x - defaultStart.x, a.y - defaultStart.y)
1073
1299
  - Math.hypot(b.x - defaultStart.x, b.y - defaultStart.y))
1074
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
+
1075
1319
  let straight: { curve: Curve, crossing: number, cost: number } | undefined
1076
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)
1077
1324
  for (const [index, start] of [defaultStart, ...exits].entries()) {
1078
- const end = endPoint
1079
- ? backOff(endPoint, start, targetMarkType.value !== 'none' ? destination.width / 2 : 6)
1080
- : edgePoint(destination, start.x, start.y, 6)
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
1081
1335
  for (const side of [1, -1] as const) {
1082
- const curve = leaderCurve(start, end, side)
1336
+ const curve = leaderCurve(start, end, side, out, into)
1083
1337
  if (curve.distance < 4)
1084
1338
  continue
1085
- // Crossing text costs its length; the small terms only break ties.
1086
- const crossing = curveCrossing(curve, obstacles)
1087
- const cost = crossing + index * 2 + (side < 0 ? 1 : 0)
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)
1088
1344
  if (index === 0 && (!straight || cost < straight.cost))
1089
1345
  straight = { curve, crossing, cost }
1090
1346
  if (!best || cost < best.cost)
@@ -1098,29 +1354,6 @@ function routeLeader(root: HTMLElement, toLocal: (rect: DOMRect) => Box, markBox
1098
1354
  return straight.curve
1099
1355
  }
1100
1356
 
1101
- // Elements considered while measuring obstacles, capped: the collectors run on
1102
- // animation frames while the slide moves, and a slide with more elements than
1103
- // this has no room for an automatic label anyway.
1104
- const OBSTACLE_ELEMENT_CAP = 600
1105
- const MEDIA_TAGS = ['IMG', 'VIDEO', 'CANVAS', 'SVG']
1106
-
1107
- function isMedia(element: HTMLElement) {
1108
- return MEDIA_TAGS.includes(element.tagName.toUpperCase())
1109
- }
1110
-
1111
- /**
1112
- * The slide elements obstacle collection looks at. Excludes this component's
1113
- * own strokes and labels, content still hidden behind a later click, and the
1114
- * internals of inline SVGs — parts of an illustration do not count on their
1115
- * own; the whole graphic does.
1116
- */
1117
- function obstacleCandidates(slide: HTMLElement): HTMLElement[] {
1118
- return Array.from(slide.querySelectorAll<HTMLElement>('*'))
1119
- .slice(0, OBSTACLE_ELEMENT_CAP)
1120
- .filter(element => !element.closest('.annotation-ignore, .slidev-vclick-hidden')
1121
- && !element.parentElement?.closest('svg'))
1122
- }
1123
-
1124
1357
  /**
1125
1358
  * The slide's text and media, as the tight boxes of the rendered lines rather
1126
1359
  * than the elements around them. This is what a leader line must not strike
@@ -1129,25 +1362,29 @@ function obstacleCandidates(slide: HTMLElement): HTMLElement[] {
1129
1362
  */
1130
1363
  function collectTextObstacles(root: HTMLElement, toLocal: (rect: DOMRect) => Box): Box[] {
1131
1364
  const slide = slideRoot() ?? root
1132
- const boxes: Box[] = []
1133
- for (const element of obstacleCandidates(slide)) {
1134
- if (isMedia(element)) {
1135
- const rect = element.getBoundingClientRect()
1136
- if (rect.width >= 6 && rect.height >= 6)
1137
- boxes.push(toLocal(rect))
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)
1138
1374
  continue
1139
- }
1140
- for (const node of Array.from(element.childNodes)) {
1141
- if (node.nodeType !== Node.TEXT_NODE || !node.nodeValue?.trim())
1142
- continue
1143
- const range = document.createRange()
1144
- range.selectNodeContents(node)
1145
- for (const rect of Array.from(range.getClientRects())) {
1146
- if (rect.width >= 4 && rect.height >= 4)
1147
- boxes.push(toLocal(rect))
1148
- }
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))
1149
1379
  }
1150
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
+ }
1151
1388
  return boxes
1152
1389
  }
1153
1390
 
@@ -1166,7 +1403,18 @@ const LATERAL_OFFSETS = (() => {
1166
1403
  return offsets
1167
1404
  })()
1168
1405
 
1406
+ // Measured label sizes per width cap. Writing a candidate max-width and
1407
+ // reading the resulting box back forces a synchronous layout, and the answer
1408
+ // only changes with the label's text or font — never from frame to frame while
1409
+ // the slide animates. Sizes are in slide coordinates, so they survive window
1410
+ // resizes too. Cleared on every click and whenever the props or fonts change.
1411
+ const labelSizeCache = new Map<number | 'natural', { width: number, height: number }>()
1412
+
1169
1413
  function measureLabel(toLocal: (rect: DOMRect) => Box, maxWidth?: number) {
1414
+ const cached = labelSizeCache.get(maxWidth ?? 'natural')
1415
+ if (cached)
1416
+ return cached
1417
+
1170
1418
  const label = labelEl.value
1171
1419
  if (!label)
1172
1420
  return { width: maxWidth ?? 0, height: FALLBACK_LABEL_HEIGHT }
@@ -1181,10 +1429,14 @@ function measureLabel(toLocal: (rect: DOMRect) => Box, maxWidth?: number) {
1181
1429
  const rect = label.getBoundingClientRect()
1182
1430
  label.style.maxWidth = previousMaxWidth
1183
1431
 
1432
+ // Only a real measurement is worth remembering; the fallbacks stand in for a
1433
+ // label that cannot be measured yet.
1184
1434
  if (!rect.width)
1185
1435
  return { width: maxWidth ?? 0, height: FALLBACK_LABEL_HEIGHT }
1186
1436
  const box = toLocal(rect)
1187
- return { width: box.width, height: box.height }
1437
+ const size = { width: box.width, height: box.height }
1438
+ labelSizeCache.set(maxWidth ?? 'natural', size)
1439
+ return size
1188
1440
  }
1189
1441
 
1190
1442
  /**
@@ -1197,12 +1449,20 @@ function fitLabel(
1197
1449
  root: HTMLElement,
1198
1450
  toLocal: (rect: DOMRect) => Box,
1199
1451
  anchor: Box,
1200
- width: number,
1201
- height: number,
1452
+ bounds: Box,
1202
1453
  ): { box: Box, width: number | undefined } {
1454
+ // 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))
1203
1463
  const natural = measureLabel(toLocal)
1204
- const unwrapped = placeLabel(root, toLocal, anchor, natural, width, height)
1205
- const fitsSlide = natural.width <= width - SLIDE_MARGIN * 2 && natural.height <= height - SLIDE_MARGIN * 2
1464
+ const unwrapped = placeLabel(anchor, natural, bounds, obstacles)
1465
+ const fitsSlide = natural.width <= bounds.width - SLIDE_MARGIN * 2 && natural.height <= bounds.height - SLIDE_MARGIN * 2
1206
1466
  const respectsExplicitMaximum = props.labelWidth === undefined || natural.width <= props.labelWidth
1207
1467
 
1208
1468
  if (fitsSlide && unwrapped.overlap === 0 && respectsExplicitMaximum)
@@ -1210,7 +1470,7 @@ function fitLabel(
1210
1470
 
1211
1471
  // An explicit `label-width` remains a useful author override. Without one,
1212
1472
  // the slide edges are the only width limit.
1213
- const maximum = Math.min(natural.width, props.labelWidth ?? natural.width, width - SLIDE_MARGIN * 2)
1473
+ const maximum = Math.min(natural.width, props.labelWidth ?? natural.width, bounds.width - SLIDE_MARGIN * 2)
1214
1474
  const minimum = Math.min(maximum, 160)
1215
1475
  let best: { box: Box, width: number, overlap: number } | undefined
1216
1476
 
@@ -1219,7 +1479,7 @@ function fitLabel(
1219
1479
  // Magic Move animations.
1220
1480
  for (let cap = maximum; cap >= minimum; cap -= 48) {
1221
1481
  const size = measureLabel(toLocal, cap)
1222
- const placed = placeLabel(root, toLocal, anchor, size, width, height)
1482
+ const placed = placeLabel(anchor, size, bounds, obstacles)
1223
1483
  if (placed.overlap === 0)
1224
1484
  return { box: placed.box, width: cap }
1225
1485
  if (!best || placed.overlap < best.overlap)
@@ -1229,7 +1489,7 @@ function fitLabel(
1229
1489
  // Include the lower bound when the step above did not land on it.
1230
1490
  if (!best || best.width !== minimum) {
1231
1491
  const size = measureLabel(toLocal, minimum)
1232
- const placed = placeLabel(root, toLocal, anchor, size, width, height)
1492
+ const placed = placeLabel(anchor, size, bounds, obstacles)
1233
1493
  if (placed.overlap === 0)
1234
1494
  return { box: placed.box, width: minimum }
1235
1495
  if (!best || placed.overlap < best.overlap)
@@ -1240,12 +1500,10 @@ function fitLabel(
1240
1500
  }
1241
1501
 
1242
1502
  function placeLabel(
1243
- root: HTMLElement,
1244
- toLocal: (rect: DOMRect) => Box,
1245
1503
  anchor: Box,
1246
1504
  size: { width: number, height: number },
1247
- width: number,
1248
- height: number,
1505
+ bounds: Box,
1506
+ obstacles: Box[],
1249
1507
  ): { box: Box, overlap: number } {
1250
1508
  const halfW = size.width / 2
1251
1509
  const halfH = size.height / 2
@@ -1254,21 +1512,16 @@ function placeLabel(
1254
1512
  if (props.labelX !== undefined || props.labelY !== undefined) {
1255
1513
  return {
1256
1514
  box: centred(
1257
- props.labelX !== undefined ? width * props.labelX / 100 : anchor.cx,
1258
- props.labelY !== undefined ? height * props.labelY / 100 : anchor.cy,
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,
1259
1517
  ),
1260
1518
  overlap: 0,
1261
1519
  }
1262
1520
  }
1263
1521
 
1264
- // Obstacles are inflated so the label breathes: a label that ends up flush
1265
- // against the bottom of a code block reads as part of it.
1266
- const obstacles = collectObstacles(root, toLocal)
1267
- .map(box => padBox(box, props.clearance))
1268
- .concat(padBox(anchor, 8))
1269
1522
  const placement = resolvedPlacement.value
1270
1523
  const preferred = placement === 'auto'
1271
- ? (anchor.cy < height / 2 ? 'down' : 'up')
1524
+ ? (anchor.cy < bounds.cy ? 'down' : 'up')
1272
1525
  : placement
1273
1526
  const directions = placement === 'auto'
1274
1527
  ? [preferred, preferred === 'down' ? 'up' : 'down', 'right', 'left'] as const
@@ -1288,8 +1541,8 @@ function placeLabel(
1288
1541
  : anchor.cy + lateral
1289
1542
 
1290
1543
  const box = centred(
1291
- clamp(cx, SLIDE_MARGIN + halfW, width - SLIDE_MARGIN - halfW),
1292
- clamp(cy, SLIDE_MARGIN + halfH, height - SLIDE_MARGIN - halfH),
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),
1293
1546
  )
1294
1547
  const overlap = obstacles.reduce((total, obstacle) => total + overlapArea(box, obstacle), 0)
1295
1548
  const score = overlap * 6 + gap + Math.abs(lateral) * 0.6 + order * 400
@@ -1312,30 +1565,17 @@ function placeLabel(
1312
1565
  }
1313
1566
 
1314
1567
  /**
1315
- * Everything the label has to stay clear of: the leaf elements of the slide,
1316
- * which is what actually carries text and images, plus anything the slide opted
1317
- * in through `avoid-selector`. `.card` and `.kodee-character` are the Kotlin
1318
- * theme's callouts and mascot.
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.
1319
1574
  */
1320
- const BLOCK_OBSTACLES = 'pre, .slidev-code, .slidev-code-wrapper, .card, table, blockquote, .kodee-character'
1321
-
1322
1575
  function collectObstacles(root: HTMLElement, toLocal: (rect: DOMRect) => Box): Box[] {
1323
1576
  const slide = slideRoot() ?? root
1324
- const boxes: Box[] = []
1325
- for (const element of obstacleCandidates(slide)) {
1326
- // Empty leaves are spacers and other invisible layout helpers, which the
1327
- // label is free to cover.
1328
- const leaf = element.childElementCount === 0 && !!element.textContent?.trim()
1329
- // Blocks are added whole, so a label never lands in the padding of a code
1330
- // block or a card, which their leaf elements alone would leave free.
1331
- const block = element.matches(BLOCK_OBSTACLES)
1332
- if (!leaf && !block && !isMedia(element))
1333
- continue
1334
- const rect = element.getBoundingClientRect()
1335
- if (rect.width < 6 || rect.height < 6)
1336
- continue
1337
- boxes.push(toLocal(rect))
1338
- }
1577
+ const scan = scanObstacles(slide)
1578
+ const boxes: Box[] = [...scan.blocks, ...scan.media, ...scan.texts].map(toLocal)
1339
1579
  if (props.avoidSelector) {
1340
1580
  for (const element of Array.from(slide.querySelectorAll<HTMLElement>(props.avoidSelector)))
1341
1581
  boxes.push(toLocal(element.getBoundingClientRect()))
@@ -1418,7 +1658,9 @@ onMounted(async () => {
1418
1658
  }
1419
1659
  // Navigating backwards remounts the slide. If this click was already reached,
1420
1660
  // render the final state instead of replaying the entrance animation.
1421
- showImmediately.value = $clicks.value >= resolvedClick.value && withinRange.value
1661
+ showImmediately.value = isCurrentSlide.value
1662
+ && $clicks.value >= resolvedClick.value
1663
+ && withinRange.value
1422
1664
  unsettle()
1423
1665
  scheduleUpdate()
1424
1666
 
@@ -1444,12 +1686,16 @@ onMounted(async () => {
1444
1686
  mutationObserver.observe(element, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['style', 'class'] })
1445
1687
  }
1446
1688
 
1447
- document.fonts?.ready.then(scheduleUpdate)
1689
+ document.fonts?.ready.then(() => {
1690
+ labelSizeCache.clear()
1691
+ scheduleUpdate()
1692
+ })
1448
1693
  window.addEventListener('resize', scheduleUpdate)
1449
1694
  })
1450
1695
 
1451
1696
  onBeforeUnmount(() => {
1452
1697
  mounted = false
1698
+ settleRun++
1453
1699
  clearTimeout(exitFadeTimer)
1454
1700
  $clicksContext.unregister(ownClicks)
1455
1701
  cancelAnimationFrame(frame)
@@ -1466,12 +1712,29 @@ onBeforeUnmount(() => {
1466
1712
  // the annotated element for a while after it changes.
1467
1713
  watch($clicks, () => {
1468
1714
  unsettle()
1469
- track()
1470
- })
1715
+ track(CLICK_TRACK_DURATION)
1716
+ }, { flush: 'sync' })
1717
+
1718
+ // Preloaded slides can already contain their annotations before navigation
1719
+ // starts, so mount-time detection alone is not enough. Watching this annotation's
1720
+ // active-slide state also covers a preloaded component becoming visible inside
1721
+ // document.startViewTransition(); the grace period lets the browser create the
1722
+ // document-level pseudo-elements before the first animation scan.
1723
+ watch(isCurrentSlide, (current) => {
1724
+ if (current) {
1725
+ unsettle(VIEW_TRANSITION_START_GRACE)
1726
+ track()
1727
+ }
1728
+ }, { flush: 'sync' })
1471
1729
 
1472
1730
  // Any prop can change what is drawn or where the label may go, so re-measure
1473
1731
  // on all of them instead of maintaining a list that can silently go stale.
1474
- watch(props, scheduleUpdate)
1732
+ // The caches assume unchanged props, so they are dropped along the way.
1733
+ watch(props, () => {
1734
+ labelSizeCache.clear()
1735
+ lastMarkKey = ''
1736
+ scheduleUpdate()
1737
+ })
1475
1738
  </script>
1476
1739
 
1477
1740
  <template>
@@ -1558,6 +1821,14 @@ watch(props, scheduleUpdate)
1558
1821
  {{ props.label }}
1559
1822
  </div>
1560
1823
  <slot />
1824
+ <!-- Keep the live region mounted so screen readers announce the label when
1825
+ its click is reached. The positioned copy is presentation-only. -->
1826
+ <span
1827
+ class="annotation-label-status annotation-ignore"
1828
+ role="status"
1829
+ aria-live="polite"
1830
+ aria-atomic="true"
1831
+ >{{ labelActive && geometry.ready ? props.label : '' }}</span>
1561
1832
  </div>
1562
1833
  </template>
1563
1834
 
@@ -1572,6 +1843,14 @@ watch(props, scheduleUpdate)
1572
1843
  Slidev hides them when no annotation is in the way. */
1573
1844
  .drawn-annotation.slidev-vclick-hidden { visibility: hidden; }
1574
1845
  .click-marker { position: absolute; width: 0; height: 0; overflow: hidden; }
1846
+ .annotation-label-status {
1847
+ position: absolute;
1848
+ width: 1px;
1849
+ height: 1px;
1850
+ overflow: hidden;
1851
+ clip-path: inset(50%);
1852
+ white-space: nowrap;
1853
+ }
1575
1854
 
1576
1855
  .annotation-overlay {
1577
1856
  position: absolute;
@@ -1599,8 +1878,8 @@ watch(props, scheduleUpdate)
1599
1878
  made them disappear much more harshly than the content around them.
1600
1879
  `--exit-fade` mirrors the EXIT_FADE_DURATION constant in the script. */
1601
1880
  transition:
1602
- stroke-dashoffset 1ms linear var(--exit-fade, 280ms),
1603
- opacity var(--exit-fade, 280ms) ease-out;
1881
+ stroke-dashoffset 1ms linear var(--exit-fade, 300ms),
1882
+ opacity var(--exit-fade, 300ms) ease-out;
1604
1883
  }
1605
1884
 
1606
1885
  .is-active .annotation-mark {
@@ -1648,7 +1927,7 @@ watch(props, scheduleUpdate)
1648
1927
  pointer-events: none;
1649
1928
  opacity: 0;
1650
1929
  visibility: hidden;
1651
- transition: opacity var(--label-fade, 240ms) ease-out;
1930
+ transition: opacity var(--label-fade, 250ms) ease-out;
1652
1931
  }
1653
1932
 
1654
1933
  /* Measured before it is placed, so keep it laid out but invisible until then. */