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