@qti-components/test 1.8.0 → 1.10.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/components/qti-assessment-item-ref/qti-assessment-item-ref.d.ts +4 -0
  2. package/dist/components/qti-assessment-item-ref/qti-assessment-item-ref.js +16 -28
  3. package/dist/components/qti-assessment-item-ref/qti-assessment-item-ref.js.map +1 -1
  4. package/dist/components/qti-assessment-test/qti-assessment-test.d.ts +5 -0
  5. package/dist/components/qti-assessment-test/qti-assessment-test.js +2 -5
  6. package/dist/components/qti-assessment-test/qti-assessment-test.js.map +1 -1
  7. package/dist/components/qti-number-selected/qti-number-selected.js +2 -1
  8. package/dist/components/qti-number-selected/qti-number-selected.js.map +1 -1
  9. package/dist/components/qti-test/qti-test.d.ts +16 -2
  10. package/dist/components/qti-test/qti-test.js +33 -6
  11. package/dist/components/qti-test/qti-test.js.map +1 -1
  12. package/dist/components/qti-test-variables/qti-test-variables.js +2 -1
  13. package/dist/components/qti-test-variables/qti-test-variables.js.map +1 -1
  14. package/dist/components/test-check-item/test-check-item.d.ts +2 -0
  15. package/dist/components/test-check-item/test-check-item.js +16 -3
  16. package/dist/components/test-check-item/test-check-item.js.map +1 -1
  17. package/dist/components/test-container/test-container.d.ts +3 -0
  18. package/dist/components/test-container/test-container.js +5 -1
  19. package/dist/components/test-container/test-container.js.map +1 -1
  20. package/dist/components/test-end-attempt/test-end-attempt.js +2 -1
  21. package/dist/components/test-end-attempt/test-end-attempt.js.map +1 -1
  22. package/dist/components/test-item-link/test-item-link.js +2 -8
  23. package/dist/components/test-item-link/test-item-link.js.map +1 -1
  24. package/dist/components/test-item-to-speech/test-item-to-speech.d.ts +61 -15
  25. package/dist/components/test-item-to-speech/test-item-to-speech.js +287 -103
  26. package/dist/components/test-item-to-speech/test-item-to-speech.js.map +1 -1
  27. package/dist/components/test-navigation/test-navigation.d.ts +9 -9
  28. package/dist/components/test-navigation/test-navigation.js +68 -21
  29. package/dist/components/test-navigation/test-navigation.js.map +1 -1
  30. package/dist/components/test-next/test-next.js +2 -8
  31. package/dist/components/test-next/test-next.js.map +1 -1
  32. package/dist/components/test-prev/test-prev.js +2 -8
  33. package/dist/components/test-prev/test-prev.js.map +1 -1
  34. package/dist/components/test-scoring-buttons/test-scoring-buttons.d.ts +1 -1
  35. package/dist/components/test-scoring-buttons/test-scoring-buttons.js +6 -8
  36. package/dist/components/test-scoring-buttons/test-scoring-buttons.js.map +1 -1
  37. package/dist/components/test-section-link/test-section-link.js +2 -8
  38. package/dist/components/test-section-link/test-section-link.js.map +1 -1
  39. package/dist/components/test-view-toggle/test-view-toggle.js +2 -5
  40. package/dist/components/test-view-toggle/test-view-toggle.js.map +1 -1
  41. package/dist/components/test-view-toggle/test-view.js +2 -5
  42. package/dist/components/test-view-toggle/test-view.js.map +1 -1
  43. package/dist/index.d.ts +1 -0
  44. package/dist/index.js +1 -0
  45. package/dist/index.js.map +1 -1
  46. package/dist/internal/item-ref-selection.js.map +1 -1
  47. package/dist/internal/test-host.context.d.ts +24 -0
  48. package/dist/internal/test-host.context.js +3 -0
  49. package/dist/internal/test-host.context.js.map +1 -0
  50. package/dist/mixins/index.d.ts +1 -0
  51. package/dist/mixins/index.js +1 -0
  52. package/dist/mixins/index.js.map +1 -1
  53. package/dist/mixins/test-base.d.ts +7 -2
  54. package/dist/mixins/test-base.js +55 -20
  55. package/dist/mixins/test-base.js.map +1 -1
  56. package/dist/mixins/test-navigation.mixin.d.ts +3 -4
  57. package/dist/mixins/test-navigation.mixin.js +26 -40
  58. package/dist/mixins/test-navigation.mixin.js.map +1 -1
  59. package/dist/mixins/test-processing.mixin.js +3 -1
  60. package/dist/mixins/test-processing.mixin.js.map +1 -1
  61. package/dist/mixins/test-state.mixin.d.ts +33 -0
  62. package/dist/mixins/test-state.mixin.js +131 -0
  63. package/dist/mixins/test-state.mixin.js.map +1 -0
  64. package/dist/mixins/test-view.mixin.js +3 -2
  65. package/dist/mixins/test-view.mixin.js.map +1 -1
  66. package/dist/public-events.d.ts +62 -0
  67. package/dist/public-events.js +33 -0
  68. package/dist/public-events.js.map +1 -0
  69. package/dist/types/iqti-test.d.ts +8 -5
  70. package/dist/types/iqti-test.js.map +1 -1
  71. package/dist/types/qti-test-state.d.ts +45 -0
  72. package/dist/types/qti-test-state.js +2 -0
  73. package/dist/types/qti-test-state.js.map +1 -0
  74. package/package.json +5 -5
@@ -9,6 +9,7 @@ import { consume, provide, createContext } from '@lit/context';
9
9
  import { property, state } from 'lit/decorators.js';
10
10
  import { ifDefined } from 'lit/directives/if-defined.js';
11
11
  import { sessionContext } from '@qti-components/base';
12
+ import { testHostContext } from '../../internal/test-host.context';
12
13
  import * as styles from '../styles';
13
14
  // ─── CSS Custom Highlight ─────────────────────────────────────────────────────
14
15
  const HIGHLIGHT_ELEMENT = 'tts-element'; // navigation cursor — whole element
@@ -39,8 +40,12 @@ const ICONS = {
39
40
  pick: 'M5 3l13 7-5.5 1.6 3.4 6.6-2.4 1.3-3.4-6.7L6 17z'
40
41
  };
41
42
  /** Default button content: the icon, plus a visually hidden label as the accessible name. */
42
- const iconContent = (icon, label) => html `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${ICONS[icon]}></path></svg
43
- ><span class="label">${label}</span>`;
43
+ const iconContent = (icon, label) => {
44
+ const svg = html `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
45
+ <path d="${ICONS[icon]}"></path>
46
+ </svg>`;
47
+ return html `${svg}<span class="label">${label}</span>`;
48
+ };
44
49
  // ─── Shared base for child button elements ────────────────────────────────────
45
50
  /**
46
51
  * Base class shared by all TTS control elements. Consumes `ttsContext` and
@@ -56,6 +61,10 @@ class TtsButtonBase extends LitElement {
56
61
  ${styles.btn};
57
62
  min-inline-size: var(--test-button-size, 2.25rem);
58
63
  padding-inline: 0.5rem;
64
+ /* Containing block for the visually hidden .label. Without it the label is placed against
65
+ the nearest positioned ancestor, which can sit outside a scroll container and make the
66
+ page as tall as the scrolled content. */
67
+ position: relative;
59
68
  }
60
69
  button:hover:not(:disabled) {
61
70
  ${styles.btnInteractive};
@@ -149,17 +158,66 @@ __decorate([
149
158
  * The transformer copies `xml:lang` over as a plain `lang` attribute, so QTI authored with
150
159
  * `xml:lang="en-GB"` on a `<p>` or on the item root is honoured without further work.
151
160
  *
152
- * ### Which item is read
161
+ * ### What is read
162
+ *
163
+ * Decided once per connect, by where the player is placed. The first rule that matches wins:
164
+ *
165
+ * 1. **Next to a stimulus placeholder** — the player shares its parent with a
166
+ * `[data-stimulus-idref]` element, e.g. in a reading-text panel beside the questions: the
167
+ * player reads that stimulus (its `qti-stimulus-body`), and only that. Not inside the
168
+ * placeholder: loading a stimulus replaces the placeholder's content. Items and navigation
169
+ * are ignored; when the stimulus is (re)loaded or the placeholder swapped, the player starts
170
+ * over on the new content.
171
+ * 2. **Next to `[data-tts-content]`** — the player shares its parent with an element marked
172
+ * `data-tts-content`: any HTML, not QTI, e.g. a start screen rendered by React. The marker goes
173
+ * on one container; the player reads the readable elements inside it. Navigation is ignored.
174
+ * The reading list is rebuilt when the player starts from the top, and when an element in it
175
+ * has left the page — so a re-render of the content never interrupts speech.
176
+ * 3. **Inside a `qti-assessment-item-ref`** — e.g. in a `<template item-ref>` on `<qti-test>`,
177
+ * so every item gets a player of its own: the player reads that item, and only that item.
178
+ * The navigation cursor is ignored; speech stops when the player leaves the page with its item.
179
+ * 4. **Anywhere else** — a toolbar in the page chrome: the player follows the navigation cursor
180
+ * and reads the item `navItemRefId` (session context) points at, found in any
181
+ * `test-container` reachable from the player. Navigating stops speech and starts the next
182
+ * item from the top.
183
+ *
184
+ * ```html
185
+ * <!-- 1. a player for the shared reading text -->
186
+ * <aside>
187
+ * <test-item-to-speech>…</test-item-to-speech>
188
+ * <div data-stimulus-idref="Stimulus1"></div>
189
+ * </aside>
190
+ *
191
+ * <!-- 2. a player for any other HTML -->
192
+ * <div>
193
+ * <test-item-to-speech>…</test-item-to-speech>
194
+ * <section data-tts-content lang="nl-NL">…</section>
195
+ * </div>
196
+ *
197
+ * <!-- 3. one player per item -->
198
+ * <qti-test>
199
+ * <template item-ref>
200
+ * <test-item-to-speech>…</test-item-to-speech>
201
+ * {{ xmlDoc }}
202
+ * </template>
203
+ * …
204
+ * </qti-test>
153
205
  *
154
- * By default the player reads the item the test is navigated to (`navItemRefId` from the
155
- * session context). When several items share one page — a keep-together section or a
156
- * vertically scrolling booklet — give each player its own `item-ref-id` so it reads that
157
- * item regardless of the navigation cursor. The item is looked up by its
158
- * `qti-assessment-item-ref` identifier, in the player's own tree first and otherwise in
159
- * any `test-container` shadow root reachable from it, so the player can live inside the
160
- * item card, next to it, or in the page chrome.
206
+ * <!-- 4. one player in the toolbar, following navigation -->
207
+ * <test-navigation>
208
+ * <header><test-item-to-speech>…</test-item-to-speech></header>
209
+ * <test-container test-url="…"></test-container>
210
+ * </test-navigation>
211
+ * ```
161
212
  *
162
- * Only one item can be spoken at a time; starting one player stops any other.
213
+ * In modes 3 and 4 the item re-rendering (navigating to the item already shown) restarts the
214
+ * player on the fresh content. An item player reads the item body as rendered: a stimulus
215
+ * placed inside the item is read with it, one placed outside (mode 1) is not. Only one player
216
+ * can speak at a time; starting one stops any other.
217
+ *
218
+ * Read are `p`, `h1`–`h6`, `li`, `dt`, `dd`, `th`, `td`, `caption`, `blockquote`, `figcaption`,
219
+ * `qti-prompt` and `qti-simple-choice` — the innermost match only — unless hidden (`display: none`)
220
+ * or inside `aria-hidden="true"`.
163
221
  *
164
222
  * ### Starting somewhere in the middle
165
223
  *
@@ -182,10 +240,24 @@ export class TestItemToSpeech extends LitElement {
182
240
  }
183
241
  `; }
184
242
  #internals;
185
- #itemElements;
186
- #boundHandleItemConnected;
243
+ // Stimulus mode: set on connect when a stimulus placeholder sits next to the player. The
244
+ // placeholder itself is looked up on every use — a host may swap the element.
245
+ #stimulusMode;
246
+ // Stimulus mode: resets the player when the stimulus content next to it is replaced.
247
+ #stimulusObserver;
248
+ // Content mode: set on connect when a `[data-tts-content]` element sits next to the player.
249
+ // Any HTML, not QTI. No observer: the reading list is rebuilt on demand (#getReadingElements).
250
+ #contentMode;
251
+ // Item-ref mode: the item-ref this player sits in, resolved on connect. Null means cursor mode.
252
+ #itemRef;
253
+ // Where the item-connected (and, in cursor mode, navigation) events are listened for.
187
254
  #eventHost;
188
- // Current set of block-level reading elements for the active item
255
+ #boundHandleItemConnected;
256
+ #boundHandleNavigation;
257
+ // Cursor mode: the previous navigation position, to detect moving to another item or section.
258
+ #prevNavItemRefId;
259
+ #prevNavSectionId;
260
+ // Current set of block-level reading elements for the item
189
261
  #readingElements;
190
262
  #currentElementIndex;
191
263
  // Text nodes of the element currently being spoken (for word-boundary highlight)
@@ -203,19 +275,29 @@ export class TestItemToSpeech extends LitElement {
203
275
  // Two separate CSS Highlight objects
204
276
  #elementHighlight; // whole-element cursor
205
277
  #wordHighlight; // current word during speech
206
- // Tracks previous navItemRefId to detect item switches
207
- #prevNavItemRefId;
208
- #prevNavSectionId;
209
- #boundHandleNavigation;
210
278
  constructor() {
211
279
  super();
212
280
  /** Fallback language when neither the item content nor the document declares one. */
213
281
  this.language = 'nl-NL';
214
282
  this.#internals = this.attachInternals();
215
- this.#itemElements = new Map();
216
- this.#boundHandleItemConnected = this.#handleItemConnected.bind(this);
283
+ // Stimulus mode: set on connect when a stimulus placeholder sits next to the player. The
284
+ // placeholder itself is looked up on every use — a host may swap the element.
285
+ this.#stimulusMode = false;
286
+ // Stimulus mode: resets the player when the stimulus content next to it is replaced.
287
+ this.#stimulusObserver = null;
288
+ // Content mode: set on connect when a `[data-tts-content]` element sits next to the player.
289
+ // Any HTML, not QTI. No observer: the reading list is rebuilt on demand (#getReadingElements).
290
+ this.#contentMode = false;
291
+ // Item-ref mode: the item-ref this player sits in, resolved on connect. Null means cursor mode.
292
+ this.#itemRef = null;
293
+ // Where the item-connected (and, in cursor mode, navigation) events are listened for.
217
294
  this.#eventHost = null;
218
- // Current set of block-level reading elements for the active item
295
+ this.#boundHandleItemConnected = this.#handleItemConnected.bind(this);
296
+ this.#boundHandleNavigation = () => this.#stop();
297
+ // Cursor mode: the previous navigation position, to detect moving to another item or section.
298
+ this.#prevNavItemRefId = undefined;
299
+ this.#prevNavSectionId = undefined;
300
+ // Current set of block-level reading elements for the item
219
301
  this.#readingElements = null;
220
302
  this.#currentElementIndex = 0;
221
303
  // Text nodes of the element currently being spoken (for word-boundary highlight)
@@ -233,10 +315,6 @@ export class TestItemToSpeech extends LitElement {
233
315
  // Two separate CSS Highlight objects
234
316
  this.#elementHighlight = new Highlight(); // whole-element cursor
235
317
  this.#wordHighlight = new Highlight(); // current word during speech
236
- // Tracks previous navItemRefId to detect item switches
237
- this.#prevNavItemRefId = undefined;
238
- this.#prevNavSectionId = undefined;
239
- this.#boundHandleNavigation = () => this.#stop();
240
318
  this._ttsContext = {
241
319
  state: 'idle',
242
320
  currentElementIndex: 0,
@@ -254,27 +332,23 @@ export class TestItemToSpeech extends LitElement {
254
332
  picking: false
255
333
  };
256
334
  }
335
+ // willUpdate, not updated: resetting writes _ttsContext, and state set here goes into the
336
+ // render already under way instead of scheduling a second one (Lit's change-in-update).
257
337
  willUpdate(changed) {
258
- // no property-driven context updates needed currently
259
- void changed;
260
- }
261
- updated(changed) {
262
- if (changed.has('itemRefId') && changed.get('itemRefId') !== undefined) {
263
- this.#resetReadingPosition();
264
- }
265
- const current = this._sessionContext?.navItemRefId ?? null;
266
- // Stop speech when navItemRefId changes (ignore the initial undefined → value transition).
267
- // A player pinned to an item keeps its reading position: the cursor moving elsewhere on a
268
- // multi-item page does not change what this player reads.
269
- // Moving to another section does take a pinned player's item off the page, so that
270
- // stops every player; section navigation leaves navItemRefId null, so it needs its own check.
338
+ super.willUpdate(changed);
339
+ // Stimulus, content and item-ref mode: the navigation cursor does not change what this player reads.
340
+ if (this.#stimulusMode || this.#contentMode || this.#itemRef)
341
+ return;
342
+ // Cursor mode: moving to another item or section stops speech and starts over (ignore the
343
+ // initial undefined → value transition). Section navigation leaves navItemRefId null, so it
344
+ // needs its own check.
345
+ const item = this._sessionContext?.navItemRefId ?? null;
271
346
  const section = this._sessionContext?.navSectionId ?? null;
272
- const itemChanged = this.#prevNavItemRefId !== undefined && this.#prevNavItemRefId !== current;
347
+ const itemChanged = this.#prevNavItemRefId !== undefined && this.#prevNavItemRefId !== item;
273
348
  const sectionChanged = this.#prevNavSectionId !== undefined && this.#prevNavSectionId !== section;
274
- if (sectionChanged || (itemChanged && !this.itemRefId)) {
349
+ if (itemChanged || sectionChanged)
275
350
  this.#resetReadingPosition();
276
- }
277
- this.#prevNavItemRefId = current;
351
+ this.#prevNavItemRefId = item;
278
352
  this.#prevNavSectionId = section;
279
353
  }
280
354
  /** Stop speech and forget the collected reading elements, so the next play starts afresh. */
@@ -291,12 +365,35 @@ export class TestItemToSpeech extends LitElement {
291
365
  this.#setSpeechState('idle');
292
366
  // NOTE: #ensureHighlightStyles() is called lazily on first highlight use
293
367
  // because test-container may not be in the DOM yet at this point.
294
- // qti-assessment-item-connected is bubbles+composed, so it reaches test-navigation / qti-test
368
+ this.#stimulusMode = this.#stimulusPlaceholder() !== null;
369
+ if (this.#stimulusMode) {
370
+ // Stimulus mode: neither items nor navigation decide what is read, only the content of the
371
+ // placeholder. qti-components replaces it whenever it loads a stimulus (innerHTML, then
372
+ // append), so watch the parent — that also catches a host swapping the placeholder itself.
373
+ this.#stimulusObserver = new MutationObserver(records => {
374
+ if (records.some(record => !this.contains(record.target)))
375
+ this.#handleStimulusReplaced();
376
+ });
377
+ this.#stimulusObserver.observe(this.parentElement, { childList: true, subtree: true });
378
+ return;
379
+ }
380
+ // Content mode: plain HTML next to the player. Nothing to listen for: what is read only
381
+ // depends on that element, and the reading list is rebuilt when it goes stale.
382
+ this.#contentMode = this.#contentElement() !== null;
383
+ if (this.#contentMode)
384
+ return;
385
+ this.#itemRef = this.closest('qti-assessment-item-ref');
386
+ // qti-assessment-item-connected is bubbles+composed: it passes the item's own item-ref, and
387
+ // reaches test-navigation / qti-test from inside test-container's shadow root.
295
388
  this.#eventHost =
296
- this.closest('test-navigation') ?? this.closest('qti-test') ?? this.getRootNode();
389
+ this.#itemRef ?? this.closest('test-navigation') ?? this.testHost ?? this.getRootNode();
297
390
  this.#eventHost.addEventListener('qti-assessment-item-connected', this.#boundHandleItemConnected);
298
- // qti-request-navigation fires synchronously when the user clicks prev/next — stop immediately
299
- this.#eventHost.addEventListener('qti-request-navigation', this.#boundHandleNavigation);
391
+ if (!this.#itemRef) {
392
+ // Cursor mode: cito-test-navigate fires synchronously on prev/next — stop right away
393
+ // instead of waiting for the new position to arrive through the session context.
394
+ this.#eventHost.addEventListener('cito-test-navigate', this.#boundHandleNavigation);
395
+ this.#eventHost.addEventListener('qti-request-navigation', this.#boundHandleNavigation); // deprecated name, still sent by hosts
396
+ }
300
397
  }
301
398
  disconnectedCallback() {
302
399
  super.disconnectedCallback();
@@ -308,57 +405,115 @@ export class TestItemToSpeech extends LitElement {
308
405
  this.#stopPicking();
309
406
  this.#clearAllHighlights();
310
407
  this.#eventHost?.removeEventListener('qti-assessment-item-connected', this.#boundHandleItemConnected);
408
+ this.#eventHost?.removeEventListener('cito-test-navigate', this.#boundHandleNavigation);
311
409
  this.#eventHost?.removeEventListener('qti-request-navigation', this.#boundHandleNavigation);
312
410
  this.#eventHost = null;
313
- this.#itemElements.clear();
411
+ this.#itemRef = null;
412
+ this.#stimulusObserver?.disconnect();
413
+ this.#stimulusObserver = null;
414
+ this.#stimulusMode = false;
415
+ this.#contentMode = false;
314
416
  }
315
417
  render() {
316
418
  return html `<slot></slot>`;
317
419
  }
420
+ /**
421
+ * An item (re)rendered. If it is ours — e.g. after navigating to the item already shown — the
422
+ * elements collected earlier are detached now. That does not move the navigation cursor, so
423
+ * the check in updated() does not catch it.
424
+ */
318
425
  #handleItemConnected(event) {
319
- const item = event.detail;
320
- if (item?.identifier) {
321
- this.#itemElements.set(item.identifier, item);
322
- // Our item was (re)rendered: the elements we collected earlier are detached now.
323
- if (this.itemRefId && item.identifier === this.itemRefId && this.#readingElements !== null) {
324
- this.#resetReadingPosition();
325
- }
426
+ if (this.#readingElements === null)
427
+ return;
428
+ // In item-ref mode the event came through our own item-ref, so it is always ours.
429
+ const identifier = event.detail?.identifier;
430
+ if (this.#itemRef || identifier === this._sessionContext?.navItemRefId)
431
+ this.#resetReadingPosition();
432
+ }
433
+ /**
434
+ * Stimulus mode: the stimulus next to the player was (re)loaded or swapped. Forget what was
435
+ * collected, so the next play reads the new content from the top. Unlike
436
+ * #resetReadingPosition this only cancels speech that is ours: a stimulus can finish loading
437
+ * while an item player on the same page is speaking.
438
+ */
439
+ #handleStimulusReplaced() {
440
+ if (this.#currentUtterance) {
441
+ this.#currentUtterance = null;
442
+ speechSynthesis.cancel();
326
443
  }
444
+ this.#stopPicking();
445
+ this.#clearAllHighlights();
446
+ this.#setSpeechState('idle');
447
+ this.#readingElements = null;
448
+ this.#currentElementIndex = 0;
449
+ this.#finished = false;
450
+ this.#updateContext();
451
+ }
452
+ /**
453
+ * Stimulus mode: the `[data-stimulus-idref]` placeholder that shares this player's parent, or
454
+ * null. A placeholder holds the stimulus once loaded; the player cannot sit inside it, because
455
+ * loading replaces the placeholder's content.
456
+ */
457
+ #stimulusPlaceholder() {
458
+ return this.parentElement?.querySelector(':scope > [data-stimulus-idref]') ?? null;
327
459
  }
328
460
  /**
329
- * Find the rendered `qti-assessment-item` for an item-ref identifier without relying on the
330
- * connected-event cache — the player may be added after the item rendered (a header built
331
- * around an existing item) or sit in a shadow root the event never bubbled through.
461
+ * Content mode: the `[data-tts-content]` element that shares this player's parent, or null.
462
+ * The marker goes on one container; the player finds the readable elements inside it.
463
+ */
464
+ #contentElement() {
465
+ return this.parentElement?.querySelector(':scope > [data-tts-content]') ?? null;
466
+ }
467
+ /**
468
+ * The element whose text is read: the stimulus body next to the player (stimulus mode), the
469
+ * marked content next to it (content mode), or the item body of the item to read.
470
+ */
471
+ #resolveReadingRoot() {
472
+ if (this.#stimulusMode)
473
+ return this.#stimulusPlaceholder()?.querySelector('qti-stimulus-body') ?? null;
474
+ if (this.#contentMode)
475
+ return this.#contentElement();
476
+ return this.#resolveItem()?.querySelector('qti-item-body') ?? null;
477
+ }
478
+ /** The item to read: our item-ref's (item-ref mode), or the navigated one (cursor mode). */
479
+ #resolveItem() {
480
+ if (this.#itemRef)
481
+ return this.#itemRef.assessmentItem;
482
+ const identifier = this._sessionContext?.navItemRefId;
483
+ return identifier ? this.#findItemInDom(identifier) : null;
484
+ }
485
+ /**
486
+ * Cursor mode: find the rendered item for an item-ref identifier. Our own `<qti-test>` first —
487
+ * a page can hold several tests showing the same item — then every root from here up to the
488
+ * document; each scope directly and in the `test-container` shadow roots inside it.
332
489
  */
333
490
  #findItemInDom(identifier) {
334
- const esc = (v) => (typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(v) : v.replace(/"/g, '\\"'));
335
- const selector = `qti-assessment-item-ref[identifier="${esc(identifier)}"] qti-assessment-item, ` +
336
- `qti-assessment-item[identifier="${esc(identifier)}"]`;
337
- // Nearest first: a player placed inside the item's own card.
338
- const ownRef = this.closest('qti-assessment-item-ref');
339
- if (ownRef?.getAttribute('identifier') === identifier) {
340
- const own = ownRef.querySelector('qti-assessment-item');
341
- if (own)
342
- return own;
343
- }
344
- // Then every root from here up to the document, and the test-container shadow roots in them.
345
- let root = this.getRootNode();
346
- while (root) {
347
- const scope = root;
348
- const direct = scope.querySelector?.(selector);
491
+ const selector = `qti-assessment-item-ref[identifier="${CSS.escape(identifier)}"] qti-assessment-item`;
492
+ const search = (scope) => {
493
+ const direct = scope.querySelector(selector);
349
494
  if (direct)
350
495
  return direct;
351
- for (const container of Array.from(scope.querySelectorAll?.('test-container') ?? [])) {
496
+ for (const container of Array.from(scope.querySelectorAll('test-container'))) {
352
497
  const inShadow = container.shadowRoot?.querySelector(selector);
353
498
  if (inShadow)
354
499
  return inShadow;
355
500
  }
501
+ return null;
502
+ };
503
+ const test = this.closest('qti-test');
504
+ const inTest = test && search(test);
505
+ if (inTest)
506
+ return inTest;
507
+ let root = this.getRootNode();
508
+ for (;;) {
509
+ const found = search(root);
510
+ if (found)
511
+ return found;
356
512
  const host = root.host;
357
513
  if (!host)
358
- break;
514
+ return null;
359
515
  root = host.getRootNode();
360
516
  }
361
- return null;
362
517
  }
363
518
  /** Update speech state on both the context (notifies children) and the host's CSS custom states. */
364
519
  #setSpeechState(state) {
@@ -373,28 +528,48 @@ export class TestItemToSpeech extends LitElement {
373
528
  this._ttsContext = {
374
529
  ...this._ttsContext,
375
530
  currentElementIndex: this.#currentElementIndex,
376
- elementCount: this.#readingElements?.length ?? 0
531
+ elementCount: this.#getReadingElements().length
377
532
  };
378
533
  }
379
- /** Return cached reading elements, collecting them lazily on first call for the active item. */
534
+ /**
535
+ * Return the currently readable elements: cached candidates for the item or stimulus (collected lazily on
536
+ * first call), filtered live for visibility on every call. Feedback and other
537
+ * conditionally-shown content (e.g. `qti-feedback-block`, which is `display: none` until a
538
+ * CSS custom state reveals it) is excluded while hidden and picked up again once shown,
539
+ * without needing to re-collect the candidate set.
540
+ */
380
541
  #getReadingElements() {
381
- if (this.#readingElements !== null)
382
- return this.#readingElements;
383
- const identifier = this.itemRefId || this._sessionContext?.navItemRefId;
384
- if (!identifier)
385
- return [];
386
- const cached = this.#itemElements.get(identifier);
387
- const assessmentItem = cached?.isConnected ? cached : this.#findItemInDom(identifier);
388
- if (!assessmentItem)
389
- return [];
390
- const itemBody = assessmentItem.querySelector('qti-item-body');
391
- if (!itemBody)
392
- return [];
393
- // Collect block-level elements (and QTI prompt / choice elements) that contain readable text.
394
- // Keep only the innermost matches so `<li><p>…</p></li>` is not read twice.
395
- const selector = 'p, h1, h2, h3, h4, h5, h6, li, blockquote, figcaption, qti-prompt, qti-simple-choice';
396
- this.#readingElements = Array.from(itemBody.querySelectorAll(selector)).filter(el => (el.textContent ?? '').trim().length > 0 && !el.querySelector(selector));
397
- return this.#readingElements;
542
+ // Content mode has no events or observer telling it the content changed (a framework like
543
+ // React re-renders it at will). Rebuild the list once an element in it has left the page;
544
+ // text changed inside an element needs nothing, it is read when that element is spoken.
545
+ if (this.#contentMode && this.#readingElements?.some(el => !el.isConnected)) {
546
+ this.#readingElements = null;
547
+ this.#currentElementIndex = 0;
548
+ this.#finished = false;
549
+ }
550
+ if (this.#readingElements === null) {
551
+ const root = this.#resolveReadingRoot();
552
+ // Leave the cache empty (rather than `[]`) while the item or stimulus has not rendered yet,
553
+ // so the next call retries instead of getting stuck on an empty result forever.
554
+ if (!root)
555
+ return [];
556
+ // Collect block-level elements (and QTI prompt / choice elements) that contain readable text.
557
+ // Keep only the innermost matches so `<li><p>…</p></li>` is not read twice. Content hidden
558
+ // from assistive technology (`aria-hidden="true"`, e.g. decorative icons) is not read either.
559
+ const selector = 'p, h1, h2, h3, h4, h5, h6, li, dt, dd, th, td, caption, blockquote, figcaption, qti-prompt, qti-simple-choice';
560
+ this.#readingElements = Array.from(root.querySelectorAll(selector)).filter(el => (el.textContent ?? '').trim().length > 0 && !el.querySelector(selector) && !el.closest('[aria-hidden="true"]'));
561
+ }
562
+ return this.#readingElements.filter(el => this.#isVisible(el));
563
+ }
564
+ /** True when an element is actually rendered — not `display: none` (itself or an ancestor). */
565
+ #isVisible(element) {
566
+ if (typeof element.checkVisibility === 'function') {
567
+ return element.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
568
+ }
569
+ // Older Safari (< 17.4) fallback: display:none leaves no client rects. Doesn't catch
570
+ // visibility:hidden, which still occupies layout, but display:none is what QTI feedback
571
+ // elements actually use (see qti-feedback-block/qti-feedback-inline default styles).
572
+ return element.getClientRects().length > 0;
398
573
  }
399
574
  /**
400
575
  * Resolve the speech language for a reading element.
@@ -417,7 +592,7 @@ export class TestItemToSpeech extends LitElement {
417
592
  #playSpeech() {
418
593
  const elements = this.#getReadingElements();
419
594
  if (!elements.length) {
420
- console.warn('test-item-to-speech: no readable elements found in qti-item-body');
595
+ console.warn('test-item-to-speech: no readable elements found');
421
596
  return;
422
597
  }
423
598
  this.#stopPicking();
@@ -428,11 +603,15 @@ export class TestItemToSpeech extends LitElement {
428
603
  this.#finished = false;
429
604
  this.#currentElementIndex = 0;
430
605
  }
606
+ // Content mode: starting from the top rebuilds the list, so elements the page added since
607
+ // the last read (a framework re-render) are included.
608
+ if (this.#contentMode && this.#currentElementIndex === 0)
609
+ this.#readingElements = null;
431
610
  this.#speakElement(this.#currentElementIndex);
432
611
  }
433
612
  /** Speak the element at the given index, then auto-advance when it ends. */
434
613
  #speakElement(index) {
435
- const elements = this.#readingElements ?? [];
614
+ const elements = this.#getReadingElements();
436
615
  if (index >= elements.length) {
437
616
  // Finished all elements — stay on the last element so the user can walk back with prev
438
617
  this.#clearWordHighlight();
@@ -509,9 +688,12 @@ export class TestItemToSpeech extends LitElement {
509
688
  }
510
689
  /** Highlight every reading element and wait for a click on one of them. */
511
690
  #startPicking() {
691
+ // Content mode: pick from the page as it is now, like starting from the top does.
692
+ if (this.#contentMode)
693
+ this.#readingElements = null;
512
694
  const elements = this.#getReadingElements();
513
695
  if (!elements.length) {
514
- console.warn('test-item-to-speech: no readable elements found in qti-item-body');
696
+ console.warn('test-item-to-speech: no readable elements found');
515
697
  return;
516
698
  }
517
699
  this.#stop();
@@ -535,7 +717,7 @@ export class TestItemToSpeech extends LitElement {
535
717
  this._ttsContext = { ...this._ttsContext, picking: false };
536
718
  }
537
719
  #handlePickClick(event) {
538
- const elements = this.#readingElements ?? [];
720
+ const elements = this.#getReadingElements();
539
721
  const path = event.composedPath();
540
722
  let index = elements.findIndex(el => path.includes(el));
541
723
  if (index < 0) {
@@ -589,7 +771,9 @@ export class TestItemToSpeech extends LitElement {
589
771
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
590
772
  let node;
591
773
  while ((node = walker.nextNode())) {
592
- if ((node.textContent ?? '').length > 0) {
774
+ // Text hidden from assistive technology inside a read element — a decorative icon in a
775
+ // list item — is not spoken either. Skipped here, so speech and word highlight agree.
776
+ if ((node.textContent ?? '').length > 0 && !node.parentElement?.closest('[aria-hidden="true"]')) {
593
777
  nodes.push(node);
594
778
  }
595
779
  }
@@ -685,7 +869,7 @@ export class TestItemToSpeech extends LitElement {
685
869
  // root when the player itself sits inside a shadow tree (e.g. built into an item card).
686
870
  const roots = new Set();
687
871
  const testContainer = this.closest('test-navigation')?.querySelector('test-container') ??
688
- this.closest('qti-test')?.querySelector('test-container');
872
+ this.testHost?.querySelector('test-container');
689
873
  if (testContainer?.shadowRoot)
690
874
  roots.add(testContainer.shadowRoot);
691
875
  const ownRoot = this.getRootNode();
@@ -704,12 +888,12 @@ export class TestItemToSpeech extends LitElement {
704
888
  __decorate([
705
889
  property({ type: String })
706
890
  ], TestItemToSpeech.prototype, "language", void 0);
707
- __decorate([
708
- property({ type: String, attribute: 'item-ref-id' })
709
- ], TestItemToSpeech.prototype, "itemRefId", void 0);
710
891
  __decorate([
711
892
  consume({ context: sessionContext, subscribe: true })
712
893
  ], TestItemToSpeech.prototype, "_sessionContext", void 0);
894
+ __decorate([
895
+ consume({ context: testHostContext, subscribe: true })
896
+ ], TestItemToSpeech.prototype, "testHost", void 0);
713
897
  __decorate([
714
898
  state(),
715
899
  provide({ context: ttsContext })