@pie-qti/item-player 1.0.0-beta.1 → 1.0.0-beta.3

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.
@@ -5,23 +5,13 @@ interface CatalogComponentRegistry {
5
5
  }
6
6
  export interface GlossaryPlayer {
7
7
  getPnp(): PnpProfile | undefined;
8
+ /** Typed `unknown` to match `ItemSessionBinding`; read through `playerI18n`. */
9
+ getI18nProvider?(): unknown;
8
10
  getCatalogEntry(idref: string, usage: string, lang?: string, options?: {
9
11
  stimulusIdentifier?: string;
10
12
  }): HtmlContent | null;
11
13
  getComponentRegistry(): CatalogComponentRegistry;
12
14
  }
13
- /**
14
- * Inject glossary/keyword-translation trigger buttons into a rendered item container.
15
- *
16
- * When pnp.content.glossaryOnScreen is true, each [data-catalog-idref] element gets a
17
- * trigger button. Clicking the button looks up the catalog entry and shows a floating
18
- * popup rendered by the 'catalogPopup' component from the registry (defaults to
19
- * pie-qti-catalog-popup). Clicking again or pressing Escape closes it.
20
- *
21
- * For platform-level usages (tts-pronunciation, signing-definition, braille-text,
22
- * audio-description) the player fires a `qti-catalog-lookup` CustomEvent instead of
23
- * mounting a popup — the host application handles those usages.
24
- */
25
15
  export declare function applyGlossaryTriggers(container: HTMLElement, player: GlossaryPlayer): () => void;
26
16
  export declare function cleanupGlossaryTriggers(container: HTMLElement): void;
27
17
  export {};
@@ -1,10 +1,11 @@
1
+ import { isImeComposing, translate } from '@pie-qti/i18n';
1
2
  import { htmlToString } from '../core/trustedTypes.js';
2
3
  const PLATFORM_USAGES = [
3
- { usage: 'tts-pronunciation', flag: 'ttsPronunciation', label: 'Request pronunciation', text: 'P' },
4
- { usage: 'signing-definition', flag: 'signingDefinition', label: 'Request signing definition', text: 'S' },
5
- { usage: 'braille-text', flag: 'brailleText', label: 'Request braille text', text: 'B' },
6
- { usage: 'audio-description', flag: 'audioDescription', label: 'Request audio description', text: 'A' },
7
- { usage: 'extended-description', flag: 'extendedDescription', label: 'Request extended description', text: 'D' },
4
+ { usage: 'tts-pronunciation', flag: 'ttsPronunciation', labelKey: 'accessibility.catalogRequestPronunciation', label: 'Request pronunciation: {term}', text: 'P' },
5
+ { usage: 'signing-definition', flag: 'signingDefinition', labelKey: 'accessibility.catalogRequestSigningDefinition', label: 'Request signing definition: {term}', text: 'S' },
6
+ { usage: 'braille-text', flag: 'brailleText', labelKey: 'accessibility.catalogRequestBrailleText', label: 'Request braille text: {term}', text: 'B' },
7
+ { usage: 'audio-description', flag: 'audioDescription', labelKey: 'accessibility.catalogRequestAudioDescription', label: 'Request audio description: {term}', text: 'A' },
8
+ { usage: 'extended-description', flag: 'extendedDescription', labelKey: 'accessibility.catalogRequestExtendedDescription', label: 'Request extended description: {term}', text: 'D' },
8
9
  ];
9
10
  const ILLUSTRATED_GLOSSARY_USAGE = 'illustrated-glossary';
10
11
  const BUILT_IN_POPUP_USAGES = new Set([
@@ -27,11 +28,15 @@ const SAFE_CATALOG_USAGE = /^[a-z][a-z0-9._-]*$/;
27
28
  * audio-description) the player fires a `qti-catalog-lookup` CustomEvent instead of
28
29
  * mounting a popup — the host application handles those usages.
29
30
  */
31
+ function playerI18n(player) {
32
+ return player.getI18nProvider?.();
33
+ }
30
34
  export function applyGlossaryTriggers(container, player) {
31
35
  cleanupGlossaryTriggers(container);
32
36
  const pnp = player.getPnp();
33
37
  if (!pnp)
34
38
  return () => cleanupGlossaryTriggers(container);
39
+ const i18n = playerI18n(player);
35
40
  const glossaryOn = pnp.content?.glossaryOnScreen === true;
36
41
  const kwTranslation = pnp.content?.keywordTranslation;
37
42
  const kwOn = kwTranslation?.active === true && !!kwTranslation.languageCode;
@@ -59,7 +64,7 @@ export function applyGlossaryTriggers(container, player) {
59
64
  termEl.parentNode?.insertBefore(wrapper, termEl);
60
65
  wrapper.appendChild(termEl);
61
66
  if (glossaryOn) {
62
- const btn = createTriggerButton(termEl.textContent ?? idref, 'glossary-on-screen', 'Show definition');
67
+ const btn = createTriggerButton(translate(i18n, 'accessibility.catalogShowDefinition', 'Show definition: {term}', { term: termEl.textContent ?? idref }), 'glossary-on-screen');
63
68
  wrapper.appendChild(btn);
64
69
  btn.addEventListener('click', () => {
65
70
  if (currentCleanup) {
@@ -77,7 +82,7 @@ export function applyGlossaryTriggers(container, player) {
77
82
  }
78
83
  if (kwOn) {
79
84
  const lang = kwTranslation.languageCode;
80
- const btn = createTriggerButton(termEl.textContent ?? idref, 'keyword-translation', 'Show translation');
85
+ const btn = createTriggerButton(translate(i18n, 'accessibility.catalogShowTranslation', 'Show translation: {term}', { term: termEl.textContent ?? idref }), 'keyword-translation');
81
86
  wrapper.appendChild(btn);
82
87
  btn.addEventListener('click', () => {
83
88
  if (currentCleanup) {
@@ -94,7 +99,9 @@ export function applyGlossaryTriggers(container, player) {
94
99
  });
95
100
  }
96
101
  if (illustratedOn) {
97
- const btn = createTriggerButton(termEl.textContent ?? idref, ILLUSTRATED_GLOSSARY_USAGE, 'Show illustrated glossary');
102
+ const btn = createTriggerButton(translate(i18n, 'accessibility.catalogShowIllustratedGlossary', 'Show illustrated glossary: {term}', {
103
+ term: termEl.textContent ?? idref,
104
+ }), ILLUSTRATED_GLOSSARY_USAGE);
98
105
  wrapper.appendChild(btn);
99
106
  btn.addEventListener('click', () => {
100
107
  if (currentCleanup) {
@@ -137,13 +144,13 @@ export function cleanupGlossaryTriggers(container) {
137
144
  wrapper.remove();
138
145
  }
139
146
  }
140
- function createTriggerButton(termText, usage, labelPrefix, text) {
147
+ function createTriggerButton(label, usage, text) {
141
148
  const btn = document.createElement('button');
142
149
  btn.type = 'button';
143
150
  btn.className = 'qti-catalog-trigger';
144
151
  btn.style.cssText =
145
152
  'display:inline-flex;align-items:center;justify-content:center;min-width:1.75rem;min-height:1.75rem;margin-inline:0.25rem;line-height:1;';
146
- btn.setAttribute('aria-label', `${labelPrefix}: ${termText}`);
153
+ btn.setAttribute('aria-label', label);
147
154
  btn.setAttribute('data-catalog-usage', usage);
148
155
  btn.textContent = text ?? (usage === 'keyword-translation' ? 'T' : usage === ILLUSTRATED_GLOSSARY_USAGE ? 'I' : '?');
149
156
  return btn;
@@ -152,7 +159,12 @@ function addHostCatalogSupportButton(wrapper, termEl, idref, support, player, st
152
159
  const html = player.getCatalogEntry(idref, support.usage, support.languageCode, { stimulusIdentifier });
153
160
  if (html === null)
154
161
  return;
155
- const btn = createTriggerButton(termEl.textContent ?? idref, support.usage, support.label, support.text);
162
+ const i18n = playerI18n(player);
163
+ const label = translate(i18n, support.labelKey, support.label, {
164
+ term: termEl.textContent ?? idref,
165
+ usage: support.usage.replace(/[-_]+/g, ' '),
166
+ });
167
+ const btn = createTriggerButton(label, support.usage, support.text);
156
168
  wrapper.appendChild(btn);
157
169
  btn.addEventListener('click', () => {
158
170
  btn.dispatchEvent(new CustomEvent('qti-catalog-lookup', {
@@ -178,7 +190,8 @@ function getHostCatalogSupports(platformSupports) {
178
190
  .filter(({ usage, preference }) => usage !== null && isSupportActive(preference) && !isReservedCatalogUsage(usage))
179
191
  .map(({ usage, preference }) => ({
180
192
  usage: usage,
181
- label: `Request ${usage.replace(/[-_]+/g, ' ')}`,
193
+ labelKey: 'accessibility.catalogRequestUsage',
194
+ label: 'Request {usage}: {term}',
182
195
  text: usage.slice(0, 1).toUpperCase(),
183
196
  languageCode: getSupportLanguageCode(preference),
184
197
  }));
@@ -232,13 +245,14 @@ function mountPopup(anchor, label, html, triggerBtn, player, onClose) {
232
245
  const el = document.createElement(catalogPopupTag);
233
246
  el.content = html;
234
247
  el.label = label;
248
+ el.i18n = playerI18n(player);
235
249
  el.onClose = cleanup;
236
250
  anchor.appendChild(el);
237
251
  popupEl = el;
238
252
  }
239
253
  else {
240
254
  // Minimal fallback for environments without default-components
241
- popupEl = buildFallbackPopup(label, html, cleanup);
255
+ popupEl = buildFallbackPopup(label, html, cleanup, playerI18n(player));
242
256
  anchor.appendChild(popupEl);
243
257
  }
244
258
  return cleanup;
@@ -247,7 +261,7 @@ function mountPopup(anchor, label, html, triggerBtn, player, onClose) {
247
261
  * Minimal accessible fallback popup used when no catalogPopup component is registered.
248
262
  * Uses DaisyUI card classes where available; degrades gracefully without them.
249
263
  */
250
- function buildFallbackPopup(label, html, close) {
264
+ function buildFallbackPopup(label, html, close, i18n) {
251
265
  const popup = document.createElement('div');
252
266
  popup.className = 'card card-bordered bg-base-100 shadow-lg qti-catalog-popup';
253
267
  popup.setAttribute('role', 'dialog');
@@ -262,7 +276,7 @@ function buildFallbackPopup(label, html, close) {
262
276
  const closeBtn = document.createElement('button');
263
277
  closeBtn.type = 'button';
264
278
  closeBtn.className = 'btn btn-ghost btn-xs';
265
- closeBtn.setAttribute('aria-label', 'Close');
279
+ closeBtn.setAttribute('aria-label', translate(i18n, 'common.close', 'Close'));
266
280
  closeBtn.textContent = '✕';
267
281
  header.appendChild(title);
268
282
  header.appendChild(closeBtn);
@@ -285,7 +299,7 @@ function buildFallbackPopup(label, html, close) {
285
299
  // Focus trap + Escape
286
300
  const focusableSelector = 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])';
287
301
  function handleKeyDown(e) {
288
- if (e.key === 'Escape') {
302
+ if (e.key === 'Escape' && !isImeComposing(e)) {
289
303
  e.preventDefault();
290
304
  closeBtn.click();
291
305
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"applyGlossaryTriggers.js","sourceRoot":"","sources":["../../src/catalog/applyGlossaryTriggers.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAGvD,MAAM,eAAe,GAAG;IACvB,EAAE,KAAK,EAAE,mBAAmB,EAAE,IAAI,EAAE,kBAAkB,EAAE,KAAK,EAAE,uBAAuB,EAAE,IAAI,EAAE,GAAG,EAAE;IACnG,EAAE,KAAK,EAAE,oBAAoB,EAAE,IAAI,EAAE,mBAAmB,EAAE,KAAK,EAAE,4BAA4B,EAAE,IAAI,EAAE,GAAG,EAAE;IAC1G,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,E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AAK,EAAE,CAAC;gBACpD,CAAC,CAAC,cAAc,EAAE,CAAC;gBACnB,IAAI,CAAC,KAAK,EAAE,CAAC;YACd,CAAC;iBAAM,IAAI,CAAC,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,aAAa,KAAK,IAAI,EAAE,CAAC;gBAC3D,CAAC,CAAC,cAAc,EAAE,CAAC;gBACnB,KAAK,CAAC,KAAK,EAAE,CAAC;YACf,CAAC;QACF,CAAC;IACF,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IACjD,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC;IAElD,6BAA6B;IAC7B,UAAU,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC;IAEtC,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import type { CatalogSupportPreference } from '../pnp/types.js';\nimport type { PnpProfile } from '../pnp/types.js';\nimport { htmlToString } from '../core/trustedTypes.js';\nimport type { HtmlContent } from '../types/index.js';\n\nconst PLATFORM_USAGES = [\n\t{ usage: 'tts-pronunciation', flag: 'ttsPronunciation', label: 'Request pronunciation', text: 'P' },\n\t{ usage: 'signing-definition', flag: 'signingDefinition', label: 'Request signing definition', text: 'S' },\n\t{ usage: 'braille-text', flag: 'brailleText', label: 'Request braille text', text: 'B' },\n\t{ usage: 'audio-description', flag: 'audioDescription', label: 'Request audio description', text: 'A' },\n\t{ usage: 'extended-description', flag: 'extendedDescription', label: 'Request extended description', text: 'D' },\n] as const;\nconst ILLUSTRATED_GLOSSARY_USAGE = 'illustrated-glossary';\nconst BUILT_IN_POPUP_USAGES = new Set<string>([\n\t'glossary-on-screen',\n\t'keyword-translation',\n\tILLUSTRATED_GLOSSARY_USAGE,\n]);\nconst RESERVED_PLATFORM_FLAGS = new Set<string>(PLATFORM_USAGES.map((support) => support.flag));\nconst RESERVED_PLATFORM_USAGES = new Set<string>(PLATFORM_USAGES.map((support) => support.usage));\nconst SAFE_CATALOG_USAGE = /^[a-z][a-z0-9._-]*$/;\n\ninterface HostCatalogSupport {\n\tusage: string;\n\tlabel: string;\n\ttext: string;\n\tlanguageCode?: string;\n}\n\ninterface CatalogComponentRegistry {\n\tgetTagNameForType(type: string): string | null;\n}\n\nexport interface GlossaryPlayer {\n\tgetPnp(): PnpProfile | undefined;\n\tgetCatalogEntry(\n\t\tidref: string,\n\t\tusage: string,\n\t\tlang?: string,\n\t\toptions?: { stimulusIdentifier?: string }\n\t): HtmlContent | null;\n\tgetComponentRegistry(): CatalogComponentRegistry;\n}\n\n/**\n * Inject glossary/keyword-translation trigger buttons into a rendered item container.\n *\n * When pnp.content.glossaryOnScreen is true, each [data-catalog-idref] element gets a\n * trigger button. Clicking the button looks up the catalog entry and shows a floating\n * popup rendered by the 'catalogPopup' component from the registry (defaults to\n * pie-qti-catalog-popup). Clicking again or pressing Escape closes it.\n *\n * For platform-level usages (tts-pronunciation, signing-definition, braille-text,\n * audio-description) the player fires a `qti-catalog-lookup` CustomEvent instead of\n * mounting a popup — the host application handles those usages.\n */\nexport function applyGlossaryTriggers(container: HTMLElement, player: GlossaryPlayer): () => void {\n\tcleanupGlossaryTriggers(container);\n\tconst pnp = player.getPnp();\n\tif (!pnp) return () => cleanupGlossaryTriggers(container);\n\n\tconst glossaryOn = pnp.content?.glossaryOnScreen === true;\n\tconst kwTranslation = pnp.content?.keywordTranslation;\n\tconst kwOn = kwTranslation?.active === true && !!kwTranslation.languageCode;\n\tconst illustratedOn = pnp.content?.illustratedGlossary === true;\n\tconst platformSupports = pnp.content?.catalogSupports ?? {};\n\tconst hostSupports = getHostCatalogSupports(platformSupports);\n\n\tconst anyPlatformOn = PLATFORM_USAGES.some((support) => isSupportActive(getPlatformSupportPreference(platformSupports, support)));\n\tif (!glossaryOn && !kwOn && !illustratedOn && !anyPlatformOn && hostSupports.length === 0) return () => cleanupGlossaryTriggers(container);\n\n\tconst terms = container.querySelectorAll<HTMLElement>('[data-catalog-idref]');\n\tif (terms.length === 0) return () => cleanupGlossaryTriggers(container);\n\n\t// Track open popup so only one is open at a time\n\tlet currentCleanup: (() => void) | null = null;\n\n\tfor (const termEl of Array.from(terms)) {\n\t\tconst idref = termEl.getAttribute('data-catalog-idref');\n\t\tif (!idref) continue;\n\t\tconst stimulusIdentifier = getStimulusIdentifier(termEl);\n\t\tconst contentLanguage = getContentLanguage(termEl);\n\n\t\t// Wrap term in a relative-positioned span so we can position popup against it\n\t\tconst wrapper = document.createElement('span');\n\t\twrapper.className = 'qti-catalog-term';\n\t\twrapper.style.cssText = 'position:relative;display:inline';\n\n\t\ttermEl.parentNode?.insertBefore(wrapper, termEl);\n\t\twrapper.appendChild(termEl);\n\n\t\tif (glossaryOn) {\n\t\t\tconst btn = createTriggerButton(termEl.textContent ?? idref, 'glossary-on-screen', 'Show definition');\n\t\t\twrapper.appendChild(btn);\n\n\t\t\tbtn.addEventListener('click', () => {\n\t\t\t\tif (currentCleanup) {\n\t\t\t\t\tcurrentCleanup();\n\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst html = player.getCatalogEntry(idref, 'glossary-on-screen', contentLanguage, { stimulusIdentifier });\n\t\t\t\tif (html !== null) {\n\t\t\t\t\tcurrentCleanup = mountPopup(wrapper, termEl.textContent ?? idref, html, btn, player, () => {\n\t\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (kwOn) {\n\t\t\tconst lang = kwTranslation!.languageCode;\n\t\t\tconst btn = createTriggerButton(termEl.textContent ?? idref, 'keyword-translation', 'Show translation');\n\t\t\twrapper.appendChild(btn);\n\n\t\t\tbtn.addEventListener('click', () => {\n\t\t\t\tif (currentCleanup) {\n\t\t\t\t\tcurrentCleanup();\n\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst html = player.getCatalogEntry(idref, 'keyword-translation', lang, { stimulusIdentifier });\n\t\t\t\tif (html !== null) {\n\t\t\t\t\tcurrentCleanup = mountPopup(wrapper, termEl.textContent ?? idref, html, btn, player, () => {\n\t\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (illustratedOn) {\n\t\t\tconst btn = createTriggerButton(termEl.textContent ?? idref, ILLUSTRATED_GLOSSARY_USAGE, 'Show illustrated glossary');\n\t\t\twrapper.appendChild(btn);\n\n\t\t\tbtn.addEventListener('click', () => {\n\t\t\t\tif (currentCleanup) {\n\t\t\t\t\tcurrentCleanup();\n\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst html = player.getCatalogEntry(idref, ILLUSTRATED_GLOSSARY_USAGE, contentLanguage, { stimulusIdentifier });\n\t\t\t\tif (html !== null) {\n\t\t\t\t\tcurrentCleanup = mountPopup(wrapper, termEl.textContent ?? idref, html, btn, player, () => {\n\t\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tfor (const support of PLATFORM_USAGES) {\n\t\t\tconst preference = getPlatformSupportPreference(platformSupports, support);\n\t\t\tif (!isSupportActive(preference)) continue;\n\t\t\taddHostCatalogSupportButton(wrapper, termEl, idref, {\n\t\t\t\t...support,\n\t\t\t\tlanguageCode: getSupportLanguageCode(preference),\n\t\t\t}, player, stimulusIdentifier);\n\t\t}\n\n\t\tfor (const support of hostSupports) {\n\t\t\taddHostCatalogSupportButton(wrapper, termEl, idref, support, player, stimulusIdentifier);\n\t\t}\n\t}\n\n\treturn () => {\n\t\tcurrentCleanup?.();\n\t\tcleanupGlossaryTriggers(container);\n\t};\n}\n\nexport function cleanupGlossaryTriggers(container: HTMLElement): void {\n\tfor (const wrapper of Array.from(container.querySelectorAll<HTMLElement>('.qti-catalog-term'))) {\n\t\tconst term = Array.from(wrapper.children).find((child) =>\n\t\t\t(child as HTMLElement).getAttribute?.('data-catalog-idref') !== null\n\t\t) as HTMLElement | undefined;\n\t\tif (term && wrapper.parentNode) {\n\t\t\twrapper.parentNode.insertBefore(term, wrapper);\n\t\t}\n\t\twrapper.remove();\n\t}\n}\n\nfunction createTriggerButton(termText: string, usage: string, labelPrefix: string, text?: string): HTMLButtonElement {\n\tconst btn = document.createElement('button');\n\tbtn.type = 'button';\n\tbtn.className = 'qti-catalog-trigger';\n\tbtn.style.cssText =\n\t\t'display:inline-flex;align-items:center;justify-content:center;min-width:1.75rem;min-height:1.75rem;margin-inline:0.25rem;line-height:1;';\n\tbtn.setAttribute('aria-label', `${labelPrefix}: ${termText}`);\n\tbtn.setAttribute('data-catalog-usage', usage);\n\tbtn.textContent = text ?? (usage === 'keyword-translation' ? 'T' : usage === ILLUSTRATED_GLOSSARY_USAGE ? 'I' : '?');\n\treturn btn;\n}\n\nfunction addHostCatalogSupportButton(\n\twrapper: HTMLElement,\n\ttermEl: HTMLElement,\n\tidref: string,\n\tsupport: HostCatalogSupport,\n\tplayer: GlossaryPlayer,\n\tstimulusIdentifier?: string\n): void {\n\tconst html = player.getCatalogEntry(idref, support.usage, support.languageCode, { stimulusIdentifier });\n\tif (html === null) return;\n\tconst btn = createTriggerButton(termEl.textContent ?? idref, support.usage, support.label, support.text);\n\twrapper.appendChild(btn);\n\tbtn.addEventListener('click', () => {\n\t\tbtn.dispatchEvent(\n\t\t\tnew CustomEvent('qti-catalog-lookup', {\n\t\t\t\tbubbles: true,\n\t\t\t\tcomposed: true,\n\t\t\t\tdetail: { idref, usage: support.usage, html, content: html, languageCode: support.languageCode },\n\t\t\t})\n\t\t);\n\t});\n}\n\n/** The language of the term's content: the nearest `lang`, which the item body sets from `xml:lang`. */\nfunction getContentLanguage(termEl: HTMLElement): string | undefined {\n\tconst language = termEl.closest?.('[lang]')?.getAttribute?.('lang')?.trim();\n\treturn language || undefined;\n}\n\nfunction getStimulusIdentifier(termEl: HTMLElement): string | undefined {\n\tconst scopeEl = termEl.closest?.('[data-stimulus-idref]');\n\tconst identifier = scopeEl?.getAttribute?.('data-stimulus-idref')?.trim();\n\treturn identifier || undefined;\n}\n\nfunction getHostCatalogSupports(platformSupports: Record<string, CatalogSupportPreference | undefined>): HostCatalogSupport[] {\n\treturn Object.entries(platformSupports)\n\t\t.map(([usage, preference]) => ({ usage: normalizeCatalogUsage(usage), preference }))\n\t\t.filter(({ usage, preference }) => usage !== null && isSupportActive(preference) && !isReservedCatalogUsage(usage))\n\t\t.map(({ usage, preference }) => ({\n\t\t\tusage: usage!,\n\t\t\tlabel: `Request ${usage!.replace(/[-_]+/g, ' ')}`,\n\t\t\ttext: usage!.slice(0, 1).toUpperCase(),\n\t\t\tlanguageCode: getSupportLanguageCode(preference),\n\t\t}));\n}\n\nfunction getPlatformSupportPreference(\n\tplatformSupports: Record<string, CatalogSupportPreference | undefined>,\n\tsupport: (typeof PLATFORM_USAGES)[number]\n): CatalogSupportPreference | undefined {\n\treturn platformSupports[support.flag] ?? platformSupports[support.usage];\n}\n\nfunction isSupportActive(preference: CatalogSupportPreference | undefined): boolean {\n\tif (preference === undefined) return false;\n\tif (typeof preference === 'boolean') return preference;\n\treturn preference.active !== false;\n}\n\nfunction getSupportLanguageCode(preference: CatalogSupportPreference | undefined): string | undefined {\n\tif (!preference || typeof preference === 'boolean') return undefined;\n\tconst languageCode = preference.languageCode?.trim();\n\tif (!languageCode || !/^[a-zA-Z]{2,8}(?:-[a-zA-Z0-9]{1,8})*$/.test(languageCode)) return undefined;\n\treturn languageCode;\n}\n\nfunction normalizeCatalogUsage(value: string): string | null {\n\tconst usage = value.trim().toLowerCase();\n\tif (!SAFE_CATALOG_USAGE.test(usage)) return null;\n\treturn usage;\n}\n\nfunction isReservedCatalogUsage(usage: string): boolean {\n\treturn RESERVED_PLATFORM_FLAGS.has(usage) || RESERVED_PLATFORM_USAGES.has(usage) || BUILT_IN_POPUP_USAGES.has(usage);\n}\n\n/**\n * Mount a catalog popup via the component registry. Falls back to a minimal\n * vanilla-JS popup if no 'catalogPopup' component is registered (e.g. in tests\n * that don't load default-components). Returns a cleanup function.\n */\nfunction mountPopup(\n\tanchor: HTMLElement,\n\tlabel: string,\n\thtml: HtmlContent,\n\ttriggerBtn: HTMLButtonElement,\n\tplayer: GlossaryPlayer,\n\tonClose: () => void\n): () => void {\n\tconst registry = player.getComponentRegistry();\n\n\tlet popupEl: HTMLElement;\n\tlet closed = false;\n\n\tfunction cleanup() {\n\t\tif (closed) return;\n\t\tclosed = true;\n\t\tpopupEl.remove();\n\t\ttriggerBtn.focus();\n\t\tonClose();\n\t}\n\n\tconst catalogPopupTag = registry.getTagNameForType('catalogPopup');\n\tif (catalogPopupTag !== null) {\n\t\tconst el = document.createElement(catalogPopupTag) as HTMLElement & {\n\t\t\tcontent: HtmlContent;\n\t\t\tlabel: string;\n\t\t\tonClose: () => void;\n\t\t};\n\t\tel.content = html;\n\t\tel.label = label;\n\t\tel.onClose = cleanup;\n\t\tanchor.appendChild(el);\n\t\tpopupEl = el;\n\t} else {\n\t\t// Minimal fallback for environments without default-components\n\t\tpopupEl = buildFallbackPopup(label, html, cleanup);\n\t\tanchor.appendChild(popupEl);\n\t}\n\n\treturn cleanup;\n}\n\n/**\n * Minimal accessible fallback popup used when no catalogPopup component is registered.\n * Uses DaisyUI card classes where available; degrades gracefully without them.\n */\nfunction buildFallbackPopup(label: string, html: HtmlContent, close: () => void): HTMLElement {\n\tconst popup = document.createElement('div');\n\tpopup.className = 'card card-bordered bg-base-100 shadow-lg qti-catalog-popup';\n\tpopup.setAttribute('role', 'dialog');\n\tpopup.setAttribute('aria-label', label);\n\tpopup.setAttribute('aria-modal', 'true');\n\tpopup.style.cssText = 'position:absolute;z-index:1000;min-width:16rem;max-width:24rem';\n\n\tconst header = document.createElement('div');\n\theader.className = 'card-title flex justify-between items-center px-3 py-2 border-b border-base-300 bg-base-200';\n\n\tconst title = document.createElement('span');\n\ttitle.className = 'text-sm font-semibold';\n\ttitle.textContent = label;\n\n\tconst closeBtn = document.createElement('button');\n\tcloseBtn.type = 'button';\n\tcloseBtn.className = 'btn btn-ghost btn-xs';\n\tcloseBtn.setAttribute('aria-label', 'Close');\n\tcloseBtn.textContent = '✕';\n\n\theader.appendChild(title);\n\theader.appendChild(closeBtn);\n\n\tconst body = document.createElement('div');\n\tbody.className = 'card-body p-3';\n\n\tconst htmlString = htmlToString(html);\n\tconst isUrl = /^(https?:\\/\\/|\\/)/i.test(htmlString.trim());\n\tif (isUrl) {\n\t\tconst img = document.createElement('img');\n\t\timg.src = htmlString.trim();\n\t\timg.alt = label;\n\t\timg.className = 'max-w-full h-auto block mx-auto';\n\t\tbody.appendChild(img);\n\t} else {\n\t\tbody.innerHTML = html as any;\n\t}\n\n\tpopup.appendChild(header);\n\tpopup.appendChild(body);\n\n\t// Focus trap + Escape\n\tconst focusableSelector = 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])';\n\n\tfunction handleKeyDown(e: KeyboardEvent) {\n\t\tif (e.key === 'Escape') {\n\t\t\te.preventDefault();\n\t\t\tcloseBtn.click();\n\t\t\treturn;\n\t\t}\n\t\tif (e.key === 'Tab') {\n\t\t\tconst focusable = Array.from(popup.querySelectorAll<HTMLElement>(focusableSelector)).filter(\n\t\t\t\t(el) => el.offsetParent !== null\n\t\t\t);\n\t\t\tif (focusable.length === 0) { e.preventDefault(); return; }\n\t\t\tconst first = focusable[0];\n\t\t\tconst last = focusable[focusable.length - 1];\n\t\t\tif (e.shiftKey && document.activeElement === first) {\n\t\t\t\te.preventDefault();\n\t\t\t\tlast.focus();\n\t\t\t} else if (!e.shiftKey && document.activeElement === last) {\n\t\t\t\te.preventDefault();\n\t\t\t\tfirst.focus();\n\t\t\t}\n\t\t}\n\t}\n\n\tpopup.addEventListener('keydown', handleKeyDown);\n\tcloseBtn.addEventListener('click', () => close());\n\n\t// Move focus in on next tick\n\tsetTimeout(() => closeBtn.focus(), 0);\n\n\treturn popup;\n}\n"]}
1
+ {"version":3,"file":"applyGlossaryTriggers.js","sourceRoot":"","sources":["../../src/catalog/applyGlossaryTriggers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAqB,MAAM,eAAe,CAAC;AAG7E,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAGvD,MAAM,eAAe,GAAG;IACvB,EAAE,KAAK,EAAE,mBAAmB,EAAE,IAAI,EAAE,kBAAkB,EAAE,QAAQ,EAAE,2CAA2C,EAAE,KAAK,EAAE,+BAA+B,EAAE,IAAI,EAAE,GAAG,EAAE;IAClK,EAAE,KAAK,EAAE,oBAAoB,EAAE,IAAI,EAAE,mBAAmB,EAAE,QAAQ,EAAE,+CAA+C,EAAE,KAAK,EAAE,oCAAoC,EAAE,IAAI,EAAE,GAAG,EAAE;IAC7K,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,aAAa,EAAE,QAAQ,EAAE,yCAAyC,EAAE,KAAK,EAAE,8BAA8B,EAAE,IAAI,EAAE,GAAG,EAAE;IACrJ,EAAE,KAAK,EAAE,mBAAmB,EAAE,IAAI,EAAE,kBAAkB,EAAE,QAAQ,EAAE,8CAA8C,EAAE,KAAK,EAAE,mCAAmC,EAAE,IAAI,EAAE,GAAG,EAAE;IACzK,EAAE,KAAK,EAAE,sBAAsB,EAAE,IAAI,EAAE,qBAAqB,EAAE,QAAQ,EAAE,iDAAiD,EAAE,KAAK,EAAE,sCAAsC,EAAE,IAAI,EAAE,GAAG,EAAE;CAC5K,CAAC;AACX,MAAM,0BAA0B,GAAG,sBAAsB,CAAC;AAC1D,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAS;IAC7C,oBAAoB;IACpB,qBAAqB;IACrB,0BAA0B;CAC1B,CAAC,CAAC;AACH,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAAS,eAAe,CAAC,GAAG,CAAC,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3D,MAAM,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;YAC3B,MAAM,IAAI,GAAG,SAAS,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAC7C,IAAI,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,aAAa,KAAK,KAAK,EAAE,CAAC;gBACpD,CAAC,CAAC,cAAc,EAAE,CAAC;gBACnB,IAAI,CAAC,KAAK,EAAE,CAAC;YACd,CAAC;iBAAM,IAAI,CAAC,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,aAAa,KAAK,IAAI,EAAE,CAAC;gBAC3D,CAAC,CAAC,cAAc,EAAE,CAAC;gBACnB,KAAK,CAAC,KAAK,EAAE,CAAC;YACf,CAAC;QACF,CAAC;IACF,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IACjD,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC;IAElD,6BAA6B;IAC7B,UAAU,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC;IAEtC,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import { isImeComposing, translate, type I18nProvider } from '@pie-qti/i18n';\nimport type { CatalogSupportPreference } from '../pnp/types.js';\nimport type { PnpProfile } from '../pnp/types.js';\nimport { htmlToString } from '../core/trustedTypes.js';\nimport type { HtmlContent } from '../types/index.js';\n\nconst PLATFORM_USAGES = [\n\t{ usage: 'tts-pronunciation', flag: 'ttsPronunciation', labelKey: 'accessibility.catalogRequestPronunciation', label: 'Request pronunciation: {term}', text: 'P' },\n\t{ usage: 'signing-definition', flag: 'signingDefinition', labelKey: 'accessibility.catalogRequestSigningDefinition', label: 'Request signing definition: {term}', text: 'S' },\n\t{ usage: 'braille-text', flag: 'brailleText', labelKey: 'accessibility.catalogRequestBrailleText', label: 'Request braille text: {term}', text: 'B' },\n\t{ usage: 'audio-description', flag: 'audioDescription', labelKey: 'accessibility.catalogRequestAudioDescription', label: 'Request audio description: {term}', text: 'A' },\n\t{ usage: 'extended-description', flag: 'extendedDescription', labelKey: 'accessibility.catalogRequestExtendedDescription', label: 'Request extended description: {term}', text: 'D' },\n] as const;\nconst ILLUSTRATED_GLOSSARY_USAGE = 'illustrated-glossary';\nconst BUILT_IN_POPUP_USAGES = new Set<string>([\n\t'glossary-on-screen',\n\t'keyword-translation',\n\tILLUSTRATED_GLOSSARY_USAGE,\n]);\nconst RESERVED_PLATFORM_FLAGS = new Set<string>(PLATFORM_USAGES.map((support) => support.flag));\nconst RESERVED_PLATFORM_USAGES = new Set<string>(PLATFORM_USAGES.map((support) => support.usage));\nconst SAFE_CATALOG_USAGE = /^[a-z][a-z0-9._-]*$/;\n\ninterface HostCatalogSupport {\n\tusage: string;\n\t/** Catalog key of the button's accessible name; `label` is its English fallback, with `{term}` and `{usage}` placeholders. */\n\tlabelKey: string;\n\tlabel: string;\n\ttext: string;\n\tlanguageCode?: string;\n}\n\ninterface CatalogComponentRegistry {\n\tgetTagNameForType(type: string): string | null;\n}\n\nexport interface GlossaryPlayer {\n\tgetPnp(): PnpProfile | undefined;\n\t/** Typed `unknown` to match `ItemSessionBinding`; read through `playerI18n`. */\n\tgetI18nProvider?(): unknown;\n\tgetCatalogEntry(\n\t\tidref: string,\n\t\tusage: string,\n\t\tlang?: string,\n\t\toptions?: { stimulusIdentifier?: string }\n\t): HtmlContent | null;\n\tgetComponentRegistry(): CatalogComponentRegistry;\n}\n\n/**\n * Inject glossary/keyword-translation trigger buttons into a rendered item container.\n *\n * When pnp.content.glossaryOnScreen is true, each [data-catalog-idref] element gets a\n * trigger button. Clicking the button looks up the catalog entry and shows a floating\n * popup rendered by the 'catalogPopup' component from the registry (defaults to\n * pie-qti-catalog-popup). Clicking again or pressing Escape closes it.\n *\n * For platform-level usages (tts-pronunciation, signing-definition, braille-text,\n * audio-description) the player fires a `qti-catalog-lookup` CustomEvent instead of\n * mounting a popup — the host application handles those usages.\n */\nfunction playerI18n(player: GlossaryPlayer): I18nProvider | undefined {\n\treturn player.getI18nProvider?.() as I18nProvider | undefined;\n}\n\nexport function applyGlossaryTriggers(container: HTMLElement, player: GlossaryPlayer): () => void {\n\tcleanupGlossaryTriggers(container);\n\tconst pnp = player.getPnp();\n\tif (!pnp) return () => cleanupGlossaryTriggers(container);\n\tconst i18n = playerI18n(player);\n\n\tconst glossaryOn = pnp.content?.glossaryOnScreen === true;\n\tconst kwTranslation = pnp.content?.keywordTranslation;\n\tconst kwOn = kwTranslation?.active === true && !!kwTranslation.languageCode;\n\tconst illustratedOn = pnp.content?.illustratedGlossary === true;\n\tconst platformSupports = pnp.content?.catalogSupports ?? {};\n\tconst hostSupports = getHostCatalogSupports(platformSupports);\n\n\tconst anyPlatformOn = PLATFORM_USAGES.some((support) => isSupportActive(getPlatformSupportPreference(platformSupports, support)));\n\tif (!glossaryOn && !kwOn && !illustratedOn && !anyPlatformOn && hostSupports.length === 0) return () => cleanupGlossaryTriggers(container);\n\n\tconst terms = container.querySelectorAll<HTMLElement>('[data-catalog-idref]');\n\tif (terms.length === 0) return () => cleanupGlossaryTriggers(container);\n\n\t// Track open popup so only one is open at a time\n\tlet currentCleanup: (() => void) | null = null;\n\n\tfor (const termEl of Array.from(terms)) {\n\t\tconst idref = termEl.getAttribute('data-catalog-idref');\n\t\tif (!idref) continue;\n\t\tconst stimulusIdentifier = getStimulusIdentifier(termEl);\n\t\tconst contentLanguage = getContentLanguage(termEl);\n\n\t\t// Wrap term in a relative-positioned span so we can position popup against it\n\t\tconst wrapper = document.createElement('span');\n\t\twrapper.className = 'qti-catalog-term';\n\t\twrapper.style.cssText = 'position:relative;display:inline';\n\n\t\ttermEl.parentNode?.insertBefore(wrapper, termEl);\n\t\twrapper.appendChild(termEl);\n\n\t\tif (glossaryOn) {\n\t\t\tconst btn = createTriggerButton(\n\t\t\t\ttranslate(i18n, 'accessibility.catalogShowDefinition', 'Show definition: {term}', { term: termEl.textContent ?? idref }),\n\t\t\t\t'glossary-on-screen',\n\t\t\t);\n\t\t\twrapper.appendChild(btn);\n\n\t\t\tbtn.addEventListener('click', () => {\n\t\t\t\tif (currentCleanup) {\n\t\t\t\t\tcurrentCleanup();\n\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst html = player.getCatalogEntry(idref, 'glossary-on-screen', contentLanguage, { stimulusIdentifier });\n\t\t\t\tif (html !== null) {\n\t\t\t\t\tcurrentCleanup = mountPopup(wrapper, termEl.textContent ?? idref, html, btn, player, () => {\n\t\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (kwOn) {\n\t\t\tconst lang = kwTranslation!.languageCode;\n\t\t\tconst btn = createTriggerButton(\n\t\t\t\ttranslate(i18n, 'accessibility.catalogShowTranslation', 'Show translation: {term}', { term: termEl.textContent ?? idref }),\n\t\t\t\t'keyword-translation',\n\t\t\t);\n\t\t\twrapper.appendChild(btn);\n\n\t\t\tbtn.addEventListener('click', () => {\n\t\t\t\tif (currentCleanup) {\n\t\t\t\t\tcurrentCleanup();\n\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst html = player.getCatalogEntry(idref, 'keyword-translation', lang, { stimulusIdentifier });\n\t\t\t\tif (html !== null) {\n\t\t\t\t\tcurrentCleanup = mountPopup(wrapper, termEl.textContent ?? idref, html, btn, player, () => {\n\t\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (illustratedOn) {\n\t\t\tconst btn = createTriggerButton(\n\t\t\t\ttranslate(i18n, 'accessibility.catalogShowIllustratedGlossary', 'Show illustrated glossary: {term}', {\n\t\t\t\t\tterm: termEl.textContent ?? idref,\n\t\t\t\t}),\n\t\t\t\tILLUSTRATED_GLOSSARY_USAGE,\n\t\t\t);\n\t\t\twrapper.appendChild(btn);\n\n\t\t\tbtn.addEventListener('click', () => {\n\t\t\t\tif (currentCleanup) {\n\t\t\t\t\tcurrentCleanup();\n\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst html = player.getCatalogEntry(idref, ILLUSTRATED_GLOSSARY_USAGE, contentLanguage, { stimulusIdentifier });\n\t\t\t\tif (html !== null) {\n\t\t\t\t\tcurrentCleanup = mountPopup(wrapper, termEl.textContent ?? idref, html, btn, player, () => {\n\t\t\t\t\t\tcurrentCleanup = null;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tfor (const support of PLATFORM_USAGES) {\n\t\t\tconst preference = getPlatformSupportPreference(platformSupports, support);\n\t\t\tif (!isSupportActive(preference)) continue;\n\t\t\taddHostCatalogSupportButton(wrapper, termEl, idref, {\n\t\t\t\t...support,\n\t\t\t\tlanguageCode: getSupportLanguageCode(preference),\n\t\t\t}, player, stimulusIdentifier);\n\t\t}\n\n\t\tfor (const support of hostSupports) {\n\t\t\taddHostCatalogSupportButton(wrapper, termEl, idref, support, player, stimulusIdentifier);\n\t\t}\n\t}\n\n\treturn () => {\n\t\tcurrentCleanup?.();\n\t\tcleanupGlossaryTriggers(container);\n\t};\n}\n\nexport function cleanupGlossaryTriggers(container: HTMLElement): void {\n\tfor (const wrapper of Array.from(container.querySelectorAll<HTMLElement>('.qti-catalog-term'))) {\n\t\tconst term = Array.from(wrapper.children).find((child) =>\n\t\t\t(child as HTMLElement).getAttribute?.('data-catalog-idref') !== null\n\t\t) as HTMLElement | undefined;\n\t\tif (term && wrapper.parentNode) {\n\t\t\twrapper.parentNode.insertBefore(term, wrapper);\n\t\t}\n\t\twrapper.remove();\n\t}\n}\n\nfunction createTriggerButton(label: string, usage: string, text?: string): HTMLButtonElement {\n\tconst btn = document.createElement('button');\n\tbtn.type = 'button';\n\tbtn.className = 'qti-catalog-trigger';\n\tbtn.style.cssText =\n\t\t'display:inline-flex;align-items:center;justify-content:center;min-width:1.75rem;min-height:1.75rem;margin-inline:0.25rem;line-height:1;';\n\tbtn.setAttribute('aria-label', label);\n\tbtn.setAttribute('data-catalog-usage', usage);\n\tbtn.textContent = text ?? (usage === 'keyword-translation' ? 'T' : usage === ILLUSTRATED_GLOSSARY_USAGE ? 'I' : '?');\n\treturn btn;\n}\n\nfunction addHostCatalogSupportButton(\n\twrapper: HTMLElement,\n\ttermEl: HTMLElement,\n\tidref: string,\n\tsupport: HostCatalogSupport,\n\tplayer: GlossaryPlayer,\n\tstimulusIdentifier?: string\n): void {\n\tconst html = player.getCatalogEntry(idref, support.usage, support.languageCode, { stimulusIdentifier });\n\tif (html === null) return;\n\tconst i18n = playerI18n(player);\n\tconst label = translate(i18n, support.labelKey, support.label, {\n\t\tterm: termEl.textContent ?? idref,\n\t\tusage: support.usage.replace(/[-_]+/g, ' '),\n\t});\n\tconst btn = createTriggerButton(label, support.usage, support.text);\n\twrapper.appendChild(btn);\n\tbtn.addEventListener('click', () => {\n\t\tbtn.dispatchEvent(\n\t\t\tnew CustomEvent('qti-catalog-lookup', {\n\t\t\t\tbubbles: true,\n\t\t\t\tcomposed: true,\n\t\t\t\tdetail: { idref, usage: support.usage, html, content: html, languageCode: support.languageCode },\n\t\t\t})\n\t\t);\n\t});\n}\n\n/** The language of the term's content: the nearest `lang`, which the item body sets from `xml:lang`. */\nfunction getContentLanguage(termEl: HTMLElement): string | undefined {\n\tconst language = termEl.closest?.('[lang]')?.getAttribute?.('lang')?.trim();\n\treturn language || undefined;\n}\n\nfunction getStimulusIdentifier(termEl: HTMLElement): string | undefined {\n\tconst scopeEl = termEl.closest?.('[data-stimulus-idref]');\n\tconst identifier = scopeEl?.getAttribute?.('data-stimulus-idref')?.trim();\n\treturn identifier || undefined;\n}\n\nfunction getHostCatalogSupports(platformSupports: Record<string, CatalogSupportPreference | undefined>): HostCatalogSupport[] {\n\treturn Object.entries(platformSupports)\n\t\t.map(([usage, preference]) => ({ usage: normalizeCatalogUsage(usage), preference }))\n\t\t.filter(({ usage, preference }) => usage !== null && isSupportActive(preference) && !isReservedCatalogUsage(usage))\n\t\t.map(({ usage, preference }) => ({\n\t\t\tusage: usage!,\n\t\t\tlabelKey: 'accessibility.catalogRequestUsage',\n\t\t\tlabel: 'Request {usage}: {term}',\n\t\t\ttext: usage!.slice(0, 1).toUpperCase(),\n\t\t\tlanguageCode: getSupportLanguageCode(preference),\n\t\t}));\n}\n\nfunction getPlatformSupportPreference(\n\tplatformSupports: Record<string, CatalogSupportPreference | undefined>,\n\tsupport: (typeof PLATFORM_USAGES)[number]\n): CatalogSupportPreference | undefined {\n\treturn platformSupports[support.flag] ?? platformSupports[support.usage];\n}\n\nfunction isSupportActive(preference: CatalogSupportPreference | undefined): boolean {\n\tif (preference === undefined) return false;\n\tif (typeof preference === 'boolean') return preference;\n\treturn preference.active !== false;\n}\n\nfunction getSupportLanguageCode(preference: CatalogSupportPreference | undefined): string | undefined {\n\tif (!preference || typeof preference === 'boolean') return undefined;\n\tconst languageCode = preference.languageCode?.trim();\n\tif (!languageCode || !/^[a-zA-Z]{2,8}(?:-[a-zA-Z0-9]{1,8})*$/.test(languageCode)) return undefined;\n\treturn languageCode;\n}\n\nfunction normalizeCatalogUsage(value: string): string | null {\n\tconst usage = value.trim().toLowerCase();\n\tif (!SAFE_CATALOG_USAGE.test(usage)) return null;\n\treturn usage;\n}\n\nfunction isReservedCatalogUsage(usage: string): boolean {\n\treturn RESERVED_PLATFORM_FLAGS.has(usage) || RESERVED_PLATFORM_USAGES.has(usage) || BUILT_IN_POPUP_USAGES.has(usage);\n}\n\n/**\n * Mount a catalog popup via the component registry. Falls back to a minimal\n * vanilla-JS popup if no 'catalogPopup' component is registered (e.g. in tests\n * that don't load default-components). Returns a cleanup function.\n */\nfunction mountPopup(\n\tanchor: HTMLElement,\n\tlabel: string,\n\thtml: HtmlContent,\n\ttriggerBtn: HTMLButtonElement,\n\tplayer: GlossaryPlayer,\n\tonClose: () => void\n): () => void {\n\tconst registry = player.getComponentRegistry();\n\n\tlet popupEl: HTMLElement;\n\tlet closed = false;\n\n\tfunction cleanup() {\n\t\tif (closed) return;\n\t\tclosed = true;\n\t\tpopupEl.remove();\n\t\ttriggerBtn.focus();\n\t\tonClose();\n\t}\n\n\tconst catalogPopupTag = registry.getTagNameForType('catalogPopup');\n\tif (catalogPopupTag !== null) {\n\t\tconst el = document.createElement(catalogPopupTag) as HTMLElement & {\n\t\t\tcontent: HtmlContent;\n\t\t\tlabel: string;\n\t\t\ti18n?: I18nProvider;\n\t\t\tonClose: () => void;\n\t\t};\n\t\tel.content = html;\n\t\tel.label = label;\n\t\tel.i18n = playerI18n(player);\n\t\tel.onClose = cleanup;\n\t\tanchor.appendChild(el);\n\t\tpopupEl = el;\n\t} else {\n\t\t// Minimal fallback for environments without default-components\n\t\tpopupEl = buildFallbackPopup(label, html, cleanup, playerI18n(player));\n\t\tanchor.appendChild(popupEl);\n\t}\n\n\treturn cleanup;\n}\n\n/**\n * Minimal accessible fallback popup used when no catalogPopup component is registered.\n * Uses DaisyUI card classes where available; degrades gracefully without them.\n */\nfunction buildFallbackPopup(label: string, html: HtmlContent, close: () => void, i18n?: I18nProvider): HTMLElement {\n\tconst popup = document.createElement('div');\n\tpopup.className = 'card card-bordered bg-base-100 shadow-lg qti-catalog-popup';\n\tpopup.setAttribute('role', 'dialog');\n\tpopup.setAttribute('aria-label', label);\n\tpopup.setAttribute('aria-modal', 'true');\n\tpopup.style.cssText = 'position:absolute;z-index:1000;min-width:16rem;max-width:24rem';\n\n\tconst header = document.createElement('div');\n\theader.className = 'card-title flex justify-between items-center px-3 py-2 border-b border-base-300 bg-base-200';\n\n\tconst title = document.createElement('span');\n\ttitle.className = 'text-sm font-semibold';\n\ttitle.textContent = label;\n\n\tconst closeBtn = document.createElement('button');\n\tcloseBtn.type = 'button';\n\tcloseBtn.className = 'btn btn-ghost btn-xs';\n\tcloseBtn.setAttribute('aria-label', translate(i18n, 'common.close', 'Close'));\n\tcloseBtn.textContent = '✕';\n\n\theader.appendChild(title);\n\theader.appendChild(closeBtn);\n\n\tconst body = document.createElement('div');\n\tbody.className = 'card-body p-3';\n\n\tconst htmlString = htmlToString(html);\n\tconst isUrl = /^(https?:\\/\\/|\\/)/i.test(htmlString.trim());\n\tif (isUrl) {\n\t\tconst img = document.createElement('img');\n\t\timg.src = htmlString.trim();\n\t\timg.alt = label;\n\t\timg.className = 'max-w-full h-auto block mx-auto';\n\t\tbody.appendChild(img);\n\t} else {\n\t\tbody.innerHTML = html as any;\n\t}\n\n\tpopup.appendChild(header);\n\tpopup.appendChild(body);\n\n\t// Focus trap + Escape\n\tconst focusableSelector = 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])';\n\n\tfunction handleKeyDown(e: KeyboardEvent) {\n\t\tif (e.key === 'Escape' && !isImeComposing(e)) {\n\t\t\te.preventDefault();\n\t\t\tcloseBtn.click();\n\t\t\treturn;\n\t\t}\n\t\tif (e.key === 'Tab') {\n\t\t\tconst focusable = Array.from(popup.querySelectorAll<HTMLElement>(focusableSelector)).filter(\n\t\t\t\t(el) => el.offsetParent !== null\n\t\t\t);\n\t\t\tif (focusable.length === 0) { e.preventDefault(); return; }\n\t\t\tconst first = focusable[0];\n\t\t\tconst last = focusable[focusable.length - 1];\n\t\t\tif (e.shiftKey && document.activeElement === first) {\n\t\t\t\te.preventDefault();\n\t\t\t\tlast.focus();\n\t\t\t} else if (!e.shiftKey && document.activeElement === last) {\n\t\t\t\te.preventDefault();\n\t\t\t\tfirst.focus();\n\t\t\t}\n\t\t}\n\t}\n\n\tpopup.addEventListener('keydown', handleKeyDown);\n\tcloseBtn.addEventListener('click', () => close());\n\n\t// Move focus in on next tick\n\tsetTimeout(() => closeBtn.focus(), 0);\n\n\treturn popup;\n}\n"]}
@@ -2,11 +2,15 @@ import type { CatalogIndex } from './types.js';
2
2
  /**
3
3
  * Look up a catalog entry by card identifier, usage type, and optional language.
4
4
  *
5
- * Language fallback order (mirrors APIP 1.0 / HTTP Accept-Language conventions):
6
- * 1. Exact lang match (e.g. 'en-US')
7
- * 2. Language-prefix match (e.g. 'en' matches entry with lang 'en-US')
5
+ * Language fallback order, comparing tags through `normalizeLanguageTag` so a
6
+ * POSIX `es_ES` entry answers an `es-ES` request:
7
+ * 1. The request's RFC 4647 lookup sequence, most specific first
8
+ * (`es-MX` tries `es-mx`, then `es`), as pie-players' catalog resolver does
9
+ * 2. Any entry in the requested language (`en` reaches `en-US`, `en-GB`
10
+ * reaches `en-US`)
8
11
  * 3. Entry with no lang specified (universal fallback)
9
- * 4. null — no match found
12
+ * 4. The only entry for the usage, whatever its lang
13
+ * 5. null — no match found
10
14
  *
11
15
  * @param index CatalogIndex built by extractCatalog / extractCatalogFromItemXml
12
16
  * @param idref The data-catalog-idref value (maps to qti-card identifier)
@@ -1,11 +1,16 @@
1
+ import { languageTagLookupSequence, normalizeLanguageTag } from '@pie-qti/i18n';
1
2
  /**
2
3
  * Look up a catalog entry by card identifier, usage type, and optional language.
3
4
  *
4
- * Language fallback order (mirrors APIP 1.0 / HTTP Accept-Language conventions):
5
- * 1. Exact lang match (e.g. 'en-US')
6
- * 2. Language-prefix match (e.g. 'en' matches entry with lang 'en-US')
5
+ * Language fallback order, comparing tags through `normalizeLanguageTag` so a
6
+ * POSIX `es_ES` entry answers an `es-ES` request:
7
+ * 1. The request's RFC 4647 lookup sequence, most specific first
8
+ * (`es-MX` tries `es-mx`, then `es`), as pie-players' catalog resolver does
9
+ * 2. Any entry in the requested language (`en` reaches `en-US`, `en-GB`
10
+ * reaches `en-US`)
7
11
  * 3. Entry with no lang specified (universal fallback)
8
- * 4. null — no match found
12
+ * 4. The only entry for the usage, whatever its lang
13
+ * 5. null — no match found
9
14
  *
10
15
  * @param index CatalogIndex built by extractCatalog / extractCatalogFromItemXml
11
16
  * @param idref The data-catalog-idref value (maps to qti-card identifier)
@@ -20,18 +25,22 @@ export function getCatalogEntry(index, idref, usage, lang) {
20
25
  const candidates = card.entries.filter((e) => e.usage === usage);
21
26
  if (candidates.length === 0)
22
27
  return null;
23
- // 1. Exact language match
24
- if (lang) {
25
- const exact = candidates.find((e) => e.lang === lang);
26
- if (exact)
27
- return exact.html;
28
- // 2. Language-prefix match: requested lang prefix matches entry lang
29
- // e.g. lang='en' matches entry.lang='en-US'
30
- // e.g. lang='en-US' matches entry.lang='en' (broader fallback)
31
- const prefix = lang.split('-')[0];
32
- const prefixMatch = candidates.find((e) => e.lang && (e.lang === prefix || e.lang.startsWith(`${prefix}-`) || lang.startsWith(`${e.lang}-`)));
33
- if (prefixMatch)
34
- return prefixMatch.html;
28
+ const sequence = languageTagLookupSequence(lang);
29
+ if (sequence.length > 0) {
30
+ const tagged = candidates
31
+ .filter((e) => e.lang)
32
+ .map((entry) => ({ entry, tag: normalizeLanguageTag(entry.lang) }));
33
+ // 1. Lookup sequence
34
+ for (const step of sequence) {
35
+ const hit = tagged.find((t) => t.tag === step);
36
+ if (hit)
37
+ return hit.entry.html;
38
+ }
39
+ // 2. Same language, narrower or sibling tag
40
+ const language = sequence[sequence.length - 1];
41
+ const sameLanguage = tagged.find((t) => t.tag.split('-')[0] === language);
42
+ if (sameLanguage)
43
+ return sameLanguage.entry.html;
35
44
  }
36
45
  // 3. No-lang fallback (entry without a lang attribute)
37
46
  const noLang = candidates.find((e) => !e.lang);
@@ -1 +1 @@
1
- {"version":3,"file":"catalogLookup.js","sourceRoot":"","sources":["../../src/catalog/catalogLookup.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,eAAe,CAC9B,KAAmB,EACnB,KAAa,EACb,KAAa,EACb,IAAa;IAEb,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC9B,IAAI,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IAEvB,MAAM,UAAU,GAAG,IAAI,CAAC,OA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,aAAa,GAAqC;IAC9D,cAAc,EAAE,SAAS;IACzB,oBAAoB,EAAE,eAAe;CACrC,CAAC;AAEF,4FAA4F;AAC5F,MAAM,UAAU,0BAA0B,CACzC,KAAmB,EACnB,KAAa,EACb,KAAa,EACb,IAAa;IAEb,MAAM,MAAM,GAAG,eAAe,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IAC1D,IAAI,MAAM,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IACnC,MAAM,KAAK,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,CAAC,CAAC,eAAe,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAClE,CAAC","sourcesContent":["import type { CatalogIndex } from './types.js';\n\n/**\n * Look up a catalog entry by card identifier, usage type, and optional language.\n *\n * Language fallback order (mirrors APIP 1.0 / HTTP Accept-Language conventions):\n * 1. Exact lang match (e.g. 'en-US')\n * 2. Language-prefix match (e.g. 'en' matches entry with lang 'en-US')\n * 3. Entry with no lang specified (universal fallback)\n * 4. null — no match found\n *\n * @param index CatalogIndex built by extractCatalog / extractCatalogFromItemXml\n * @param idref The data-catalog-idref value (maps to qti-card identifier)\n * @param usage Catalog usage type (e.g. 'glossary-on-screen')\n * @param lang Optional preferred language code (e.g. 'en-US', 'es')\n * @returns The matched entry's html string, or null if nothing found\n */\nexport function getCatalogEntry(\n\tindex: CatalogIndex,\n\tidref: string,\n\tusage: string,\n\tlang?: string\n): string | null {\n\tconst card = index.get(idref);\n\tif (!card) return null;\n\n\tconst candidates = card.entries.filter((e) => e.usage === usage);\n\tif (candidates.length === 0) return null;\n\n\t// 1. Exact language match\n\tif (lang) {\n\t\tconst exact = candidates.find((e) => e.lang === lang);\n\t\tif (exact) return exact.html;\n\n\t\t// 2. Language-prefix match: requested lang prefix matches entry lang\n\t\t// e.g. lang='en' matches entry.lang='en-US'\n\t\t// e.g. lang='en-US' matches entry.lang='en' (broader fallback)\n\t\tconst prefix = lang.split('-')[0];\n\t\tconst prefixMatch = candidates.find(\n\t\t\t(e) => e.lang && (e.lang === prefix || e.lang.startsWith(`${prefix}-`) || lang.startsWith(`${e.lang}-`))\n\t\t);\n\t\tif (prefixMatch) return prefixMatch.html;\n\t}\n\n\t// 3. No-lang fallback (entry without a lang attribute)\n\tconst noLang = candidates.find((e) => !e.lang);\n\tif (noLang) return noLang.html;\n\n\t// 4. If we get here and there's only one candidate, return it regardless of lang\n\tif (candidates.length === 1) return candidates[0].html;\n\n\treturn null;\n}\n\n/**\n * Delivery-level usage aliases: APIP-derived catalogs name a few supports by their AfA\n * support name, where QTI 3 catalogs use the newer usage string. A lookup under a QTI 3\n * usage falls back to its alias so host routing finds both catalog flavors.\n */\nexport const USAGE_ALIASES: Readonly<Record<string, string>> = {\n\t'braille-text': 'braille',\n\t'signing-definition': 'sign-language',\n};\n\n/** Look `usage` up, then its QTI 3 → APIP alias, so one idref answers under either name. */\nexport function getCatalogEntryWithAliases(\n\tindex: CatalogIndex,\n\tidref: string,\n\tusage: string,\n\tlang?: string\n): string | null {\n\tconst direct = getCatalogEntry(index, idref, usage, lang);\n\tif (direct !== null) return direct;\n\tconst alias = USAGE_ALIASES[usage];\n\treturn alias ? getCatalogEntry(index, idref, alias, lang) : null;\n}\n"]}
1
+ {"version":3,"file":"catalogLookup.js","sourceRoot":"","sources":["../../src/catalog/catalogLookup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAGhF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,eAAe,CAC9B,KAAmB,EACnB,KAAa,EACb,KAAa,EACb,IAAa;IAEb,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC9B,IAAI,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IAEvB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AAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAC/C,IAAI,MAAM;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC;IAE/B,iFAAiF;IACjF,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAEvD,OAAO,IAAI,CAAC;AACb,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,aAAa,GAAqC;IAC9D,cAAc,EAAE,SAAS;IACzB,oBAAoB,EAAE,eAAe;CACrC,CAAC;AAEF,4FAA4F;AAC5F,MAAM,UAAU,0BAA0B,CACzC,KAAmB,EACnB,KAAa,EACb,KAAa,EACb,IAAa;IAEb,MAAM,MAAM,GAAG,eAAe,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IAC1D,IAAI,MAAM,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IACnC,MAAM,KAAK,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,CAAC,CAAC,eAAe,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAClE,CAAC","sourcesContent":["import { languageTagLookupSequence, normalizeLanguageTag } from '@pie-qti/i18n';\nimport type { CatalogIndex } from './types.js';\n\n/**\n * Look up a catalog entry by card identifier, usage type, and optional language.\n *\n * Language fallback order, comparing tags through `normalizeLanguageTag` so a\n * POSIX `es_ES` entry answers an `es-ES` request:\n * 1. The request's RFC 4647 lookup sequence, most specific first\n * (`es-MX` tries `es-mx`, then `es`), as pie-players' catalog resolver does\n * 2. Any entry in the requested language (`en` reaches `en-US`, `en-GB`\n * reaches `en-US`)\n * 3. Entry with no lang specified (universal fallback)\n * 4. The only entry for the usage, whatever its lang\n * 5. null — no match found\n *\n * @param index CatalogIndex built by extractCatalog / extractCatalogFromItemXml\n * @param idref The data-catalog-idref value (maps to qti-card identifier)\n * @param usage Catalog usage type (e.g. 'glossary-on-screen')\n * @param lang Optional preferred language code (e.g. 'en-US', 'es')\n * @returns The matched entry's html string, or null if nothing found\n */\nexport function getCatalogEntry(\n\tindex: CatalogIndex,\n\tidref: string,\n\tusage: string,\n\tlang?: string\n): string | null {\n\tconst card = index.get(idref);\n\tif (!card) return null;\n\n\tconst candidates = card.entries.filter((e) => e.usage === usage);\n\tif (candidates.length === 0) return null;\n\n\tconst sequence = languageTagLookupSequence(lang);\n\tif (sequence.length > 0) {\n\t\tconst tagged = candidates\n\t\t\t.filter((e) => e.lang)\n\t\t\t.map((entry) => ({ entry, tag: normalizeLanguageTag(entry.lang) }));\n\n\t\t// 1. Lookup sequence\n\t\tfor (const step of sequence) {\n\t\t\tconst hit = tagged.find((t) => t.tag === step);\n\t\t\tif (hit) return hit.entry.html;\n\t\t}\n\n\t\t// 2. Same language, narrower or sibling tag\n\t\tconst language = sequence[sequence.length - 1];\n\t\tconst sameLanguage = tagged.find((t) => t.tag.split('-')[0] === language);\n\t\tif (sameLanguage) return sameLanguage.entry.html;\n\t}\n\n\t// 3. No-lang fallback (entry without a lang attribute)\n\tconst noLang = candidates.find((e) => !e.lang);\n\tif (noLang) return noLang.html;\n\n\t// 4. If we get here and there's only one candidate, return it regardless of lang\n\tif (candidates.length === 1) return candidates[0].html;\n\n\treturn null;\n}\n\n/**\n * Delivery-level usage aliases: APIP-derived catalogs name a few supports by their AfA\n * support name, where QTI 3 catalogs use the newer usage string. A lookup under a QTI 3\n * usage falls back to its alias so host routing finds both catalog flavors.\n */\nexport const USAGE_ALIASES: Readonly<Record<string, string>> = {\n\t'braille-text': 'braille',\n\t'signing-definition': 'sign-language',\n};\n\n/** Look `usage` up, then its QTI 3 → APIP alias, so one idref answers under either name. */\nexport function getCatalogEntryWithAliases(\n\tindex: CatalogIndex,\n\tidref: string,\n\tusage: string,\n\tlang?: string\n): string | null {\n\tconst direct = getCatalogEntry(index, idref, usage, lang);\n\tif (direct !== null) return direct;\n\tconst alias = USAGE_ALIASES[usage];\n\treturn alias ? getCatalogEntry(index, idref, alias, lang) : null;\n}\n"]}
@@ -184,6 +184,10 @@ export class LiveItemSession {
184
184
  this.assertActive();
185
185
  return this.player.onPnpChange(() => listener());
186
186
  },
187
+ getContentLanguage: () => {
188
+ this.assertActive();
189
+ return this.player.getContentLanguage();
190
+ },
187
191
  getCatalogEntry: (idref, usage, lang, options) => {
188
192
  this.assertActive();
189
193
  return this.player.getCatalogEntry(idref, usage, lang, options);
@@ -1 +1 @@
1
- {"version":3,"file":"ItemSession.js","sourceRoot":"","sources":["../../src/core/ItemSession.ts"],"names":[],"mappings":"AAGA,OAAO,EACN,sBAAsB,GAGtB,MAAM,yCAAyC,CAAC;AAcjD,OAAO,EAAE,gCAAgC,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AA4GvE;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAAoB;IACzD,MAAM,cAAc,GAAG,OAEtB,CAAC;IACF,IAAI,OAAO,cAAc,CAAC,iBAAiB,KAAK,UAAU,EAAE,CAAC;QAC5D,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,cAAc,CAAC,iBAAiB,EAAE,CAAC;AAC3C,CAAC;AAED;;;GAGG;AACH,MAAM,OAAO,eAAe;IAU3B,mFAAmF;IACnF,YACkB,cAAsB,EACvC,MAA+B,EAC/B,UAAkC,EAAE,EACpC,QAAkB;QAHD,mBAAc,GAAd,cAAc,CAAQ;QAVvB,cAAS,GAAG,IAAI,GAAG,EAAuB,CAAC;QAGpD,aAAQ,GAAG,CAAC,CAAC;QACb,aAAQ,GAAG,KAAK,CAAC;QAWxB,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,IAAI,IAAI,WAAW,CAAC;QAC9C,IAAI,CAAC,YAAY,GAAG,EAAE,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;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AQ,CAAM,CAAC;AACrC,CAAC","sourcesContent":["import type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\nimport type { PnpProfile } from '../pnp/types.js';\nimport type { ExtractedPci, PciHostController } from '../pci/types.js';\nimport {\n\tcreateItemPresentation,\n\ttype CreateItemPresentationOptions,\n\ttype ItemPresentation,\n} from '../presentation/itemPresentationPlan.js';\nimport type {\n\tCompletionStatus,\n\tHtmlContent,\n\tItemLifecycleStatus,\n\tItemSessionActionCommand,\n\tItemSessionActionResult,\n\tItemSessionEngineConfig,\n\tPlayerSecurityConfig,\n\tQTIRole,\n\tSerializedItemSessionState,\n\tSerializedItemSessionVariable,\n} from '../types/index.js';\nimport type { BaseInteractionData } from '../interactions/shared/types.js';\nimport { createPlayerFromPreparedInternal, Player } from './Player.js';\n\nexport interface OpenItemSessionOptions {\n\t/** Restore a previously serialized state before applying response overrides. */\n\trestore?: SerializedItemSessionState;\n\t/** Initial responses, or overrides applied after restore. */\n\tresponses?: Readonly<Record<string, unknown>>;\n\t/** Resume a suspended handoff as an active interaction session. */\n\tactivate?: boolean;\n\t/**\n\t * Values for the item's context variables, e.g. `QTI_CONTEXT`, set before template processing.\n\t * A restored session keeps its saved context values.\n\t */\n\tcontextVariables?: Readonly<Record<string, unknown>>;\n\t/**\n\t * Default values for template variables, set before template processing, as an\n\t * assessmentItemRef's `templateDefault` requires. A restored session keeps its saved values.\n\t */\n\ttemplateDefaults?: Readonly<Record<string, unknown>>;\n\t/** Test-level item session control applied by `present()`. */\n\tpresentation?: ItemSessionPresentationPolicy;\n}\n\nexport interface ItemSessionPresentationPolicy {\n\t/** False hides integrated feedback (`showFeedback=\"false\"`). Defaults to true. */\n\tshowFeedback?: boolean;\n\t/** True shows correct responses once the attempt has ended (`showSolution=\"true\"`). */\n\tshowSolution?: boolean;\n}\n\nexport type ItemSessionCommand =\n\t| ItemSessionActionCommand\n\t| { action: 'setResponse'; responseIdentifier: string; value: unknown }\n\t| { action: 'setResponses'; responses: Readonly<Record<string, unknown>> }\n\t| { action: 'updatePnp'; profile: Partial<PnpProfile> };\n\nexport type ItemSessionEventCommand = ItemSessionCommand | { action: 'dispose' };\n\nexport interface ItemSessionView {\n\treadonly revision: number;\n\treadonly itemIdentifier?: string;\n\treadonly role: QTIRole;\n\treadonly lifecycleStatus: ItemLifecycleStatus;\n\treadonly completionStatus: CompletionStatus;\n\treadonly numAttempts: number;\n\treadonly duration: number;\n\treadonly adaptive: boolean;\n\treadonly completed: boolean;\n\treadonly canSubmit: boolean;\n\treadonly disposed: boolean;\n\treadonly responses: Readonly<Record<string, unknown>>;\n\treadonly outcomes: Readonly<Record<string, unknown>>;\n\treadonly templates: Readonly<Record<string, unknown>>;\n\treadonly context: Readonly<Record<string, unknown>>;\n}\n\nexport interface ItemSessionTransition {\n\treadonly command: ItemSessionEventCommand;\n\treadonly previous: ItemSessionView;\n\treadonly current: ItemSessionView;\n\treadonly result?: ItemSessionActionResult;\n}\n\nexport type ItemSessionListener = (transition: ItemSessionTransition) => void;\n\nexport type ItemPresentationView = Omit<\n\tCreateItemPresentationOptions,\n\t'outcomeValues' | 'responses' | 'role' | 'source' | 'showFeedback' | 'showSolution'\n>;\n\nexport interface ItemSession {\n\tstate(): ItemSessionView;\n\tdispatch(command: ItemSessionCommand): ItemSessionTransition;\n\tpresent(view?: ItemPresentationView): ItemPresentation;\n\tsubscribe(listener: ItemSessionListener): () => void;\n\tserialize(): SerializedItemSessionState;\n\tdispose(): void;\n}\n\n/**\n * Narrow browser/runtime capabilities needed after a presentation has been produced.\n * This interface deliberately excludes Player, parser nodes, declarations, and extraction registries.\n * @internal\n */\nexport interface ItemSessionBinding {\n\treadonly role: QTIRole;\n\tapplyPnp(root: HTMLElement): void;\n\tgetPnp(): PnpProfile | undefined;\n\tonPnpChange(listener: () => void): () => void;\n\tgetCatalogEntry(\n\t\tidref: string,\n\t\tusage: string,\n\t\tlang?: string,\n\t\toptions?: { stimulusIdentifier?: string }\n\t): HtmlContent | null;\n\tgetComponentRegistry(): ItemSessionComponentRegistry;\n\tgetDeliveryContext(): ResolvedItemDeliveryContext | undefined;\n\tgetSecurityConfig(): PlayerSecurityConfig | undefined;\n\tgetI18nProvider(): unknown;\n\tcreatePciHost(data: ExtractedPci): PciHostController;\n}\n\n/** @internal */\nexport interface ItemSessionComponentRegistry {\n\tgetTagName(interaction: BaseInteractionData): string;\n\tgetTagNameForType(type: string): string | null;\n}\n\n/**\n * Browser adapters use this without gaining access to the private session engine.\n * @internal\n */\nexport function getItemSessionBinding(session: ItemSession): ItemSessionBinding {\n\tconst runtimeSession = session as ItemSession & {\n\t\tgetRuntimeBinding?: () => ItemSessionBinding;\n\t};\n\tif (typeof runtimeSession.getRuntimeBinding !== 'function') {\n\t\tthrow new Error('ItemSession runtime binding is unavailable');\n\t}\n\treturn runtimeSession.getRuntimeBinding();\n}\n\n/**\n * Construct sessions through AssessmentItemDefinition.openSession().\n * @internal\n */\nexport class LiveItemSession implements ItemSession {\n\tprivate readonly player: Player;\n\tprivate readonly listeners = new Set<ItemSessionListener>();\n\tprivate readonly defaultRole: QTIRole;\n\tprivate readonly presentation: ItemSessionPresentationPolicy;\n\tprivate revision = 0;\n\tprivate disposed = false;\n\tprivate currentView: ItemSessionView;\n\tprivate readonly runtimeBinding: ItemSessionBinding;\n\n\t/** @internal Construct sessions through AssessmentItemDefinition.openSession(). */\n\tconstructor(\n\t\tprivate readonly itemIdentifier: string,\n\t\tconfig: ItemSessionEngineConfig,\n\t\toptions: OpenItemSessionOptions = {},\n\t\tprepared?: unknown,\n\t) {\n\t\tthis.defaultRole = config.role ?? 'candidate';\n\t\tthis.presentation = { ...options.presentation };\n\t\tconst playerConfig = {\n\t\t\t...config,\n\t\t\t...(options.contextVariables ? { contextVariables: options.contextVariables } : {}),\n\t\t\t...(options.templateDefaults ? { templateDefaults: options.templateDefaults } : {}),\n\t\t};\n\t\tthis.player = prepared\n\t\t\t? createPlayerFromPreparedInternal(playerConfig, prepared, Boolean(options.restore))\n\t\t\t: new Player(playerConfig);\n\n\t\ttry {\n\t\t\tif (options.responses) {\n\t\t\t\tthis.assertKnownResponseIdentifiers(Object.keys(options.responses));\n\t\t\t}\n\t\t\tif (options.restore) this.player.restoreItemSession(options.restore);\n\t\t\tif (options.activate && this.player.getLifecycleStatus() === 'suspended') {\n\t\t\t\tthis.player.activateAttempt();\n\t\t\t}\n\t\t\tif (options.responses) {\n\t\t\t\tconst lifecycle = this.player.getLifecycleStatus();\n\t\t\t\tif (!isResponseWritableLifecycle(lifecycle)) {\n\t\t\t\t\tthrow new Error(`Cannot override responses while item session is ${lifecycle}`);\n\t\t\t\t}\n\t\t\t\tthis.player.setResponses({ ...options.responses });\n\t\t\t}\n\t\t\tthis.currentView = this.captureView();\n\t\t} catch (error) {\n\t\t\tthis.player.destroy();\n\t\t\tthrow error;\n\t\t}\n\n\t\tthis.runtimeBinding = this.createBinding();\n\t}\n\n\tstate(): ItemSessionView {\n\t\treturn immutableSnapshot(this.currentView);\n\t}\n\n\tdispatch(command: ItemSessionCommand): ItemSessionTransition {\n\t\tthis.assertActive();\n\t\tif (\n\t\t\tcommandRequiresWritableLifecycle(command) &&\n\t\t\t!isResponseWritableLifecycle(this.currentView.lifecycleStatus)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot ${describeCommand(command)} while item session is ${this.currentView.lifecycleStatus}`\n\t\t\t);\n\t\t}\n\t\tconst previous = this.currentView;\n\t\tlet result: ItemSessionActionResult | undefined;\n\n\t\tswitch (command.action) {\n\t\t\tcase 'setResponse':\n\t\t\t\tthis.assertKnownResponseIdentifiers([command.responseIdentifier]);\n\t\t\t\tthis.player.setResponses({ [command.responseIdentifier]: command.value });\n\t\t\t\tbreak;\n\t\t\tcase 'setResponses':\n\t\t\t\tthis.assertKnownResponseIdentifiers(Object.keys(command.responses));\n\t\t\t\tthis.player.setResponses({ ...command.responses });\n\t\t\t\tbreak;\n\t\t\tcase 'updatePnp':\n\t\t\t\tthis.player.updatePnp(command.profile);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tresult = this.player.runItemSessionAction(command);\n\t\t}\n\n\t\tthis.revision += 1;\n\t\tthis.currentView = this.captureView(result?.sessionState);\n\t\tconst transition = freezeTransition({ command, previous, current: this.currentView, result });\n\t\tthis.notify(transition);\n\t\treturn transition;\n\t}\n\n\tpresent(view: ItemPresentationView = {}): ItemPresentation {\n\t\tthis.assertActive();\n\t\tconst lifecycle = this.currentView.lifecycleStatus;\n\t\tconst attemptEnded = !isResponseWritableLifecycle(lifecycle) && lifecycle !== 'suspended';\n\t\treturn createItemPresentation({\n\t\t\t...view,\n\t\t\tdisabled: view.disabled === true || !isResponseWritableLifecycle(lifecycle),\n\t\t\tshowFeedback: this.presentation.showFeedback !== false,\n\t\t\tshowSolution: this.presentation.showSolution === true && attemptEnded,\n\t\t\tsource: {\n\t\t\t\titemBodyHtml: this.player.getItemBodyHtml(),\n\t\t\t\tcontentLanguage: this.player.getContentLanguage(),\n\t\t\t\tinteractions: this.player.getInteractionData(),\n\t\t\t\tcorrectResponses: this.player.getCorrectResponses(),\n\t\t\t\tcomponentRegistry: this.player.getComponentRegistry(),\n\t\t\t\tdeliveryContext: this.player.getDeliveryContext(),\n\t\t\t\tpnp: this.player.getPnp(),\n\t\t\t\tsecurity: this.player.getSecurityConfig(),\n\t\t\t\tdirectRubrics: this.player.getRubrics({ scope: 'direct' }),\n\t\t\t},\n\t\t\tresponses: immutableSnapshot(this.currentView.responses),\n\t\t\toutcomeValues: immutableSnapshot(this.currentView.outcomes),\n\t\t\trole: this.defaultRole,\n\t\t});\n\t}\n\n\tsubscribe(listener: ItemSessionListener): () => void {\n\t\tthis.assertActive();\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\tserialize(): SerializedItemSessionState {\n\t\tthis.assertActive();\n\t\treturn immutableSnapshot(this.player.saveItemSession());\n\t}\n\n\t/**\n\t * Browser/runtime capabilities carried by the session across package bundles.\n\t * @internal\n\t */\n\tgetRuntimeBinding(): ItemSessionBinding {\n\t\tthis.assertActive();\n\t\treturn this.runtimeBinding;\n\t}\n\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tconst previous = this.currentView;\n\t\tthis.disposed = true;\n\t\tthis.revision += 1;\n\t\tthis.currentView = immutableSnapshot({\n\t\t\t...previous,\n\t\t\trevision: this.revision,\n\t\t\tdisposed: true,\n\t\t});\n\t\tthis.player.destroy();\n\t\tthis.notify(\n\t\t\tfreezeTransition({\n\t\t\t\tcommand: { action: 'dispose' },\n\t\t\t\tprevious,\n\t\t\t\tcurrent: this.currentView,\n\t\t\t})\n\t\t);\n\t\tthis.listeners.clear();\n\t}\n\n\tprivate captureView(serialized = this.player.saveItemSession()): ItemSessionView {\n\t\tconst responses = valuesOf(serialized.responseVariables);\n\t\treturn immutableSnapshot({\n\t\t\trevision: this.revision,\n\t\t\titemIdentifier: serialized.itemIdentifier || this.itemIdentifier || undefined,\n\t\t\trole: this.defaultRole,\n\t\t\tlifecycleStatus: serialized.lifecycleStatus,\n\t\t\tcompletionStatus: serialized.completionStatus,\n\t\t\tnumAttempts: serialized.numAttempts,\n\t\t\tduration: serialized.duration,\n\t\t\tadaptive: this.player.isAdaptive(),\n\t\t\tcompleted: this.player.isCompleted(),\n\t\t\tcanSubmit: this.player.canSubmitResponses(responses),\n\t\t\tdisposed: this.disposed,\n\t\t\tresponses,\n\t\t\toutcomes: valuesOf(serialized.outcomeVariables),\n\t\t\ttemplates: valuesOf(serialized.templateVariables),\n\t\t\tcontext: valuesOf(serialized.contextVariables),\n\t\t});\n\t}\n\n\tprivate createBinding(): ItemSessionBinding {\n\t\treturn Object.freeze({\n\t\t\trole: this.defaultRole,\n\t\t\tapplyPnp: (root: HTMLElement) => {\n\t\t\t\tthis.assertActive();\n\t\t\t\tthis.player.applyPnp(root);\n\t\t\t},\n\t\t\tgetPnp: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getPnp();\n\t\t\t},\n\t\t\tonPnpChange: (listener: () => void) => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.onPnpChange(() => listener());\n\t\t\t},\n\t\t\tgetCatalogEntry: (\n\t\t\t\tidref: string,\n\t\t\t\tusage: string,\n\t\t\t\tlang?: string,\n\t\t\t\toptions?: { stimulusIdentifier?: string }\n\t\t\t) => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getCatalogEntry(idref, usage, lang, options);\n\t\t\t},\n\t\t\tgetComponentRegistry: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getComponentRegistry();\n\t\t\t},\n\t\t\tgetDeliveryContext: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getDeliveryContext();\n\t\t\t},\n\t\t\tgetSecurityConfig: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getSecurityConfig();\n\t\t\t},\n\t\t\tgetI18nProvider: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getI18nProvider();\n\t\t\t},\n\t\t\tcreatePciHost: (data: ExtractedPci) => {\n\t\t\t\tthis.assertActive();\n\t\t\t\tconst host = this.player.createPciHost(data);\n\t\t\t\thost.onResponseChange(() => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.disposed ||\n\t\t\t\t\t\t!isResponseWritableLifecycle(this.currentView.lifecycleStatus)\n\t\t\t\t\t) return;\n\t\t\t\t\tconst previous = this.currentView;\n\t\t\t\t\tthis.revision += 1;\n\t\t\t\t\tthis.currentView = this.captureView();\n\t\t\t\t\tthis.notify(\n\t\t\t\t\t\tfreezeTransition({\n\t\t\t\t\t\t\tcommand: {\n\t\t\t\t\t\t\t\taction: 'setResponse',\n\t\t\t\t\t\t\t\tresponseIdentifier: data.responseIdentifier,\n\t\t\t\t\t\t\t\tvalue: host.getResponse(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tprevious,\n\t\t\t\t\t\t\tcurrent: this.currentView,\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\treturn host;\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate notify(transition: ItemSessionTransition): void {\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\ttry {\n\t\t\t\tlistener(immutableSnapshot(transition));\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[QTI ItemSession] subscriber failed:', error);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate assertActive(): void {\n\t\tif (this.disposed) throw new Error('ItemSession has been disposed');\n\t}\n\n\tprivate assertKnownResponseIdentifiers(responseIdentifiers: readonly string[]): void {\n\t\tconst knownIdentifiers = new Set(Object.keys(this.player.getResponses()));\n\t\tconst unknown = responseIdentifiers.find((identifier) => !knownIdentifiers.has(identifier));\n\t\tif (unknown) throw new Error(`Unknown response identifier '${unknown}'`);\n\t}\n}\n\nfunction isResponseWritableLifecycle(status: ItemLifecycleStatus): boolean {\n\treturn status === 'initial' || status === 'interacting';\n}\n\nfunction commandRequiresWritableLifecycle(command: ItemSessionCommand): boolean {\n\treturn command.action === 'setResponse' ||\n\t\tcommand.action === 'setResponses' ||\n\t\tcommand.action === 'suspendAttempt' ||\n\t\tcommand.action === 'endAttempt' ||\n\t\tcommand.action === 'submitAttempt';\n}\n\nfunction describeCommand(command: ItemSessionCommand): string {\n\treturn command.action === 'setResponse' || command.action === 'setResponses'\n\t\t? 'update responses'\n\t\t: `run ${command.action}`;\n}\n\nfunction valuesOf(\n\tvariables: Record<string, SerializedItemSessionVariable>\n): Readonly<Record<string, unknown>> {\n\treturn Object.fromEntries(\n\t\tObject.entries(variables).map(([identifier, variable]) => [\n\t\t\tidentifier,\n\t\t\timmutableSnapshot(variable.value),\n\t\t])\n\t);\n}\n\nfunction freezeTransition(transition: ItemSessionTransition): ItemSessionTransition {\n\treturn immutableSnapshot(transition);\n}\n\n/** Clone and freeze plain data without mutating values owned by the caller or a PCI module. */\nfunction immutableSnapshot<T>(value: T): T {\n\tif (Array.isArray(value)) {\n\t\treturn Object.freeze(value.map((entry) => immutableSnapshot(entry))) as T;\n\t}\n\tif (!value || typeof value !== 'object') return value;\n\tif (ArrayBuffer.isView(value)) return structuredClone(value);\n\tif (value instanceof ArrayBuffer) return value.slice(0) as T;\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) return value;\n\tconst snapshot = Object.fromEntries(\n\t\tObject.entries(value as Record<string, unknown>).map(([key, entry]) => [\n\t\t\tkey,\n\t\t\timmutableSnapshot(entry),\n\t\t])\n\t);\n\treturn Object.freeze(snapshot) as T;\n}\n"]}
1
+ {"version":3,"file":"ItemSession.js","sourceRoot":"","sources":["../../src/core/ItemSession.ts"],"names":[],"mappings":"AAGA,OAAO,EACN,sBAAsB,GAGtB,MAAM,yCAAyC,CAAC;AAcjD,OAAO,EAAE,gCAAgC,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AA6GvE;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAAoB;IACzD,MAAM,cAAc,GAAG,OAEtB,CAAC;IACF,IAAI,OAAO,cAAc,CAAC,iBAAiB,KAAK,UAAU,EAAE,CAAC;QAC5D,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,cAAc,CAAC,iBAAiB,EAAE,CAAC;AAC3C,CAAC;AAED;;;GAGG;AACH,MAAM,OAAO,eAAe;IAU3B,mFAAmF;IACnF,YACkB,cAAsB,EACvC,MAA+B,EAC/B,UAAkC,EAAE,EACpC,QAAkB;QAHD,mBAAc,GAAd,cAAc,CAAQ;QAVvB,cAAS,GAAG,IAAI,GAAG,EAAuB,CAAC;QAGpD,aAAQ,GAAG,CAAC,CAAC;QACb,aAAQ,GAAG,KAAK,CAAC;QAWxB,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,IAAI,IAAI,WAAW,CAAC;QAC9C,IAAI,CAAC,YAAY,GAAG,EAAE,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;QAChD,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AAK,CAAC,EAAE,EAAE,CAAC;QACtE,GAAG;QACH,iBAAiB,CAAC,KAAK,CAAC;KACxB,CAAC,CACF,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAM,CAAC;AACrC,CAAC","sourcesContent":["import type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\nimport type { PnpProfile } from '../pnp/types.js';\nimport type { ExtractedPci, PciHostController } from '../pci/types.js';\nimport {\n\tcreateItemPresentation,\n\ttype CreateItemPresentationOptions,\n\ttype ItemPresentation,\n} from '../presentation/itemPresentationPlan.js';\nimport type {\n\tCompletionStatus,\n\tHtmlContent,\n\tItemLifecycleStatus,\n\tItemSessionActionCommand,\n\tItemSessionActionResult,\n\tItemSessionEngineConfig,\n\tPlayerSecurityConfig,\n\tQTIRole,\n\tSerializedItemSessionState,\n\tSerializedItemSessionVariable,\n} from '../types/index.js';\nimport type { BaseInteractionData } from '../interactions/shared/types.js';\nimport { createPlayerFromPreparedInternal, Player } from './Player.js';\n\nexport interface OpenItemSessionOptions {\n\t/** Restore a previously serialized state before applying response overrides. */\n\trestore?: SerializedItemSessionState;\n\t/** Initial responses, or overrides applied after restore. */\n\tresponses?: Readonly<Record<string, unknown>>;\n\t/** Resume a suspended handoff as an active interaction session. */\n\tactivate?: boolean;\n\t/**\n\t * Values for the item's context variables, e.g. `QTI_CONTEXT`, set before template processing.\n\t * A restored session keeps its saved context values.\n\t */\n\tcontextVariables?: Readonly<Record<string, unknown>>;\n\t/**\n\t * Default values for template variables, set before template processing, as an\n\t * assessmentItemRef's `templateDefault` requires. A restored session keeps its saved values.\n\t */\n\ttemplateDefaults?: Readonly<Record<string, unknown>>;\n\t/** Test-level item session control applied by `present()`. */\n\tpresentation?: ItemSessionPresentationPolicy;\n}\n\nexport interface ItemSessionPresentationPolicy {\n\t/** False hides integrated feedback (`showFeedback=\"false\"`). Defaults to true. */\n\tshowFeedback?: boolean;\n\t/** True shows correct responses once the attempt has ended (`showSolution=\"true\"`). */\n\tshowSolution?: boolean;\n}\n\nexport type ItemSessionCommand =\n\t| ItemSessionActionCommand\n\t| { action: 'setResponse'; responseIdentifier: string; value: unknown }\n\t| { action: 'setResponses'; responses: Readonly<Record<string, unknown>> }\n\t| { action: 'updatePnp'; profile: Partial<PnpProfile> };\n\nexport type ItemSessionEventCommand = ItemSessionCommand | { action: 'dispose' };\n\nexport interface ItemSessionView {\n\treadonly revision: number;\n\treadonly itemIdentifier?: string;\n\treadonly role: QTIRole;\n\treadonly lifecycleStatus: ItemLifecycleStatus;\n\treadonly completionStatus: CompletionStatus;\n\treadonly numAttempts: number;\n\treadonly duration: number;\n\treadonly adaptive: boolean;\n\treadonly completed: boolean;\n\treadonly canSubmit: boolean;\n\treadonly disposed: boolean;\n\treadonly responses: Readonly<Record<string, unknown>>;\n\treadonly outcomes: Readonly<Record<string, unknown>>;\n\treadonly templates: Readonly<Record<string, unknown>>;\n\treadonly context: Readonly<Record<string, unknown>>;\n}\n\nexport interface ItemSessionTransition {\n\treadonly command: ItemSessionEventCommand;\n\treadonly previous: ItemSessionView;\n\treadonly current: ItemSessionView;\n\treadonly result?: ItemSessionActionResult;\n}\n\nexport type ItemSessionListener = (transition: ItemSessionTransition) => void;\n\nexport type ItemPresentationView = Omit<\n\tCreateItemPresentationOptions,\n\t'outcomeValues' | 'responses' | 'role' | 'source' | 'showFeedback' | 'showSolution'\n>;\n\nexport interface ItemSession {\n\tstate(): ItemSessionView;\n\tdispatch(command: ItemSessionCommand): ItemSessionTransition;\n\tpresent(view?: ItemPresentationView): ItemPresentation;\n\tsubscribe(listener: ItemSessionListener): () => void;\n\tserialize(): SerializedItemSessionState;\n\tdispose(): void;\n}\n\n/**\n * Narrow browser/runtime capabilities needed after a presentation has been produced.\n * This interface deliberately excludes Player, parser nodes, declarations, and extraction registries.\n * @internal\n */\nexport interface ItemSessionBinding {\n\treadonly role: QTIRole;\n\tapplyPnp(root: HTMLElement): void;\n\tgetPnp(): PnpProfile | undefined;\n\tonPnpChange(listener: () => void): () => void;\n\tgetCatalogEntry(\n\t\tidref: string,\n\t\tusage: string,\n\t\tlang?: string,\n\t\toptions?: { stimulusIdentifier?: string }\n\t): HtmlContent | null;\n\tgetContentLanguage(): string | undefined;\n\tgetComponentRegistry(): ItemSessionComponentRegistry;\n\tgetDeliveryContext(): ResolvedItemDeliveryContext | undefined;\n\tgetSecurityConfig(): PlayerSecurityConfig | undefined;\n\tgetI18nProvider(): unknown;\n\tcreatePciHost(data: ExtractedPci): PciHostController;\n}\n\n/** @internal */\nexport interface ItemSessionComponentRegistry {\n\tgetTagName(interaction: BaseInteractionData): string;\n\tgetTagNameForType(type: string): string | null;\n}\n\n/**\n * Browser adapters use this without gaining access to the private session engine.\n * @internal\n */\nexport function getItemSessionBinding(session: ItemSession): ItemSessionBinding {\n\tconst runtimeSession = session as ItemSession & {\n\t\tgetRuntimeBinding?: () => ItemSessionBinding;\n\t};\n\tif (typeof runtimeSession.getRuntimeBinding !== 'function') {\n\t\tthrow new Error('ItemSession runtime binding is unavailable');\n\t}\n\treturn runtimeSession.getRuntimeBinding();\n}\n\n/**\n * Construct sessions through AssessmentItemDefinition.openSession().\n * @internal\n */\nexport class LiveItemSession implements ItemSession {\n\tprivate readonly player: Player;\n\tprivate readonly listeners = new Set<ItemSessionListener>();\n\tprivate readonly defaultRole: QTIRole;\n\tprivate readonly presentation: ItemSessionPresentationPolicy;\n\tprivate revision = 0;\n\tprivate disposed = false;\n\tprivate currentView: ItemSessionView;\n\tprivate readonly runtimeBinding: ItemSessionBinding;\n\n\t/** @internal Construct sessions through AssessmentItemDefinition.openSession(). */\n\tconstructor(\n\t\tprivate readonly itemIdentifier: string,\n\t\tconfig: ItemSessionEngineConfig,\n\t\toptions: OpenItemSessionOptions = {},\n\t\tprepared?: unknown,\n\t) {\n\t\tthis.defaultRole = config.role ?? 'candidate';\n\t\tthis.presentation = { ...options.presentation };\n\t\tconst playerConfig = {\n\t\t\t...config,\n\t\t\t...(options.contextVariables ? { contextVariables: options.contextVariables } : {}),\n\t\t\t...(options.templateDefaults ? { templateDefaults: options.templateDefaults } : {}),\n\t\t};\n\t\tthis.player = prepared\n\t\t\t? createPlayerFromPreparedInternal(playerConfig, prepared, Boolean(options.restore))\n\t\t\t: new Player(playerConfig);\n\n\t\ttry {\n\t\t\tif (options.responses) {\n\t\t\t\tthis.assertKnownResponseIdentifiers(Object.keys(options.responses));\n\t\t\t}\n\t\t\tif (options.restore) this.player.restoreItemSession(options.restore);\n\t\t\tif (options.activate && this.player.getLifecycleStatus() === 'suspended') {\n\t\t\t\tthis.player.activateAttempt();\n\t\t\t}\n\t\t\tif (options.responses) {\n\t\t\t\tconst lifecycle = this.player.getLifecycleStatus();\n\t\t\t\tif (!isResponseWritableLifecycle(lifecycle)) {\n\t\t\t\t\tthrow new Error(`Cannot override responses while item session is ${lifecycle}`);\n\t\t\t\t}\n\t\t\t\tthis.player.setResponses({ ...options.responses });\n\t\t\t}\n\t\t\tthis.currentView = this.captureView();\n\t\t} catch (error) {\n\t\t\tthis.player.destroy();\n\t\t\tthrow error;\n\t\t}\n\n\t\tthis.runtimeBinding = this.createBinding();\n\t}\n\n\tstate(): ItemSessionView {\n\t\treturn immutableSnapshot(this.currentView);\n\t}\n\n\tdispatch(command: ItemSessionCommand): ItemSessionTransition {\n\t\tthis.assertActive();\n\t\tif (\n\t\t\tcommandRequiresWritableLifecycle(command) &&\n\t\t\t!isResponseWritableLifecycle(this.currentView.lifecycleStatus)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot ${describeCommand(command)} while item session is ${this.currentView.lifecycleStatus}`\n\t\t\t);\n\t\t}\n\t\tconst previous = this.currentView;\n\t\tlet result: ItemSessionActionResult | undefined;\n\n\t\tswitch (command.action) {\n\t\t\tcase 'setResponse':\n\t\t\t\tthis.assertKnownResponseIdentifiers([command.responseIdentifier]);\n\t\t\t\tthis.player.setResponses({ [command.responseIdentifier]: command.value });\n\t\t\t\tbreak;\n\t\t\tcase 'setResponses':\n\t\t\t\tthis.assertKnownResponseIdentifiers(Object.keys(command.responses));\n\t\t\t\tthis.player.setResponses({ ...command.responses });\n\t\t\t\tbreak;\n\t\t\tcase 'updatePnp':\n\t\t\t\tthis.player.updatePnp(command.profile);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tresult = this.player.runItemSessionAction(command);\n\t\t}\n\n\t\tthis.revision += 1;\n\t\tthis.currentView = this.captureView(result?.sessionState);\n\t\tconst transition = freezeTransition({ command, previous, current: this.currentView, result });\n\t\tthis.notify(transition);\n\t\treturn transition;\n\t}\n\n\tpresent(view: ItemPresentationView = {}): ItemPresentation {\n\t\tthis.assertActive();\n\t\tconst lifecycle = this.currentView.lifecycleStatus;\n\t\tconst attemptEnded = !isResponseWritableLifecycle(lifecycle) && lifecycle !== 'suspended';\n\t\treturn createItemPresentation({\n\t\t\t...view,\n\t\t\tdisabled: view.disabled === true || !isResponseWritableLifecycle(lifecycle),\n\t\t\tshowFeedback: this.presentation.showFeedback !== false,\n\t\t\tshowSolution: this.presentation.showSolution === true && attemptEnded,\n\t\t\tsource: {\n\t\t\t\titemBodyHtml: this.player.getItemBodyHtml(),\n\t\t\t\tcontentLanguage: this.player.getContentLanguage(),\n\t\t\t\tinteractions: this.player.getInteractionData(),\n\t\t\t\tcorrectResponses: this.player.getCorrectResponses(),\n\t\t\t\tcomponentRegistry: this.player.getComponentRegistry(),\n\t\t\t\tdeliveryContext: this.player.getDeliveryContext(),\n\t\t\t\tpnp: this.player.getPnp(),\n\t\t\t\tsecurity: this.player.getSecurityConfig(),\n\t\t\t\tdirectRubrics: this.player.getRubrics({ scope: 'direct' }),\n\t\t\t},\n\t\t\tresponses: immutableSnapshot(this.currentView.responses),\n\t\t\toutcomeValues: immutableSnapshot(this.currentView.outcomes),\n\t\t\trole: this.defaultRole,\n\t\t});\n\t}\n\n\tsubscribe(listener: ItemSessionListener): () => void {\n\t\tthis.assertActive();\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\tserialize(): SerializedItemSessionState {\n\t\tthis.assertActive();\n\t\treturn immutableSnapshot(this.player.saveItemSession());\n\t}\n\n\t/**\n\t * Browser/runtime capabilities carried by the session across package bundles.\n\t * @internal\n\t */\n\tgetRuntimeBinding(): ItemSessionBinding {\n\t\tthis.assertActive();\n\t\treturn this.runtimeBinding;\n\t}\n\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tconst previous = this.currentView;\n\t\tthis.disposed = true;\n\t\tthis.revision += 1;\n\t\tthis.currentView = immutableSnapshot({\n\t\t\t...previous,\n\t\t\trevision: this.revision,\n\t\t\tdisposed: true,\n\t\t});\n\t\tthis.player.destroy();\n\t\tthis.notify(\n\t\t\tfreezeTransition({\n\t\t\t\tcommand: { action: 'dispose' },\n\t\t\t\tprevious,\n\t\t\t\tcurrent: this.currentView,\n\t\t\t})\n\t\t);\n\t\tthis.listeners.clear();\n\t}\n\n\tprivate captureView(serialized = this.player.saveItemSession()): ItemSessionView {\n\t\tconst responses = valuesOf(serialized.responseVariables);\n\t\treturn immutableSnapshot({\n\t\t\trevision: this.revision,\n\t\t\titemIdentifier: serialized.itemIdentifier || this.itemIdentifier || undefined,\n\t\t\trole: this.defaultRole,\n\t\t\tlifecycleStatus: serialized.lifecycleStatus,\n\t\t\tcompletionStatus: serialized.completionStatus,\n\t\t\tnumAttempts: serialized.numAttempts,\n\t\t\tduration: serialized.duration,\n\t\t\tadaptive: this.player.isAdaptive(),\n\t\t\tcompleted: this.player.isCompleted(),\n\t\t\tcanSubmit: this.player.canSubmitResponses(responses),\n\t\t\tdisposed: this.disposed,\n\t\t\tresponses,\n\t\t\toutcomes: valuesOf(serialized.outcomeVariables),\n\t\t\ttemplates: valuesOf(serialized.templateVariables),\n\t\t\tcontext: valuesOf(serialized.contextVariables),\n\t\t});\n\t}\n\n\tprivate createBinding(): ItemSessionBinding {\n\t\treturn Object.freeze({\n\t\t\trole: this.defaultRole,\n\t\t\tapplyPnp: (root: HTMLElement) => {\n\t\t\t\tthis.assertActive();\n\t\t\t\tthis.player.applyPnp(root);\n\t\t\t},\n\t\t\tgetPnp: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getPnp();\n\t\t\t},\n\t\t\tonPnpChange: (listener: () => void) => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.onPnpChange(() => listener());\n\t\t\t},\n\t\t\tgetContentLanguage: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getContentLanguage();\n\t\t\t},\n\t\t\tgetCatalogEntry: (\n\t\t\t\tidref: string,\n\t\t\t\tusage: string,\n\t\t\t\tlang?: string,\n\t\t\t\toptions?: { stimulusIdentifier?: string }\n\t\t\t) => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getCatalogEntry(idref, usage, lang, options);\n\t\t\t},\n\t\t\tgetComponentRegistry: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getComponentRegistry();\n\t\t\t},\n\t\t\tgetDeliveryContext: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getDeliveryContext();\n\t\t\t},\n\t\t\tgetSecurityConfig: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getSecurityConfig();\n\t\t\t},\n\t\t\tgetI18nProvider: () => {\n\t\t\t\tthis.assertActive();\n\t\t\t\treturn this.player.getI18nProvider();\n\t\t\t},\n\t\t\tcreatePciHost: (data: ExtractedPci) => {\n\t\t\t\tthis.assertActive();\n\t\t\t\tconst host = this.player.createPciHost(data);\n\t\t\t\thost.onResponseChange(() => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.disposed ||\n\t\t\t\t\t\t!isResponseWritableLifecycle(this.currentView.lifecycleStatus)\n\t\t\t\t\t) return;\n\t\t\t\t\tconst previous = this.currentView;\n\t\t\t\t\tthis.revision += 1;\n\t\t\t\t\tthis.currentView = this.captureView();\n\t\t\t\t\tthis.notify(\n\t\t\t\t\t\tfreezeTransition({\n\t\t\t\t\t\t\tcommand: {\n\t\t\t\t\t\t\t\taction: 'setResponse',\n\t\t\t\t\t\t\t\tresponseIdentifier: data.responseIdentifier,\n\t\t\t\t\t\t\t\tvalue: host.getResponse(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tprevious,\n\t\t\t\t\t\t\tcurrent: this.currentView,\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\treturn host;\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate notify(transition: ItemSessionTransition): void {\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\ttry {\n\t\t\t\tlistener(immutableSnapshot(transition));\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[QTI ItemSession] subscriber failed:', error);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate assertActive(): void {\n\t\tif (this.disposed) throw new Error('ItemSession has been disposed');\n\t}\n\n\tprivate assertKnownResponseIdentifiers(responseIdentifiers: readonly string[]): void {\n\t\tconst knownIdentifiers = new Set(Object.keys(this.player.getResponses()));\n\t\tconst unknown = responseIdentifiers.find((identifier) => !knownIdentifiers.has(identifier));\n\t\tif (unknown) throw new Error(`Unknown response identifier '${unknown}'`);\n\t}\n}\n\nfunction isResponseWritableLifecycle(status: ItemLifecycleStatus): boolean {\n\treturn status === 'initial' || status === 'interacting';\n}\n\nfunction commandRequiresWritableLifecycle(command: ItemSessionCommand): boolean {\n\treturn command.action === 'setResponse' ||\n\t\tcommand.action === 'setResponses' ||\n\t\tcommand.action === 'suspendAttempt' ||\n\t\tcommand.action === 'endAttempt' ||\n\t\tcommand.action === 'submitAttempt';\n}\n\nfunction describeCommand(command: ItemSessionCommand): string {\n\treturn command.action === 'setResponse' || command.action === 'setResponses'\n\t\t? 'update responses'\n\t\t: `run ${command.action}`;\n}\n\nfunction valuesOf(\n\tvariables: Record<string, SerializedItemSessionVariable>\n): Readonly<Record<string, unknown>> {\n\treturn Object.fromEntries(\n\t\tObject.entries(variables).map(([identifier, variable]) => [\n\t\t\tidentifier,\n\t\t\timmutableSnapshot(variable.value),\n\t\t])\n\t);\n}\n\nfunction freezeTransition(transition: ItemSessionTransition): ItemSessionTransition {\n\treturn immutableSnapshot(transition);\n}\n\n/** Clone and freeze plain data without mutating values owned by the caller or a PCI module. */\nfunction immutableSnapshot<T>(value: T): T {\n\tif (Array.isArray(value)) {\n\t\treturn Object.freeze(value.map((entry) => immutableSnapshot(entry))) as T;\n\t}\n\tif (!value || typeof value !== 'object') return value;\n\tif (ArrayBuffer.isView(value)) return structuredClone(value);\n\tif (value instanceof ArrayBuffer) return value.slice(0) as T;\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) return value;\n\tconst snapshot = Object.fromEntries(\n\t\tObject.entries(value as Record<string, unknown>).map(([key, entry]) => [\n\t\t\tkey,\n\t\t\timmutableSnapshot(entry),\n\t\t])\n\t);\n\treturn Object.freeze(snapshot) as T;\n}\n"]}
@@ -159,8 +159,8 @@ export declare class Player {
159
159
  */
160
160
  private getAttrMapped;
161
161
  /**
162
- * Create a simple fallback i18n provider when none is provided
163
- * This avoids a hard dependency on @pie-qti/i18n
162
+ * The provider used when the host passes none: English, from the catalog
163
+ * `@pie-qti/i18n` bundles eagerly.
164
164
  */
165
165
  private createDefaultI18nProvider;
166
166
  /**
@@ -257,6 +257,8 @@ export declare class Player {
257
257
  * Used by assessment/session controllers to track "answered" state.
258
258
  */
259
259
  isAttempted(responses: Record<string, any>): boolean;
260
+ /** The evaluator's environment, which reads responses in the item's content language. */
261
+ private processingEnv;
260
262
  private execTemplateProcessing;
261
263
  private execResponseProcessingProgram;
262
264
  private execOutcomeProcessingProgram;