@qti-components/extended 0.0.0-stage → 0.0.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 (62) hide show
  1. package/LICENSE.md +674 -0
  2. package/dist/elements.d.ts +100 -0
  3. package/dist/elements.js +44 -0
  4. package/dist/elements.js.map +1 -0
  5. package/dist/index.d.ts +11 -0
  6. package/dist/index.js +12 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/qti-extended-jsx.d.ts +1894 -0
  9. package/dist/qti-extended-jsx.js +1 -0
  10. package/dist/register.d.ts +1 -0
  11. package/dist/register.js +7 -0
  12. package/dist/register.js.map +1 -0
  13. package/dist/test-bookmark/test-bookmark.d.ts +45 -0
  14. package/dist/test-bookmark/test-bookmark.js +136 -0
  15. package/dist/test-bookmark/test-bookmark.js.map +1 -0
  16. package/dist/test-character-sheet/test-character-sheet.d.ts +46 -0
  17. package/dist/test-character-sheet/test-character-sheet.js +259 -0
  18. package/dist/test-character-sheet/test-character-sheet.js.map +1 -0
  19. package/dist/test-item-link/test-item-link.d.ts +13 -0
  20. package/dist/test-item-link/test-item-link.js +28 -0
  21. package/dist/test-item-link/test-item-link.js.map +1 -0
  22. package/dist/test-lock/test-lock.d.ts +72 -0
  23. package/dist/test-lock/test-lock.js +242 -0
  24. package/dist/test-lock/test-lock.js.map +1 -0
  25. package/dist/test-print-context/test-print-context.d.ts +11 -0
  26. package/dist/test-print-context/test-print-context.js +20 -0
  27. package/dist/test-print-context/test-print-context.js.map +1 -0
  28. package/dist/test-print-item-variables/test-print-item-variables.d.ts +17 -0
  29. package/dist/test-print-item-variables/test-print-item-variables.js +95 -0
  30. package/dist/test-print-item-variables/test-print-item-variables.js.map +1 -0
  31. package/dist/test-print-state/test-print-state.d.ts +29 -0
  32. package/dist/test-print-state/test-print-state.js +101 -0
  33. package/dist/test-print-state/test-print-state.js.map +1 -0
  34. package/dist/test-scoring-buttons/test-scoring-buttons.d.ts +19 -0
  35. package/dist/test-scoring-buttons/test-scoring-buttons.js +95 -0
  36. package/dist/test-scoring-buttons/test-scoring-buttons.js.map +1 -0
  37. package/dist/test-scoring-feedback/test-scoring-feedback.d.ts +13 -0
  38. package/dist/test-scoring-feedback/test-scoring-feedback.js +54 -0
  39. package/dist/test-scoring-feedback/test-scoring-feedback.js.map +1 -0
  40. package/dist/test-section-link/test-section-link.d.ts +13 -0
  41. package/dist/test-section-link/test-section-link.js +28 -0
  42. package/dist/test-section-link/test-section-link.js.map +1 -0
  43. package/dist/test-stamp/test-stamp.d.ts +29 -0
  44. package/dist/test-stamp/test-stamp.js +105 -0
  45. package/dist/test-stamp/test-stamp.js.map +1 -0
  46. package/dist/test-view-toggle/test-view-toggle.d.ts +16 -0
  47. package/dist/test-view-toggle/test-view-toggle.js +49 -0
  48. package/dist/test-view-toggle/test-view-toggle.js.map +1 -0
  49. package/dist/test-view-toggle/test-view.d.ts +20 -0
  50. package/dist/test-view-toggle/test-view.js +73 -0
  51. package/dist/test-view-toggle/test-view.js.map +1 -0
  52. package/dist/test-zoom/test-zoom.d.ts +75 -0
  53. package/dist/test-zoom/test-zoom.js +158 -0
  54. package/dist/test-zoom/test-zoom.js.map +1 -0
  55. package/dist/tts/elements.d.ts +28 -0
  56. package/dist/tts/elements.js +14 -0
  57. package/dist/tts/elements.js.map +1 -0
  58. package/dist/tts/test-item-to-speech.d.ts +260 -0
  59. package/dist/tts/test-item-to-speech.js +1091 -0
  60. package/dist/tts/test-item-to-speech.js.map +1 -0
  61. package/package.json +65 -3
  62. package/README.md +0 -3
@@ -0,0 +1,1091 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { html, LitElement, css } from 'lit';
8
+ import { consume, provide, createContext } from '@lit/context';
9
+ import { property, state } from 'lit/decorators.js';
10
+ import { ifDefined } from 'lit/directives/if-defined.js';
11
+ import { computedContext } from '@citolab/qti-components/qti-base';
12
+ import { controlStyles as styles } from '@citolab/qti-components/qti-test/plugin-api';
13
+ // ─── CSS Custom Highlight ─────────────────────────────────────────────────────
14
+ /**
15
+ * Whether `node` sits inside `ancestor`, also through shadow roots: the test a notification comes
16
+ * from is this element's own test when the element is somewhere inside it.
17
+ */
18
+ const isInside = (node, ancestor) => {
19
+ for (let current = node; current;) {
20
+ if (current === ancestor)
21
+ return true;
22
+ current = current.parentNode ?? (current instanceof ShadowRoot ? current.host : null);
23
+ }
24
+ return false;
25
+ };
26
+ const HIGHLIGHT_ELEMENT = 'tts-element'; // navigation cursor — whole element
27
+ const HIGHLIGHT_WORD = 'tts-word'; // word boundary during speech
28
+ // Shared across all instances — added to whichever shadow root needs it. The two highlights are
29
+ // tints of the theme's info (the element being read) and warning (the word being spoken) colours,
30
+ // see-through so the text and its own background stay visible. Without the theme they fall back to
31
+ // the system Highlight and Mark colours. A host repaints them with --test-tts-element-highlight and
32
+ // --test-tts-word-highlight.
33
+ let highlightSheet = null;
34
+ function getHighlightSheet() {
35
+ if (!highlightSheet) {
36
+ highlightSheet = new CSSStyleSheet();
37
+ highlightSheet.replaceSync(`
38
+ ::highlight(${HIGHLIGHT_ELEMENT}) {
39
+ background-color: var(--test-tts-element-highlight, color-mix(in oklab, var(--qti-color-info, var(--qc-color-info, var(--cito-color-info, Highlight))) 15%, transparent));
40
+ color: inherit;
41
+ }
42
+ ::highlight(${HIGHLIGHT_WORD}) {
43
+ background-color: var(--test-tts-word-highlight, color-mix(in oklab, var(--qti-color-warning, var(--qc-color-warning, var(--cito-color-warning, Mark))) 55%, transparent));
44
+ color: inherit;
45
+ }
46
+ `);
47
+ }
48
+ return highlightSheet;
49
+ }
50
+ export const ttsContext = createContext(Symbol('tts-context'));
51
+ // ─── Icons ────────────────────────────────────────────────────────────────────
52
+ // Plain geometric glyphs on a 24-unit grid, painted in currentColor. SVG rather than text so
53
+ // every button gets the same box: text glyphs (◀◀ ▶ ⏸ ■ ☞) differ in width, and some fall back
54
+ // to an emoji font with different line metrics.
55
+ const ICONS = {
56
+ play: 'M8 5v14l11-7z',
57
+ pause: 'M6 5h4v14H6zM14 5h4v14h-4z',
58
+ stop: 'M6 6h12v12H6z',
59
+ prev: 'M6 5h2v14H6zM20 5v14L9 12z',
60
+ next: 'M16 5h2v14h-2zM4 5v14l11-7z',
61
+ pick: 'M5 3l13 7-5.5 1.6 3.4 6.6-2.4 1.3-3.4-6.7L6 17z'
62
+ };
63
+ /** Default button content: the icon, plus a visually hidden label as the accessible name. */
64
+ const iconContent = (icon, label) => {
65
+ const svg = html `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
66
+ <path d="${ICONS[icon]}"></path>
67
+ </svg>`;
68
+ return html `${svg}<span class="label">${label}</span>`;
69
+ };
70
+ // ─── Shared base for child button elements ────────────────────────────────────
71
+ /**
72
+ * Base class shared by all TTS control elements. Consumes `ttsContext` and
73
+ * mirrors the current speech state onto CSS custom states so each child can
74
+ * be styled with `:state(playing)`, `:state(paused)`, `:state(idle)`.
75
+ */
76
+ class TtsButtonBase extends LitElement {
77
+ static { this.styles = css `
78
+ :host {
79
+ display: inline-flex;
80
+ }
81
+ button {
82
+ ${styles.btn};
83
+ min-inline-size: var(--button-size, var(--test-button-size, 2.25rem));
84
+ padding-inline: 0.5rem;
85
+ /* Containing block for the visually hidden .label. Without it the label is placed against
86
+ the nearest positioned ancestor, which can sit outside a scroll container and make the
87
+ page as tall as the scrolled content. */
88
+ position: relative;
89
+ }
90
+ @media (hover: hover) and (pointer: fine) {
91
+ button:hover:not(:disabled) {
92
+ ${styles.btnInteractive};
93
+ }
94
+ }
95
+ button:active:not(:disabled) {
96
+ ${styles.btnActive};
97
+ }
98
+ button:focus-visible {
99
+ ${styles.focusRing};
100
+ }
101
+ button:disabled {
102
+ ${styles.dis};
103
+ }
104
+ /* A toggle that is on (the pick button in pick mode). The host carries :state(selected) for a
105
+ page's own rules; in here the inner button's aria-pressed says the same thing and matches in
106
+ a browser without :state(), so the look keys on that. */
107
+ button[aria-pressed='true'],
108
+ button[aria-pressed='true']:hover {
109
+ background-color: var(
110
+ --button-selected-background-color,
111
+ var(--test-button-selected-background-color, var(--qti-selected-bg, Highlight))
112
+ );
113
+ color: var(--button-selected-color, var(--test-button-selected-color, var(--qti-selected-color, HighlightText)));
114
+ }
115
+ svg,
116
+ ::slotted(svg) {
117
+ flex: none;
118
+ inline-size: var(--test-tts-icon-size, 1.125rem);
119
+ block-size: var(--test-tts-icon-size, 1.125rem);
120
+ }
121
+ svg {
122
+ fill: currentColor;
123
+ }
124
+ /* The default content is icon-only; this keeps the button's accessible name. */
125
+ .label {
126
+ position: absolute;
127
+ inline-size: 1px;
128
+ block-size: 1px;
129
+ overflow: hidden;
130
+ clip-path: inset(50%);
131
+ white-space: nowrap;
132
+ }
133
+ `; }
134
+ #internals = this.attachInternals();
135
+ #mirroredState;
136
+ #mirroredPicking = false;
137
+ #mirroredSelected = false;
138
+ /** Whether this control is a toggle that is on; mirrored as `:state(selected)`. A plain button never is. */
139
+ get selected() {
140
+ return false;
141
+ }
142
+ updated(_changed) {
143
+ // `_tts` is a context field, not a reactive property, so it never shows up in `changed`:
144
+ // compare against what was last mirrored instead.
145
+ const state = this._tts?.state;
146
+ const picking = this._tts?.picking ?? false;
147
+ const selected = this.selected;
148
+ if (state === this.#mirroredState && picking === this.#mirroredPicking && selected === this.#mirroredSelected)
149
+ return;
150
+ this.#mirroredState = state;
151
+ this.#mirroredPicking = picking;
152
+ this.#mirroredSelected = selected;
153
+ this.#internals.states.clear();
154
+ if (state)
155
+ this.#internals.states.add(state);
156
+ if (picking)
157
+ this.#internals.states.add('picking');
158
+ if (selected)
159
+ this.#internals.states.add('selected');
160
+ }
161
+ }
162
+ __decorate([
163
+ property({ type: String })
164
+ ], TtsButtonBase.prototype, "label", void 0);
165
+ __decorate([
166
+ consume({ context: ttsContext, subscribe: true })
167
+ ], TtsButtonBase.prototype, "_tts", void 0);
168
+ // ─── Controller element ───────────────────────────────────────────────────────
169
+ /**
170
+ * `<test-item-to-speech>` is the controller and context provider. It manages
171
+ * speech synthesis, word highlighting, and item element lookup. Compose your
172
+ * own player by placing control elements as children.
173
+ *
174
+ * @example
175
+ * ```html
176
+ * <test-item-to-speech language="nl-NL">
177
+ * <test-tts-play></test-tts-play>
178
+ * <test-tts-prev></test-tts-prev>
179
+ * <test-tts-next></test-tts-next>
180
+ * <test-tts-stop></test-tts-stop>
181
+ * </test-item-to-speech>
182
+ * ```
183
+ *
184
+ * The controller lays its controls out as a wrapping row; each control draws an icon button,
185
+ * and slotted content replaces the icon — a slotted `<svg>` is sized like the default one. Give a
186
+ * control with a slotted icon a `label`, since an icon has no text to name the button by. Buttons read the qti-theme tokens (with the theme's
187
+ * defaults as fallbacks), are painted through the `--button-*` slots every button in the theme shares
188
+ * (`--test-button-*` still works as an alias), and can be sized with `--button-size` and
189
+ * `--test-tts-icon-size`.
190
+ *
191
+ * ### Language resolution
192
+ *
193
+ * Each reading element is spoken in the language of the nearest `lang` attribute:
194
+ *
195
+ * 1. `lang` (or `xml:lang`) on the element itself
196
+ * 2. `lang` on the closest ancestor — including `<qti-assessment-item xml:lang>` and, across
197
+ * shadow roots, anything wrapping the test
198
+ * 3. `lang` on the document's `<html>` element
199
+ * 4. the `language` attribute on `<test-item-to-speech>`
200
+ *
201
+ * The transformer copies `xml:lang` over as a plain `lang` attribute, so QTI authored with
202
+ * `xml:lang="en-GB"` on a `<p>` or on the item root is honoured without further work.
203
+ *
204
+ * ### What is read
205
+ *
206
+ * Decided once per connect, by where the player is placed. The first rule that matches wins:
207
+ *
208
+ * 1. **Next to a stimulus placeholder** — the player shares its parent with a
209
+ * `[data-stimulus-idref]` element, e.g. in a reading-text panel beside the questions: the
210
+ * player reads that stimulus (its `qti-stimulus-body`), and only that. Not inside the
211
+ * placeholder: loading a stimulus replaces the placeholder's content. Items and navigation
212
+ * are ignored; when the stimulus is (re)loaded or the placeholder swapped, the player starts
213
+ * over on the new content.
214
+ * 2. **Next to `[data-tts-content]`** — the player shares its parent with an element marked
215
+ * `data-tts-content`: any HTML, not QTI, e.g. a start screen rendered by React. The marker goes
216
+ * on one container; the player reads the readable elements inside it. Navigation is ignored.
217
+ * The reading list is rebuilt when the player starts from the top, and when an element in it
218
+ * has left the page — so a re-render of the content never interrupts speech.
219
+ * 3. **Inside a `qti-assessment-item-ref`** — e.g. in a `<template item-ref>` on `<qti-test>`,
220
+ * so every item gets a player of its own: the player reads that item, and only that item.
221
+ * The navigation cursor is ignored; speech stops when the player leaves the page with its item.
222
+ * 4. **Anywhere else inside `<test-navigation>`** — e.g. a toolbar: the player follows the
223
+ * navigation cursor and reads the active item of the computed context. Navigating stops
224
+ * speech and starts the next item from the top.
225
+ *
226
+ * ```html
227
+ * <!-- 1. a player for the shared reading text -->
228
+ * <aside>
229
+ * <test-item-to-speech>…</test-item-to-speech>
230
+ * <div data-stimulus-idref="Stimulus1"></div>
231
+ * </aside>
232
+ *
233
+ * <!-- 2. a player for any other HTML -->
234
+ * <div>
235
+ * <test-item-to-speech>…</test-item-to-speech>
236
+ * <section data-tts-content lang="nl-NL">…</section>
237
+ * </div>
238
+ *
239
+ * <!-- 3. one player per item -->
240
+ * <qti-test>
241
+ * <template item-ref>
242
+ * <test-item-to-speech>…</test-item-to-speech>
243
+ * {{ xmlDoc }}
244
+ * </template>
245
+ * …
246
+ * </qti-test>
247
+ *
248
+ * <!-- 4. one player in the toolbar, following navigation -->
249
+ * <test-navigation>
250
+ * <header><test-item-to-speech>…</test-item-to-speech></header>
251
+ * <test-container test-url="…"></test-container>
252
+ * </test-navigation>
253
+ * ```
254
+ *
255
+ * In modes 3 and 4 the item re-rendering (navigating to the item already shown) restarts the
256
+ * player on the fresh content. An item player reads the item body as rendered: a stimulus
257
+ * placed inside the item is read with it, one placed outside (mode 1) is not. Only one player
258
+ * can speak at a time; starting one stops any other.
259
+ *
260
+ * Read are `p`, `h1`–`h6`, `li`, `dt`, `dd`, `th`, `td`, `caption`, `blockquote`, `figcaption`,
261
+ * `qti-prompt` and `qti-simple-choice` — the innermost match only — unless hidden (`display: none`)
262
+ * or inside `aria-hidden="true"`.
263
+ *
264
+ * ### Starting somewhere in the middle
265
+ *
266
+ * `<test-tts-pick>` switches the player into pick mode: every reading element gets the blue
267
+ * cursor highlight, and the first click on one of them leaves pick mode and starts reading
268
+ * from that element. Pressing the button again leaves pick mode without reading.
269
+ *
270
+ * @cssstate idle - No speech active
271
+ * @cssstate picking - Pick mode: all reading elements highlighted, waiting for a click
272
+ * @cssstate playing - Speech is playing
273
+ * @cssstate paused - Speech is paused
274
+ */
275
+ export class TestItemToSpeech extends LitElement {
276
+ static { this.styles = css `
277
+ :host {
278
+ display: inline-flex;
279
+ flex-wrap: wrap;
280
+ align-items: center;
281
+ gap: var(--test-tts-gap, 0.25rem);
282
+ }
283
+ `; }
284
+ #internals;
285
+ // Stimulus mode: set on connect when a stimulus placeholder sits next to the player. The
286
+ // placeholder itself is looked up on every use — a host may swap the element.
287
+ #stimulusMode;
288
+ // Stimulus mode: resets the player when the stimulus content next to it is replaced.
289
+ #stimulusObserver;
290
+ // Content mode: set on connect when a `[data-tts-content]` element sits next to the player.
291
+ // Any HTML, not QTI. No observer: the reading list is rebuilt on demand (#getReadingElements).
292
+ #contentMode;
293
+ // Item-ref mode: the item-ref this player sits in, resolved on connect. Null means cursor mode.
294
+ #itemRef;
295
+ // Item-ref mode: our item-ref, for its item-connected event. Cursor mode: where prev/next's
296
+ // navigation request is heard.
297
+ #boundHandleItemConnected;
298
+ #boundHandleNavigation;
299
+ // Cursor mode: the previous navigation position, to detect moving to another item or section.
300
+ #prevNavItemRefId;
301
+ #prevNavSectionId;
302
+ // Current set of block-level reading elements for the item, and the root they were collected from
303
+ #readingElements;
304
+ #readingRoot;
305
+ #currentElementIndex;
306
+ // Text nodes of the element currently being spoken (for word-boundary highlight)
307
+ #textNodes;
308
+ // The utterance this player is speaking; lets the error handler tell "our speech was
309
+ // cancelled by another player" apart from a cancel we issued ourselves.
310
+ #currentUtterance;
311
+ // Pick mode: all elements highlighted, a click on one starts reading from there.
312
+ #picking;
313
+ #pickRoot;
314
+ #boundHandlePickClick;
315
+ // Set when the last element has been read: the cursor stays on it (so prev still works),
316
+ // but the next play starts the item over instead of repeating that last element.
317
+ #finished;
318
+ // Two separate CSS Highlight objects
319
+ #elementHighlight; // whole-element cursor
320
+ #wordHighlight; // current word during speech
321
+ constructor() {
322
+ super();
323
+ /** Fallback language when neither the item content nor the document declares one. */
324
+ this.language = 'nl-NL';
325
+ this.#internals = this.attachInternals();
326
+ // Stimulus mode: set on connect when a stimulus placeholder sits next to the player. The
327
+ // placeholder itself is looked up on every use — a host may swap the element.
328
+ this.#stimulusMode = false;
329
+ // Stimulus mode: resets the player when the stimulus content next to it is replaced.
330
+ this.#stimulusObserver = null;
331
+ // Content mode: set on connect when a `[data-tts-content]` element sits next to the player.
332
+ // Any HTML, not QTI. No observer: the reading list is rebuilt on demand (#getReadingElements).
333
+ this.#contentMode = false;
334
+ // Item-ref mode: the item-ref this player sits in, resolved on connect. Null means cursor mode.
335
+ this.#itemRef = null;
336
+ // Item-ref mode: our item-ref, for its item-connected event. Cursor mode: where prev/next's
337
+ // navigation request is heard.
338
+ this.#boundHandleItemConnected = this.#handleItemConnected.bind(this);
339
+ this.#boundHandleNavigation = (event) => {
340
+ if (isInside(this, event.composedPath()[0]))
341
+ this.#stop();
342
+ };
343
+ // Cursor mode: the previous navigation position, to detect moving to another item or section.
344
+ this.#prevNavItemRefId = undefined;
345
+ this.#prevNavSectionId = undefined;
346
+ // Current set of block-level reading elements for the item, and the root they were collected from
347
+ this.#readingElements = null;
348
+ this.#readingRoot = null;
349
+ this.#currentElementIndex = 0;
350
+ // Text nodes of the element currently being spoken (for word-boundary highlight)
351
+ this.#textNodes = [];
352
+ // The utterance this player is speaking; lets the error handler tell "our speech was
353
+ // cancelled by another player" apart from a cancel we issued ourselves.
354
+ this.#currentUtterance = null;
355
+ // Pick mode: all elements highlighted, a click on one starts reading from there.
356
+ this.#picking = false;
357
+ this.#pickRoot = null;
358
+ this.#boundHandlePickClick = this.#handlePickClick.bind(this);
359
+ // Set when the last element has been read: the cursor stays on it (so prev still works),
360
+ // but the next play starts the item over instead of repeating that last element.
361
+ this.#finished = false;
362
+ // Two separate CSS Highlight objects
363
+ this.#elementHighlight = new Highlight(); // whole-element cursor
364
+ this.#wordHighlight = new Highlight(); // current word during speech
365
+ this._ttsContext = {
366
+ state: 'idle',
367
+ currentElementIndex: 0,
368
+ elementCount: 0,
369
+ play: () => this.#playSpeech(),
370
+ pause: () => this.#pause(),
371
+ resume: () => this.#resume(),
372
+ stop: () => {
373
+ this.#stopPicking();
374
+ this.#stop();
375
+ },
376
+ prevElement: () => this.#prevElement(),
377
+ nextElement: () => this.#nextElement(),
378
+ togglePick: () => this.#togglePick(),
379
+ picking: false
380
+ };
381
+ }
382
+ // willUpdate, not updated: resetting writes _ttsContext, and state set here goes into the
383
+ // render already under way instead of scheduling a second one (Lit's change-in-update).
384
+ willUpdate(changed) {
385
+ super.willUpdate(changed);
386
+ // Stimulus, content and item-ref mode: the navigation cursor does not change what this player reads.
387
+ if (this.#stimulusMode || this.#contentMode || this.#itemRef)
388
+ return;
389
+ // Cursor mode: moving to another item or section stops speech and starts over (ignore the
390
+ // initial undefined → value transition). Section navigation leaves no item active, so it
391
+ // needs its own check.
392
+ const { item, section } = this.#activePosition();
393
+ const itemChanged = this.#prevNavItemRefId !== undefined && this.#prevNavItemRefId !== item;
394
+ const sectionChanged = this.#prevNavSectionId !== undefined && this.#prevNavSectionId !== section;
395
+ // The same item rendered again (e.g. linking to the item already shown): the elements
396
+ // collected earlier are detached. The context updates when an item renders, so check here.
397
+ const rerendered = this.#readingElements !== null && this.#readingRoot !== null && this.#readingRoot !== this.#resolveReadingRoot();
398
+ if (itemChanged || sectionChanged || rerendered)
399
+ this.#resetReadingPosition();
400
+ this.#prevNavItemRefId = item;
401
+ this.#prevNavSectionId = section;
402
+ }
403
+ /** Stop speech and forget the collected reading elements, so the next play starts afresh. */
404
+ #resetReadingPosition() {
405
+ this.#stopPicking();
406
+ this.#stop();
407
+ this.#readingElements = null;
408
+ this.#currentElementIndex = 0;
409
+ this.#finished = false;
410
+ this.#updateContext();
411
+ }
412
+ connectedCallback() {
413
+ super.connectedCallback();
414
+ this.#setSpeechState('idle');
415
+ // NOTE: #ensureHighlightStyles() is called lazily on first highlight use
416
+ // because the item to read may not be in the DOM yet at this point.
417
+ this.#stimulusMode = this.#stimulusPlaceholder() !== null;
418
+ if (this.#stimulusMode) {
419
+ // Stimulus mode: neither items nor navigation decide what is read, only the content of the
420
+ // placeholder. qti-components replaces it whenever it loads a stimulus (innerHTML, then
421
+ // append), so watch the parent — that also catches a host swapping the placeholder itself.
422
+ this.#stimulusObserver = new MutationObserver(records => {
423
+ if (records.some(record => !this.contains(record.target)))
424
+ this.#handleStimulusReplaced();
425
+ });
426
+ this.#stimulusObserver.observe(this.parentElement, { childList: true, subtree: true });
427
+ return;
428
+ }
429
+ // Content mode: plain HTML next to the player. Nothing to listen for: what is read only
430
+ // depends on that element, and the reading list is rebuilt when it goes stale.
431
+ this.#contentMode = this.#contentElement() !== null;
432
+ if (this.#contentMode)
433
+ return;
434
+ this.#itemRef = this.closest('qti-assessment-item-ref');
435
+ if (this.#itemRef) {
436
+ // Item-ref mode: `qc-item-rendered` (bubbles, composed) passes our own item-ref when our item
437
+ // renders again. Listened to under both names, directly: `listenPublic` has no unsubscribe,
438
+ // and a reset is idempotent, so the alias copy of the dual dispatch is harmless.
439
+ this.#itemRef.addEventListener('qc-item-rendered', this.#boundHandleItemConnected);
440
+ this.#itemRef.addEventListener('cito-item-rendered', this.#boundHandleItemConnected); // old name, one major
441
+ }
442
+ else {
443
+ // Cursor mode: the test sends `qc-test-navigation-started` as soon as it takes a navigation
444
+ // request — stop right away instead of waiting for the new position to arrive through the
445
+ // computed context. A notification goes up from the test, so it is heard on the document and
446
+ // kept only when it comes from the test this player sits in. Both names, for the reason above.
447
+ this.ownerDocument.addEventListener('qc-test-navigation-started', this.#boundHandleNavigation);
448
+ this.ownerDocument.addEventListener('cito-test-navigation-started', this.#boundHandleNavigation); // old name, one major
449
+ }
450
+ }
451
+ disconnectedCallback() {
452
+ super.disconnectedCallback();
453
+ // Only silence the synthesizer if it is speaking for this player.
454
+ if (this.#currentUtterance) {
455
+ this.#currentUtterance = null;
456
+ speechSynthesis.cancel();
457
+ }
458
+ this.#stopPicking();
459
+ this.#clearAllHighlights();
460
+ this.#itemRef?.removeEventListener('qc-item-rendered', this.#boundHandleItemConnected);
461
+ this.#itemRef?.removeEventListener('cito-item-rendered', this.#boundHandleItemConnected);
462
+ this.ownerDocument.removeEventListener('qc-test-navigation-started', this.#boundHandleNavigation);
463
+ this.ownerDocument.removeEventListener('cito-test-navigation-started', this.#boundHandleNavigation);
464
+ this.#itemRef = null;
465
+ this.#stimulusObserver?.disconnect();
466
+ this.#stimulusObserver = null;
467
+ this.#stimulusMode = false;
468
+ this.#contentMode = false;
469
+ }
470
+ render() {
471
+ return html `<slot></slot>`;
472
+ }
473
+ /** Item-ref mode: our item rendered again, so the elements collected earlier are detached. */
474
+ #handleItemConnected() {
475
+ if (this.#readingElements !== null)
476
+ this.#resetReadingPosition();
477
+ }
478
+ /** Cursor mode: the active item and section, from the computed context. */
479
+ #activePosition() {
480
+ for (const part of this._computedContext?.testParts ?? []) {
481
+ for (const section of part.sections) {
482
+ if (!section.active)
483
+ continue;
484
+ return { item: section.items.find(item => item.active)?.identifier ?? null, section: section.identifier };
485
+ }
486
+ }
487
+ return { item: null, section: null };
488
+ }
489
+ /**
490
+ * Stimulus mode: the stimulus next to the player was (re)loaded or swapped. Forget what was
491
+ * collected, so the next play reads the new content from the top. Unlike
492
+ * #resetReadingPosition this only cancels speech that is ours: a stimulus can finish loading
493
+ * while an item player on the same page is speaking.
494
+ */
495
+ #handleStimulusReplaced() {
496
+ if (this.#currentUtterance) {
497
+ this.#currentUtterance = null;
498
+ speechSynthesis.cancel();
499
+ }
500
+ this.#stopPicking();
501
+ this.#clearAllHighlights();
502
+ this.#setSpeechState('idle');
503
+ this.#readingElements = null;
504
+ this.#currentElementIndex = 0;
505
+ this.#finished = false;
506
+ this.#updateContext();
507
+ }
508
+ /**
509
+ * Stimulus mode: the `[data-stimulus-idref]` placeholder that shares this player's parent, or
510
+ * null. A placeholder holds the stimulus once loaded; the player cannot sit inside it, because
511
+ * loading replaces the placeholder's content.
512
+ */
513
+ #stimulusPlaceholder() {
514
+ return this.parentElement?.querySelector(':scope > [data-stimulus-idref]') ?? null;
515
+ }
516
+ /**
517
+ * Content mode: the `[data-tts-content]` element that shares this player's parent, or null.
518
+ * The marker goes on one container; the player finds the readable elements inside it.
519
+ */
520
+ #contentElement() {
521
+ return this.parentElement?.querySelector(':scope > [data-tts-content]') ?? null;
522
+ }
523
+ /**
524
+ * The element whose text is read: the stimulus body next to the player (stimulus mode), the
525
+ * marked content next to it (content mode), or the item body of the item to read.
526
+ */
527
+ #resolveReadingRoot() {
528
+ if (this.#stimulusMode)
529
+ return this.#stimulusPlaceholder()?.querySelector('qti-stimulus-body') ?? null;
530
+ if (this.#contentMode)
531
+ return this.#contentElement();
532
+ return this.#resolveItem()?.querySelector('qti-item-body') ?? null;
533
+ }
534
+ /**
535
+ * The item to read: our item-ref's (item-ref mode), or the active one (cursor mode). The test
536
+ * looks the active one up in its own items (`computedContext.itemElement`), so a page with
537
+ * several tests showing the same item still reads the right one.
538
+ */
539
+ #resolveItem() {
540
+ if (this.#itemRef)
541
+ return this.#itemRef.assessmentItem;
542
+ const { item } = this.#activePosition();
543
+ return item ? (this._computedContext?.itemElement?.(item) ?? null) : null;
544
+ }
545
+ /** Update speech state on both the context (notifies children) and the host's CSS custom states. */
546
+ #setSpeechState(state) {
547
+ this._ttsContext = { ...this._ttsContext, state };
548
+ this.#internals.states.delete('idle');
549
+ this.#internals.states.delete('playing');
550
+ this.#internals.states.delete('paused');
551
+ this.#internals.states.add(state);
552
+ }
553
+ /** Push currentElementIndex and elementCount into context so children can react. */
554
+ #updateContext() {
555
+ this._ttsContext = {
556
+ ...this._ttsContext,
557
+ currentElementIndex: this.#currentElementIndex,
558
+ elementCount: this.#getReadingElements().length
559
+ };
560
+ }
561
+ /**
562
+ * Return the currently readable elements: cached candidates for the item or stimulus (collected lazily on
563
+ * first call), filtered live for visibility on every call. Feedback and other
564
+ * conditionally-shown content (e.g. `qti-feedback-block`, which is `display: none` until a
565
+ * CSS custom state reveals it) is excluded while hidden and picked up again once shown,
566
+ * without needing to re-collect the candidate set.
567
+ */
568
+ #getReadingElements() {
569
+ // Content mode has no events or observer telling it the content changed (a framework like
570
+ // React re-renders it at will). Rebuild the list once an element in it has left the page;
571
+ // text changed inside an element needs nothing, it is read when that element is spoken.
572
+ if (this.#contentMode && this.#readingElements?.some(el => !el.isConnected)) {
573
+ this.#readingElements = null;
574
+ this.#currentElementIndex = 0;
575
+ this.#finished = false;
576
+ }
577
+ if (this.#readingElements === null) {
578
+ const root = this.#resolveReadingRoot();
579
+ // Leave the cache empty (rather than `[]`) while the item or stimulus has not rendered yet,
580
+ // so the next call retries instead of getting stuck on an empty result forever.
581
+ if (!root)
582
+ return [];
583
+ this.#readingRoot = root;
584
+ // Collect block-level elements (and QTI prompt / choice elements) that contain readable text.
585
+ // Keep only the innermost matches so `<li><p>…</p></li>` is not read twice. Content hidden
586
+ // from assistive technology (`aria-hidden="true"`, e.g. decorative icons) is not read either.
587
+ const selector = 'p, h1, h2, h3, h4, h5, h6, li, dt, dd, th, td, caption, blockquote, figcaption, qti-prompt, qti-simple-choice';
588
+ this.#readingElements = Array.from(root.querySelectorAll(selector)).filter(el => (el.textContent ?? '').trim().length > 0 && !el.querySelector(selector) && !el.closest('[aria-hidden="true"]'));
589
+ }
590
+ return this.#readingElements.filter(el => this.#isVisible(el));
591
+ }
592
+ /** True when an element is actually rendered — not `display: none` (itself or an ancestor). */
593
+ #isVisible(element) {
594
+ if (typeof element.checkVisibility === 'function') {
595
+ return element.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
596
+ }
597
+ // Older Safari (< 17.4) fallback: display:none leaves no client rects. Doesn't catch
598
+ // visibility:hidden, which still occupies layout, but display:none is what QTI feedback
599
+ // elements actually use (see qti-feedback-block/qti-feedback-inline default styles).
600
+ return element.getClientRects().length > 0;
601
+ }
602
+ /**
603
+ * Resolve the speech language for a reading element.
604
+ * Element `lang` → closest ancestor `lang` (crossing shadow hosts) → `<html lang>` → `language` attribute.
605
+ * Empty `lang=""` is treated as absent.
606
+ */
607
+ #resolveLang(element) {
608
+ let node = element;
609
+ while (node) {
610
+ const lang = node.getAttribute('lang') || node.getAttribute('xml:lang');
611
+ if (lang?.trim())
612
+ return lang.trim();
613
+ node = node.parentElement ?? node.getRootNode().host ?? null;
614
+ }
615
+ const documentLang = document.documentElement.getAttribute('lang');
616
+ if (documentLang?.trim())
617
+ return documentLang.trim();
618
+ return this.language;
619
+ }
620
+ #playSpeech() {
621
+ const elements = this.#getReadingElements();
622
+ if (!elements.length) {
623
+ console.warn('test-item-to-speech: no readable elements found');
624
+ return;
625
+ }
626
+ this.#stopPicking();
627
+ // speechSynthesis is one global queue: another player mid-sentence would otherwise
628
+ // finish first and this one would silently wait its turn.
629
+ speechSynthesis.cancel();
630
+ if (this.#finished) {
631
+ this.#finished = false;
632
+ this.#currentElementIndex = 0;
633
+ }
634
+ // Content mode: starting from the top rebuilds the list, so elements the page added since
635
+ // the last read (a framework re-render) are included.
636
+ if (this.#contentMode && this.#currentElementIndex === 0)
637
+ this.#readingElements = null;
638
+ this.#speakElement(this.#currentElementIndex);
639
+ }
640
+ /** Speak the element at the given index, then auto-advance when it ends. */
641
+ #speakElement(index) {
642
+ const elements = this.#getReadingElements();
643
+ if (index >= elements.length) {
644
+ // Finished all elements — stay on the last element so the user can walk back with prev
645
+ this.#clearWordHighlight();
646
+ this.#currentElementIndex = elements.length - 1;
647
+ if (elements.length > 0)
648
+ this.#highlightElement(elements[this.#currentElementIndex]);
649
+ this.#finished = true;
650
+ this.#setSpeechState('idle');
651
+ this.#updateContext();
652
+ return;
653
+ }
654
+ this.#currentElementIndex = index;
655
+ this.#finished = false;
656
+ this.#updateContext();
657
+ const element = elements[index];
658
+ element.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
659
+ this.#highlightElement(element);
660
+ // Collect text nodes of this element for word-boundary mapping
661
+ this.#textNodes = this.#collectTextNodes(element);
662
+ const text = this.#textNodes.map(n => n.textContent ?? '').join('');
663
+ if (!text.trim()) {
664
+ // Skip blank element and move to next
665
+ this.#speakElement(index + 1);
666
+ return;
667
+ }
668
+ const utterance = new SpeechSynthesisUtterance(text);
669
+ utterance.lang = this.#resolveLang(element);
670
+ utterance.rate = 1;
671
+ utterance.onboundary = (event) => {
672
+ if (event.name !== 'word')
673
+ return;
674
+ this.#updateWordHighlight(event.charIndex, event.charLength ?? 0);
675
+ };
676
+ utterance.onend = () => {
677
+ if (this.#currentUtterance !== utterance)
678
+ return;
679
+ this.#currentUtterance = null;
680
+ this.#clearWordHighlight();
681
+ this.#speakElement(this.#currentElementIndex + 1);
682
+ };
683
+ // Fires when speech is cancelled from outside this player (another player starting,
684
+ // or the browser); a cancel we issued ourselves has already cleared #currentUtterance.
685
+ utterance.onerror = () => {
686
+ if (this.#currentUtterance !== utterance)
687
+ return;
688
+ this.#currentUtterance = null;
689
+ this.#clearAllHighlights();
690
+ this.#setSpeechState('idle');
691
+ };
692
+ this.#currentUtterance = utterance;
693
+ speechSynthesis.speak(utterance);
694
+ this.#setSpeechState('playing');
695
+ }
696
+ #pause() {
697
+ speechSynthesis.pause();
698
+ this.#setSpeechState('paused');
699
+ }
700
+ #resume() {
701
+ speechSynthesis.resume();
702
+ this.#setSpeechState('playing');
703
+ }
704
+ #stop() {
705
+ this.#currentUtterance = null;
706
+ speechSynthesis.cancel();
707
+ this.#clearAllHighlights();
708
+ this.#setSpeechState('idle');
709
+ }
710
+ // ─── Pick mode ────────────────────────────────────────────────────────────
711
+ #togglePick() {
712
+ if (this.#picking)
713
+ this.#stopPicking();
714
+ else
715
+ this.#startPicking();
716
+ }
717
+ /** Highlight every reading element and wait for a click on one of them. */
718
+ #startPicking() {
719
+ // Content mode: pick from the page as it is now, like starting from the top does.
720
+ if (this.#contentMode)
721
+ this.#readingElements = null;
722
+ const elements = this.#getReadingElements();
723
+ if (!elements.length) {
724
+ console.warn('test-item-to-speech: no readable elements found');
725
+ return;
726
+ }
727
+ this.#stop();
728
+ this.#picking = true;
729
+ this.#internals.states.add('picking');
730
+ this.#highlightElements(elements);
731
+ // Listen on the item's root so the click is seen before any interaction handles it — in
732
+ // pick mode a click on a choice picks the sentence, it does not answer the question.
733
+ this.#pickRoot = elements[0].getRootNode();
734
+ this.#pickRoot.addEventListener('click', this.#boundHandlePickClick, true);
735
+ this._ttsContext = { ...this._ttsContext, picking: true };
736
+ }
737
+ #stopPicking() {
738
+ if (!this.#picking)
739
+ return;
740
+ this.#picking = false;
741
+ this.#internals.states.delete('picking');
742
+ this.#pickRoot?.removeEventListener('click', this.#boundHandlePickClick, true);
743
+ this.#pickRoot = null;
744
+ this.#clearAllHighlights();
745
+ this._ttsContext = { ...this._ttsContext, picking: false };
746
+ }
747
+ #handlePickClick(event) {
748
+ const elements = this.#getReadingElements();
749
+ const path = event.composedPath();
750
+ let index = elements.findIndex(el => path.includes(el));
751
+ if (index < 0) {
752
+ // Not on the text itself. A click on the choice or list item around it (its radio button,
753
+ // the padding) still means "this one": take the first reading element inside it.
754
+ const container = path.find((node) => node instanceof Element && node.matches('qti-simple-choice, li, qti-prompt'));
755
+ if (container)
756
+ index = elements.findIndex(el => container.contains(el));
757
+ }
758
+ if (index < 0)
759
+ return; // not on a highlighted element — stay in pick mode
760
+ event.preventDefault();
761
+ event.stopPropagation();
762
+ this.#stopPicking();
763
+ speechSynthesis.cancel();
764
+ this.#speakElement(index);
765
+ }
766
+ #prevElement() {
767
+ const elements = this.#getReadingElements();
768
+ if (!elements.length)
769
+ return;
770
+ this.#currentUtterance = null;
771
+ speechSynthesis.cancel();
772
+ this.#clearWordHighlight();
773
+ this.#currentElementIndex = Math.max(0, this.#currentElementIndex - 1);
774
+ this.#finished = false;
775
+ this.#updateContext();
776
+ const el = elements[this.#currentElementIndex];
777
+ el.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
778
+ this.#highlightElement(el);
779
+ this.#setSpeechState('idle');
780
+ }
781
+ #nextElement() {
782
+ const elements = this.#getReadingElements();
783
+ if (!elements.length)
784
+ return;
785
+ this.#currentUtterance = null;
786
+ speechSynthesis.cancel();
787
+ this.#clearWordHighlight();
788
+ this.#currentElementIndex = Math.min(elements.length - 1, this.#currentElementIndex + 1);
789
+ this.#finished = false;
790
+ this.#updateContext();
791
+ const el = elements[this.#currentElementIndex];
792
+ el.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
793
+ this.#highlightElement(el);
794
+ this.#setSpeechState('idle');
795
+ }
796
+ /** Walk text nodes without crossing shadow DOM boundaries. */
797
+ #collectTextNodes(root) {
798
+ const nodes = [];
799
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
800
+ let node;
801
+ while ((node = walker.nextNode())) {
802
+ // Text hidden from assistive technology inside a read element — a decorative icon in a
803
+ // list item — is not spoken either. Skipped here, so speech and word highlight agree.
804
+ if ((node.textContent ?? '').length > 0 && !node.parentElement?.closest('[aria-hidden="true"]')) {
805
+ nodes.push(node);
806
+ }
807
+ }
808
+ return nodes;
809
+ }
810
+ /** Highlight the whole element as the navigation cursor (blue). */
811
+ #highlightElement(element) {
812
+ this.#highlightElements([element]);
813
+ }
814
+ /** Put the blue cursor highlight on several elements at once (pick mode). */
815
+ #highlightElements(elements) {
816
+ if (!('highlights' in CSS))
817
+ return;
818
+ this.#ensureHighlightStyles();
819
+ this.#elementHighlight.clear();
820
+ for (const element of elements) {
821
+ const range = new Range();
822
+ range.selectNodeContents(element);
823
+ this.#elementHighlight.add(range);
824
+ }
825
+ CSS.highlights.set(HIGHLIGHT_ELEMENT, this.#elementHighlight);
826
+ }
827
+ /** Highlight the current word within #textNodes (yellow, during speech). */
828
+ #updateWordHighlight(charIndex, charLength) {
829
+ if (!('highlights' in CSS))
830
+ return;
831
+ this.#ensureHighlightStyles();
832
+ this.#wordHighlight.clear();
833
+ const text = this.#textNodes.map(n => n.textContent ?? '').join('');
834
+ const endIndex = charIndex + (charLength > 0 ? charLength : this.#wordLengthAt(charIndex, text));
835
+ let offset = 0;
836
+ let startNode = null;
837
+ let startOffset = 0;
838
+ let endNode = null;
839
+ let endOffset = 0;
840
+ for (const node of this.#textNodes) {
841
+ const len = node.textContent?.length ?? 0;
842
+ if (!startNode && offset + len > charIndex) {
843
+ startNode = node;
844
+ startOffset = charIndex - offset;
845
+ }
846
+ if (startNode && offset + len >= endIndex) {
847
+ endNode = node;
848
+ endOffset = endIndex - offset;
849
+ break;
850
+ }
851
+ offset += len;
852
+ }
853
+ if (startNode && endNode) {
854
+ const range = new Range();
855
+ range.setStart(startNode, startOffset);
856
+ range.setEnd(endNode, endOffset);
857
+ this.#wordHighlight.add(range);
858
+ CSS.highlights.set(HIGHLIGHT_WORD, this.#wordHighlight);
859
+ }
860
+ }
861
+ #clearWordHighlight() {
862
+ if (!('highlights' in CSS))
863
+ return;
864
+ this.#wordHighlight.clear();
865
+ // The registry is shared by every player on the page: only drop the entry if it is ours.
866
+ if (CSS.highlights.get(HIGHLIGHT_WORD) === this.#wordHighlight)
867
+ CSS.highlights.delete(HIGHLIGHT_WORD);
868
+ }
869
+ #clearAllHighlights() {
870
+ if (!('highlights' in CSS))
871
+ return;
872
+ this.#clearWordHighlight();
873
+ this.#elementHighlight.clear();
874
+ if (CSS.highlights.get(HIGHLIGHT_ELEMENT) === this.#elementHighlight)
875
+ CSS.highlights.delete(HIGHLIGHT_ELEMENT);
876
+ }
877
+ /** Fallback word-length when charLength is 0. */
878
+ #wordLengthAt(charIndex, text) {
879
+ const right = text.slice(charIndex).search(/\s/);
880
+ return right < 0 ? text.length - charIndex : right;
881
+ }
882
+ /**
883
+ * Add ::highlight() rules both to the shadow root the highlighted text lives in and to the
884
+ * document (safety net — spec allows document rules to apply across shadow DOM). Called lazily
885
+ * on first highlight use, once the reading elements have been collected.
886
+ */
887
+ #ensureHighlightStyles() {
888
+ if (!('highlights' in CSS))
889
+ return;
890
+ const sheet = getHighlightSheet();
891
+ // 1. Document-level rule — applies broadly regardless of shadow DOM depth
892
+ if (!document.adoptedStyleSheets.includes(sheet)) {
893
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
894
+ }
895
+ // 2. Shadow roots the highlighted text may live in: the item's (e.g. test-container's), and
896
+ // the player's own root when the player itself sits inside a shadow tree (e.g. built into
897
+ // an item card).
898
+ const roots = new Set();
899
+ const ownRoot = this.getRootNode();
900
+ if (ownRoot instanceof ShadowRoot)
901
+ roots.add(ownRoot);
902
+ const itemRoot = this.#readingElements?.[0]?.getRootNode();
903
+ if (itemRoot instanceof ShadowRoot)
904
+ roots.add(itemRoot);
905
+ for (const root of roots) {
906
+ if (!root.adoptedStyleSheets.includes(sheet)) {
907
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
908
+ }
909
+ }
910
+ }
911
+ }
912
+ __decorate([
913
+ property({ type: String })
914
+ ], TestItemToSpeech.prototype, "language", void 0);
915
+ __decorate([
916
+ consume({ context: computedContext, subscribe: true })
917
+ ], TestItemToSpeech.prototype, "_computedContext", void 0);
918
+ __decorate([
919
+ state(),
920
+ provide({ context: ttsContext })
921
+ ], TestItemToSpeech.prototype, "_ttsContext", void 0);
922
+ // ─── Child control elements ───────────────────────────────────────────────────
923
+ /**
924
+ * Play/pause/resume toggle button — always enabled, cycles through states.
925
+ * Use named slots `play` and `pause` to customise the icons/labels independently; `label` and
926
+ * `pause-label` name the button in each state (set them when the slotted content is an icon).
927
+ *
928
+ * @example
929
+ * ```html
930
+ * <test-tts-play>
931
+ * <span slot="play">Voorlezen</span>
932
+ * <span slot="pause">Pauzeren</span>
933
+ * </test-tts-play>
934
+ * ```
935
+ *
936
+ * @cssstate idle / playing / paused
937
+ * @csspart button
938
+ */
939
+ export class TestTtsPlay extends TtsButtonBase {
940
+ #toggle() {
941
+ if (!this._tts)
942
+ return;
943
+ if (this._tts.state === 'idle')
944
+ this._tts.play();
945
+ else if (this._tts.state === 'playing')
946
+ this._tts.pause();
947
+ else
948
+ this._tts.resume();
949
+ }
950
+ render() {
951
+ const playing = this._tts?.state === 'playing';
952
+ return html `
953
+ <button part="button" aria-label=${ifDefined(playing ? this.pauseLabel : this.label)} @click=${this.#toggle}>
954
+ ${playing
955
+ ? html `<slot name="pause">${iconContent('pause', this.pauseLabel ?? 'Pause')}</slot>`
956
+ : html `<slot name="play">${iconContent('play', this.label ?? 'Play')}</slot>`}
957
+ </button>
958
+ `;
959
+ }
960
+ }
961
+ __decorate([
962
+ property({ type: String, attribute: 'pause-label' })
963
+ ], TestTtsPlay.prototype, "pauseLabel", void 0);
964
+ /**
965
+ * Pause button — enabled only when playing.
966
+ * @cssstate idle / playing / paused
967
+ * @csspart button
968
+ */
969
+ export class TestTtsPause extends TtsButtonBase {
970
+ render() {
971
+ return html `
972
+ <button
973
+ part="button"
974
+ aria-label=${ifDefined(this.label)}
975
+ ?disabled=${this._tts?.state !== 'playing'}
976
+ @click=${() => this._tts?.pause()}
977
+ >
978
+ <slot>${iconContent('pause', this.label ?? 'Pause')}</slot>
979
+ </button>
980
+ `;
981
+ }
982
+ }
983
+ /**
984
+ * Resume button — enabled only when paused.
985
+ * @cssstate idle / playing / paused
986
+ * @csspart button
987
+ */
988
+ export class TestTtsResume extends TtsButtonBase {
989
+ render() {
990
+ return html `
991
+ <button
992
+ part="button"
993
+ aria-label=${ifDefined(this.label)}
994
+ ?disabled=${this._tts?.state !== 'paused'}
995
+ @click=${() => this._tts?.resume()}
996
+ >
997
+ <slot>${iconContent('play', this.label ?? 'Resume')}</slot>
998
+ </button>
999
+ `;
1000
+ }
1001
+ }
1002
+ /**
1003
+ * Stop button — enabled when playing, paused, or in pick mode (where it leaves pick mode).
1004
+ * @cssstate idle / playing / paused
1005
+ * @csspart button
1006
+ */
1007
+ export class TestTtsStop extends TtsButtonBase {
1008
+ render() {
1009
+ const idle = this._tts?.state === 'idle' && !this._tts?.picking;
1010
+ return html `
1011
+ <button part="button" aria-label=${ifDefined(this.label)} ?disabled=${idle} @click=${() => this._tts?.stop()}>
1012
+ <slot>${iconContent('stop', this.label ?? 'Stop')}</slot>
1013
+ </button>
1014
+ `;
1015
+ }
1016
+ }
1017
+ /**
1018
+ * Prev-element button — moves cursor to the previous reading element and pauses.
1019
+ * Disabled at the first element. Reading elements are collected lazily, so an element count
1020
+ * of 0 means "not looked yet" rather than "nothing to read": the button stays enabled and the
1021
+ * first click collects them.
1022
+ * @cssstate idle / playing / paused
1023
+ * @csspart button
1024
+ */
1025
+ export class TestTtsPrev extends TtsButtonBase {
1026
+ render() {
1027
+ const collected = (this._tts?.elementCount ?? 0) > 0;
1028
+ const atStart = (this._tts?.currentElementIndex ?? 0) === 0;
1029
+ return html `
1030
+ <button
1031
+ part="button"
1032
+ aria-label=${ifDefined(this.label)}
1033
+ ?disabled=${collected && atStart}
1034
+ @click=${() => this._tts?.prevElement()}
1035
+ >
1036
+ <slot>${iconContent('prev', this.label ?? 'Previous sentence')}</slot>
1037
+ </button>
1038
+ `;
1039
+ }
1040
+ }
1041
+ /**
1042
+ * Next-element button — moves cursor to the next reading element and pauses.
1043
+ * Disabled at the last element; enabled while the elements have not been collected yet
1044
+ * (see `TestTtsPrev`).
1045
+ * @cssstate idle / playing / paused
1046
+ * @csspart button
1047
+ */
1048
+ export class TestTtsNext extends TtsButtonBase {
1049
+ render() {
1050
+ const count = this._tts?.elementCount ?? 0;
1051
+ const atEnd = count > 0 && (this._tts?.currentElementIndex ?? 0) >= count - 1;
1052
+ return html `
1053
+ <button
1054
+ part="button"
1055
+ aria-label=${ifDefined(this.label)}
1056
+ ?disabled=${atEnd}
1057
+ @click=${() => this._tts?.nextElement()}
1058
+ >
1059
+ <slot>${iconContent('next', this.label ?? 'Next sentence')}</slot>
1060
+ </button>
1061
+ `;
1062
+ }
1063
+ }
1064
+ /**
1065
+ * Pick button — toggles pick mode on the controller: every reading element is highlighted and
1066
+ * a click on one of them starts reading from there. Reflects the mode as `:state(picking)`, and,
1067
+ * being the toggle that switched it on, as `:state(selected)`, painted through
1068
+ * `--button-selected-background-color` / `--button-selected-color`.
1069
+ * @cssstate idle / playing / paused
1070
+ * @cssstate picking
1071
+ * @cssstate selected - This toggle is on: pick mode is active
1072
+ * @csspart button
1073
+ */
1074
+ export class TestTtsPick extends TtsButtonBase {
1075
+ get selected() {
1076
+ return this._tts?.picking ?? false;
1077
+ }
1078
+ render() {
1079
+ return html `
1080
+ <button
1081
+ part="button"
1082
+ aria-label=${ifDefined(this.label)}
1083
+ aria-pressed=${this._tts?.picking ? 'true' : 'false'}
1084
+ @click=${() => this._tts?.togglePick()}
1085
+ >
1086
+ <slot>${iconContent('pick', this.label ?? 'Read from here')}</slot>
1087
+ </button>
1088
+ `;
1089
+ }
1090
+ }
1091
+ //# sourceMappingURL=test-item-to-speech.js.map