@vocasync/astro 1.0.1 → 2.1.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 (148) hide show
  1. package/README.md +735 -93
  2. package/dist/api/client.d.ts.map +1 -1
  3. package/dist/api/client.js.map +1 -1
  4. package/dist/api/index.d.ts +1 -1
  5. package/dist/api/index.d.ts.map +1 -1
  6. package/dist/api/index.js +1 -1
  7. package/dist/api/index.js.map +1 -1
  8. package/dist/cli.js.map +1 -1
  9. package/dist/components/AudioPlayer.astro +305 -1141
  10. package/dist/components/index.d.ts +10 -32
  11. package/dist/components/index.d.ts.map +1 -1
  12. package/dist/components/index.js +1 -3
  13. package/dist/components/index.js.map +1 -1
  14. package/dist/components/types.d.ts +117 -0
  15. package/dist/components/types.d.ts.map +1 -0
  16. package/dist/components/types.js +2 -0
  17. package/dist/components/types.js.map +1 -0
  18. package/dist/config/index.d.ts +3 -2
  19. package/dist/config/index.d.ts.map +1 -1
  20. package/dist/config/index.js +2 -1
  21. package/dist/config/index.js.map +1 -1
  22. package/dist/config/languages.d.ts +33 -0
  23. package/dist/config/languages.d.ts.map +1 -0
  24. package/dist/config/languages.js +167 -0
  25. package/dist/config/languages.js.map +1 -0
  26. package/dist/config/schema.d.ts +225 -172
  27. package/dist/config/schema.d.ts.map +1 -1
  28. package/dist/config/schema.js +45 -24
  29. package/dist/config/schema.js.map +1 -1
  30. package/dist/core/content-loader.js +1 -1
  31. package/dist/core/content-loader.js.map +1 -1
  32. package/dist/core/index.d.ts +2 -2
  33. package/dist/core/index.d.ts.map +1 -1
  34. package/dist/core/index.js +2 -2
  35. package/dist/core/index.js.map +1 -1
  36. package/dist/core/speech-builder.js.map +1 -1
  37. package/dist/index.d.ts +6 -7
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +5 -6
  40. package/dist/index.js.map +1 -1
  41. package/dist/integration.d.ts +28 -2
  42. package/dist/integration.d.ts.map +1 -1
  43. package/dist/integration.js +40 -3
  44. package/dist/integration.js.map +1 -1
  45. package/dist/lib/latex-to-speech/index.d.ts.map +1 -1
  46. package/dist/lib/latex-to-speech/index.js.map +1 -1
  47. package/dist/player-core/boot.d.ts +9 -0
  48. package/dist/player-core/boot.d.ts.map +1 -0
  49. package/dist/player-core/boot.js +59 -0
  50. package/dist/player-core/boot.js.map +1 -0
  51. package/dist/player-core/highlighter.d.ts +31 -0
  52. package/dist/player-core/highlighter.d.ts.map +1 -0
  53. package/dist/player-core/highlighter.js +103 -0
  54. package/dist/player-core/highlighter.js.map +1 -0
  55. package/dist/player-core/index.d.ts +17 -0
  56. package/dist/player-core/index.d.ts.map +1 -0
  57. package/dist/player-core/index.js +24 -0
  58. package/dist/player-core/index.js.map +1 -0
  59. package/dist/player-core/media-url.d.ts +18 -0
  60. package/dist/player-core/media-url.d.ts.map +1 -0
  61. package/dist/player-core/media-url.js +33 -0
  62. package/dist/player-core/media-url.js.map +1 -0
  63. package/dist/player-core/player.d.ts +9 -0
  64. package/dist/player-core/player.d.ts.map +1 -0
  65. package/dist/player-core/player.js +622 -0
  66. package/dist/player-core/player.js.map +1 -0
  67. package/dist/player-core/registry.d.ts +20 -0
  68. package/dist/player-core/registry.d.ts.map +1 -0
  69. package/dist/player-core/registry.js +31 -0
  70. package/dist/player-core/registry.js.map +1 -0
  71. package/dist/player-core/seek-delegate.d.ts +24 -0
  72. package/dist/player-core/seek-delegate.d.ts.map +1 -0
  73. package/dist/player-core/seek-delegate.js +64 -0
  74. package/dist/player-core/seek-delegate.js.map +1 -0
  75. package/dist/player-core/storage.d.ts +38 -0
  76. package/dist/player-core/storage.d.ts.map +1 -0
  77. package/dist/player-core/storage.js +107 -0
  78. package/dist/player-core/storage.js.map +1 -0
  79. package/dist/player-core/strings.d.ts +53 -0
  80. package/dist/player-core/strings.d.ts.map +1 -0
  81. package/dist/player-core/strings.js +45 -0
  82. package/dist/player-core/strings.js.map +1 -0
  83. package/dist/player-core/timings.d.ts +56 -0
  84. package/dist/player-core/timings.d.ts.map +1 -0
  85. package/dist/player-core/timings.js +90 -0
  86. package/dist/player-core/timings.js.map +1 -0
  87. package/dist/rehype/audio-words.d.ts +9 -3
  88. package/dist/rehype/audio-words.d.ts.map +1 -1
  89. package/dist/rehype/audio-words.js +17 -9
  90. package/dist/rehype/audio-words.js.map +1 -1
  91. package/dist/rehype/index.d.ts +2 -2
  92. package/dist/rehype/index.d.ts.map +1 -1
  93. package/dist/rehype/index.js.map +1 -1
  94. package/dist/rehype/rehype-math-speech.d.ts.map +1 -1
  95. package/dist/rehype/rehype-math-speech.js +2 -0
  96. package/dist/rehype/rehype-math-speech.js.map +1 -1
  97. package/dist/styles/content.css +41 -0
  98. package/dist/styles/layers.css +13 -0
  99. package/dist/styles/player.css +517 -0
  100. package/dist/styles/preset-shadcn.css +31 -0
  101. package/dist/styles/tokens.css +266 -0
  102. package/dist/styles/vocasync.css +10 -0
  103. package/dist/sync/index.d.ts +1 -1
  104. package/dist/sync/index.d.ts.map +1 -1
  105. package/dist/sync/index.js +1 -1
  106. package/dist/sync/index.js.map +1 -1
  107. package/dist/sync/orchestrator.d.ts.map +1 -1
  108. package/dist/sync/orchestrator.js +101 -47
  109. package/dist/sync/orchestrator.js.map +1 -1
  110. package/dist/types/index.d.ts +19 -5
  111. package/dist/types/index.d.ts.map +1 -1
  112. package/package.json +39 -17
  113. package/src/api/index.ts +4 -4
  114. package/src/components/AudioPlayer.astro +305 -1141
  115. package/src/components/index.ts +19 -34
  116. package/src/components/types.ts +140 -0
  117. package/src/config/index.ts +29 -24
  118. package/src/config/languages.ts +171 -0
  119. package/src/config/schema.ts +47 -24
  120. package/src/core/content-loader.ts +1 -1
  121. package/src/core/index.ts +7 -7
  122. package/src/env.d.ts +2 -0
  123. package/src/index.ts +23 -28
  124. package/src/integration.ts +66 -4
  125. package/src/player-core/boot.ts +62 -0
  126. package/src/player-core/highlighter.ts +159 -0
  127. package/src/player-core/index.ts +45 -0
  128. package/src/player-core/media-url.ts +35 -0
  129. package/src/player-core/player.ts +725 -0
  130. package/src/player-core/registry.ts +40 -0
  131. package/src/player-core/seek-delegate.ts +92 -0
  132. package/src/player-core/storage.ts +112 -0
  133. package/src/player-core/strings.ts +89 -0
  134. package/src/player-core/timings.ts +115 -0
  135. package/src/rehype/audio-words.ts +25 -12
  136. package/src/rehype/index.ts +2 -3
  137. package/src/rehype/rehype-math-speech.ts +3 -1
  138. package/src/styles/content.css +41 -0
  139. package/src/styles/layers.css +13 -0
  140. package/src/styles/player.css +517 -0
  141. package/src/styles/preset-shadcn.css +31 -0
  142. package/src/styles/tokens.css +266 -0
  143. package/src/styles/vocasync.css +10 -0
  144. package/src/sync/index.ts +1 -1
  145. package/src/sync/orchestrator.ts +120 -56
  146. package/src/types/index.ts +19 -5
  147. package/dist/styles/variables.css +0 -164
  148. package/src/styles/variables.css +0 -164
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Tracks live player instances on the page.
3
+ *
4
+ * Exists for two reasons: exclusive playback (starting one player stops the others,
5
+ * rather than letting several tracks overlap), and teardown, which a view-transition
6
+ * navigation needs so animation loops and observers do not leak across pages.
7
+ */
8
+
9
+ export interface RegisteredPlayer {
10
+ readonly root: Element;
11
+ pause(): void;
12
+ destroy(): void;
13
+ }
14
+
15
+ const instances = new Set<RegisteredPlayer>();
16
+
17
+ export function register(player: RegisteredPlayer): void {
18
+ instances.add(player);
19
+ }
20
+
21
+ export function unregister(player: RegisteredPlayer): void {
22
+ instances.delete(player);
23
+ }
24
+
25
+ /** Pause every player except the one starting. */
26
+ export function pauseOthers(except: RegisteredPlayer): void {
27
+ for (const player of instances) {
28
+ if (player !== except) player.pause();
29
+ }
30
+ }
31
+
32
+ /** Destroy every instance. Called before a view-transition swap. */
33
+ export function destroyAll(): void {
34
+ for (const player of Array.from(instances)) player.destroy();
35
+ instances.clear();
36
+ }
37
+
38
+ export function count(): number {
39
+ return instances.size;
40
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Click-to-seek delegation, keyed by the article root rather than the document.
3
+ *
4
+ * The shipped player attached a `click` listener to `document` from inside every
5
+ * player's init function. On a page with one player per post -- an index page, the
6
+ * common case -- clicking any word ran every listener, so every player seeked to that
7
+ * word and called play(). Several tracks started at once.
8
+ *
9
+ * Here each article root gets exactly one listener no matter how many players are on
10
+ * the page, and a word only ever reaches the player that owns the root containing it.
11
+ */
12
+
13
+ export type SeekHandler = (dataI: number) => void;
14
+
15
+ interface RootBinding {
16
+ handlers: SeekHandler[];
17
+ listener: (event: Event) => void;
18
+ }
19
+
20
+ const bindings = new WeakMap<Element, RootBinding>();
21
+
22
+ export interface SeekDelegateOptions {
23
+ wordSelector?: string;
24
+ /** Marks the root so CSS can show a pointer cursor over words. */
25
+ activeClass?: string;
26
+ /** Reports an ambiguous configuration; defaults to console.warn. */
27
+ onWarn?: (message: string) => void;
28
+ }
29
+
30
+ /**
31
+ * Route word clicks inside `root` to `handler`. Returns an unregister function.
32
+ */
33
+ export function registerSeekRoot(
34
+ root: Element,
35
+ handler: SeekHandler,
36
+ options: SeekDelegateOptions = {}
37
+ ): () => void {
38
+ const {
39
+ wordSelector = ".vocasync-word[data-i]",
40
+ activeClass = "vocasync-click-seek",
41
+ onWarn = (message: string) => console.warn(message),
42
+ } = options;
43
+
44
+ let binding = bindings.get(root);
45
+
46
+ if (!binding) {
47
+ const created: RootBinding = {
48
+ handlers: [],
49
+ listener: (event: Event) => {
50
+ const target = event.target as Element | null;
51
+ const span = target?.closest?.(wordSelector) as HTMLElement | null;
52
+ if (!span) return;
53
+
54
+ // Never hijack a text selection the reader is making.
55
+ const selection = root.ownerDocument?.defaultView?.getSelection?.();
56
+ if (selection && selection.toString().length > 0) return;
57
+
58
+ const dataI = Number.parseInt(span.dataset.i ?? "", 10);
59
+ if (!Number.isFinite(dataI)) return;
60
+
61
+ // Only the owning player acts. Notifying every handler is precisely the
62
+ // bug this module exists to fix.
63
+ created.handlers[0]?.(dataI);
64
+ },
65
+ };
66
+ root.addEventListener("click", created.listener);
67
+ root.classList.add(activeClass);
68
+ bindings.set(root, created);
69
+ binding = created;
70
+ }
71
+
72
+ binding.handlers.push(handler);
73
+ if (binding.handlers.length > 1) {
74
+ onWarn(
75
+ "[vocasync] Two players resolve to the same article root, so click-to-seek is " +
76
+ "ambiguous and only the first player will respond. Give each player its own " +
77
+ "`articleSelector`."
78
+ );
79
+ }
80
+
81
+ return () => {
82
+ const current = bindings.get(root);
83
+ if (!current) return;
84
+ const index = current.handlers.indexOf(handler);
85
+ if (index !== -1) current.handlers.splice(index, 1);
86
+ if (current.handlers.length === 0) {
87
+ root.removeEventListener("click", current.listener);
88
+ root.classList.remove(activeClass);
89
+ bindings.delete(root);
90
+ }
91
+ };
92
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Remembered playback preferences and positions.
3
+ *
4
+ * Every access is guarded. `localStorage` throws outright when a browser is
5
+ * configured to block site data, and in Safari's private mode writes throw once the
6
+ * quota is hit -- a player that crashes on boot because someone hardened their
7
+ * browser would be a poor trade for remembering a volume setting.
8
+ */
9
+
10
+ const PREFS_KEY = "vocasync:prefs";
11
+ const POSITION_PREFIX = "vocasync:pos:";
12
+
13
+ /** Preferences shared by every player on the site. */
14
+ export interface PlayerPrefs {
15
+ rate?: number;
16
+ volume?: number;
17
+ muted?: boolean;
18
+ highlighting?: boolean;
19
+ }
20
+
21
+ export interface StorageLike {
22
+ getItem(key: string): string | null;
23
+ setItem(key: string, value: string): void;
24
+ removeItem(key: string): void;
25
+ }
26
+
27
+ /** Returns null rather than throwing when storage is unavailable. */
28
+ export function getStorage(view?: { localStorage?: StorageLike } | null): StorageLike | null {
29
+ try {
30
+ const store = view?.localStorage;
31
+ if (!store) return null;
32
+ // Presence is not permission: probe before trusting it.
33
+ const probe = "vocasync:probe";
34
+ store.setItem(probe, "1");
35
+ store.removeItem(probe);
36
+ return store;
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ function readJson(store: StorageLike | null, key: string): unknown {
43
+ if (!store) return null;
44
+ try {
45
+ const raw = store.getItem(key);
46
+ return raw ? JSON.parse(raw) : null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ const isFiniteNumber = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
53
+
54
+ export function readPrefs(store: StorageLike | null): PlayerPrefs {
55
+ const raw = readJson(store, PREFS_KEY);
56
+ if (!raw || typeof raw !== "object") return {};
57
+ const { rate, volume, muted, highlighting } = raw as Record<string, unknown>;
58
+ const prefs: PlayerPrefs = {};
59
+ // Validate rather than trust: this is user-writable storage, and a bad rate would
60
+ // be assigned straight to playbackRate.
61
+ if (isFiniteNumber(rate) && rate > 0 && rate <= 5) prefs.rate = rate;
62
+ if (isFiniteNumber(volume) && volume >= 0 && volume <= 1) prefs.volume = volume;
63
+ if (typeof muted === "boolean") prefs.muted = muted;
64
+ if (typeof highlighting === "boolean") prefs.highlighting = highlighting;
65
+ return prefs;
66
+ }
67
+
68
+ export function writePrefs(store: StorageLike | null, patch: PlayerPrefs): void {
69
+ if (!store) return;
70
+ try {
71
+ store.setItem(PREFS_KEY, JSON.stringify({ ...readPrefs(store), ...patch }));
72
+ } catch {
73
+ // Quota or a blocked write; preferences are a convenience, not a requirement.
74
+ }
75
+ }
76
+
77
+ export function readPosition(store: StorageLike | null, slug: string): number | null {
78
+ const raw = readJson(store, POSITION_PREFIX + slug);
79
+ return isFiniteNumber(raw) && raw > 0 ? raw : null;
80
+ }
81
+
82
+ export function writePosition(store: StorageLike | null, slug: string, seconds: number): void {
83
+ if (!store || !Number.isFinite(seconds)) return;
84
+ try {
85
+ store.setItem(POSITION_PREFIX + slug, JSON.stringify(seconds));
86
+ } catch {
87
+ /* ignore */
88
+ }
89
+ }
90
+
91
+ export function clearPosition(store: StorageLike | null, slug: string): void {
92
+ if (!store) return;
93
+ try {
94
+ store.removeItem(POSITION_PREFIX + slug);
95
+ } catch {
96
+ /* ignore */
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Where to resume, given a remembered position.
102
+ *
103
+ * Declines when the reader was essentially at the start or had all but finished, so a
104
+ * fresh listen is not skipped a few seconds in and a completed article does not
105
+ * reopen at its final second.
106
+ */
107
+ export function resumePoint(saved: number | null, duration: number): number | null {
108
+ if (saved === null || !Number.isFinite(duration) || duration <= 0) return null;
109
+ if (saved < 5) return null;
110
+ if (saved > duration - 10) return null;
111
+ return saved;
112
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Every piece of text the player can show or announce.
3
+ *
4
+ * All of it was hardcoded English -- including the aria-labels -- in a product whose
5
+ * premise is 57 languages. The keys are the contract; how they get filled is up to the
6
+ * platform (a `strings` prop here, gettext in the WordPress plugin).
7
+ */
8
+ export interface PlayerStrings {
9
+ /** Accessible name for the player region. */
10
+ label: string;
11
+ loading: string;
12
+ /** Shown when the article has no audio. */
13
+ unavailable: string;
14
+ /** Shown when the audio exists but failed to load. */
15
+ error: string;
16
+ retry: string;
17
+ play: string;
18
+ pause: string;
19
+ seek: string;
20
+ /**
21
+ * Announced by the seek slider. `{current}` and `{total}` are replaced with spoken
22
+ * durations, e.g. "2 minutes 30 seconds of 10 minutes".
23
+ */
24
+ seekPosition: string;
25
+ mute: string;
26
+ unmute: string;
27
+ volume: string;
28
+ speed: string;
29
+ /** Label for a speed step. `{rate}` is replaced with the playback rate. */
30
+ speedValue: string;
31
+ highlightOn: string;
32
+ highlightOff: string;
33
+ /** Accessible name for skip-back. `{seconds}` is replaced with the interval. */
34
+ skipBack: string;
35
+ skipForward: string;
36
+ }
37
+
38
+ export const defaultStrings: PlayerStrings = {
39
+ label: "Listen to this article",
40
+ loading: "Loading audio…",
41
+ unavailable: "Audio not available for this article",
42
+ error: "Audio could not be loaded",
43
+ retry: "Try again",
44
+ play: "Play",
45
+ pause: "Pause",
46
+ seek: "Seek",
47
+ seekPosition: "{current} of {total}",
48
+ mute: "Mute",
49
+ unmute: "Unmute",
50
+ volume: "Volume",
51
+ speed: "Playback speed",
52
+ speedValue: "{rate}x",
53
+ highlightOn: "Disable word highlighting",
54
+ highlightOff: "Enable word highlighting",
55
+ skipBack: "Back {seconds} seconds",
56
+ skipForward: "Forward {seconds} seconds",
57
+ };
58
+
59
+ /**
60
+ * Every string is a plain string, so all of them are translatable and all of them
61
+ * survive JSON. They were briefly functions, which quietly made the four
62
+ * placeholder-bearing ones -- the skip labels, the rate label and the seek
63
+ * announcement -- impossible to override at all.
64
+ */
65
+ export type SerializableStrings = PlayerStrings;
66
+
67
+ export function resolveStrings(overrides?: Partial<PlayerStrings>): PlayerStrings {
68
+ return { ...defaultStrings, ...(overrides ?? {}) };
69
+ }
70
+
71
+ /**
72
+ * Substitute `{name}` placeholders. Unknown placeholders are left alone rather than
73
+ * blanked, so a mistyped key in a translation is visible instead of silently missing.
74
+ */
75
+ export function formatString(template: string, vars: Record<string, string | number>): string {
76
+ return template.replace(/\{(\w+)\}/g, (match, key) => (key in vars ? String(vars[key]) : match));
77
+ }
78
+
79
+ /** Spoken duration for aria-valuetext: "2 minutes 30 seconds", not "150". */
80
+ export function describeTime(seconds: number): string {
81
+ if (!Number.isFinite(seconds) || seconds < 0) return "0 seconds";
82
+ const total = Math.floor(seconds);
83
+ const m = Math.floor(total / 60);
84
+ const s = total % 60;
85
+ const parts: string[] = [];
86
+ if (m) parts.push(`${m} minute${m === 1 ? "" : "s"}`);
87
+ if (s || !m) parts.push(`${s} second${s === 1 ? "" : "s"}`);
88
+ return parts.join(" ");
89
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Pure word-highlighting math. No DOM, no audio element, no side effects.
3
+ *
4
+ * The rehype plugin wraps each visible word in a span carrying `data-i` (its start
5
+ * index in the alignment word stream) and `data-n` (how many alignment tokens it
6
+ * consumes). One visible unit can span several tokens -- "$50" is spoken as two
7
+ * tokens, an equation as many -- so its span runs from the earliest start to the
8
+ * latest end of the tokens it covers.
9
+ *
10
+ * `ref` is passed through opaquely: the DOM element in the browser, an id in tests.
11
+ */
12
+
13
+ /** Tolerance for float comparisons against alignment timings. */
14
+ export const EPS = 0.0001;
15
+
16
+ /** A word timing from the alignment stream. */
17
+ export interface WordTiming {
18
+ start: number;
19
+ end: number;
20
+ }
21
+
22
+ /** A visible unit and the slice of the alignment stream it covers. */
23
+ export interface SpanItem<Ref> {
24
+ dataI: number;
25
+ dataN: number;
26
+ ref: Ref;
27
+ }
28
+
29
+ /** A visible unit resolved to a time span. */
30
+ export interface SpanTiming<Ref> {
31
+ start: number;
32
+ end: number;
33
+ ref: Ref;
34
+ }
35
+
36
+ /**
37
+ * Resolve each visible unit to `min(start)..max(end)` over the alignment tokens it
38
+ * covers. Units whose tokens are all missing are dropped rather than guessed at, so a
39
+ * stale audio map degrades to "some words never highlight" instead of highlighting
40
+ * the wrong ones. The result is sorted by start time, which `idxForTime` relies on.
41
+ */
42
+ export function computeSpanTimings<Ref>(
43
+ items: readonly SpanItem<Ref>[],
44
+ words: readonly WordTiming[]
45
+ ): SpanTiming<Ref>[] {
46
+ const out: SpanTiming<Ref>[] = [];
47
+
48
+ for (const item of items) {
49
+ const { dataI, dataN, ref } = item;
50
+ if (!Number.isFinite(dataI) || !Number.isFinite(dataN) || dataN < 1) continue;
51
+
52
+ let minStart = Number.POSITIVE_INFINITY;
53
+ let maxEnd = Number.NEGATIVE_INFINITY;
54
+ for (let k = dataI; k < dataI + dataN; k++) {
55
+ const t = words[k];
56
+ if (!t) continue;
57
+ if (t.start < minStart) minStart = t.start;
58
+ if (t.end > maxEnd) maxEnd = t.end;
59
+ }
60
+
61
+ if (Number.isFinite(minStart) && Number.isFinite(maxEnd)) {
62
+ // Widen a zero-length or inverted span. `idxForTime` advances past any span
63
+ // whose end is <= t, so a span with end == start can never be selected and the
64
+ // word would silently never highlight. Only degenerate alignment data is
65
+ // affected; every real span already has end > start.
66
+ if (!(maxEnd > minStart)) maxEnd = minStart + EPS;
67
+ out.push({ start: minStart, end: maxEnd, ref });
68
+ }
69
+ }
70
+
71
+ out.sort((a, b) => a.start - b.start);
72
+ return out;
73
+ }
74
+
75
+ /**
76
+ * Index of the first span whose end is after `t`. Returns `spanTimings.length` when
77
+ * `t` is past every span, and -1 when there are none. The result is a *candidate*:
78
+ * the caller still has to check that `t` falls inside that span, because the audio
79
+ * has real silence between words where nothing should be highlighted.
80
+ */
81
+ export function idxForTime<Ref>(spanTimings: readonly SpanTiming<Ref>[], t: number): number {
82
+ const n = spanTimings.length;
83
+ if (!n) return -1;
84
+
85
+ let lo = 0;
86
+ let hi = n - 1;
87
+ while (lo <= hi) {
88
+ const mid = (lo + hi) >> 1;
89
+ if (spanTimings[mid].end <= t) lo = mid + 1;
90
+ else hi = mid - 1;
91
+ }
92
+ return lo;
93
+ }
94
+
95
+ /**
96
+ * The span active at `t`, or null when `t` falls in silence between words.
97
+ */
98
+ export function spanAtTime<Ref>(
99
+ spanTimings: readonly SpanTiming<Ref>[],
100
+ t: number
101
+ ): SpanTiming<Ref> | null {
102
+ if (!Number.isFinite(t)) return null;
103
+ const lo = idxForTime(spanTimings, t + EPS);
104
+ const entry = spanTimings[lo];
105
+ if (!entry) return null;
106
+ return t >= entry.start - EPS && t < entry.end + EPS ? entry : null;
107
+ }
108
+
109
+ /**
110
+ * The half-open range `[start, end)` of spans forming the trail behind index `lo`.
111
+ */
112
+ export function trailRange(lo: number, trailLength: number): { start: number; end: number } {
113
+ const end = Math.max(0, lo);
114
+ return { start: Math.max(0, end - Math.max(0, trailLength)), end };
115
+ }
@@ -14,10 +14,16 @@ export interface RehypeAudioWordsOptions {
14
14
  */
15
15
  audioMapPath?: string;
16
16
  /**
17
- * CSS class for generated word spans.
18
- * @default "vocasync" (spans get the class `${classPrefix}-word`)
17
+ * An extra class added to every word span, alongside `vocasync-word`.
18
+ *
19
+ * Additive on purpose. The previous `classPrefix` option renamed the span class but
20
+ * nothing else: `.vocasync-word` stayed hardcoded in the stylesheet, the player and
21
+ * the WordPress fork, and `.vocasync-click-seek` and `.vocasync-math` were never
22
+ * covered at all -- so setting it silently broke highlighting. If you need to
23
+ * restyle the spans, target this class or override the tokens; if you need entirely
24
+ * different markup, drive the engine yourself via `@vocasync/astro/player-core`.
19
25
  */
20
- classPrefix?: string;
26
+ extraWordClass?: string;
21
27
  /**
22
28
  * Content collection folder name used to extract slugs.
23
29
  * @default "articles"
@@ -63,17 +69,24 @@ const SKIP_CLASSES = new Set(["katex", "katex-mathml", "katex-html"]);
63
69
  const rehypeAudioWords: Plugin<[RehypeAudioWordsOptions?], Root> = (options = {}) => {
64
70
  const {
65
71
  audioMapPath = ".vocasync/audio-map.json",
66
- classPrefix = "vocasync",
72
+ extraWordClass,
67
73
  collectionName = "articles",
68
74
  } = options;
69
- const wordClass = `${classPrefix}-word`;
75
+ const wordClasses = extraWordClass ? ["vocasync-word", extraWordClass] : ["vocasync-word"];
70
76
 
71
77
  return (tree, file) => {
72
78
  const audioMap = loadAudioMapSync(audioMapPath);
73
79
  if (!audioMap) return;
74
80
 
75
81
  const slug = resolveSlug(file, collectionName);
76
- if (!slug || !audioMap.entries[slug]) return; // only wrap posts that have audio
82
+ if (!slug) return;
83
+ const entry = audioMap.entries[slug];
84
+ if (!entry) return; // only wrap posts that have audio
85
+
86
+ // A post synthesised without alignment has no word stream, so `data-i` would index
87
+ // into nothing. Wrapping anyway would bloat the HTML and leave spans that look
88
+ // interactive but can never highlight.
89
+ if (!Array.isArray(entry.words) || entry.words.length === 0) return;
77
90
 
78
91
  let nextIndex = 0;
79
92
  const replacements: Array<{
@@ -100,7 +113,7 @@ const rehypeAudioWords: Plugin<[RehypeAudioWordsOptions?], Root> = (options = {}
100
113
  replacements.push({
101
114
  parent,
102
115
  index,
103
- nodes: [wrapSpan([node as Element], nextIndex, count, wordClass)],
116
+ nodes: [wrapSpan([node as Element], nextIndex, count, wordClasses)],
104
117
  });
105
118
  nextIndex += count;
106
119
  return;
@@ -124,7 +137,7 @@ const rehypeAudioWords: Plugin<[RehypeAudioWordsOptions?], Root> = (options = {}
124
137
  if (start > cursor) out.push({ type: "text", value: text.slice(cursor, start) });
125
138
  const count = spokenTokenCount(m[0]);
126
139
  if (count > 0) {
127
- out.push(wrapText(m[0], nextIndex, count, wordClass));
140
+ out.push(wrapText(m[0], nextIndex, count, wordClasses));
128
141
  nextIndex += count;
129
142
  } else {
130
143
  out.push({ type: "text", value: m[0] });
@@ -145,12 +158,12 @@ const rehypeAudioWords: Plugin<[RehypeAudioWordsOptions?], Root> = (options = {}
145
158
  };
146
159
  };
147
160
 
148
- function wrapText(word: string, dataI: number, dataN: number, wordClass: string): Element {
161
+ function wrapText(word: string, dataI: number, dataN: number, wordClasses: string[]): Element {
149
162
  return {
150
163
  type: "element",
151
164
  tagName: "span",
152
165
  properties: {
153
- className: [wordClass],
166
+ className: [...wordClasses],
154
167
  "data-i": String(dataI),
155
168
  "data-n": String(dataN),
156
169
  },
@@ -162,13 +175,13 @@ function wrapSpan(
162
175
  children: (Text | Element)[],
163
176
  dataI: number,
164
177
  dataN: number,
165
- wordClass: string
178
+ wordClasses: string[]
166
179
  ): Element {
167
180
  return {
168
181
  type: "element",
169
182
  tagName: "span",
170
183
  properties: {
171
- className: [wordClass],
184
+ className: [...wordClasses],
172
185
  "data-i": String(dataI),
173
186
  "data-n": String(dataN),
174
187
  },
@@ -1,5 +1,4 @@
1
- export { default, rehypeAudioWords } from "./audio-words.js";
2
1
  export type { RehypeAudioWordsOptions } from "./audio-words.js";
3
-
4
- export { default as rehypeMathSpeech } from "./rehype-math-speech.js";
2
+ export { default, rehypeAudioWords } from "./audio-words.js";
5
3
  export type { RehypeMathSpeechOptions } from "./rehype-math-speech.js";
4
+ export { default as rehypeMathSpeech } from "./rehype-math-speech.js";
@@ -75,7 +75,9 @@ export default function rehypeMathSpeech(options: RehypeMathSpeechOptions = {})
75
75
  }
76
76
 
77
77
  function classNames(el: Element): string[] {
78
- const cls = el.properties?.className;
78
+ // @types/hast declares className as string[], but plugins earlier in the chain
79
+ // can leave a raw string, so both shapes are handled at runtime.
80
+ const cls: unknown = el.properties?.className;
79
81
  if (Array.isArray(cls)) return cls.filter((c): c is string => typeof c === "string");
80
82
  if (typeof cls === "string") return cls.split(/\s+/);
81
83
  return [];
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Styles for the article body, not the player chrome.
3
+ *
4
+ * The word spans are emitted at build time by the rehype plugin, so these rules are
5
+ * required whenever highlighting is used -- including by a consumer who drives the
6
+ * engine headlessly and ships no player chrome at all. That is why they are a
7
+ * separate file from player.css rather than part of it.
8
+ */
9
+ @layer vocasync.tokens, vocasync.base, vocasync.variants;
10
+
11
+ @layer vocasync.base {
12
+ :where(.vocasync-word) {
13
+ border-radius: var(--vocasync-word-radius);
14
+ padding: 0 0.0625rem;
15
+ margin: 0 -0.0625rem;
16
+ transition:
17
+ background-color var(--vocasync-transition-fast),
18
+ color var(--vocasync-transition-fast);
19
+ }
20
+
21
+ :where(.vocasync-word).is-active {
22
+ background-color: var(--vocasync-highlight-active-bg);
23
+ color: var(--vocasync-highlight-active-text, inherit);
24
+ }
25
+
26
+ /* The words already spoken, fading out behind the active one. */
27
+ :where(.vocasync-word).is-trail {
28
+ background-color: var(--vocasync-highlight-trail-bg);
29
+ }
30
+
31
+ /* Click-to-seek is opt-in, so the affordance only appears when it is wired up. */
32
+ :where(.vocasync-click-seek) :where(.vocasync-word) {
33
+ cursor: pointer;
34
+ }
35
+
36
+ @media (prefers-reduced-motion: reduce) {
37
+ :where(.vocasync-word) {
38
+ transition: none;
39
+ }
40
+ }
41
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Layer order for every VocaSync stylesheet.
3
+ *
4
+ * Import this FIRST if you care about deterministic ordering. Layer precedence is
5
+ * fixed by the order layer names are first seen, and an @import elsewhere in your app
6
+ * could otherwise register them later than your own layers -- which would let our
7
+ * rules outrank utilities that should win.
8
+ *
9
+ * Everything we ship lives in a layer, so any unlayered rule of yours beats it
10
+ * regardless of specificity. Selectors are additionally wrapped in :where(), which
11
+ * drops their specificity to zero, so even a layered rule of yours wins.
12
+ */
13
+ @layer vocasync.tokens, vocasync.base, vocasync.variants;