@qti-components/test 1.8.0 → 1.9.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 (45) 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 +10 -23
  3. package/dist/components/qti-assessment-item-ref/qti-assessment-item-ref.js.map +1 -1
  4. package/dist/components/qti-test/qti-test.d.ts +16 -2
  5. package/dist/components/qti-test/qti-test.js +33 -6
  6. package/dist/components/qti-test/qti-test.js.map +1 -1
  7. package/dist/components/test-check-item/test-check-item.d.ts +2 -0
  8. package/dist/components/test-check-item/test-check-item.js +14 -2
  9. package/dist/components/test-check-item/test-check-item.js.map +1 -1
  10. package/dist/components/test-container/test-container.d.ts +3 -0
  11. package/dist/components/test-container/test-container.js +5 -1
  12. package/dist/components/test-container/test-container.js.map +1 -1
  13. package/dist/components/test-item-to-speech/test-item-to-speech.d.ts +61 -15
  14. package/dist/components/test-item-to-speech/test-item-to-speech.js +285 -103
  15. package/dist/components/test-item-to-speech/test-item-to-speech.js.map +1 -1
  16. package/dist/components/test-navigation/test-navigation.d.ts +9 -1
  17. package/dist/components/test-navigation/test-navigation.js +62 -17
  18. package/dist/components/test-navigation/test-navigation.js.map +1 -1
  19. package/dist/components/test-scoring-buttons/test-scoring-buttons.d.ts +1 -1
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.js +1 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/internal/test-host.context.d.ts +24 -0
  24. package/dist/internal/test-host.context.js +3 -0
  25. package/dist/internal/test-host.context.js.map +1 -0
  26. package/dist/mixins/index.d.ts +1 -0
  27. package/dist/mixins/index.js +1 -0
  28. package/dist/mixins/index.js.map +1 -1
  29. package/dist/mixins/test-base.d.ts +7 -2
  30. package/dist/mixins/test-base.js +53 -19
  31. package/dist/mixins/test-base.js.map +1 -1
  32. package/dist/mixins/test-navigation.mixin.d.ts +3 -4
  33. package/dist/mixins/test-navigation.mixin.js +11 -12
  34. package/dist/mixins/test-navigation.mixin.js.map +1 -1
  35. package/dist/mixins/test-processing.mixin.js +3 -1
  36. package/dist/mixins/test-processing.mixin.js.map +1 -1
  37. package/dist/mixins/test-state.mixin.d.ts +33 -0
  38. package/dist/mixins/test-state.mixin.js +130 -0
  39. package/dist/mixins/test-state.mixin.js.map +1 -0
  40. package/dist/types/iqti-test.d.ts +8 -5
  41. package/dist/types/iqti-test.js.map +1 -1
  42. package/dist/types/qti-test-state.d.ts +45 -0
  43. package/dist/types/qti-test-state.js +2 -0
  44. package/dist/types/qti-test-state.js.map +1 -0
  45. package/package.json +3 -3
@@ -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,34 @@ 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: qti-request-navigation 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('qti-request-navigation', this.#boundHandleNavigation);
395
+ }
300
396
  }
301
397
  disconnectedCallback() {
302
398
  super.disconnectedCallback();
@@ -310,55 +406,112 @@ export class TestItemToSpeech extends LitElement {
310
406
  this.#eventHost?.removeEventListener('qti-assessment-item-connected', this.#boundHandleItemConnected);
311
407
  this.#eventHost?.removeEventListener('qti-request-navigation', this.#boundHandleNavigation);
312
408
  this.#eventHost = null;
313
- this.#itemElements.clear();
409
+ this.#itemRef = null;
410
+ this.#stimulusObserver?.disconnect();
411
+ this.#stimulusObserver = null;
412
+ this.#stimulusMode = false;
413
+ this.#contentMode = false;
314
414
  }
315
415
  render() {
316
416
  return html `<slot></slot>`;
317
417
  }
418
+ /**
419
+ * An item (re)rendered. If it is ours — e.g. after navigating to the item already shown — the
420
+ * elements collected earlier are detached now. That does not move the navigation cursor, so
421
+ * the check in updated() does not catch it.
422
+ */
318
423
  #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
- }
424
+ if (this.#readingElements === null)
425
+ return;
426
+ // In item-ref mode the event came through our own item-ref, so it is always ours.
427
+ const identifier = event.detail?.identifier;
428
+ if (this.#itemRef || identifier === this._sessionContext?.navItemRefId)
429
+ this.#resetReadingPosition();
430
+ }
431
+ /**
432
+ * Stimulus mode: the stimulus next to the player was (re)loaded or swapped. Forget what was
433
+ * collected, so the next play reads the new content from the top. Unlike
434
+ * #resetReadingPosition this only cancels speech that is ours: a stimulus can finish loading
435
+ * while an item player on the same page is speaking.
436
+ */
437
+ #handleStimulusReplaced() {
438
+ if (this.#currentUtterance) {
439
+ this.#currentUtterance = null;
440
+ speechSynthesis.cancel();
326
441
  }
442
+ this.#stopPicking();
443
+ this.#clearAllHighlights();
444
+ this.#setSpeechState('idle');
445
+ this.#readingElements = null;
446
+ this.#currentElementIndex = 0;
447
+ this.#finished = false;
448
+ this.#updateContext();
449
+ }
450
+ /**
451
+ * Stimulus mode: the `[data-stimulus-idref]` placeholder that shares this player's parent, or
452
+ * null. A placeholder holds the stimulus once loaded; the player cannot sit inside it, because
453
+ * loading replaces the placeholder's content.
454
+ */
455
+ #stimulusPlaceholder() {
456
+ return this.parentElement?.querySelector(':scope > [data-stimulus-idref]') ?? null;
327
457
  }
328
458
  /**
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.
459
+ * Content mode: the `[data-tts-content]` element that shares this player's parent, or null.
460
+ * The marker goes on one container; the player finds the readable elements inside it.
461
+ */
462
+ #contentElement() {
463
+ return this.parentElement?.querySelector(':scope > [data-tts-content]') ?? null;
464
+ }
465
+ /**
466
+ * The element whose text is read: the stimulus body next to the player (stimulus mode), the
467
+ * marked content next to it (content mode), or the item body of the item to read.
468
+ */
469
+ #resolveReadingRoot() {
470
+ if (this.#stimulusMode)
471
+ return this.#stimulusPlaceholder()?.querySelector('qti-stimulus-body') ?? null;
472
+ if (this.#contentMode)
473
+ return this.#contentElement();
474
+ return this.#resolveItem()?.querySelector('qti-item-body') ?? null;
475
+ }
476
+ /** The item to read: our item-ref's (item-ref mode), or the navigated one (cursor mode). */
477
+ #resolveItem() {
478
+ if (this.#itemRef)
479
+ return this.#itemRef.assessmentItem;
480
+ const identifier = this._sessionContext?.navItemRefId;
481
+ return identifier ? this.#findItemInDom(identifier) : null;
482
+ }
483
+ /**
484
+ * Cursor mode: find the rendered item for an item-ref identifier. Our own `<qti-test>` first —
485
+ * a page can hold several tests showing the same item — then every root from here up to the
486
+ * document; each scope directly and in the `test-container` shadow roots inside it.
332
487
  */
333
488
  #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);
489
+ const selector = `qti-assessment-item-ref[identifier="${CSS.escape(identifier)}"] qti-assessment-item`;
490
+ const search = (scope) => {
491
+ const direct = scope.querySelector(selector);
349
492
  if (direct)
350
493
  return direct;
351
- for (const container of Array.from(scope.querySelectorAll?.('test-container') ?? [])) {
494
+ for (const container of Array.from(scope.querySelectorAll('test-container'))) {
352
495
  const inShadow = container.shadowRoot?.querySelector(selector);
353
496
  if (inShadow)
354
497
  return inShadow;
355
498
  }
499
+ return null;
500
+ };
501
+ const test = this.closest('qti-test');
502
+ const inTest = test && search(test);
503
+ if (inTest)
504
+ return inTest;
505
+ let root = this.getRootNode();
506
+ for (;;) {
507
+ const found = search(root);
508
+ if (found)
509
+ return found;
356
510
  const host = root.host;
357
511
  if (!host)
358
- break;
512
+ return null;
359
513
  root = host.getRootNode();
360
514
  }
361
- return null;
362
515
  }
363
516
  /** Update speech state on both the context (notifies children) and the host's CSS custom states. */
364
517
  #setSpeechState(state) {
@@ -373,28 +526,48 @@ export class TestItemToSpeech extends LitElement {
373
526
  this._ttsContext = {
374
527
  ...this._ttsContext,
375
528
  currentElementIndex: this.#currentElementIndex,
376
- elementCount: this.#readingElements?.length ?? 0
529
+ elementCount: this.#getReadingElements().length
377
530
  };
378
531
  }
379
- /** Return cached reading elements, collecting them lazily on first call for the active item. */
532
+ /**
533
+ * Return the currently readable elements: cached candidates for the item or stimulus (collected lazily on
534
+ * first call), filtered live for visibility on every call. Feedback and other
535
+ * conditionally-shown content (e.g. `qti-feedback-block`, which is `display: none` until a
536
+ * CSS custom state reveals it) is excluded while hidden and picked up again once shown,
537
+ * without needing to re-collect the candidate set.
538
+ */
380
539
  #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;
540
+ // Content mode has no events or observer telling it the content changed (a framework like
541
+ // React re-renders it at will). Rebuild the list once an element in it has left the page;
542
+ // text changed inside an element needs nothing, it is read when that element is spoken.
543
+ if (this.#contentMode && this.#readingElements?.some(el => !el.isConnected)) {
544
+ this.#readingElements = null;
545
+ this.#currentElementIndex = 0;
546
+ this.#finished = false;
547
+ }
548
+ if (this.#readingElements === null) {
549
+ const root = this.#resolveReadingRoot();
550
+ // Leave the cache empty (rather than `[]`) while the item or stimulus has not rendered yet,
551
+ // so the next call retries instead of getting stuck on an empty result forever.
552
+ if (!root)
553
+ return [];
554
+ // Collect block-level elements (and QTI prompt / choice elements) that contain readable text.
555
+ // Keep only the innermost matches so `<li><p>…</p></li>` is not read twice. Content hidden
556
+ // from assistive technology (`aria-hidden="true"`, e.g. decorative icons) is not read either.
557
+ const selector = 'p, h1, h2, h3, h4, h5, h6, li, dt, dd, th, td, caption, blockquote, figcaption, qti-prompt, qti-simple-choice';
558
+ this.#readingElements = Array.from(root.querySelectorAll(selector)).filter(el => (el.textContent ?? '').trim().length > 0 && !el.querySelector(selector) && !el.closest('[aria-hidden="true"]'));
559
+ }
560
+ return this.#readingElements.filter(el => this.#isVisible(el));
561
+ }
562
+ /** True when an element is actually rendered — not `display: none` (itself or an ancestor). */
563
+ #isVisible(element) {
564
+ if (typeof element.checkVisibility === 'function') {
565
+ return element.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
566
+ }
567
+ // Older Safari (< 17.4) fallback: display:none leaves no client rects. Doesn't catch
568
+ // visibility:hidden, which still occupies layout, but display:none is what QTI feedback
569
+ // elements actually use (see qti-feedback-block/qti-feedback-inline default styles).
570
+ return element.getClientRects().length > 0;
398
571
  }
399
572
  /**
400
573
  * Resolve the speech language for a reading element.
@@ -417,7 +590,7 @@ export class TestItemToSpeech extends LitElement {
417
590
  #playSpeech() {
418
591
  const elements = this.#getReadingElements();
419
592
  if (!elements.length) {
420
- console.warn('test-item-to-speech: no readable elements found in qti-item-body');
593
+ console.warn('test-item-to-speech: no readable elements found');
421
594
  return;
422
595
  }
423
596
  this.#stopPicking();
@@ -428,11 +601,15 @@ export class TestItemToSpeech extends LitElement {
428
601
  this.#finished = false;
429
602
  this.#currentElementIndex = 0;
430
603
  }
604
+ // Content mode: starting from the top rebuilds the list, so elements the page added since
605
+ // the last read (a framework re-render) are included.
606
+ if (this.#contentMode && this.#currentElementIndex === 0)
607
+ this.#readingElements = null;
431
608
  this.#speakElement(this.#currentElementIndex);
432
609
  }
433
610
  /** Speak the element at the given index, then auto-advance when it ends. */
434
611
  #speakElement(index) {
435
- const elements = this.#readingElements ?? [];
612
+ const elements = this.#getReadingElements();
436
613
  if (index >= elements.length) {
437
614
  // Finished all elements — stay on the last element so the user can walk back with prev
438
615
  this.#clearWordHighlight();
@@ -509,9 +686,12 @@ export class TestItemToSpeech extends LitElement {
509
686
  }
510
687
  /** Highlight every reading element and wait for a click on one of them. */
511
688
  #startPicking() {
689
+ // Content mode: pick from the page as it is now, like starting from the top does.
690
+ if (this.#contentMode)
691
+ this.#readingElements = null;
512
692
  const elements = this.#getReadingElements();
513
693
  if (!elements.length) {
514
- console.warn('test-item-to-speech: no readable elements found in qti-item-body');
694
+ console.warn('test-item-to-speech: no readable elements found');
515
695
  return;
516
696
  }
517
697
  this.#stop();
@@ -535,7 +715,7 @@ export class TestItemToSpeech extends LitElement {
535
715
  this._ttsContext = { ...this._ttsContext, picking: false };
536
716
  }
537
717
  #handlePickClick(event) {
538
- const elements = this.#readingElements ?? [];
718
+ const elements = this.#getReadingElements();
539
719
  const path = event.composedPath();
540
720
  let index = elements.findIndex(el => path.includes(el));
541
721
  if (index < 0) {
@@ -589,7 +769,9 @@ export class TestItemToSpeech extends LitElement {
589
769
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
590
770
  let node;
591
771
  while ((node = walker.nextNode())) {
592
- if ((node.textContent ?? '').length > 0) {
772
+ // Text hidden from assistive technology inside a read element — a decorative icon in a
773
+ // list item — is not spoken either. Skipped here, so speech and word highlight agree.
774
+ if ((node.textContent ?? '').length > 0 && !node.parentElement?.closest('[aria-hidden="true"]')) {
593
775
  nodes.push(node);
594
776
  }
595
777
  }
@@ -685,7 +867,7 @@ export class TestItemToSpeech extends LitElement {
685
867
  // root when the player itself sits inside a shadow tree (e.g. built into an item card).
686
868
  const roots = new Set();
687
869
  const testContainer = this.closest('test-navigation')?.querySelector('test-container') ??
688
- this.closest('qti-test')?.querySelector('test-container');
870
+ this.testHost?.querySelector('test-container');
689
871
  if (testContainer?.shadowRoot)
690
872
  roots.add(testContainer.shadowRoot);
691
873
  const ownRoot = this.getRootNode();
@@ -704,12 +886,12 @@ export class TestItemToSpeech extends LitElement {
704
886
  __decorate([
705
887
  property({ type: String })
706
888
  ], TestItemToSpeech.prototype, "language", void 0);
707
- __decorate([
708
- property({ type: String, attribute: 'item-ref-id' })
709
- ], TestItemToSpeech.prototype, "itemRefId", void 0);
710
889
  __decorate([
711
890
  consume({ context: sessionContext, subscribe: true })
712
891
  ], TestItemToSpeech.prototype, "_sessionContext", void 0);
892
+ __decorate([
893
+ consume({ context: testHostContext, subscribe: true })
894
+ ], TestItemToSpeech.prototype, "testHost", void 0);
713
895
  __decorate([
714
896
  state(),
715
897
  provide({ context: ttsContext })