@pie-qti/item-player 0.1.6 → 0.1.7

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 (40) hide show
  1. package/dist/catalog/applyGlossaryTriggers.d.ts +2 -1
  2. package/dist/catalog/applyGlossaryTriggers.d.ts.map +1 -1
  3. package/dist/catalog/applyGlossaryTriggers.js +145 -30
  4. package/dist/catalog/glossaryAction.d.ts.map +1 -1
  5. package/dist/catalog/glossaryAction.js +14 -4
  6. package/dist/components/utils/stimulusRender.d.ts +17 -0
  7. package/dist/components/utils/stimulusRender.d.ts.map +1 -0
  8. package/dist/components/utils/stimulusRender.js +70 -0
  9. package/dist/components/utils/stylesheetRender.d.ts +4 -0
  10. package/dist/components/utils/stylesheetRender.d.ts.map +1 -0
  11. package/dist/components/utils/stylesheetRender.js +57 -0
  12. package/dist/core/Player.d.ts +37 -2
  13. package/dist/core/Player.d.ts.map +1 -1
  14. package/dist/core/Player.js +320 -48
  15. package/dist/element.js +1288 -924
  16. package/dist/element.js.map +1 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/pnp/applyPnp.d.ts.map +1 -1
  20. package/dist/pnp/applyPnp.js +9 -2
  21. package/dist/pnp/parsePnpXml.d.ts.map +1 -1
  22. package/dist/pnp/parsePnpXml.js +91 -3
  23. package/dist/pnp/types.d.ts +24 -1
  24. package/dist/pnp/types.d.ts.map +1 -1
  25. package/dist/types/index.d.ts +47 -0
  26. package/dist/types/index.d.ts.map +1 -1
  27. package/package.json +6 -6
  28. package/src/catalog/applyGlossaryTriggers.ts +174 -34
  29. package/src/catalog/glossaryAction.ts +14 -4
  30. package/src/components/ItemBody.svelte +36 -27
  31. package/src/components/utils/stimulusRender.ts +93 -0
  32. package/src/components/utils/stylesheetRender.ts +58 -0
  33. package/src/core/Player.ts +355 -48
  34. package/src/index.ts +1 -0
  35. package/src/pnp/applyPnp.ts +8 -2
  36. package/src/pnp/parsePnpXml.ts +102 -5
  37. package/src/pnp/types.ts +43 -1
  38. package/src/types/index.ts +53 -0
  39. package/src/__tests__/glossaryTriggers.test.ts +0 -411
  40. package/src/__tests__/pnp.test.ts +0 -250
@@ -1,6 +1,6 @@
1
1
  import { parse as parseHtml } from 'node-html-parser';
2
2
  import type { HTMLElement as NhpElement } from 'node-html-parser';
3
- import type { PnpProfile } from './types.js';
3
+ import type { CatalogSupportPreference, PnpProfile } from './types.js';
4
4
 
5
5
  /**
6
6
  * Parse a QTI 3.0 <personalNeedsProfile> element (or legacy <pnp> element) into a PnpProfile.
@@ -63,6 +63,43 @@ function extractProfile(root: NhpElement): PnpProfile {
63
63
  if (languageCode) profile.content.keywordTranslation = { active, languageCode };
64
64
  }
65
65
 
66
+ const illustratedEl = findChild(contentEl, [
67
+ 'illustratedglossary',
68
+ 'illustrated-glossary',
69
+ 'ext:sbacglossaryillustration',
70
+ 'ext:sbac-glossary-illustration',
71
+ ]);
72
+ if (illustratedEl) {
73
+ profile.content.illustratedGlossary = parseBool(
74
+ illustratedEl.getAttribute('enabled') ?? illustratedEl.getAttribute('active') ?? illustratedEl.text ?? 'true'
75
+ );
76
+ }
77
+
78
+ const catalogSupportMap = [
79
+ ['ttsPronunciation', ['ttspronunciation', 'tts-pronunciation']],
80
+ ['signingDefinition', ['signingdefinition', 'signing-definition']],
81
+ ['brailleText', ['brailletext', 'braille-text']],
82
+ ['audioDescription', ['audiodescription', 'audio-description']],
83
+ ['extendedDescription', ['extendeddescription', 'extended-description']],
84
+ ] as const;
85
+ for (const [key, names] of catalogSupportMap) {
86
+ const el = findChild(contentEl, names);
87
+ if (el) {
88
+ profile.content.catalogSupports ??= {};
89
+ profile.content.catalogSupports[key] = parseCatalogSupportPreference(el);
90
+ }
91
+ }
92
+
93
+ for (const el of findChildren(contentEl, ['catalogsupport', 'catalog-support', 'qti-catalog-support'])) {
94
+ const usage = normalizeCatalogUsage(
95
+ el.getAttribute('usage') ?? el.getAttribute('support') ?? el.getAttribute('name') ?? ''
96
+ );
97
+ if (!usage) continue;
98
+ const key = catalogSupportPreferenceKey(usage);
99
+ profile.content.catalogSupports ??= {};
100
+ profile.content.catalogSupports[key] = parseCatalogSupportPreference(el);
101
+ }
102
+
66
103
  const etEl = findChild(contentEl, ['extendedtime', 'extended-time']);
67
104
  if (etEl) {
68
105
  const active = parseBool(etEl.getAttribute('active') ?? 'true');
@@ -96,14 +133,19 @@ function extractProfile(root: NhpElement): PnpProfile {
96
133
  // Helpers
97
134
  // ---------------------------------------------------------------------------
98
135
 
99
- function findChild(parent: NhpElement, names: string[]): NhpElement | null {
136
+ function findChild(parent: NhpElement, names: readonly string[]): NhpElement | null {
137
+ return findChildren(parent, names)[0] ?? null;
138
+ }
139
+
140
+ function findChildren(parent: NhpElement, names: readonly string[]): NhpElement[] {
141
+ const matches: NhpElement[] = [];
100
142
  for (const child of parent.childNodes) {
101
143
  if (child.nodeType !== 1) continue; // element nodes only
102
144
  const el = child as NhpElement;
103
145
  const tag = (el.rawTagName ?? '').toLowerCase();
104
- if (names.includes(tag)) return el;
146
+ if (names.includes(tag)) matches.push(el);
105
147
  }
106
- return null;
148
+ return matches;
107
149
  }
108
150
 
109
151
  function parseBool(value: string): boolean {
@@ -111,8 +153,63 @@ function parseBool(value: string): boolean {
111
153
  return v !== 'false' && v !== '0' && v !== 'no';
112
154
  }
113
155
 
156
+ function parseCatalogSupportPreference(el: NhpElement): CatalogSupportPreference {
157
+ const active = parseBool(el.getAttribute('enabled') ?? el.getAttribute('active') ?? el.text ?? 'true');
158
+ const languageCode = normalizeLanguageCode(
159
+ el.getAttribute('languagecode') ?? el.getAttribute('language-code') ?? el.getAttribute('lang') ?? ''
160
+ );
161
+ return languageCode ? { active, languageCode } : active;
162
+ }
163
+
114
164
  type ColorScheme = PnpProfile['display'] extends { colorScheme?: infer C } ? Exclude<C, undefined> : never;
115
- const COLOR_SCHEMES = new Set<string>(['default', 'blackwhite', 'whitenav', 'blackcream', 'yellowblue', 'medgray']);
165
+ const COLOR_SCHEMES = new Set<string>([
166
+ 'default',
167
+ 'defaultreverse',
168
+ 'blackwhite',
169
+ 'whiteblack',
170
+ 'blackrose',
171
+ 'roseblack',
172
+ 'yellowblue',
173
+ 'blueyellow',
174
+ 'mgraydgray',
175
+ 'dgraymgray',
176
+ 'blackcyan',
177
+ 'cyanblack',
178
+ 'blackcream',
179
+ 'creamblack',
180
+ 'whitenav',
181
+ 'medgray',
182
+ ]);
116
183
  function isColorScheme(v: string): v is ColorScheme {
117
184
  return COLOR_SCHEMES.has(v);
118
185
  }
186
+
187
+ function normalizeCatalogUsage(value: string): string | null {
188
+ const usage = value.trim().toLowerCase();
189
+ if (!/^[a-z][a-z0-9._-]*$/.test(usage)) return null;
190
+ return usage;
191
+ }
192
+
193
+ function normalizeLanguageCode(value: string): string | undefined {
194
+ const languageCode = value.trim();
195
+ if (!languageCode) return undefined;
196
+ if (!/^[a-zA-Z]{2,8}(?:-[a-zA-Z0-9]{1,8})*$/.test(languageCode)) return undefined;
197
+ return languageCode;
198
+ }
199
+
200
+ function catalogSupportPreferenceKey(usage: string): string {
201
+ switch (usage) {
202
+ case 'tts-pronunciation':
203
+ return 'ttsPronunciation';
204
+ case 'signing-definition':
205
+ return 'signingDefinition';
206
+ case 'braille-text':
207
+ return 'brailleText';
208
+ case 'audio-description':
209
+ return 'audioDescription';
210
+ case 'extended-description':
211
+ return 'extendedDescription';
212
+ default:
213
+ return usage;
214
+ }
215
+ }
package/src/pnp/types.ts CHANGED
@@ -8,7 +8,23 @@ export interface PnpProfile {
8
8
  * Named color scheme. Maps to the data-qti-colorscheme attribute on the player root.
9
9
  * 'default' or undefined → attribute removed (browser/host default).
10
10
  */
11
- colorScheme?: 'default' | 'blackwhite' | 'whitenav' | 'blackcream' | 'yellowblue' | 'medgray';
11
+ colorScheme?:
12
+ | 'default'
13
+ | 'defaultreverse'
14
+ | 'blackwhite'
15
+ | 'whiteblack'
16
+ | 'blackrose'
17
+ | 'roseblack'
18
+ | 'yellowblue'
19
+ | 'blueyellow'
20
+ | 'mgraydgray'
21
+ | 'dgraymgray'
22
+ | 'blackcyan'
23
+ | 'cyanblack'
24
+ | 'blackcream'
25
+ | 'creamblack'
26
+ | 'whitenav'
27
+ | 'medgray';
12
28
  /**
13
29
  * CSS zoom factor (1.0 = 100%). Deferred — set by browser zoom or host stylesheet.
14
30
  * Stored here for forward-compatibility but not yet applied by the player.
@@ -20,6 +36,10 @@ export interface PnpProfile {
20
36
  glossaryOnScreen?: boolean;
21
37
  /** Show keyword-translation trigger buttons using the given language code. */
22
38
  keywordTranslation?: { active: boolean; languageCode: string };
39
+ /** Show illustrated glossary supports when catalog entries provide them. */
40
+ illustratedGlossary?: boolean;
41
+ /** Enable user-initiated host-routed catalog supports. */
42
+ catalogSupports?: CatalogSupportPreferences;
23
43
  /**
24
44
  * Scale assessment time limits. multiplier: 1.5 means 50% extra time.
25
45
  * multiplier: Infinity removes the time limit entirely.
@@ -31,3 +51,25 @@ export interface PnpProfile {
31
51
  eliminationTool?: boolean;
32
52
  };
33
53
  }
54
+
55
+ export interface CatalogSupportPreferences {
56
+ ttsPronunciation?: CatalogSupportPreference;
57
+ signingDefinition?: CatalogSupportPreference;
58
+ brailleText?: CatalogSupportPreference;
59
+ audioDescription?: CatalogSupportPreference;
60
+ extendedDescription?: CatalogSupportPreference;
61
+ /**
62
+ * Host-defined catalog usage names. Use QTI/catalog usage strings such as
63
+ * "custom-audio" rather than DOM event names or implementation-specific APIs.
64
+ */
65
+ [usage: string]: CatalogSupportPreference | undefined;
66
+ }
67
+
68
+ export type CatalogSupportPreference = boolean | CatalogSupportPreferenceOptions;
69
+
70
+ export interface CatalogSupportPreferenceOptions {
71
+ /** Defaults to true when omitted. */
72
+ active?: boolean;
73
+ /** Preferred catalog entry language for this support, such as "en-US" or "es". */
74
+ languageCode?: string;
75
+ }
@@ -7,6 +7,8 @@ import type {
7
7
  Cardinality as ProcessingCardinality,
8
8
  QtiValue,
9
9
  } from '@pie-qti/qti-processing';
10
+ import type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';
11
+ import type { ResponseValidationResult } from './responseValidation.js';
10
12
 
11
13
  /**
12
14
  * QTI base type identifier
@@ -78,6 +80,51 @@ export interface ItemSessionState {
78
80
  [variableId: string]: any;
79
81
  }
80
82
 
83
+ export type ItemLifecycleStatus = 'initial' | 'interacting' | 'suspended' | 'closed' | 'review' | 'solution' | 'answer';
84
+
85
+ export type SerializedVariableKind = 'response' | 'outcome' | 'template' | 'context';
86
+
87
+ export interface SerializedItemSessionVariable {
88
+ identifier: string;
89
+ kind: SerializedVariableKind;
90
+ baseType: VariableBaseType;
91
+ cardinality: VariableCardinality;
92
+ value: any;
93
+ defaultValue?: any;
94
+ }
95
+
96
+ export interface SerializedItemSessionState {
97
+ itemIdentifier?: string;
98
+ sessionGuid: string;
99
+ lifecycleStatus: ItemLifecycleStatus;
100
+ completionStatus: CompletionStatus;
101
+ numAttempts: number;
102
+ /**
103
+ * Time-on-task in milliseconds, stored as the QTI built-in duration variable value.
104
+ */
105
+ duration: number;
106
+ responseVariables: Record<string, SerializedItemSessionVariable>;
107
+ outcomeVariables: Record<string, SerializedItemSessionVariable>;
108
+ templateVariables: Record<string, SerializedItemSessionVariable>;
109
+ contextVariables: Record<string, SerializedItemSessionVariable>;
110
+ validationMessages: ResponseValidationResult['issues'];
111
+ savedAt: string;
112
+ }
113
+
114
+ export type ItemSessionAction = 'suspendAttempt' | 'endAttempt' | 'scoreAttempt' | 'newTemplate';
115
+
116
+ export interface ItemSessionActionResult {
117
+ action: ItemSessionAction;
118
+ lifecycleStatus: ItemLifecycleStatus;
119
+ completionStatus: CompletionStatus;
120
+ numAttempts: number;
121
+ duration: number;
122
+ completed: boolean;
123
+ sessionState: SerializedItemSessionState;
124
+ validation?: ResponseValidationResult;
125
+ scoring?: ScoringResult;
126
+ }
127
+
81
128
  export interface InteractionResponse {
82
129
  [responseId: string]: any;
83
130
  }
@@ -190,6 +237,12 @@ export interface PlayerConfig {
190
237
  * Deferred: external catalog files from IMS manifest (G-15) are not yet supported.
191
238
  */
192
239
  catalogXml?: string;
240
+ /**
241
+ * Optional resolved delivery context produced by IMS package/assessment layers.
242
+ * This is additive to catalogXml: shared catalog sources are merged first, then
243
+ * catalogXml, then item-embedded catalog entries so item-local entries win.
244
+ */
245
+ deliveryContext?: ResolvedItemDeliveryContext;
193
246
  sessionState?: ItemSessionState;
194
247
  responses?: InteractionResponse;
195
248
  role?: QTIRole;
@@ -1,411 +0,0 @@
1
- /**
2
- * Tests for applyGlossaryTriggers using a minimal DOM mock.
3
- * We set up a lightweight global DOM before each test so the module
4
- * can call document.createElement, querySelectorAll, etc.
5
- */
6
- import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
7
- import { applyGlossaryTriggers } from '../catalog/applyGlossaryTriggers.js';
8
-
9
- // ---------------------------------------------------------------------------
10
- // Minimal DOM bootstrap (no external deps)
11
- // ---------------------------------------------------------------------------
12
-
13
- type Attrs = Record<string, string>;
14
- type EventMap = Record<string, ((...args: any[]) => void)[]>;
15
-
16
- class FakeElement {
17
- tagName: string;
18
- className = '';
19
- textContent = '';
20
- innerHTML = '';
21
- style: Record<string, string> = {};
22
- children: FakeElement[] = [];
23
- parent: FakeElement | null = null;
24
- private attrs: Attrs = {};
25
- private events: EventMap = {};
26
-
27
- constructor(tag: string) {
28
- this.tagName = tag.toUpperCase();
29
- }
30
-
31
- setAttribute(name: string, value: string) { this.attrs[name] = value; }
32
- getAttribute(name: string) { return this.attrs[name] ?? null; }
33
- removeAttribute(name: string) { delete this.attrs[name]; }
34
- hasAttribute(name: string) { return name in this.attrs; }
35
-
36
- appendChild<T extends FakeElement>(child: T): T {
37
- // Detach from previous parent (matches real DOM behavior)
38
- if (child.parent && child.parent !== this) {
39
- child.parent.children = child.parent.children.filter((c) => c !== child);
40
- }
41
- child.parent = this;
42
- if (!this.children.includes(child)) {
43
- this.children.push(child);
44
- }
45
- return child;
46
- }
47
-
48
- insertBefore<T extends FakeElement>(newChild: T, ref: FakeElement | null): T {
49
- if (ref === null || !this.children.includes(ref)) {
50
- return this.appendChild(newChild);
51
- }
52
- const idx = this.children.indexOf(ref);
53
- newChild.parent = this;
54
- this.children.splice(idx, 0, newChild);
55
- return newChild;
56
- }
57
-
58
- remove() {
59
- if (this.parent) {
60
- this.parent.children = this.parent.children.filter((c) => c !== this);
61
- this.parent = null;
62
- }
63
- }
64
-
65
- addEventListener(type: string, handler: (...args: any[]) => void) {
66
- (this.events[type] ??= []).push(handler);
67
- }
68
-
69
- removeEventListener(type: string, handler: (...args: any[]) => void) {
70
- this.events[type] = (this.events[type] ?? []).filter((h) => h !== handler);
71
- }
72
-
73
- dispatchEvent(event: any): boolean {
74
- for (const h of this.events[event.type] ?? []) h(event);
75
- if (event.bubbles && this.parent) this.parent.dispatchEvent(event);
76
- return true;
77
- }
78
-
79
- focus() {}
80
-
81
- // querySelectorAll for [data-catalog-idref] and focusable selectors
82
- querySelectorAll(selector: string): FakeElement[] {
83
- const results: FakeElement[] = [];
84
- const visit = (el: FakeElement) => {
85
- if (matchesSelector(el, selector)) results.push(el);
86
- for (const c of el.children) visit(c);
87
- };
88
- for (const c of this.children) visit(c);
89
- return results;
90
- }
91
-
92
- // offsetParent: fake non-null so focusable elements are considered visible
93
- get offsetParent(): FakeElement | null { return this.parent ?? new FakeElement('body'); }
94
-
95
- get parentNode() { return this.parent; }
96
- }
97
-
98
- class FakeEvent {
99
- type: string;
100
- bubbles: boolean;
101
- composed: boolean;
102
- detail: any;
103
- defaultPrevented = false;
104
- key = '';
105
- shiftKey = false;
106
-
107
- constructor(type: string, opts: any = {}) {
108
- this.type = type;
109
- this.bubbles = opts.bubbles ?? false;
110
- this.composed = opts.composed ?? false;
111
- this.detail = opts.detail ?? {};
112
- }
113
-
114
- preventDefault() { this.defaultPrevented = true; }
115
- }
116
-
117
- class FakeDocument {
118
- createElement(tag: string): FakeElement {
119
- return new FakeElement(tag);
120
- }
121
- }
122
-
123
- // Simple CSS selector matching for our tests
124
- function matchesSelector(el: FakeElement, selector: string): boolean {
125
- // [data-catalog-idref]
126
- if (selector === '[data-catalog-idref]') {
127
- return el.getAttribute('data-catalog-idref') !== null;
128
- }
129
- // focusable selector used by the focus trap
130
- if (selector.includes('button:not([disabled])')) {
131
- return el.tagName === 'BUTTON' && el.getAttribute('disabled') === null;
132
- }
133
- return false;
134
- }
135
-
136
- let savedDocument: any;
137
- let savedCustomEvent: any;
138
- let savedEvent: any;
139
-
140
- function makeEnv() {
141
- savedDocument = (globalThis as any).document;
142
- savedCustomEvent = (globalThis as any).CustomEvent;
143
- savedEvent = (globalThis as any).Event;
144
- const doc = new FakeDocument();
145
- (globalThis as any).document = doc;
146
- (globalThis as any).CustomEvent = FakeEvent;
147
- (globalThis as any).Event = FakeEvent;
148
- }
149
-
150
- function clearEnv() {
151
- if (savedDocument !== undefined) (globalThis as any).document = savedDocument;
152
- else delete (globalThis as any).document;
153
- if (savedCustomEvent !== undefined) (globalThis as any).CustomEvent = savedCustomEvent;
154
- else delete (globalThis as any).CustomEvent;
155
- if (savedEvent !== undefined) (globalThis as any).Event = savedEvent;
156
- else delete (globalThis as any).Event;
157
- }
158
-
159
- // ---------------------------------------------------------------------------
160
- // Test helpers
161
- // ---------------------------------------------------------------------------
162
-
163
- const CATALOG_XML = `
164
- <qti-catalog-info>
165
- <qti-card identifier="word-osmosis">
166
- <qti-card-entry usage="glossary-on-screen" xml:lang="en">
167
- <qti-html-content>Movement of water through a membrane.</qti-html-content>
168
- </qti-card-entry>
169
- <qti-card-entry usage="keyword-translation" xml:lang="es">
170
- <qti-html-content>ósmosis</qti-html-content>
171
- </qti-card-entry>
172
- <qti-card-entry usage="tts-pronunciation">
173
- <qti-html-content>oz-MOH-sis</qti-html-content>
174
- </qti-card-entry>
175
- </qti-card>
176
- </qti-catalog-info>
177
- `;
178
-
179
- const ITEM_XML = `<?xml version="1.0" encoding="UTF-8"?>
180
- <qti-assessment-item
181
- xmlns="http://www.imsglobal.org/xsd/imsqtiasi_v3p0"
182
- identifier="glossary-test" title="Glossary Test" adaptive="false" time-dependent="false">
183
- <qti-response-declaration identifier="RESPONSE" cardinality="single" base-type="identifier"/>
184
- <qti-outcome-declaration identifier="SCORE" cardinality="single" base-type="float"/>
185
- ${CATALOG_XML}
186
- <qti-item-body>
187
- <p>The process of <span data-catalog-idref="word-osmosis">osmosis</span> is important.</p>
188
- <qti-choice-interaction response-identifier="RESPONSE" max-choices="1">
189
- <qti-simple-choice identifier="A">True</qti-simple-choice>
190
- </qti-choice-interaction>
191
- </qti-item-body>
192
- </qti-assessment-item>`;
193
-
194
- function makeMockPlayer(pnp: any, catalog: Record<string, Record<string, string | null>> = {}) {
195
- return {
196
- getPnp: () => pnp,
197
- getCatalogEntry: (idref: string, usage: string, _lang?: string) => {
198
- return catalog[idref]?.[usage] ?? null;
199
- },
200
- getComponentRegistry: () => ({
201
- getTagNameForType: (_type: string) => null,
202
- }),
203
- } as any;
204
- }
205
-
206
- // ---------------------------------------------------------------------------
207
- // Tests
208
- // ---------------------------------------------------------------------------
209
-
210
- describe('applyGlossaryTriggers', () => {
211
- beforeEach(() => makeEnv());
212
- afterEach(() => clearEnv());
213
-
214
- it('does nothing when pnp is undefined', () => {
215
- const container = new FakeElement('div') as any;
216
- const term = new FakeElement('span') as any;
217
- term.setAttribute('data-catalog-idref', 'word-osmosis');
218
- term.textContent = 'osmosis';
219
- container.appendChild(term);
220
-
221
- applyGlossaryTriggers(container, makeMockPlayer(undefined));
222
- // No wrapper or button children should have been added
223
- expect(container.children.length).toBe(1);
224
- expect(container.children[0]).toBe(term);
225
- });
226
-
227
- it('does nothing when neither glossaryOnScreen nor keywordTranslation is active', () => {
228
- const container = new FakeElement('div') as any;
229
- const term = new FakeElement('span') as any;
230
- term.setAttribute('data-catalog-idref', 'word-osmosis');
231
- container.appendChild(term);
232
-
233
- applyGlossaryTriggers(container, makeMockPlayer({ content: { glossaryOnScreen: false } }));
234
- expect(container.children.length).toBe(1);
235
- });
236
-
237
- it('wraps term in a .qti-catalog-term span and adds a trigger button when glossaryOnScreen', () => {
238
- const container = new FakeElement('div') as any;
239
- const term = new FakeElement('span') as any;
240
- term.setAttribute('data-catalog-idref', 'word-osmosis');
241
- term.textContent = 'osmosis';
242
- container.appendChild(term);
243
-
244
- const player = makeMockPlayer(
245
- { content: { glossaryOnScreen: true } },
246
- { 'word-osmosis': { 'glossary-on-screen': 'Movement of water.' } }
247
- );
248
-
249
- applyGlossaryTriggers(container, player);
250
-
251
- // The container's first child should now be the wrapper
252
- const wrapper = container.children[0];
253
- expect(wrapper.className).toBe('qti-catalog-term');
254
- // Wrapper should contain the original term + 1 trigger button
255
- expect(wrapper.children.length).toBe(2);
256
- const btn = wrapper.children[1];
257
- expect(btn.tagName).toBe('BUTTON');
258
- expect(btn.getAttribute('aria-label')).toBe('Show definition: osmosis');
259
- expect(btn.getAttribute('data-catalog-usage')).toBe('glossary-on-screen');
260
- });
261
-
262
- it('adds a keyword-translation trigger when keywordTranslation is active', () => {
263
- const container = new FakeElement('div') as any;
264
- const term = new FakeElement('span') as any;
265
- term.setAttribute('data-catalog-idref', 'word-osmosis');
266
- term.textContent = 'osmosis';
267
- container.appendChild(term);
268
-
269
- const player = makeMockPlayer(
270
- { content: { keywordTranslation: { active: true, languageCode: 'es' } } },
271
- { 'word-osmosis': { 'keyword-translation': 'ósmosis' } }
272
- );
273
-
274
- applyGlossaryTriggers(container, player);
275
-
276
- const wrapper = container.children[0];
277
- // Should have term + 1 kw-translation button
278
- const btn = wrapper.children.find((c: FakeElement) => c.getAttribute('data-catalog-usage') === 'keyword-translation');
279
- expect(btn).toBeDefined();
280
- expect((btn as FakeElement).getAttribute('aria-label')).toBe('Show definition: osmosis');
281
- });
282
-
283
- it('clicking a glossary trigger creates a popup with the entry HTML', () => {
284
- const container = new FakeElement('div') as any;
285
- const term = new FakeElement('span') as any;
286
- term.setAttribute('data-catalog-idref', 'word-osmosis');
287
- term.textContent = 'osmosis';
288
- container.appendChild(term);
289
-
290
- const player = makeMockPlayer(
291
- { content: { glossaryOnScreen: true } },
292
- { 'word-osmosis': { 'glossary-on-screen': 'Movement of water.' } }
293
- );
294
-
295
- applyGlossaryTriggers(container, player);
296
-
297
- const wrapper = container.children[0];
298
- const btn = wrapper.children[1];
299
-
300
- // Click opens popup
301
- btn.dispatchEvent(new FakeEvent('click', {}));
302
-
303
- // Wrapper should now have: term + triggerBtn + popup
304
- const popup = wrapper.children.find((c: FakeElement) => c.getAttribute('role') === 'dialog');
305
- expect(popup).toBeDefined();
306
- expect(popup!.getAttribute('aria-label')).toBe('osmosis');
307
- expect(popup!.getAttribute('aria-modal')).toBe('true');
308
- });
309
-
310
- it('clicking trigger again closes the open popup', () => {
311
- const container = new FakeElement('div') as any;
312
- const term = new FakeElement('span') as any;
313
- term.setAttribute('data-catalog-idref', 'word-osmosis');
314
- term.textContent = 'osmosis';
315
- container.appendChild(term);
316
-
317
- const player = makeMockPlayer(
318
- { content: { glossaryOnScreen: true } },
319
- { 'word-osmosis': { 'glossary-on-screen': 'Movement of water.' } }
320
- );
321
-
322
- applyGlossaryTriggers(container, player);
323
- const wrapper = container.children[0];
324
- const btn = wrapper.children[1];
325
-
326
- btn.dispatchEvent(new FakeEvent('click', {}));
327
- expect(wrapper.children.some((c: FakeElement) => c.getAttribute('role') === 'dialog')).toBe(true);
328
-
329
- btn.dispatchEvent(new FakeEvent('click', {}));
330
- expect(wrapper.children.some((c: FakeElement) => c.getAttribute('role') === 'dialog')).toBe(false);
331
- });
332
-
333
- it('does not open popup when catalog entry is null', () => {
334
- const container = new FakeElement('div') as any;
335
- const term = new FakeElement('span') as any;
336
- term.setAttribute('data-catalog-idref', 'unknown-term');
337
- term.textContent = 'unknown';
338
- container.appendChild(term);
339
-
340
- const player = makeMockPlayer({ content: { glossaryOnScreen: true } }, {});
341
-
342
- applyGlossaryTriggers(container, player);
343
- const wrapper = container.children[0];
344
- const btn = wrapper.children[1];
345
- btn.dispatchEvent(new FakeEvent('click', {}));
346
-
347
- expect(wrapper.children.some((c: FakeElement) => c.getAttribute('role') === 'dialog')).toBe(false);
348
- });
349
-
350
- it('fires qti-catalog-lookup CustomEvent for platform usages (tts-pronunciation)', () => {
351
- const container = new FakeElement('div') as any;
352
- const term = new FakeElement('span') as any;
353
- term.setAttribute('data-catalog-idref', 'word-osmosis');
354
- term.textContent = 'osmosis';
355
- container.appendChild(term);
356
-
357
- const firedEvents: any[] = [];
358
- container.addEventListener('qti-catalog-lookup', (e: any) => firedEvents.push(e));
359
- // Override addEventListener to track bubbled events from term
360
- const origDispatch = term.dispatchEvent.bind(term);
361
- term.dispatchEvent = (e: any) => {
362
- if (e.type === 'qti-catalog-lookup') firedEvents.push(e);
363
- return origDispatch(e);
364
- };
365
-
366
- const player = makeMockPlayer(
367
- { content: { glossaryOnScreen: true } },
368
- { 'word-osmosis': { 'glossary-on-screen': 'Movement of water.', 'tts-pronunciation': 'oz-MOH-sis' } }
369
- );
370
-
371
- applyGlossaryTriggers(container, player);
372
-
373
- const ttsFired = firedEvents.find((e) => e.detail?.usage === 'tts-pronunciation');
374
- expect(ttsFired).toBeDefined();
375
- expect(ttsFired.detail.idref).toBe('word-osmosis');
376
- expect(ttsFired.detail.html).toBe('oz-MOH-sis');
377
- // No popup was created for tts-pronunciation
378
- const wrapper = container.children[0];
379
- expect(wrapper.children.some((c: FakeElement) => c.getAttribute('role') === 'dialog')).toBe(false);
380
- });
381
-
382
- it('handles multiple catalog terms independently', () => {
383
- const container = new FakeElement('div') as any;
384
-
385
- const term1 = new FakeElement('span') as any;
386
- term1.setAttribute('data-catalog-idref', 'word-osmosis');
387
- term1.textContent = 'osmosis';
388
-
389
- const term2 = new FakeElement('span') as any;
390
- term2.setAttribute('data-catalog-idref', 'word-mitosis');
391
- term2.textContent = 'mitosis';
392
-
393
- container.appendChild(term1);
394
- container.appendChild(term2);
395
-
396
- const player = makeMockPlayer(
397
- { content: { glossaryOnScreen: true } },
398
- {
399
- 'word-osmosis': { 'glossary-on-screen': 'Water movement.' },
400
- 'word-mitosis': { 'glossary-on-screen': 'Cell division.' },
401
- }
402
- );
403
-
404
- applyGlossaryTriggers(container, player);
405
-
406
- // Two wrappers should exist
407
- expect(container.children.length).toBe(2);
408
- expect(container.children[0].className).toBe('qti-catalog-term');
409
- expect(container.children[1].className).toBe('qti-catalog-term');
410
- });
411
- });