@pie-qti/item-player 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/catalog/applyGlossaryTriggers.d.ts +2 -1
  2. package/dist/catalog/applyGlossaryTriggers.d.ts.map +1 -1
  3. package/dist/catalog/applyGlossaryTriggers.js +145 -30
  4. package/dist/catalog/glossaryAction.d.ts.map +1 -1
  5. package/dist/catalog/glossaryAction.js +14 -4
  6. package/dist/components/utils/stimulusRender.d.ts +17 -0
  7. package/dist/components/utils/stimulusRender.d.ts.map +1 -0
  8. package/dist/components/utils/stimulusRender.js +70 -0
  9. package/dist/components/utils/stylesheetRender.d.ts +4 -0
  10. package/dist/components/utils/stylesheetRender.d.ts.map +1 -0
  11. package/dist/components/utils/stylesheetRender.js +57 -0
  12. package/dist/core/Player.d.ts +37 -2
  13. package/dist/core/Player.d.ts.map +1 -1
  14. package/dist/core/Player.js +320 -48
  15. package/dist/element.js +1288 -924
  16. package/dist/element.js.map +1 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/pnp/applyPnp.d.ts.map +1 -1
  20. package/dist/pnp/applyPnp.js +9 -2
  21. package/dist/pnp/parsePnpXml.d.ts.map +1 -1
  22. package/dist/pnp/parsePnpXml.js +91 -3
  23. package/dist/pnp/types.d.ts +24 -1
  24. package/dist/pnp/types.d.ts.map +1 -1
  25. package/dist/types/index.d.ts +47 -0
  26. package/dist/types/index.d.ts.map +1 -1
  27. package/package.json +6 -6
  28. package/src/catalog/applyGlossaryTriggers.ts +174 -34
  29. package/src/catalog/glossaryAction.ts +14 -4
  30. package/src/components/ItemBody.svelte +36 -27
  31. package/src/components/utils/stimulusRender.ts +93 -0
  32. package/src/components/utils/stylesheetRender.ts +58 -0
  33. package/src/core/Player.ts +355 -48
  34. package/src/index.ts +1 -0
  35. package/src/pnp/applyPnp.ts +8 -2
  36. package/src/pnp/parsePnpXml.ts +102 -5
  37. package/src/pnp/types.ts +43 -1
  38. package/src/types/index.ts +53 -0
  39. package/src/__tests__/glossaryTriggers.test.ts +0 -411
  40. package/src/__tests__/pnp.test.ts +0 -250
@@ -1,6 +1,29 @@
1
1
  import type { Player } from '../core/Player.js';
2
-
3
- const PLATFORM_USAGES = new Set(['tts-pronunciation', 'signing-definition', 'braille-text', 'audio-description']);
2
+ import type { CatalogSupportPreference } from '../pnp/types.js';
3
+
4
+ const PLATFORM_USAGES = [
5
+ { usage: 'tts-pronunciation', flag: 'ttsPronunciation', label: 'Request pronunciation', text: 'P' },
6
+ { usage: 'signing-definition', flag: 'signingDefinition', label: 'Request signing definition', text: 'S' },
7
+ { usage: 'braille-text', flag: 'brailleText', label: 'Request braille text', text: 'B' },
8
+ { usage: 'audio-description', flag: 'audioDescription', label: 'Request audio description', text: 'A' },
9
+ { usage: 'extended-description', flag: 'extendedDescription', label: 'Request extended description', text: 'D' },
10
+ ] as const;
11
+ const ILLUSTRATED_GLOSSARY_USAGE = 'illustrated-glossary';
12
+ const BUILT_IN_POPUP_USAGES = new Set<string>([
13
+ 'glossary-on-screen',
14
+ 'keyword-translation',
15
+ ILLUSTRATED_GLOSSARY_USAGE,
16
+ ]);
17
+ const RESERVED_PLATFORM_FLAGS = new Set<string>(PLATFORM_USAGES.map((support) => support.flag));
18
+ const RESERVED_PLATFORM_USAGES = new Set<string>(PLATFORM_USAGES.map((support) => support.usage));
19
+ const SAFE_CATALOG_USAGE = /^[a-z][a-z0-9._-]*$/;
20
+
21
+ interface HostCatalogSupport {
22
+ usage: string;
23
+ label: string;
24
+ text: string;
25
+ languageCode?: string;
26
+ }
4
27
 
5
28
  /**
6
29
  * Inject glossary/keyword-translation trigger buttons into a rendered item container.
@@ -14,18 +37,23 @@ const PLATFORM_USAGES = new Set(['tts-pronunciation', 'signing-definition', 'bra
14
37
  * audio-description) the player fires a `qti-catalog-lookup` CustomEvent instead of
15
38
  * mounting a popup — the host application handles those usages.
16
39
  */
17
- export function applyGlossaryTriggers(container: HTMLElement, player: Player): void {
40
+ export function applyGlossaryTriggers(container: HTMLElement, player: Player): () => void {
41
+ cleanupGlossaryTriggers(container);
18
42
  const pnp = player.getPnp();
19
- if (!pnp) return;
43
+ if (!pnp) return () => cleanupGlossaryTriggers(container);
20
44
 
21
45
  const glossaryOn = pnp.content?.glossaryOnScreen === true;
22
46
  const kwTranslation = pnp.content?.keywordTranslation;
23
47
  const kwOn = kwTranslation?.active === true && !!kwTranslation.languageCode;
48
+ const illustratedOn = pnp.content?.illustratedGlossary === true;
49
+ const platformSupports = pnp.content?.catalogSupports ?? {};
50
+ const hostSupports = getHostCatalogSupports(platformSupports);
24
51
 
25
- if (!glossaryOn && !kwOn) return;
52
+ const anyPlatformOn = PLATFORM_USAGES.some((support) => isSupportActive(getPlatformSupportPreference(platformSupports, support)));
53
+ if (!glossaryOn && !kwOn && !illustratedOn && !anyPlatformOn && hostSupports.length === 0) return () => cleanupGlossaryTriggers(container);
26
54
 
27
55
  const terms = container.querySelectorAll<HTMLElement>('[data-catalog-idref]');
28
- if (terms.length === 0) return;
56
+ if (terms.length === 0) return () => cleanupGlossaryTriggers(container);
29
57
 
30
58
  // Track open popup so only one is open at a time
31
59
  let currentCleanup: (() => void) | null = null;
@@ -33,6 +61,7 @@ export function applyGlossaryTriggers(container: HTMLElement, player: Player): v
33
61
  for (const termEl of Array.from(terms)) {
34
62
  const idref = termEl.getAttribute('data-catalog-idref');
35
63
  if (!idref) continue;
64
+ const stimulusIdentifier = getStimulusIdentifier(termEl);
36
65
 
37
66
  // Wrap term in a relative-positioned span so we can position popup against it
38
67
  const wrapper = document.createElement('span');
@@ -43,7 +72,7 @@ export function applyGlossaryTriggers(container: HTMLElement, player: Player): v
43
72
  wrapper.appendChild(termEl);
44
73
 
45
74
  if (glossaryOn) {
46
- const btn = createTriggerButton(termEl.textContent ?? idref, 'glossary-on-screen');
75
+ const btn = createTriggerButton(termEl.textContent ?? idref, 'glossary-on-screen', 'Show definition');
47
76
  wrapper.appendChild(btn);
48
77
 
49
78
  btn.addEventListener('click', () => {
@@ -52,7 +81,7 @@ export function applyGlossaryTriggers(container: HTMLElement, player: Player): v
52
81
  currentCleanup = null;
53
82
  return;
54
83
  }
55
- const html = player.getCatalogEntry(idref, 'glossary-on-screen');
84
+ const html = player.getCatalogEntry(idref, 'glossary-on-screen', undefined, { stimulusIdentifier });
56
85
  if (html !== null) {
57
86
  currentCleanup = mountPopup(wrapper, termEl.textContent ?? idref, html, btn, player, () => {
58
87
  currentCleanup = null;
@@ -63,7 +92,7 @@ export function applyGlossaryTriggers(container: HTMLElement, player: Player): v
63
92
 
64
93
  if (kwOn) {
65
94
  const lang = kwTranslation!.languageCode;
66
- const btn = createTriggerButton(termEl.textContent ?? idref, 'keyword-translation');
95
+ const btn = createTriggerButton(termEl.textContent ?? idref, 'keyword-translation', 'Show translation');
67
96
  wrapper.appendChild(btn);
68
97
 
69
98
  btn.addEventListener('click', () => {
@@ -72,7 +101,7 @@ export function applyGlossaryTriggers(container: HTMLElement, player: Player): v
72
101
  currentCleanup = null;
73
102
  return;
74
103
  }
75
- const html = player.getCatalogEntry(idref, 'keyword-translation', lang);
104
+ const html = player.getCatalogEntry(idref, 'keyword-translation', lang, { stimulusIdentifier });
76
105
  if (html !== null) {
77
106
  currentCleanup = mountPopup(wrapper, termEl.textContent ?? idref, html, btn, player, () => {
78
107
  currentCleanup = null;
@@ -81,32 +110,140 @@ export function applyGlossaryTriggers(container: HTMLElement, player: Player): v
81
110
  });
82
111
  }
83
112
 
84
- // Platform-level usages: fire event, no popup
85
- for (const usage of PLATFORM_USAGES) {
86
- const html = player.getCatalogEntry(idref, usage);
87
- if (html !== null) {
88
- termEl.dispatchEvent(
89
- new CustomEvent('qti-catalog-lookup', {
90
- bubbles: true,
91
- composed: true,
92
- detail: { idref, usage, html },
93
- })
94
- );
95
- }
113
+ if (illustratedOn) {
114
+ const btn = createTriggerButton(termEl.textContent ?? idref, ILLUSTRATED_GLOSSARY_USAGE, 'Show illustrated glossary');
115
+ wrapper.appendChild(btn);
116
+
117
+ btn.addEventListener('click', () => {
118
+ if (currentCleanup) {
119
+ currentCleanup();
120
+ currentCleanup = null;
121
+ return;
122
+ }
123
+ const html = player.getCatalogEntry(idref, ILLUSTRATED_GLOSSARY_USAGE, undefined, { stimulusIdentifier });
124
+ if (html !== null) {
125
+ currentCleanup = mountPopup(wrapper, termEl.textContent ?? idref, html, btn, player, () => {
126
+ currentCleanup = null;
127
+ });
128
+ }
129
+ });
130
+ }
131
+
132
+ for (const support of PLATFORM_USAGES) {
133
+ const preference = getPlatformSupportPreference(platformSupports, support);
134
+ if (!isSupportActive(preference)) continue;
135
+ addHostCatalogSupportButton(wrapper, termEl, idref, {
136
+ ...support,
137
+ languageCode: getSupportLanguageCode(preference),
138
+ }, player, stimulusIdentifier);
139
+ }
140
+
141
+ for (const support of hostSupports) {
142
+ addHostCatalogSupportButton(wrapper, termEl, idref, support, player, stimulusIdentifier);
96
143
  }
97
144
  }
145
+
146
+ return () => {
147
+ currentCleanup?.();
148
+ cleanupGlossaryTriggers(container);
149
+ };
98
150
  }
99
151
 
100
- function createTriggerButton(termText: string, usage: string): HTMLButtonElement {
152
+ export function cleanupGlossaryTriggers(container: HTMLElement): void {
153
+ for (const wrapper of Array.from(container.querySelectorAll<HTMLElement>('.qti-catalog-term'))) {
154
+ const term = Array.from(wrapper.children).find((child) =>
155
+ (child as HTMLElement).getAttribute?.('data-catalog-idref') !== null
156
+ ) as HTMLElement | undefined;
157
+ if (term && wrapper.parentNode) {
158
+ wrapper.parentNode.insertBefore(term, wrapper);
159
+ }
160
+ wrapper.remove();
161
+ }
162
+ }
163
+
164
+ function createTriggerButton(termText: string, usage: string, labelPrefix: string, text?: string): HTMLButtonElement {
101
165
  const btn = document.createElement('button');
102
166
  btn.type = 'button';
103
167
  btn.className = 'qti-catalog-trigger';
104
- btn.setAttribute('aria-label', `Show definition: ${termText}`);
168
+ btn.style.cssText =
169
+ 'display:inline-flex;align-items:center;justify-content:center;min-width:1.75rem;min-height:1.75rem;margin-inline:0.25rem;line-height:1;';
170
+ btn.setAttribute('aria-label', `${labelPrefix}: ${termText}`);
105
171
  btn.setAttribute('data-catalog-usage', usage);
106
- btn.textContent = usage === 'keyword-translation' ? 'T' : '?';
172
+ btn.textContent = text ?? (usage === 'keyword-translation' ? 'T' : usage === ILLUSTRATED_GLOSSARY_USAGE ? 'I' : '?');
107
173
  return btn;
108
174
  }
109
175
 
176
+ function addHostCatalogSupportButton(
177
+ wrapper: HTMLElement,
178
+ termEl: HTMLElement,
179
+ idref: string,
180
+ support: HostCatalogSupport,
181
+ player: Player,
182
+ stimulusIdentifier?: string
183
+ ): void {
184
+ const html = player.getCatalogEntry(idref, support.usage, support.languageCode, { stimulusIdentifier });
185
+ if (html === null) return;
186
+ const btn = createTriggerButton(termEl.textContent ?? idref, support.usage, support.label, support.text);
187
+ wrapper.appendChild(btn);
188
+ btn.addEventListener('click', () => {
189
+ btn.dispatchEvent(
190
+ new CustomEvent('qti-catalog-lookup', {
191
+ bubbles: true,
192
+ composed: true,
193
+ detail: { idref, usage: support.usage, html, content: html, languageCode: support.languageCode },
194
+ })
195
+ );
196
+ });
197
+ }
198
+
199
+ function getStimulusIdentifier(termEl: HTMLElement): string | undefined {
200
+ const scopeEl = termEl.closest?.('[data-stimulus-idref]');
201
+ const identifier = scopeEl?.getAttribute?.('data-stimulus-idref')?.trim();
202
+ return identifier || undefined;
203
+ }
204
+
205
+ function getHostCatalogSupports(platformSupports: Record<string, CatalogSupportPreference | undefined>): HostCatalogSupport[] {
206
+ return Object.entries(platformSupports)
207
+ .map(([usage, preference]) => ({ usage: normalizeCatalogUsage(usage), preference }))
208
+ .filter(({ usage, preference }) => usage !== null && isSupportActive(preference) && !isReservedCatalogUsage(usage))
209
+ .map(({ usage, preference }) => ({
210
+ usage: usage!,
211
+ label: `Request ${usage!.replace(/[-_]+/g, ' ')}`,
212
+ text: usage!.slice(0, 1).toUpperCase(),
213
+ languageCode: getSupportLanguageCode(preference),
214
+ }));
215
+ }
216
+
217
+ function getPlatformSupportPreference(
218
+ platformSupports: Record<string, CatalogSupportPreference | undefined>,
219
+ support: (typeof PLATFORM_USAGES)[number]
220
+ ): CatalogSupportPreference | undefined {
221
+ return platformSupports[support.flag] ?? platformSupports[support.usage];
222
+ }
223
+
224
+ function isSupportActive(preference: CatalogSupportPreference | undefined): boolean {
225
+ if (preference === undefined) return false;
226
+ if (typeof preference === 'boolean') return preference;
227
+ return preference.active !== false;
228
+ }
229
+
230
+ function getSupportLanguageCode(preference: CatalogSupportPreference | undefined): string | undefined {
231
+ if (!preference || typeof preference === 'boolean') return undefined;
232
+ const languageCode = preference.languageCode?.trim();
233
+ if (!languageCode || !/^[a-zA-Z]{2,8}(?:-[a-zA-Z0-9]{1,8})*$/.test(languageCode)) return undefined;
234
+ return languageCode;
235
+ }
236
+
237
+ function normalizeCatalogUsage(value: string): string | null {
238
+ const usage = value.trim().toLowerCase();
239
+ if (!SAFE_CATALOG_USAGE.test(usage)) return null;
240
+ return usage;
241
+ }
242
+
243
+ function isReservedCatalogUsage(usage: string): boolean {
244
+ return RESERVED_PLATFORM_FLAGS.has(usage) || RESERVED_PLATFORM_USAGES.has(usage) || BUILT_IN_POPUP_USAGES.has(usage);
245
+ }
246
+
110
247
  /**
111
248
  * Mount a catalog popup via the component registry. Falls back to a minimal
112
249
  * vanilla-JS popup if no 'catalogPopup' component is registered (e.g. in tests
@@ -123,6 +260,15 @@ function mountPopup(
123
260
  const registry = player.getComponentRegistry();
124
261
 
125
262
  let popupEl: HTMLElement;
263
+ let closed = false;
264
+
265
+ function cleanup() {
266
+ if (closed) return;
267
+ closed = true;
268
+ popupEl.remove();
269
+ triggerBtn.focus();
270
+ onClose();
271
+ }
126
272
 
127
273
  const catalogPopupTag = registry.getTagNameForType('catalogPopup');
128
274
  if (catalogPopupTag !== null) {
@@ -138,16 +284,10 @@ function mountPopup(
138
284
  popupEl = el;
139
285
  } else {
140
286
  // Minimal fallback for environments without default-components
141
- popupEl = buildFallbackPopup(label, html);
287
+ popupEl = buildFallbackPopup(label, html, cleanup);
142
288
  anchor.appendChild(popupEl);
143
289
  }
144
290
 
145
- function cleanup() {
146
- popupEl.remove();
147
- triggerBtn.focus();
148
- onClose();
149
- }
150
-
151
291
  return cleanup;
152
292
  }
153
293
 
@@ -155,7 +295,7 @@ function mountPopup(
155
295
  * Minimal accessible fallback popup used when no catalogPopup component is registered.
156
296
  * Uses DaisyUI card classes where available; degrades gracefully without them.
157
297
  */
158
- function buildFallbackPopup(label: string, html: string): HTMLElement {
298
+ function buildFallbackPopup(label: string, html: string, close: () => void): HTMLElement {
159
299
  const popup = document.createElement('div');
160
300
  popup.className = 'card card-bordered bg-base-100 shadow-lg qti-catalog-popup';
161
301
  popup.setAttribute('role', 'dialog');
@@ -223,7 +363,7 @@ function buildFallbackPopup(label: string, html: string): HTMLElement {
223
363
  }
224
364
 
225
365
  popup.addEventListener('keydown', handleKeyDown);
226
- closeBtn.addEventListener('click', () => popup.remove());
366
+ closeBtn.addEventListener('click', () => close());
227
367
 
228
368
  // Move focus in on next tick
229
369
  setTimeout(() => closeBtn.focus(), 0);
@@ -14,15 +14,25 @@ export interface GlossaryActionParams {
14
14
  * so the walk always runs on fresh markup.
15
15
  */
16
16
  export function glossaryAction(node: HTMLElement, params: GlossaryActionParams) {
17
- applyGlossaryTriggers(node, params.player);
17
+ let cleanup = applyGlossaryTriggers(node, params.player);
18
+ let unsubscribePnp = params.player.onPnpChange?.(() => {
19
+ cleanup();
20
+ cleanup = applyGlossaryTriggers(node, params.player);
21
+ }) ?? (() => {});
18
22
 
19
23
  return {
20
24
  update(newParams: GlossaryActionParams) {
21
- // {@html} replacement already wiped any previously injected wrappers.
22
- applyGlossaryTriggers(node, newParams.player);
25
+ cleanup();
26
+ unsubscribePnp();
27
+ cleanup = applyGlossaryTriggers(node, newParams.player);
28
+ unsubscribePnp = newParams.player.onPnpChange?.(() => {
29
+ cleanup();
30
+ cleanup = applyGlossaryTriggers(node, newParams.player);
31
+ }) ?? (() => {});
23
32
  },
24
33
  destroy() {
25
- // Node is being removed from DOM — no cleanup needed.
34
+ unsubscribePnp();
35
+ cleanup();
26
36
  },
27
37
  };
28
38
  }
@@ -1,13 +1,23 @@
1
+ <script lang="ts" module>
2
+ let nextItemBodyScopeId = 0;
3
+ </script>
4
+
1
5
  <script lang="ts">
2
6
  import type { InteractionData } from '../types';
3
7
  import type { Player } from '../core/Player';
4
8
  import type { InteractionResponseValue, QTIChangeEventDetail } from '../web-components';
5
9
  import type { I18nProvider } from '@pie-qti/i18n';
6
- import { normalizeHeuristicsConfig, type QtiHeuristicsConfig } from '@pie-qti/ims-cp-core';
10
+ import {
11
+ normalizeHeuristicsConfig,
12
+ type QtiHeuristicsConfig,
13
+ type ResolvedItemDeliveryContext
14
+ } from '@pie-qti/ims-cp-core';
7
15
  import { processFeedbackInline } from './utils/feedbackUtils';
8
16
  import { typesetAction } from './actions/typesetAction';
9
17
  import { glossaryAction } from '../catalog/glossaryAction';
10
18
  import { assignProps } from './utils/assignProps';
19
+ import { buildScopedStylesheetCss } from './utils/stylesheetRender';
20
+ import { buildEffectiveStimulusContent, injectStimulusContent } from './utils/stimulusRender';
11
21
  import { getRoleCapabilities } from '../core/rolePolicy';
12
22
  import InlineChoice from '../interactions/inline-choice/InlineChoice.svelte';
13
23
  import InlineTextEntry from '../interactions/text-entry/InlineTextEntry.svelte';
@@ -29,6 +39,8 @@
29
39
  heuristicsConfig?: QtiHeuristicsConfig; // Optional heuristics configuration
30
40
  /** QTI 3.0 shared stimulus content: map of stimulus identifier → HTML string */
31
41
  stimulusContent?: Record<string, string>;
42
+ /** Package/assessment-resolved QTI 3 delivery context. */
43
+ deliveryContext?: ResolvedItemDeliveryContext;
32
44
  }
33
45
 
34
46
  let {
@@ -42,7 +54,10 @@
42
54
  outcomeValues = {},
43
55
  heuristicsConfig,
44
56
  stimulusContent = {},
57
+ deliveryContext,
45
58
  }: Props = $props();
59
+ const itemBodyScope = `qti-item-body-${++nextItemBodyScopeId}`;
60
+ const itemBodyScopeSelector = `[data-qti-item-body-scope="${itemBodyScope}"]`;
46
61
 
47
62
  // Normalize heuristics configuration with defaults
48
63
  const heuristics = $derived(normalizeHeuristicsConfig(heuristicsConfig));
@@ -89,32 +104,17 @@
89
104
  // Inline interactions are replaced with placeholders
90
105
  const itemBodyHtml = $derived.by(() => {
91
106
  let html = player.getItemBodyHtml();
107
+ const resolvedDeliveryContext = deliveryContext ?? player.getDeliveryContext();
108
+ const stylesheetCss = buildScopedStylesheetCss(resolvedDeliveryContext, itemBodyScopeSelector);
109
+ const effectiveStimulusContent = buildEffectiveStimulusContent(
110
+ resolvedDeliveryContext,
111
+ stimulusContent,
112
+ (content) => player.sanitizeHtmlContent(content)
113
+ );
92
114
 
93
- // QTI 3.0 Shared Stimulus: inject stimulus HTML at data-stimulus-idref docking points.
94
- // Any stimulus identifier that has no docking div is prepended to the body.
95
- if (stimulusContent && Object.keys(stimulusContent).length > 0) {
96
- const docked = new Set<string>();
97
- // Replace docking divs: <div ... data-stimulus-idref="ID" ...></div>
98
- html = html.replace(
99
- /<div([^>]*)\bdata-stimulus-idref="([^"]+)"([^>]*)>\s*<\/div>/gi,
100
- (match, before, identifier, after) => {
101
- const content = stimulusContent[identifier];
102
- if (content) {
103
- docked.add(identifier);
104
- // Preserve any other attributes on the docking div
105
- return `<div${before} data-stimulus-idref="${identifier}"${after} class="qti-stimulus-dock">${content}</div>`;
106
- }
107
- return match; // no content found — leave as-is
108
- }
109
- );
110
- // Prepend any stimuli that had no docking div
111
- const undocked = Object.entries(stimulusContent)
112
- .filter(([id]) => !docked.has(id))
113
- .map(([, content]) => `<div class="qti-stimulus-block">${content}</div>`)
114
- .join('');
115
- if (undocked) {
116
- html = undocked + html;
117
- }
115
+ html = injectStimulusContent(html, effectiveStimulusContent);
116
+ if (stylesheetCss) {
117
+ html = `<style data-qti-stylesheets="resolved">${stylesheetCss}</style>${html}`;
118
118
  }
119
119
 
120
120
  // Process feedbackInline elements - conditionally show/hide based on outcome values
@@ -164,6 +164,7 @@
164
164
  let rootEl: HTMLDivElement | null = $state(null);
165
165
  $effect(() => {
166
166
  if (!rootEl) return;
167
+ player.applyPnp(rootEl);
167
168
  const handler = (e: Event) => handleQtiChange(e as QtiChangeDomEvent);
168
169
  const el = rootEl; // Capture reference for cleanup
169
170
  el.addEventListener('qti-change', handler as EventListener);
@@ -215,7 +216,13 @@
215
216
  }
216
217
  </script>
217
218
 
218
- <div bind:this={rootEl} class="qti-item-body" use:typesetAction={{ typeset }} use:glossaryAction={{ player }}>
219
+ <div
220
+ bind:this={rootEl}
221
+ class="qti-item-body"
222
+ data-qti-item-body-scope={itemBodyScope}
223
+ use:typesetAction={{ typeset }}
224
+ use:glossaryAction={{ player }}
225
+ >
219
226
  <!-- Item body with inline interactions -->
220
227
  <div class="prose max-w-none mb-4">
221
228
  <div class="inline-interaction-container">
@@ -258,6 +265,8 @@
258
265
  interaction,
259
266
  response: responses[interaction.responseId] ?? null,
260
267
  correctResponse: roleCapabilities.canViewCorrectResponses ? correctRespForInteraction : null,
268
+ pnp: player.getPnp(),
269
+ eliminationTool: player.getPnp()?.cognitive?.eliminationTool === true,
261
270
  disabled: effectiveDisabled,
262
271
  // Avoid invalid ARIA role values on custom-element hosts.
263
272
  // Components default to candidate when role is omitted.
@@ -0,0 +1,93 @@
1
+ import type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';
2
+
3
+ export type StimulusSanitizer = (html: string) => string;
4
+
5
+ /**
6
+ * Build the effective stimulus content map for an item render.
7
+ *
8
+ * Resolved delivery-context content is the package/assessment source of truth.
9
+ * Explicit content remains as a compatibility override for older host wiring.
10
+ */
11
+ export function buildEffectiveStimulusContent(
12
+ deliveryContext: ResolvedItemDeliveryContext | undefined,
13
+ explicitStimulusContent: Record<string, string>,
14
+ sanitize: StimulusSanitizer
15
+ ): Record<string, string> {
16
+ const resolved = Object.fromEntries(
17
+ Object.entries(deliveryContext?.stimuli ?? {}).map(([identifier, stimulus]) => [
18
+ identifier,
19
+ sanitize(stimulus.bodyHtml),
20
+ ])
21
+ );
22
+ const explicit = Object.fromEntries(
23
+ Object.entries(explicitStimulusContent).map(([identifier, content]) => [identifier, sanitize(content)])
24
+ );
25
+ return { ...resolved, ...explicit };
26
+ }
27
+
28
+ /**
29
+ * Inject shared stimulus bodies at QTI refs or host-authored docking points.
30
+ *
31
+ * Any resolved stimulus that has no matching docking point is prepended in
32
+ * delivery-context order so undocked package content is still visible.
33
+ */
34
+ export function injectStimulusContent(itemBodyHtml: string, stimulusContent: Record<string, string>): string {
35
+ if (Object.keys(stimulusContent).length === 0) return itemBodyHtml;
36
+
37
+ const docked = new Set<string>();
38
+ let html = itemBodyHtml.replace(
39
+ /<([a-z][\w:-]*)([^>]*\bdata-stimulus-idref=(["'])([^"']+)\3[^>]*)>\s*<\/\1>/gi,
40
+ (match, tagName, attrs, _quote, identifier) => {
41
+ const content = stimulusContent[identifier];
42
+ if (!content) return match;
43
+ docked.add(identifier);
44
+ return `<${tagName}${mergeClassAttribute(attrs, 'qti-stimulus-dock')}>${content}</${tagName}>`;
45
+ }
46
+ );
47
+
48
+ html = html.replace(
49
+ /<qti-assessment-stimulus-ref\b([^>]*)\/?>\s*(?:<\/qti-assessment-stimulus-ref>)?/gi,
50
+ (match, attrs) => {
51
+ const identifier = extractAttribute(attrs, 'identifier');
52
+ if (!identifier) return match;
53
+ if (docked.has(identifier)) return '';
54
+ const content = stimulusContent[identifier];
55
+ if (!content) return match;
56
+ docked.add(identifier);
57
+ return `<div data-stimulus-idref="${escapeHtmlAttribute(identifier)}" class="qti-stimulus-dock">${content}</div>`;
58
+ }
59
+ );
60
+
61
+ const undocked = Object.entries(stimulusContent)
62
+ .filter(([identifier]) => !docked.has(identifier))
63
+ .map(
64
+ ([identifier, content]) =>
65
+ `<div data-stimulus-idref="${escapeHtmlAttribute(identifier)}" class="qti-stimulus-block">${content}</div>`
66
+ )
67
+ .join('');
68
+
69
+ return undocked ? undocked + html : html;
70
+ }
71
+
72
+ function extractAttribute(attrs: string, name: string): string | null {
73
+ const match = attrs.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`, 'i'));
74
+ return match?.[1] ?? null;
75
+ }
76
+
77
+ function mergeClassAttribute(attrs: string, className: string): string {
78
+ const classMatch = attrs.match(/\bclass\s*=\s*(["'])([^"']*)\1/i);
79
+ if (!classMatch) return `${attrs} class="${className}"`;
80
+ const quote = classMatch[1]!;
81
+ const existing = classMatch[2] ?? '';
82
+ const classes = new Set(existing.split(/\s+/).filter(Boolean));
83
+ classes.add(className);
84
+ return attrs.replace(classMatch[0], `class=${quote}${Array.from(classes).join(' ')}${quote}`);
85
+ }
86
+
87
+ function escapeHtmlAttribute(value: string): string {
88
+ return value
89
+ .replace(/&/g, '&amp;')
90
+ .replace(/"/g, '&quot;')
91
+ .replace(/</g, '&lt;')
92
+ .replace(/>/g, '&gt;');
93
+ }
@@ -0,0 +1,58 @@
1
+ import type { ResolvedItemDeliveryContext, ResolvedQtiStylesheetRef } from '@pie-qti/ims-cp-core';
2
+
3
+ const BLOCKED_CSS = /@import\b|url\s*\(|<\/style|expression\s*\(|javascript\s*:|vbscript\s*:|data\s*:/i;
4
+
5
+ export function buildScopedStylesheetCss(
6
+ deliveryContext: ResolvedItemDeliveryContext | undefined,
7
+ scopeSelector = '[data-qti-item-body-scope]'
8
+ ): string {
9
+ if (!deliveryContext) return '';
10
+ return deliveryContext.stylesheets
11
+ .map((stylesheet) => stylesheetToScopedCss(stylesheet, scopeSelector))
12
+ .filter(Boolean)
13
+ .join('\n');
14
+ }
15
+
16
+ function stylesheetToScopedCss(stylesheet: ResolvedQtiStylesheetRef, scopeSelector: string): string {
17
+ const css = stylesheet.cssText?.trim();
18
+ if (!css || BLOCKED_CSS.test(css)) return '';
19
+ const stylesheetScope = getStylesheetScopeSelector(stylesheet, scopeSelector);
20
+ const scoped = scopeCssRules(css, stylesheetScope);
21
+ if (!scoped) return '';
22
+ return scoped;
23
+ }
24
+
25
+ export function scopeCssRules(css: string, scopeSelector = '[data-qti-item-body-scope]'): string {
26
+ const withoutComments = css.replace(/\/\*[\s\S]*?\*\//g, '');
27
+ let scoped = '';
28
+ const rulePattern = /([^{}@]+)\{([^{}]*)\}/g;
29
+ for (const match of withoutComments.matchAll(rulePattern)) {
30
+ const selectorList = match[1]?.trim();
31
+ const declarations = match[2]?.trim();
32
+ if (!selectorList || !declarations) continue;
33
+ const selectors = selectorList
34
+ .split(',')
35
+ .map((selector) => scopeSelectorText(selector.trim(), scopeSelector))
36
+ .filter(Boolean);
37
+ if (selectors.length === 0) continue;
38
+ scoped += `${selectors.join(', ')} { ${declarations} }\n`;
39
+ }
40
+ return scoped.trim();
41
+ }
42
+
43
+ function getStylesheetScopeSelector(stylesheet: ResolvedQtiStylesheetRef, scopeSelector: string): string {
44
+ if (stylesheet.source !== 'stimulus' || !stylesheet.stimulusIdentifier) return scopeSelector;
45
+ return `${scopeSelector} [data-stimulus-idref="${escapeCssString(stylesheet.stimulusIdentifier)}"]`;
46
+ }
47
+
48
+ function scopeSelectorText(selector: string, scopeSelector: string): string {
49
+ if (!selector) return '';
50
+ if (selector.startsWith(scopeSelector)) return selector;
51
+ if (selector === ':root' || selector === 'html' || selector === 'body') return scopeSelector;
52
+ if (selector.startsWith(':')) return `${scopeSelector}${selector}`;
53
+ return `${scopeSelector} ${selector}`;
54
+ }
55
+
56
+ function escapeCssString(value: string): string {
57
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n|\r|\f/g, ' ');
58
+ }