@qti-components/test 2.0.0-next.14 → 2.0.0-next.15

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