@pie-qti/item-player 1.0.0-beta.3 → 1.0.0-beta.4
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.
- package/dist/{element-class-X2XXDa29.js → element-class-DdpiTalY.js} +2199 -2272
- package/dist/element-class-DdpiTalY.js.map +1 -0
- package/dist/element-class.js +1 -1
- package/dist/element.js +1 -1
- package/dist/extensions/MathLiveEditor.d.ts +1 -1
- package/dist/extensions/MathLiveEditor.js +1 -1
- package/dist/extensions/MathLiveEditor.js.map +1 -1
- package/dist/presentation/itemPresentationPlan.js +1 -1
- package/dist/presentation/itemPresentationPlan.js.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/package.json +5 -9
- package/dist/components/utils/feedbackUtils.d.ts +0 -77
- package/dist/components/utils/feedbackUtils.js +0 -138
- package/dist/components/utils/feedbackUtils.js.map +0 -1
- package/dist/components/utils/index.d.ts +0 -4
- package/dist/components/utils/index.js +0 -5
- package/dist/components/utils/index.js.map +0 -1
- package/dist/element-class-X2XXDa29.js.map +0 -1
package/dist/element-class.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as PieQtiItemPlayerElement } from "./element-class-
|
|
1
|
+
export { t as PieQtiItemPlayerElement } from "./element-class-DdpiTalY.js";
|
package/dist/element.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* Note: MathLive CSS is loaded dynamically to avoid build issues with package exports.
|
|
8
8
|
*/
|
|
9
9
|
import { type I18nProvider } from '@pie-qti/i18n';
|
|
10
|
-
import 'mathlive/
|
|
10
|
+
import 'mathlive/static.css';
|
|
11
11
|
export interface MathLiveEditorOptions {
|
|
12
12
|
/** Called when user confirms the LaTeX input */
|
|
13
13
|
onConfirm: (latex: string) => void;
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { isImeComposing } from '@pie-qti/i18n';
|
|
10
10
|
// Import MathLive CSS from the local package
|
|
11
|
-
import 'mathlive/
|
|
11
|
+
import 'mathlive/static.css';
|
|
12
12
|
const DEFAULT_MATHLIVE_CSS_URL = ''; // No longer needed - CSS is imported above
|
|
13
13
|
// Dynamically import MathLive to register the custom element
|
|
14
14
|
let mathLiveLoaded = null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MathLiveEditor.js","sourceRoot":"","sources":["../../src/extensions/MathLiveEditor.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,cAAc,EAAqB,MAAM,eAAe,CAAC;AAElE,6CAA6C;AAC7C,OAAO,8BAA8B,CAAC;AAEtC,MAAM,wBAAwB,GAAG,EAAE,CAAC,CAAC,2CAA2C;AAEhF,6DAA6D;AAC7D,IAAI,cAAc,GAAyB,IAAI,CAAC;AAEhD,KAAK,UAAU,oBAAoB,CAAC,SAAiB,wBAAwB;IAC5E,IAAI,CAAC,cAAc,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QACtD,cAAc,GAAG,CAAC,KAAK,IAAI,EAAE;YAC5B,8DAA8D;YAC9D,MAAM,MAAM,CAAC,UAAU,CAAC,CAAC;YAEzB,oFAAoF;YACpF,IAAI,MAAM,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,wBAAwB,CAAC,EAAE,CAAC;gBACjE,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;gBAC5C,IAAI,CAAC,GAAG,GAAG,YAAY,CAAC;gBACxB,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC;gBACnB,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;YACjC,CAAC;QACF,CAAC,CAAC,EAAE,CAAC;IACN,CAAC;IACD,OAAO,cAAc,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;AAC5C,CAAC;AAoBD;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,OAA8B;IACtE,MAAM,EAAE,SAAS,EAAE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DAA4D;YAC5D,qDAAqD;YACrD,MAAM,eAAe,GAAG,QAAQ,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC;YAChE,IAAI,CAAC,eAAe,EAAE,CAAC;gBACtB,YAAY,EAAE,CAAC;YAChB,CAAC;QACF,CAAC;IACF,CAAC,CAAC;IAEF,yBAAyB;IACzB,SAAS,CAAC,gBAAgB,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;IAClD,SAAS,CAAC,gBAAgB,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;IACnD,QAAQ,CAAC,gBAAgB,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;IACnD,OAAO,CAAC,gBAAgB,CAAC,OAAO,EAAE,kBAAkB,CAAC,CAAC;IAEtD,yCAAyC;IACzC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAExC,aAAa;IACb,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAEnC,qDAAqD;IACrD,UAAU,CAAC,GAAG,EAAE;QACf,SAAS,CAAC,KAAK,EAAE,CAAC;QAClB,kEAAkE;QAClE,IAAI,CAAC;YACH,SAAiB,CAAC,UAAU,CAAC;gBAC7B,0BAA0B,EAAE,EAAE;aAC9B,CAAC,CAAC;QACJ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACZ,4CAA4C;QAC7C,CAAC;IACF,CAAC,EAAE,GAAG,CAAC,CAAC;IAER,0BAA0B;IAC1B,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["/**\n * MathLive Editor Extension for TipTap\n *\n * Integrates MathLive (visual math editor) with TipTap's Mathematics extension.\n * Provides a modal dialog with MathLive mathfield for editing LaTeX formulas.\n *\n * Note: MathLive CSS is loaded dynamically to avoid build issues with package exports.\n */\n\nimport type { MathfieldElement } from 'mathlive';\nimport { isImeComposing, type I18nProvider } from '@pie-qti/i18n';\n\n// Import MathLive CSS from the local package\nimport 'mathlive/mathlive-static.css';\n\nconst DEFAULT_MATHLIVE_CSS_URL = ''; // No longer needed - CSS is imported above\n\n// Dynamically import MathLive to register the custom element\nlet mathLiveLoaded: Promise<void> | null = null;\n\nasync function ensureMathLiveLoaded(cssUrl: string = DEFAULT_MATHLIVE_CSS_URL): Promise<void> {\n\tif (!mathLiveLoaded && typeof window !== 'undefined') {\n\t\tmathLiveLoaded = (async () => {\n\t\t\t// Import MathLive to register the <math-field> custom element\n\t\t\tawait import('mathlive');\n\n\t\t\t// CSS is already imported at the top of this file, but allow custom URL if provided\n\t\t\tif (cssUrl && !document.querySelector('link[href*=\"mathlive\"]')) {\n\t\t\t\tconst link = document.createElement('link');\n\t\t\t\tlink.rel = 'stylesheet';\n\t\t\t\tlink.href = cssUrl;\n\t\t\t\tdocument.head.appendChild(link);\n\t\t\t}\n\t\t})();\n\t}\n\treturn mathLiveLoaded || Promise.resolve();\n}\n\nexport interface MathLiveEditorOptions {\n\t/** Called when user confirms the LaTeX input */\n\tonConfirm: (latex: string) => void;\n\t/** Called when user cancels */\n\tonCancel: () => void;\n\t/** Initial LaTeX value */\n\tinitialLatex?: string;\n\t/** Whether this is inline or block math */\n\tisBlock?: boolean;\n\t/**\n\t * Optional MathLive stylesheet URL. Defaults to jsdelivr CDN.\n\t * Useful for CSP-restricted deployments (serve from your own domain).\n\t */\n\tcssUrl?: string;\n\t/** Optional i18n provider for translations */\n\ti18n?: I18nProvider;\n}\n\n/**\n * Opens a modal dialog with MathLive editor for LaTeX input\n */\nexport async function openMathLiveEditor(options: MathLiveEditorOptions): Promise<() => void> {\n\tconst { onConfirm, onCancel, initialLatex = '', isBlock = false, cssUrl = DEFAULT_MATHLIVE_CSS_URL, i18n } = options;\n\n\t// Ensure MathLive is loaded and registered before creating the mathfield\n\tawait ensureMathLiveLoaded(cssUrl);\n\n\t// Create modal overlay - use DaisyUI modal classes\n\tconst overlay = document.createElement('div');\n\toverlay.className = 'modal modal-open';\n\toverlay.style.cssText = `\n\t\tposition: fixed;\n\t\tinset: 0;\n\t\tbackground: rgba(0, 0, 0, 0.5);\n\t\tdisplay: flex;\n\t\talign-items: center;\n\t\tjustify-content: center;\n\t\tz-index: 9999;\n\t`;\n\n\t// Create modal dialog - use DaisyUI modal-box class\n\tconst modal = document.createElement('div');\n\tmodal.className = 'modal-box max-w-2xl';\n\tmodal.style.cssText = `\n\t\tpadding: 1.5rem;\n\t\tposition: relative;\n\t\tz-index: 10000;\n\t`;\n\n\t// Create header - use DaisyUI font-bold text-lg\n\tconst header = document.createElement('h3');\n\theader.textContent = isBlock\n\t\t? (i18n?.t('interactions.extendedText.insertBlockMath') ?? 'Insert Block Math')\n\t\t: (i18n?.t('interactions.extendedText.insertInlineMath') ?? 'Insert Inline Math');\n\theader.className = 'font-bold text-lg mb-4';\n\n\t// Create form control wrapper\n\tconst formControl = document.createElement('div');\n\tformControl.className = 'form-control';\n\n\t// Create label for mathfield\n\tconst label = document.createElement('label');\n\tlabel.className = 'label';\n\tconst labelText = document.createElement('span');\n\tlabelText.className = 'label-text';\n\tlabelText.textContent = 'Enter your math expression:';\n\tlabel.appendChild(labelText);\n\n\t// Create MathLive mathfield - style like DaisyUI input\n\tconst mathfield = document.createElement('math-field') as MathfieldElement;\n\tmathfield.value = initialLatex;\n\tmathfield.className = 'input input-bordered w-full';\n\tmathfield.style.cssText = `\n\t\tdisplay: block;\n\t\tmin-height: 100px;\n\t\tpadding: 0.75rem;\n\t\tfont-size: 1.125rem;\n\t`;\n\n\t// Set MathLive options for better UX via attributes\n\t// Use 'manual' mode so keyboard only shows when explicitly requested\n\tmathfield.setAttribute('virtual-keyboard-mode', 'manual');\n\tmathfield.setAttribute('smart-mode', 'on');\n\t// Explicitly enable virtual keyboard\n\tmathfield.setAttribute('use-shared-virtual-keyboard', 'true');\n\t// Hide the built-in virtual keyboard toggle\n\tmathfield.setAttribute('virtual-keyboard-toggle-glyph', '');\n\n\t// Inject CSS to ensure virtual keyboard appears above modal and accepts clicks\n\tconst style = document.createElement('style');\n\tstyle.textContent = `\n\t\t/* Ensure MathLive virtual keyboard appears above the modal and is clickable */\n\t\t.ML__keyboard {\n\t\t\tz-index: 10001 !important;\n\t\t\tpointer-events: auto !important;\n\t\t}\n\t\t/* Hide the built-in keyboard toggle button in the mathfield - try multiple selectors */\n\t\t.ML__virtual-keyboard-toggle,\n\t\t.ML__keyboard-toggle,\n\t\tmath-field::part(virtual-keyboard-toggle) {\n\t\t\tdisplay: none !important;\n\t\t\tvisibility: hidden !important;\n\t\t\topacity: 0 !important;\n\t\t\tpointer-events: none !important;\n\t\t}\n\t`;\n\tdocument.head.appendChild(style);\n\n\t// Create LaTeX preview label\n\tconst previewLabel = document.createElement('label');\n\tpreviewLabel.className = 'label';\n\tconst previewLabelText = document.createElement('span');\n\tpreviewLabelText.className = 'label-text';\n\tpreviewLabelText.textContent = 'LaTeX source:';\n\tpreviewLabel.appendChild(previewLabelText);\n\n\t// Create LaTeX preview/source - use alert info styling\n\tconst latexPreview = document.createElement('div');\n\tlatexPreview.className = 'alert alert-info';\n\tlatexPreview.style.cssText = `\n\t\tfont-family: 'Monaco', 'Courier New', monospace;\n\t\tfont-size: 0.875rem;\n\t\tword-break: break-all;\n\t\tmargin-bottom: 1rem;\n\t`;\n\tlatexPreview.textContent = initialLatex || '(LaTeX will appear here)';\n\n\t// Update preview when mathfield changes\n\tmathfield.addEventListener('input', () => {\n\t\tconst latex = mathfield.value;\n\t\tlatexPreview.textContent = latex || '(LaTeX will appear here)';\n\t});\n\n\t// Create button container - use DaisyUI modal-action class\n\tconst buttons = document.createElement('div');\n\tbuttons.className = 'modal-action';\n\tbuttons.style.cssText = 'justify-content: space-between;';\n\n\t// Create left-side buttons (keyboard toggle)\n\tconst leftButtons = document.createElement('div');\n\tleftButtons.style.cssText = 'display: flex; gap: 0.5rem;';\n\n\t// Create Keyboard Toggle button\n\tconst keyboardBtn = document.createElement('button');\n\tkeyboardBtn.textContent = '⌨️ Keyboard';\n\tkeyboardBtn.type = 'button';\n\tkeyboardBtn.className = 'btn btn-sm btn-outline';\n\tkeyboardBtn.onclick = () => {\n\t\tif (mathfield.executeCommand) {\n\t\t\tmathfield.executeCommand('toggleVirtualKeyboard');\n\t\t}\n\t};\n\n\tleftButtons.appendChild(keyboardBtn);\n\n\t// Create right-side buttons (Cancel/Insert)\n\tconst rightButtons = document.createElement('div');\n\trightButtons.style.cssText = 'display: flex; gap: 0.5rem;';\n\n\t// Create Cancel button - use DaisyUI classes\n\tconst cancelBtn = document.createElement('button');\n\tcancelBtn.textContent = 'Cancel';\n\tcancelBtn.type = 'button';\n\tcancelBtn.className = 'btn btn-ghost';\n\n\t// Create Insert button - use DaisyUI classes\n\tconst insertBtn = document.createElement('button');\n\tinsertBtn.textContent = initialLatex ? 'Update' : 'Insert';\n\tinsertBtn.type = 'button';\n\tinsertBtn.className = 'btn btn-primary';\n\n\trightButtons.appendChild(cancelBtn);\n\trightButtons.appendChild(insertBtn);\n\n\t// Assemble modal\n\tbuttons.appendChild(leftButtons);\n\tbuttons.appendChild(rightButtons);\n\n\t// Assemble form-control\n\tformControl.appendChild(label);\n\tformControl.appendChild(mathfield);\n\tformControl.appendChild(previewLabel);\n\tformControl.appendChild(latexPreview);\n\n\tmodal.appendChild(header);\n\tmodal.appendChild(formControl);\n\tmodal.appendChild(buttons);\n\n\toverlay.appendChild(modal);\n\n\t// Cleanup function\n\tconst cleanup = () => {\n\t\t// Remove event listeners to prevent memory leaks\n\t\tcancelBtn.removeEventListener('click', handleCancel);\n\t\tinsertBtn.removeEventListener('click', handleConfirm);\n\t\tdocument.removeEventListener('keydown', handleEscape);\n\t\toverlay.removeEventListener('click', handleOverlayClick);\n\n\t\t// Hide virtual keyboard before cleanup\n\t\tif (mathfield.executeCommand) {\n\t\t\tmathfield.executeCommand('hideVirtualKeyboard');\n\t\t}\n\n\t\t// Remove DOM elements\n\t\toverlay.remove();\n\t\tstyle.remove();\n\n\t\t// Restore body scroll\n\t\tdocument.body.style.overflow = '';\n\t};\n\n\t// Event handlers\n\tconst handleCancel = () => {\n\t\tcleanup();\n\t\tonCancel();\n\t};\n\n\tconst handleConfirm = () => {\n\t\tconst latex = mathfield.value;\n\t\tcleanup();\n\t\tonConfirm(latex);\n\t};\n\n\tconst handleEscape = (e: KeyboardEvent) => {\n\t\tif (e.key === 'Escape' && !isImeComposing(e)) {\n\t\t\thandleCancel();\n\t\t}\n\t};\n\n\tconst handleOverlayClick = (e: MouseEvent) => {\n\t\t// Don't close if clicking on the modal content or virtual keyboard\n\t\tconst target = e.target as HTMLElement;\n\n\t\t// Check if click is on overlay background (not modal or keyboard)\n\t\tif (target === overlay) {\n\t\t\t// Additional check: don't close if virtual keyboard is open\n\t\t\t// MathLive virtual keyboard has class 'ML__keyboard'\n\t\t\tconst virtualKeyboard = document.querySelector('.ML__keyboard');\n\t\t\tif (!virtualKeyboard) {\n\t\t\t\thandleCancel();\n\t\t\t}\n\t\t}\n\t};\n\n\t// Attach event listeners\n\tcancelBtn.addEventListener('click', handleCancel);\n\tinsertBtn.addEventListener('click', handleConfirm);\n\tdocument.addEventListener('keydown', handleEscape);\n\toverlay.addEventListener('click', handleOverlayClick);\n\n\t// Prevent body scroll when modal is open\n\tdocument.body.style.overflow = 'hidden';\n\n\t// Add to DOM\n\tdocument.body.appendChild(overlay);\n\n\t// Focus the mathfield (but don't auto-show keyboard)\n\tsetTimeout(() => {\n\t\tmathfield.focus();\n\t\t// Try to programmatically disable the built-in toggle via options\n\t\ttry {\n\t\t\t(mathfield as any).setOptions({\n\t\t\t\tvirtualKeyboardToggleGlyph: '',\n\t\t\t});\n\t\t} catch (e) {\n\t\t\t// Silently ignore if this API doesn't exist\n\t\t}\n\t}, 100);\n\n\t// Return cleanup function\n\treturn cleanup;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MathLiveEditor.js","sourceRoot":"","sources":["../../src/extensions/MathLiveEditor.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,cAAc,EAAqB,MAAM,eAAe,CAAC;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,QAAQ,CAAC,gBAAgB,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;IACnD,OAAO,CAAC,gBAAgB,CAAC,OAAO,EAAE,kBAAkB,CAAC,CAAC;IAEtD,yCAAyC;IACzC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAExC,aAAa;IACb,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAEnC,qDAAqD;IACrD,UAAU,CAAC,GAAG,EAAE;QACf,SAAS,CAAC,KAAK,EAAE,CAAC;QAClB,kEAAkE;QAClE,IAAI,CAAC;YACH,SAAiB,CAAC,UAAU,CAAC;gBAC7B,0BAA0B,EAAE,EAAE;aAC9B,CAAC,CAAC;QACJ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACZ,4CAA4C;QAC7C,CAAC;IACF,CAAC,EAAE,GAAG,CAAC,CAAC;IAER,0BAA0B;IAC1B,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["/**\n * MathLive Editor Extension for TipTap\n *\n * Integrates MathLive (visual math editor) with TipTap's Mathematics extension.\n * Provides a modal dialog with MathLive mathfield for editing LaTeX formulas.\n *\n * Note: MathLive CSS is loaded dynamically to avoid build issues with package exports.\n */\n\nimport type { MathfieldElement } from 'mathlive';\nimport { isImeComposing, type I18nProvider } from '@pie-qti/i18n';\n\n// Import MathLive CSS from the local package\nimport 'mathlive/static.css';\n\nconst DEFAULT_MATHLIVE_CSS_URL = ''; // No longer needed - CSS is imported above\n\n// Dynamically import MathLive to register the custom element\nlet mathLiveLoaded: Promise<void> | null = null;\n\nasync function ensureMathLiveLoaded(cssUrl: string = DEFAULT_MATHLIVE_CSS_URL): Promise<void> {\n\tif (!mathLiveLoaded && typeof window !== 'undefined') {\n\t\tmathLiveLoaded = (async () => {\n\t\t\t// Import MathLive to register the <math-field> custom element\n\t\t\tawait import('mathlive');\n\n\t\t\t// CSS is already imported at the top of this file, but allow custom URL if provided\n\t\t\tif (cssUrl && !document.querySelector('link[href*=\"mathlive\"]')) {\n\t\t\t\tconst link = document.createElement('link');\n\t\t\t\tlink.rel = 'stylesheet';\n\t\t\t\tlink.href = cssUrl;\n\t\t\t\tdocument.head.appendChild(link);\n\t\t\t}\n\t\t})();\n\t}\n\treturn mathLiveLoaded || Promise.resolve();\n}\n\nexport interface MathLiveEditorOptions {\n\t/** Called when user confirms the LaTeX input */\n\tonConfirm: (latex: string) => void;\n\t/** Called when user cancels */\n\tonCancel: () => void;\n\t/** Initial LaTeX value */\n\tinitialLatex?: string;\n\t/** Whether this is inline or block math */\n\tisBlock?: boolean;\n\t/**\n\t * Optional MathLive stylesheet URL. Defaults to jsdelivr CDN.\n\t * Useful for CSP-restricted deployments (serve from your own domain).\n\t */\n\tcssUrl?: string;\n\t/** Optional i18n provider for translations */\n\ti18n?: I18nProvider;\n}\n\n/**\n * Opens a modal dialog with MathLive editor for LaTeX input\n */\nexport async function openMathLiveEditor(options: MathLiveEditorOptions): Promise<() => void> {\n\tconst { onConfirm, onCancel, initialLatex = '', isBlock = false, cssUrl = DEFAULT_MATHLIVE_CSS_URL, i18n } = options;\n\n\t// Ensure MathLive is loaded and registered before creating the mathfield\n\tawait ensureMathLiveLoaded(cssUrl);\n\n\t// Create modal overlay - use DaisyUI modal classes\n\tconst overlay = document.createElement('div');\n\toverlay.className = 'modal modal-open';\n\toverlay.style.cssText = `\n\t\tposition: fixed;\n\t\tinset: 0;\n\t\tbackground: rgba(0, 0, 0, 0.5);\n\t\tdisplay: flex;\n\t\talign-items: center;\n\t\tjustify-content: center;\n\t\tz-index: 9999;\n\t`;\n\n\t// Create modal dialog - use DaisyUI modal-box class\n\tconst modal = document.createElement('div');\n\tmodal.className = 'modal-box max-w-2xl';\n\tmodal.style.cssText = `\n\t\tpadding: 1.5rem;\n\t\tposition: relative;\n\t\tz-index: 10000;\n\t`;\n\n\t// Create header - use DaisyUI font-bold text-lg\n\tconst header = document.createElement('h3');\n\theader.textContent = isBlock\n\t\t? (i18n?.t('interactions.extendedText.insertBlockMath') ?? 'Insert Block Math')\n\t\t: (i18n?.t('interactions.extendedText.insertInlineMath') ?? 'Insert Inline Math');\n\theader.className = 'font-bold text-lg mb-4';\n\n\t// Create form control wrapper\n\tconst formControl = document.createElement('div');\n\tformControl.className = 'form-control';\n\n\t// Create label for mathfield\n\tconst label = document.createElement('label');\n\tlabel.className = 'label';\n\tconst labelText = document.createElement('span');\n\tlabelText.className = 'label-text';\n\tlabelText.textContent = 'Enter your math expression:';\n\tlabel.appendChild(labelText);\n\n\t// Create MathLive mathfield - style like DaisyUI input\n\tconst mathfield = document.createElement('math-field') as MathfieldElement;\n\tmathfield.value = initialLatex;\n\tmathfield.className = 'input input-bordered w-full';\n\tmathfield.style.cssText = `\n\t\tdisplay: block;\n\t\tmin-height: 100px;\n\t\tpadding: 0.75rem;\n\t\tfont-size: 1.125rem;\n\t`;\n\n\t// Set MathLive options for better UX via attributes\n\t// Use 'manual' mode so keyboard only shows when explicitly requested\n\tmathfield.setAttribute('virtual-keyboard-mode', 'manual');\n\tmathfield.setAttribute('smart-mode', 'on');\n\t// Explicitly enable virtual keyboard\n\tmathfield.setAttribute('use-shared-virtual-keyboard', 'true');\n\t// Hide the built-in virtual keyboard toggle\n\tmathfield.setAttribute('virtual-keyboard-toggle-glyph', '');\n\n\t// Inject CSS to ensure virtual keyboard appears above modal and accepts clicks\n\tconst style = document.createElement('style');\n\tstyle.textContent = `\n\t\t/* Ensure MathLive virtual keyboard appears above the modal and is clickable */\n\t\t.ML__keyboard {\n\t\t\tz-index: 10001 !important;\n\t\t\tpointer-events: auto !important;\n\t\t}\n\t\t/* Hide the built-in keyboard toggle button in the mathfield - try multiple selectors */\n\t\t.ML__virtual-keyboard-toggle,\n\t\t.ML__keyboard-toggle,\n\t\tmath-field::part(virtual-keyboard-toggle) {\n\t\t\tdisplay: none !important;\n\t\t\tvisibility: hidden !important;\n\t\t\topacity: 0 !important;\n\t\t\tpointer-events: none !important;\n\t\t}\n\t`;\n\tdocument.head.appendChild(style);\n\n\t// Create LaTeX preview label\n\tconst previewLabel = document.createElement('label');\n\tpreviewLabel.className = 'label';\n\tconst previewLabelText = document.createElement('span');\n\tpreviewLabelText.className = 'label-text';\n\tpreviewLabelText.textContent = 'LaTeX source:';\n\tpreviewLabel.appendChild(previewLabelText);\n\n\t// Create LaTeX preview/source - use alert info styling\n\tconst latexPreview = document.createElement('div');\n\tlatexPreview.className = 'alert alert-info';\n\tlatexPreview.style.cssText = `\n\t\tfont-family: 'Monaco', 'Courier New', monospace;\n\t\tfont-size: 0.875rem;\n\t\tword-break: break-all;\n\t\tmargin-bottom: 1rem;\n\t`;\n\tlatexPreview.textContent = initialLatex || '(LaTeX will appear here)';\n\n\t// Update preview when mathfield changes\n\tmathfield.addEventListener('input', () => {\n\t\tconst latex = mathfield.value;\n\t\tlatexPreview.textContent = latex || '(LaTeX will appear here)';\n\t});\n\n\t// Create button container - use DaisyUI modal-action class\n\tconst buttons = document.createElement('div');\n\tbuttons.className = 'modal-action';\n\tbuttons.style.cssText = 'justify-content: space-between;';\n\n\t// Create left-side buttons (keyboard toggle)\n\tconst leftButtons = document.createElement('div');\n\tleftButtons.style.cssText = 'display: flex; gap: 0.5rem;';\n\n\t// Create Keyboard Toggle button\n\tconst keyboardBtn = document.createElement('button');\n\tkeyboardBtn.textContent = '⌨️ Keyboard';\n\tkeyboardBtn.type = 'button';\n\tkeyboardBtn.className = 'btn btn-sm btn-outline';\n\tkeyboardBtn.onclick = () => {\n\t\tif (mathfield.executeCommand) {\n\t\t\tmathfield.executeCommand('toggleVirtualKeyboard');\n\t\t}\n\t};\n\n\tleftButtons.appendChild(keyboardBtn);\n\n\t// Create right-side buttons (Cancel/Insert)\n\tconst rightButtons = document.createElement('div');\n\trightButtons.style.cssText = 'display: flex; gap: 0.5rem;';\n\n\t// Create Cancel button - use DaisyUI classes\n\tconst cancelBtn = document.createElement('button');\n\tcancelBtn.textContent = 'Cancel';\n\tcancelBtn.type = 'button';\n\tcancelBtn.className = 'btn btn-ghost';\n\n\t// Create Insert button - use DaisyUI classes\n\tconst insertBtn = document.createElement('button');\n\tinsertBtn.textContent = initialLatex ? 'Update' : 'Insert';\n\tinsertBtn.type = 'button';\n\tinsertBtn.className = 'btn btn-primary';\n\n\trightButtons.appendChild(cancelBtn);\n\trightButtons.appendChild(insertBtn);\n\n\t// Assemble modal\n\tbuttons.appendChild(leftButtons);\n\tbuttons.appendChild(rightButtons);\n\n\t// Assemble form-control\n\tformControl.appendChild(label);\n\tformControl.appendChild(mathfield);\n\tformControl.appendChild(previewLabel);\n\tformControl.appendChild(latexPreview);\n\n\tmodal.appendChild(header);\n\tmodal.appendChild(formControl);\n\tmodal.appendChild(buttons);\n\n\toverlay.appendChild(modal);\n\n\t// Cleanup function\n\tconst cleanup = () => {\n\t\t// Remove event listeners to prevent memory leaks\n\t\tcancelBtn.removeEventListener('click', handleCancel);\n\t\tinsertBtn.removeEventListener('click', handleConfirm);\n\t\tdocument.removeEventListener('keydown', handleEscape);\n\t\toverlay.removeEventListener('click', handleOverlayClick);\n\n\t\t// Hide virtual keyboard before cleanup\n\t\tif (mathfield.executeCommand) {\n\t\t\tmathfield.executeCommand('hideVirtualKeyboard');\n\t\t}\n\n\t\t// Remove DOM elements\n\t\toverlay.remove();\n\t\tstyle.remove();\n\n\t\t// Restore body scroll\n\t\tdocument.body.style.overflow = '';\n\t};\n\n\t// Event handlers\n\tconst handleCancel = () => {\n\t\tcleanup();\n\t\tonCancel();\n\t};\n\n\tconst handleConfirm = () => {\n\t\tconst latex = mathfield.value;\n\t\tcleanup();\n\t\tonConfirm(latex);\n\t};\n\n\tconst handleEscape = (e: KeyboardEvent) => {\n\t\tif (e.key === 'Escape' && !isImeComposing(e)) {\n\t\t\thandleCancel();\n\t\t}\n\t};\n\n\tconst handleOverlayClick = (e: MouseEvent) => {\n\t\t// Don't close if clicking on the modal content or virtual keyboard\n\t\tconst target = e.target as HTMLElement;\n\n\t\t// Check if click is on overlay background (not modal or keyboard)\n\t\tif (target === overlay) {\n\t\t\t// Additional check: don't close if virtual keyboard is open\n\t\t\t// MathLive virtual keyboard has class 'ML__keyboard'\n\t\t\tconst virtualKeyboard = document.querySelector('.ML__keyboard');\n\t\t\tif (!virtualKeyboard) {\n\t\t\t\thandleCancel();\n\t\t\t}\n\t\t}\n\t};\n\n\t// Attach event listeners\n\tcancelBtn.addEventListener('click', handleCancel);\n\tinsertBtn.addEventListener('click', handleConfirm);\n\tdocument.addEventListener('keydown', handleEscape);\n\toverlay.addEventListener('click', handleOverlayClick);\n\n\t// Prevent body scroll when modal is open\n\tdocument.body.style.overflow = 'hidden';\n\n\t// Add to DOM\n\tdocument.body.appendChild(overlay);\n\n\t// Focus the mathfield (but don't auto-show keyboard)\n\tsetTimeout(() => {\n\t\tmathfield.focus();\n\t\t// Try to programmatically disable the built-in toggle via options\n\t\ttry {\n\t\t\t(mathfield as any).setOptions({\n\t\t\t\tvirtualKeyboardToggleGlyph: '',\n\t\t\t});\n\t\t} catch (e) {\n\t\t\t// Silently ignore if this API doesn't exist\n\t\t}\n\t}, 100);\n\n\t// Return cleanup function\n\treturn cleanup;\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import { parse } from 'node-html-parser';
|
|
|
3
3
|
import { sanitizeHtml } from '../core/sanitizer.js';
|
|
4
4
|
import { htmlToString, toTrustedHtml } from '../core/trustedTypes.js';
|
|
5
5
|
import { getRoleCapabilities } from '../core/rolePolicy.js';
|
|
6
|
-
import { processFeedbackInline } from '
|
|
6
|
+
import { processFeedbackInline } from '@pie-qti/qti-common';
|
|
7
7
|
import { buildScopedStylesheetCss } from '../components/utils/stylesheetRender.js';
|
|
8
8
|
import { buildEffectiveStimulusContent, injectStimulusContent } from '../components/utils/stimulusRender.js';
|
|
9
9
|
import { createInlineRenderPlan, isInlineInteractionTagName, isInlineInteractionType, } from '../interactions/inline/render-plan.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"itemPresentation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GAAG,OAAO,cAAc,EAAE,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;IACvF,OAAO,GAAG,WAAW,CAAC,IAAI,IAAI,WAAW,CAAC,UAAU,IAAI,GAAG,IAAI,MAAM,EAAE,CAAC;AACzE,CAAC","sourcesContent":["import type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\nimport {\n\tnormalizeHeuristicsConfig,\n\ttype QtiHeuristicsConfig,\n} from '@pie-qti/ims-cp-core';\nimport { parse } from 'node-html-parser';\nimport type { HTMLElement as ParsedHtmlElement } from 'node-html-parser';\nimport type { ComponentRegistry } from '../core/ComponentRegistry.js';\nimport { sanitizeHtml } from '../core/sanitizer.js';\nimport { htmlToString, toTrustedHtml } from '../core/trustedTypes.js';\nimport type { PnpProfile } from '../pnp/types.js';\nimport { getRoleCapabilities, type RoleCapabilities } from '../core/rolePolicy.js';\nimport type {\n\tHtmlContent,\n\tPlayerSecurityConfig,\n\tQTIRole,\n\tRubricBlock,\n} from '../types/index.js';\nimport { processFeedbackInline } from '../components/utils/feedbackUtils.js';\nimport { buildScopedStylesheetCss } from '../components/utils/stylesheetRender.js';\nimport { buildEffectiveStimulusContent, injectStimulusContent } from '../components/utils/stimulusRender.js';\nimport {\n\tcreateInlineRenderPlan,\n\tisInlineInteractionTagName,\n\tisInlineInteractionType,\n} from '../interactions/inline/render-plan.js';\nimport type {\n\tBaseInteractionData,\n\tInlineChoiceInteractionData,\n\tTextEntryInteractionData,\n} from '../interactions/shared/types.js';\n\nexport type ItemPresentationResponseValue = unknown;\nexport type ItemPresentationResponseMap = Record<string, ItemPresentationResponseValue>;\n\n/**\n * Immutable inputs captured from the live item session for one presentation pass.\n *\n * This deliberately contains data rather than a Player-shaped adapter. Presentation\n * cannot reach back into the session midway through a render, and its only live seam\n * is the real component registry used to resolve plugin renderers.\n */\nexport interface ItemPresentationSource {\n\titemBodyHtml: HtmlContent;\n\t/** The content's `xml:lang`, when the item declares one. */\n\tcontentLanguage?: string;\n\tinteractions: readonly BaseInteractionData[];\n\tcorrectResponses: Record<string, unknown>;\n\tcomponentRegistry: ComponentRegistry;\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\tpnp?: PnpProfile;\n\tsecurity?: PlayerSecurityConfig;\n\t/** Role-filtered, finalized direct rubrics for host placement. */\n\tdirectRubrics?: readonly RubricBlock[];\n}\n\nexport interface CreateItemPresentationOptions {\n\tsource: ItemPresentationSource;\n\tresponses?: ItemPresentationResponseMap;\n\tdisabled?: boolean;\n\trole?: QTIRole;\n\toutcomeValues?: Record<string, unknown>;\n\theuristicsConfig?: QtiHeuristicsConfig;\n\titemBodyScopeSelector?: string;\n\trenderItemBodyRubrics?: boolean;\n\t/** False drops every feedbackInline and feedbackBlock, as test-level showFeedback=\"false\" requires. */\n\tshowFeedback?: boolean;\n\t/** True exposes correct responses whatever the role, as test-level showSolution requires. */\n\tshowSolution?: boolean;\n\tonComponentError?: (interaction: BaseInteractionData, error: unknown) => void;\n}\n\nexport interface BlockInteractionMount {\n\treadonly placement: 'block';\n\treadonly renderer: 'web-component';\n\treadonly interaction: BaseInteractionData;\n\treadonly tagName: string;\n\treadonly key: string;\n\treadonly response: ItemPresentationResponseValue | null;\n\t/** Lexical companion value used by extendedTextInteraction stringIdentifier. */\n\treadonly stringResponse?: ItemPresentationResponseValue | null;\n\treadonly correctResponse: unknown;\n\treadonly pnp: PnpProfile | undefined;\n\treadonly eliminationTool: boolean;\n\treadonly answerMasking: boolean;\n\t/** Label the interaction's answer set as an ARIA group for assistive technology (G-13). */\n\treadonly structuredLabelSupport: boolean;\n\treadonly disabled: boolean;\n\treadonly componentRole: 'scorer' | undefined;\n}\n\nexport type InlineInteractionMount =\n\t| {\n\t\t\treadonly placement: 'inline';\n\t\t\treadonly renderer: 'text-entry';\n\t\t\treadonly interaction: TextEntryInteractionData;\n\t }\n\t| {\n\t\t\treadonly placement: 'inline';\n\t\t\treadonly renderer: 'inline-choice';\n\t\t\treadonly interaction: InlineChoiceInteractionData;\n\t };\n\nexport type ItemInteractionMount = InlineInteractionMount | BlockInteractionMount;\n\ndeclare const finalItemBodyHtmlBrand: unique symbol;\n\n/** HTML that has completed every body transform, sanitation, and Trusted Types finalization. */\nexport type FinalItemBodyHtml = HtmlContent & {\n\treadonly [finalItemBodyHtmlBrand]: true;\n};\n\nexport type ItemPresentationFlowNode =\n\t| { readonly kind: 'html'; readonly html: FinalItemBodyHtml }\n\t| { readonly kind: 'interaction'; readonly mount: ItemInteractionMount };\n\nexport interface ItemPresentation {\n\treadonly capabilities: RoleCapabilities;\n\treadonly disabled: boolean;\n\t/** The language the item body is written in, for its `lang`; undefined when undeclared. */\n\treadonly contentLanguage?: string;\n\treadonly correctResponses: Readonly<Record<string, unknown>>;\n\t/** Direct assessmentItem rubrics that remain outside the item-body flow. */\n\treadonly directRubrics: readonly RubricBlock[];\n\t/** Ordered, render-neutral body flow. Block mounts follow the authored body HTML. */\n\treadonly flow: readonly ItemPresentationFlowNode[];\n\t/** Policy-checked CSS is kept out of the HTML/Trusted Types pipeline. */\n\treadonly scopedCss: string;\n}\n\nexport function createItemPresentation({\n\tsource,\n\tresponses = {},\n\tdisabled = false,\n\trole = 'candidate',\n\toutcomeValues = {},\n\theuristicsConfig,\n\titemBodyScopeSelector = '[data-qti-item-body-scope]',\n\trenderItemBodyRubrics = true,\n\tshowFeedback = true,\n\tshowSolution = false,\n\tonComponentError,\n}: CreateItemPresentationOptions): ItemPresentation {\n\tconst baseCapabilities = getRoleCapabilities(role);\n\tconst roleCapabilities = showSolution\n\t\t? { ...baseCapabilities, canViewCorrectResponses: true }\n\t\t: baseCapabilities;\n\tconst effectiveDisabled = disabled || roleCapabilities.isReadOnly;\n\tconst correctResponses = roleCapabilities.canViewCorrectResponses ? source.correctResponses : {};\n\tconst { html, scopedCss } = buildItemBodyPresentation({\n\t\tsource,\n\t\trole,\n\t\toutcomeValues,\n\t\theuristicsConfig,\n\t\titemBodyScopeSelector,\n\t\trenderItemBodyRubrics,\n\t\tshowFeedback,\n\t});\n\tconst inlineFlow = createInlineRenderPlan(html, source.interactions).map(\n\t\t(segment): ItemPresentationFlowNode => {\n\t\t\tif (segment.type === 'html') {\n\t\t\t\t// Inline planning parses and reserializes the composed body, so sanitation\n\t\t\t\t// belongs after that final string transform and immediately before TT.\n\t\t\t\tconst sanitized = sanitizeHtml(segment.content, { security: source.security });\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'html',\n\t\t\t\t\thtml: finalizeItemBodyHtml(sanitized, source.security),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (segment.type === 'textEntry') {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'interaction',\n\t\t\t\t\tmount: {\n\t\t\t\t\t\tplacement: 'inline',\n\t\t\t\t\t\trenderer: 'text-entry',\n\t\t\t\t\t\tinteraction: segment.interaction,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: 'interaction',\n\t\t\t\tmount: {\n\t\t\t\t\tplacement: 'inline',\n\t\t\t\t\trenderer: 'inline-choice',\n\t\t\t\t\tinteraction: segment.interaction,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t);\n\tconst blockFlow = createBlockInteractionMounts({\n\t\tinteractions: source.interactions,\n\t\tsource,\n\t\tresponses,\n\t\tcorrectResponses,\n\t\troleCapabilities,\n\t\teffectiveDisabled,\n\t\tonComponentError,\n\t}).map(\n\t\t(mount): ItemPresentationFlowNode => ({\n\t\t\tkind: 'interaction',\n\t\t\tmount,\n\t\t})\n\t);\n\n\treturn freezePresentation({\n\t\tcapabilities: roleCapabilities,\n\t\tdisabled: effectiveDisabled,\n\t\t...(source.contentLanguage ? { contentLanguage: source.contentLanguage } : {}),\n\t\tcorrectResponses,\n\t\tdirectRubrics: source.directRubrics ?? [],\n\t\tflow: [...inlineFlow, ...blockFlow],\n\t\tscopedCss,\n\t});\n}\n\nfunction freezePresentation<T>(value: T): T {\n\tif (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return value;\n\tObject.freeze(value);\n\tfor (const child of Object.values(value as Record<string, unknown>)) {\n\t\tfreezePresentation(child);\n\t}\n\treturn value;\n}\n\nfunction buildItemBodyPresentation({\n\tsource,\n\trole,\n\toutcomeValues,\n\theuristicsConfig,\n\titemBodyScopeSelector,\n\trenderItemBodyRubrics,\n\tshowFeedback,\n}: {\n\tsource: ItemPresentationSource;\n\trole: QTIRole;\n\toutcomeValues: Record<string, unknown>;\n\theuristicsConfig: QtiHeuristicsConfig | undefined;\n\titemBodyScopeSelector: string;\n\trenderItemBodyRubrics: boolean;\n\tshowFeedback: boolean;\n}): { html: string; scopedCss: string } {\n\tlet html = htmlToString(source.itemBodyHtml);\n\tconst scopedCss = buildScopedStylesheetCss(source.deliveryContext, itemBodyScopeSelector);\n\tconst effectiveStimulusContent = buildEffectiveStimulusContent(\n\t\tsource.deliveryContext,\n\t\t(content) => sanitizeHtml(content, { security: source.security })\n\t);\n\n\thtml = injectStimulusContent(html, effectiveStimulusContent);\n\thtml = renderRubricBlocksForRole(html, role, { renderRubrics: renderItemBodyRubrics });\n\n\tconst heuristics = normalizeHeuristicsConfig(heuristicsConfig);\n\thtml = processFeedbackInline(html, {\n\t\toutcomeValues,\n\t\tapplyHeuristics: heuristics.feedbackTextFormatting,\n\t\twrapWithSpan: false,\n\t\thideAll: !showFeedback,\n\t});\n\n\treturn { html: hideBlockInteractionMarkup(html), scopedCss };\n}\n\nfunction finalizeItemBodyHtml(\n\thtml: string,\n\tsecurity: PlayerSecurityConfig | undefined\n): FinalItemBodyHtml {\n\treturn toTrustedHtml(html, security?.trustedTypesPolicyName) as FinalItemBodyHtml;\n}\n\nfunction renderRubricBlocksForRole(\n\thtml: string,\n\trole: QTIRole,\n\t{ renderRubrics }: { renderRubrics: boolean }\n): string {\n\tif (!html || !/rubric-?block/i.test(html)) {\n\t\treturn html;\n\t}\n\n\ttry {\n\t\tconst root = parse(html, { lowerCaseTagName: false, comment: false });\n\t\trenderRubricBlockChildren(root as unknown as ParsedHtmlElement, role, { renderRubrics });\n\t\treturn root.toString();\n\t} catch {\n\t\treturn html;\n\t}\n}\n\nfunction renderRubricBlockChildren(\n\telement: ParsedHtmlElement,\n\trole: QTIRole,\n\t{ renderRubrics }: { renderRubrics: boolean }\n): void {\n\tconst children = [...element.childNodes] as unknown as ParsedHtmlElement[];\n\tfor (const child of children) {\n\t\tconst tagName = child.rawTagName?.toLowerCase();\n\t\tif (\n\t\t\ttagName &&\n\t\t\tisRubricBlockTag(tagName) &&\n\t\t\t(!renderRubrics || !rubricBlockVisibleToRole(child, role))\n\t\t) {\n\t\t\tchild.remove();\n\t\t\tcontinue;\n\t\t}\n\t\tif (child.childNodes?.length) {\n\t\t\trenderRubricBlockChildren(child, role, { renderRubrics });\n\t\t}\n\t\tif (tagName && isRubricBlockTag(tagName)) {\n\t\t\tchild.replaceWith(renderRubricBlockWrapper(child));\n\t\t}\n\t}\n}\n\nfunction isRubricBlockTag(tagName: string): boolean {\n\treturn tagName === 'rubricblock' || tagName === 'qti-rubric-block';\n}\n\nfunction rubricBlockVisibleToRole(element: ParsedHtmlElement, role: QTIRole): boolean {\n\tconst view = element.getAttribute('view')?.trim();\n\tif (!view) {\n\t\treturn true;\n\t}\n\treturn splitRubricView(view).includes(role);\n}\n\nfunction renderRubricBlockWrapper(element: ParsedHtmlElement): string {\n\tconst view = element.getAttribute('view')?.trim();\n\tconst use = element.getAttribute('use')?.trim();\n\tconst attrs = [\n\t\t'class=\"qti-rubric-block\"',\n\t\tview ? `data-qti-rubric-view=\"${escapeHtmlAttribute(view)}\"` : '',\n\t\tuse ? `data-qti-rubric-use=\"${escapeHtmlAttribute(use)}\"` : '',\n\t]\n\t\t.filter(Boolean)\n\t\t.join(' ');\n\treturn `<div ${attrs}>${serializeHtmlChildren(element)}</div>`;\n}\n\nfunction splitRubricView(view: string): string[] {\n\treturn view.split(/[\\s,]+/).filter(Boolean);\n}\n\nfunction serializeHtmlChildren(element: ParsedHtmlElement): string {\n\treturn ([...element.childNodes] as unknown as ParsedHtmlElement[])\n\t\t.map((child) => child.toString())\n\t\t.join('');\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n\treturn value\n\t\t.replace(/&/g, '&')\n\t\t.replace(/\"/g, '"')\n\t\t.replace(/</g, '<')\n\t\t.replace(/>/g, '>');\n}\n\nfunction hideBlockInteractionMarkup(html: string): string {\n\t// positionObjectStage is hidden as a unit: it owns the background object and wraps its\n\t// interactions, all of which the component renders. Matching only the interaction inside it\n\t// would leave the stage's background image visible in the item body as well.\n\treturn html.replace(\n\t\t/<(\\w+Interaction|qti-[\\w-]+-interaction|positionObjectStage|qti-position-object-stage)(\\s[^>]*)?>[\\s\\S]*?<\\/\\1>/gi,\n\t\t(match, tagName) => {\n\t\t\tconst lower = tagName.toLowerCase();\n\t\t\tif (isInlineInteractionTagName(lower)) return match;\n\t\t\treturn `<span class=\"qti-hidden-interaction\">${match}</span>`;\n\t\t}\n\t);\n}\n\nfunction createBlockInteractionMounts({\n\tinteractions,\n\tsource,\n\tresponses,\n\tcorrectResponses,\n\troleCapabilities,\n\teffectiveDisabled,\n\tonComponentError,\n}: {\n\tinteractions: readonly BaseInteractionData[];\n\tsource: ItemPresentationSource;\n\tresponses: ItemPresentationResponseMap;\n\tcorrectResponses: Record<string, unknown>;\n\troleCapabilities: RoleCapabilities;\n\teffectiveDisabled: boolean;\n\tonComponentError?: (interaction: BaseInteractionData, error: unknown) => void;\n}): BlockInteractionMount[] {\n\treturn interactions\n\t\t.filter((interaction) => !isInlineInteractionType(interaction.type))\n\t\t.map((interaction) => {\n\t\t\ttry {\n\t\t\t\tconst stringIdentifier =\n\t\t\t\t\t'stringIdentifier' in interaction && typeof interaction.stringIdentifier === 'string'\n\t\t\t\t\t\t? interaction.stringIdentifier\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst block: BlockInteractionMount = {\n\t\t\t\t\tplacement: 'block',\n\t\t\t\t\trenderer: 'web-component',\n\t\t\t\t\tinteraction,\n\t\t\t\t\ttagName: source.componentRegistry.getTagName(interaction),\n\t\t\t\t\tkey: interactionKey(interaction),\n\t\t\t\t\tresponse: responses[interaction.responseId] ?? null,\n\t\t\t\t\t...(stringIdentifier\n\t\t\t\t\t\t? { stringResponse: responses[stringIdentifier] ?? null }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\tcorrectResponse: roleCapabilities.canViewCorrectResponses\n\t\t\t\t\t\t? (correctResponses[interaction.responseId] ?? null)\n\t\t\t\t\t\t: null,\n\t\t\t\t\tpnp: source.pnp,\n\t\t\t\t\teliminationTool: source.pnp?.cognitive?.eliminationTool === true,\n\t\t\t\t\tanswerMasking: source.pnp?.cognitive?.answerMasking === true,\n\t\t\t\t\tstructuredLabelSupport: source.pnp?.display?.structuredLabelSupport === true,\n\t\t\t\t\tdisabled: effectiveDisabled,\n\t\t\t\t\tcomponentRole: roleCapabilities.canViewCorrectResponses ? 'scorer' : undefined,\n\t\t\t\t};\n\t\t\t\treturn block;\n\t\t\t} catch (error) {\n\t\t\t\tonComponentError?.(interaction, error);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t})\n\t\t.filter((item): item is BlockInteractionMount => item !== null);\n}\n\nexport function interactionKey(interaction: BaseInteractionData): string {\n\tconst anyInteraction = interaction as any;\n\tconst ids =\n\t\tArray.isArray(anyInteraction?.choices) && anyInteraction.choices.length > 0\n\t\t\t? anyInteraction.choices.map((choice: any) => choice?.identifier).filter(Boolean).join(',')\n\t\t\t: '';\n\tconst prompt = typeof anyInteraction?.prompt === 'string' ? anyInteraction.prompt : '';\n\treturn `${interaction.type}|${interaction.responseId}|${ids}|${prompt}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"itemPresentationPlan.js","sourceRoot":"","sources":["../../src/presentation/itemPresentationPlan.ts"],"names":[],"mappings":"AACA,OAAO,EACN,y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CAAC,CAAC,CAAC,EAAE,CAAC;IACvF,OAAO,GAAG,WAAW,CAAC,IAAI,IAAI,WAAW,CAAC,UAAU,IAAI,GAAG,IAAI,MAAM,EAAE,CAAC;AACzE,CAAC","sourcesContent":["import type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\nimport {\n\tnormalizeHeuristicsConfig,\n\ttype QtiHeuristicsConfig,\n} from '@pie-qti/ims-cp-core';\nimport { parse } from 'node-html-parser';\nimport type { HTMLElement as ParsedHtmlElement } from 'node-html-parser';\nimport type { ComponentRegistry } from '../core/ComponentRegistry.js';\nimport { sanitizeHtml } from '../core/sanitizer.js';\nimport { htmlToString, toTrustedHtml } from '../core/trustedTypes.js';\nimport type { PnpProfile } from '../pnp/types.js';\nimport { getRoleCapabilities, type RoleCapabilities } from '../core/rolePolicy.js';\nimport type {\n\tHtmlContent,\n\tPlayerSecurityConfig,\n\tQTIRole,\n\tRubricBlock,\n} from '../types/index.js';\nimport { processFeedbackInline } from '@pie-qti/qti-common';\nimport { buildScopedStylesheetCss } from '../components/utils/stylesheetRender.js';\nimport { buildEffectiveStimulusContent, injectStimulusContent } from '../components/utils/stimulusRender.js';\nimport {\n\tcreateInlineRenderPlan,\n\tisInlineInteractionTagName,\n\tisInlineInteractionType,\n} from '../interactions/inline/render-plan.js';\nimport type {\n\tBaseInteractionData,\n\tInlineChoiceInteractionData,\n\tTextEntryInteractionData,\n} from '../interactions/shared/types.js';\n\nexport type ItemPresentationResponseValue = unknown;\nexport type ItemPresentationResponseMap = Record<string, ItemPresentationResponseValue>;\n\n/**\n * Immutable inputs captured from the live item session for one presentation pass.\n *\n * This deliberately contains data rather than a Player-shaped adapter. Presentation\n * cannot reach back into the session midway through a render, and its only live seam\n * is the real component registry used to resolve plugin renderers.\n */\nexport interface ItemPresentationSource {\n\titemBodyHtml: HtmlContent;\n\t/** The content's `xml:lang`, when the item declares one. */\n\tcontentLanguage?: string;\n\tinteractions: readonly BaseInteractionData[];\n\tcorrectResponses: Record<string, unknown>;\n\tcomponentRegistry: ComponentRegistry;\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\tpnp?: PnpProfile;\n\tsecurity?: PlayerSecurityConfig;\n\t/** Role-filtered, finalized direct rubrics for host placement. */\n\tdirectRubrics?: readonly RubricBlock[];\n}\n\nexport interface CreateItemPresentationOptions {\n\tsource: ItemPresentationSource;\n\tresponses?: ItemPresentationResponseMap;\n\tdisabled?: boolean;\n\trole?: QTIRole;\n\toutcomeValues?: Record<string, unknown>;\n\theuristicsConfig?: QtiHeuristicsConfig;\n\titemBodyScopeSelector?: string;\n\trenderItemBodyRubrics?: boolean;\n\t/** False drops every feedbackInline and feedbackBlock, as test-level showFeedback=\"false\" requires. */\n\tshowFeedback?: boolean;\n\t/** True exposes correct responses whatever the role, as test-level showSolution requires. */\n\tshowSolution?: boolean;\n\tonComponentError?: (interaction: BaseInteractionData, error: unknown) => void;\n}\n\nexport interface BlockInteractionMount {\n\treadonly placement: 'block';\n\treadonly renderer: 'web-component';\n\treadonly interaction: BaseInteractionData;\n\treadonly tagName: string;\n\treadonly key: string;\n\treadonly response: ItemPresentationResponseValue | null;\n\t/** Lexical companion value used by extendedTextInteraction stringIdentifier. */\n\treadonly stringResponse?: ItemPresentationResponseValue | null;\n\treadonly correctResponse: unknown;\n\treadonly pnp: PnpProfile | undefined;\n\treadonly eliminationTool: boolean;\n\treadonly answerMasking: boolean;\n\t/** Label the interaction's answer set as an ARIA group for assistive technology (G-13). */\n\treadonly structuredLabelSupport: boolean;\n\treadonly disabled: boolean;\n\treadonly componentRole: 'scorer' | undefined;\n}\n\nexport type InlineInteractionMount =\n\t| {\n\t\t\treadonly placement: 'inline';\n\t\t\treadonly renderer: 'text-entry';\n\t\t\treadonly interaction: TextEntryInteractionData;\n\t }\n\t| {\n\t\t\treadonly placement: 'inline';\n\t\t\treadonly renderer: 'inline-choice';\n\t\t\treadonly interaction: InlineChoiceInteractionData;\n\t };\n\nexport type ItemInteractionMount = InlineInteractionMount | BlockInteractionMount;\n\ndeclare const finalItemBodyHtmlBrand: unique symbol;\n\n/** HTML that has completed every body transform, sanitation, and Trusted Types finalization. */\nexport type FinalItemBodyHtml = HtmlContent & {\n\treadonly [finalItemBodyHtmlBrand]: true;\n};\n\nexport type ItemPresentationFlowNode =\n\t| { readonly kind: 'html'; readonly html: FinalItemBodyHtml }\n\t| { readonly kind: 'interaction'; readonly mount: ItemInteractionMount };\n\nexport interface ItemPresentation {\n\treadonly capabilities: RoleCapabilities;\n\treadonly disabled: boolean;\n\t/** The language the item body is written in, for its `lang`; undefined when undeclared. */\n\treadonly contentLanguage?: string;\n\treadonly correctResponses: Readonly<Record<string, unknown>>;\n\t/** Direct assessmentItem rubrics that remain outside the item-body flow. */\n\treadonly directRubrics: readonly RubricBlock[];\n\t/** Ordered, render-neutral body flow. Block mounts follow the authored body HTML. */\n\treadonly flow: readonly ItemPresentationFlowNode[];\n\t/** Policy-checked CSS is kept out of the HTML/Trusted Types pipeline. */\n\treadonly scopedCss: string;\n}\n\nexport function createItemPresentation({\n\tsource,\n\tresponses = {},\n\tdisabled = false,\n\trole = 'candidate',\n\toutcomeValues = {},\n\theuristicsConfig,\n\titemBodyScopeSelector = '[data-qti-item-body-scope]',\n\trenderItemBodyRubrics = true,\n\tshowFeedback = true,\n\tshowSolution = false,\n\tonComponentError,\n}: CreateItemPresentationOptions): ItemPresentation {\n\tconst baseCapabilities = getRoleCapabilities(role);\n\tconst roleCapabilities = showSolution\n\t\t? { ...baseCapabilities, canViewCorrectResponses: true }\n\t\t: baseCapabilities;\n\tconst effectiveDisabled = disabled || roleCapabilities.isReadOnly;\n\tconst correctResponses = roleCapabilities.canViewCorrectResponses ? source.correctResponses : {};\n\tconst { html, scopedCss } = buildItemBodyPresentation({\n\t\tsource,\n\t\trole,\n\t\toutcomeValues,\n\t\theuristicsConfig,\n\t\titemBodyScopeSelector,\n\t\trenderItemBodyRubrics,\n\t\tshowFeedback,\n\t});\n\tconst inlineFlow = createInlineRenderPlan(html, source.interactions).map(\n\t\t(segment): ItemPresentationFlowNode => {\n\t\t\tif (segment.type === 'html') {\n\t\t\t\t// Inline planning parses and reserializes the composed body, so sanitation\n\t\t\t\t// belongs after that final string transform and immediately before TT.\n\t\t\t\tconst sanitized = sanitizeHtml(segment.content, { security: source.security });\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'html',\n\t\t\t\t\thtml: finalizeItemBodyHtml(sanitized, source.security),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (segment.type === 'textEntry') {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'interaction',\n\t\t\t\t\tmount: {\n\t\t\t\t\t\tplacement: 'inline',\n\t\t\t\t\t\trenderer: 'text-entry',\n\t\t\t\t\t\tinteraction: segment.interaction,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: 'interaction',\n\t\t\t\tmount: {\n\t\t\t\t\tplacement: 'inline',\n\t\t\t\t\trenderer: 'inline-choice',\n\t\t\t\t\tinteraction: segment.interaction,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t);\n\tconst blockFlow = createBlockInteractionMounts({\n\t\tinteractions: source.interactions,\n\t\tsource,\n\t\tresponses,\n\t\tcorrectResponses,\n\t\troleCapabilities,\n\t\teffectiveDisabled,\n\t\tonComponentError,\n\t}).map(\n\t\t(mount): ItemPresentationFlowNode => ({\n\t\t\tkind: 'interaction',\n\t\t\tmount,\n\t\t})\n\t);\n\n\treturn freezePresentation({\n\t\tcapabilities: roleCapabilities,\n\t\tdisabled: effectiveDisabled,\n\t\t...(source.contentLanguage ? { contentLanguage: source.contentLanguage } : {}),\n\t\tcorrectResponses,\n\t\tdirectRubrics: source.directRubrics ?? [],\n\t\tflow: [...inlineFlow, ...blockFlow],\n\t\tscopedCss,\n\t});\n}\n\nfunction freezePresentation<T>(value: T): T {\n\tif (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return value;\n\tObject.freeze(value);\n\tfor (const child of Object.values(value as Record<string, unknown>)) {\n\t\tfreezePresentation(child);\n\t}\n\treturn value;\n}\n\nfunction buildItemBodyPresentation({\n\tsource,\n\trole,\n\toutcomeValues,\n\theuristicsConfig,\n\titemBodyScopeSelector,\n\trenderItemBodyRubrics,\n\tshowFeedback,\n}: {\n\tsource: ItemPresentationSource;\n\trole: QTIRole;\n\toutcomeValues: Record<string, unknown>;\n\theuristicsConfig: QtiHeuristicsConfig | undefined;\n\titemBodyScopeSelector: string;\n\trenderItemBodyRubrics: boolean;\n\tshowFeedback: boolean;\n}): { html: string; scopedCss: string } {\n\tlet html = htmlToString(source.itemBodyHtml);\n\tconst scopedCss = buildScopedStylesheetCss(source.deliveryContext, itemBodyScopeSelector);\n\tconst effectiveStimulusContent = buildEffectiveStimulusContent(\n\t\tsource.deliveryContext,\n\t\t(content) => sanitizeHtml(content, { security: source.security })\n\t);\n\n\thtml = injectStimulusContent(html, effectiveStimulusContent);\n\thtml = renderRubricBlocksForRole(html, role, { renderRubrics: renderItemBodyRubrics });\n\n\tconst heuristics = normalizeHeuristicsConfig(heuristicsConfig);\n\thtml = processFeedbackInline(html, {\n\t\toutcomeValues,\n\t\tapplyHeuristics: heuristics.feedbackTextFormatting,\n\t\twrapWithSpan: false,\n\t\thideAll: !showFeedback,\n\t});\n\n\treturn { html: hideBlockInteractionMarkup(html), scopedCss };\n}\n\nfunction finalizeItemBodyHtml(\n\thtml: string,\n\tsecurity: PlayerSecurityConfig | undefined\n): FinalItemBodyHtml {\n\treturn toTrustedHtml(html, security?.trustedTypesPolicyName) as FinalItemBodyHtml;\n}\n\nfunction renderRubricBlocksForRole(\n\thtml: string,\n\trole: QTIRole,\n\t{ renderRubrics }: { renderRubrics: boolean }\n): string {\n\tif (!html || !/rubric-?block/i.test(html)) {\n\t\treturn html;\n\t}\n\n\ttry {\n\t\tconst root = parse(html, { lowerCaseTagName: false, comment: false });\n\t\trenderRubricBlockChildren(root as unknown as ParsedHtmlElement, role, { renderRubrics });\n\t\treturn root.toString();\n\t} catch {\n\t\treturn html;\n\t}\n}\n\nfunction renderRubricBlockChildren(\n\telement: ParsedHtmlElement,\n\trole: QTIRole,\n\t{ renderRubrics }: { renderRubrics: boolean }\n): void {\n\tconst children = [...element.childNodes] as unknown as ParsedHtmlElement[];\n\tfor (const child of children) {\n\t\tconst tagName = child.rawTagName?.toLowerCase();\n\t\tif (\n\t\t\ttagName &&\n\t\t\tisRubricBlockTag(tagName) &&\n\t\t\t(!renderRubrics || !rubricBlockVisibleToRole(child, role))\n\t\t) {\n\t\t\tchild.remove();\n\t\t\tcontinue;\n\t\t}\n\t\tif (child.childNodes?.length) {\n\t\t\trenderRubricBlockChildren(child, role, { renderRubrics });\n\t\t}\n\t\tif (tagName && isRubricBlockTag(tagName)) {\n\t\t\tchild.replaceWith(renderRubricBlockWrapper(child));\n\t\t}\n\t}\n}\n\nfunction isRubricBlockTag(tagName: string): boolean {\n\treturn tagName === 'rubricblock' || tagName === 'qti-rubric-block';\n}\n\nfunction rubricBlockVisibleToRole(element: ParsedHtmlElement, role: QTIRole): boolean {\n\tconst view = element.getAttribute('view')?.trim();\n\tif (!view) {\n\t\treturn true;\n\t}\n\treturn splitRubricView(view).includes(role);\n}\n\nfunction renderRubricBlockWrapper(element: ParsedHtmlElement): string {\n\tconst view = element.getAttribute('view')?.trim();\n\tconst use = element.getAttribute('use')?.trim();\n\tconst attrs = [\n\t\t'class=\"qti-rubric-block\"',\n\t\tview ? `data-qti-rubric-view=\"${escapeHtmlAttribute(view)}\"` : '',\n\t\tuse ? `data-qti-rubric-use=\"${escapeHtmlAttribute(use)}\"` : '',\n\t]\n\t\t.filter(Boolean)\n\t\t.join(' ');\n\treturn `<div ${attrs}>${serializeHtmlChildren(element)}</div>`;\n}\n\nfunction splitRubricView(view: string): string[] {\n\treturn view.split(/[\\s,]+/).filter(Boolean);\n}\n\nfunction serializeHtmlChildren(element: ParsedHtmlElement): string {\n\treturn ([...element.childNodes] as unknown as ParsedHtmlElement[])\n\t\t.map((child) => child.toString())\n\t\t.join('');\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n\treturn value\n\t\t.replace(/&/g, '&')\n\t\t.replace(/\"/g, '"')\n\t\t.replace(/</g, '<')\n\t\t.replace(/>/g, '>');\n}\n\nfunction hideBlockInteractionMarkup(html: string): string {\n\t// positionObjectStage is hidden as a unit: it owns the background object and wraps its\n\t// interactions, all of which the component renders. Matching only the interaction inside it\n\t// would leave the stage's background image visible in the item body as well.\n\treturn html.replace(\n\t\t/<(\\w+Interaction|qti-[\\w-]+-interaction|positionObjectStage|qti-position-object-stage)(\\s[^>]*)?>[\\s\\S]*?<\\/\\1>/gi,\n\t\t(match, tagName) => {\n\t\t\tconst lower = tagName.toLowerCase();\n\t\t\tif (isInlineInteractionTagName(lower)) return match;\n\t\t\treturn `<span class=\"qti-hidden-interaction\">${match}</span>`;\n\t\t}\n\t);\n}\n\nfunction createBlockInteractionMounts({\n\tinteractions,\n\tsource,\n\tresponses,\n\tcorrectResponses,\n\troleCapabilities,\n\teffectiveDisabled,\n\tonComponentError,\n}: {\n\tinteractions: readonly BaseInteractionData[];\n\tsource: ItemPresentationSource;\n\tresponses: ItemPresentationResponseMap;\n\tcorrectResponses: Record<string, unknown>;\n\troleCapabilities: RoleCapabilities;\n\teffectiveDisabled: boolean;\n\tonComponentError?: (interaction: BaseInteractionData, error: unknown) => void;\n}): BlockInteractionMount[] {\n\treturn interactions\n\t\t.filter((interaction) => !isInlineInteractionType(interaction.type))\n\t\t.map((interaction) => {\n\t\t\ttry {\n\t\t\t\tconst stringIdentifier =\n\t\t\t\t\t'stringIdentifier' in interaction && typeof interaction.stringIdentifier === 'string'\n\t\t\t\t\t\t? interaction.stringIdentifier\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst block: BlockInteractionMount = {\n\t\t\t\t\tplacement: 'block',\n\t\t\t\t\trenderer: 'web-component',\n\t\t\t\t\tinteraction,\n\t\t\t\t\ttagName: source.componentRegistry.getTagName(interaction),\n\t\t\t\t\tkey: interactionKey(interaction),\n\t\t\t\t\tresponse: responses[interaction.responseId] ?? null,\n\t\t\t\t\t...(stringIdentifier\n\t\t\t\t\t\t? { stringResponse: responses[stringIdentifier] ?? null }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\tcorrectResponse: roleCapabilities.canViewCorrectResponses\n\t\t\t\t\t\t? (correctResponses[interaction.responseId] ?? null)\n\t\t\t\t\t\t: null,\n\t\t\t\t\tpnp: source.pnp,\n\t\t\t\t\teliminationTool: source.pnp?.cognitive?.eliminationTool === true,\n\t\t\t\t\tanswerMasking: source.pnp?.cognitive?.answerMasking === true,\n\t\t\t\t\tstructuredLabelSupport: source.pnp?.display?.structuredLabelSupport === true,\n\t\t\t\t\tdisabled: effectiveDisabled,\n\t\t\t\t\tcomponentRole: roleCapabilities.canViewCorrectResponses ? 'scorer' : undefined,\n\t\t\t\t};\n\t\t\t\treturn block;\n\t\t\t} catch (error) {\n\t\t\t\tonComponentError?.(interaction, error);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t})\n\t\t.filter((item): item is BlockInteractionMount => item !== null);\n}\n\nexport function interactionKey(interaction: BaseInteractionData): string {\n\tconst anyInteraction = interaction as any;\n\tconst ids =\n\t\tArray.isArray(anyInteraction?.choices) && anyInteraction.choices.length > 0\n\t\t\t? anyInteraction.choices.map((choice: any) => choice?.identifier).filter(Boolean).join(',')\n\t\t\t: '';\n\tconst prompt = typeof anyInteraction?.prompt === 'string' ? anyInteraction.prompt : '';\n\treturn `${interaction.type}|${interaction.responseId}|${ids}|${prompt}`;\n}\n"]}
|
package/dist/types/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAybH,cAAc,yBAAyB,CAAC","sourcesContent":["/**\n * Core QTI types for the player\n */\n\nimport type {\n\tBaseType as ProcessingBaseType,\n\tCardinality as ProcessingCardinality,\n\tProcessingFragmentResolver,\n\tQtiValue,\n} from '@pie-qti/qti-processing';\nimport type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\nimport type { PciConfiguration } from '../pci/types.js';\nimport type { ResponseValidationResult } from './responseValidation.js';\n\n/**\n * QTI base type identifier\n * Extensible string type allows custom base types\n */\nexport type VariableBaseType = ProcessingBaseType;\n\n/**\n * QTI cardinality identifier\n * Extensible string type allows custom cardinality values\n */\nexport type VariableCardinality = ProcessingCardinality;\n\nexport interface VariableDeclaration {\n\tidentifier: string;\n\t/** Omitted for record cardinality. */\n\tbaseType?: VariableBaseType;\n\tcardinality: VariableCardinality;\n\tvalue: any;\n\tdefaultValue?: any;\n\tmapping?: Mapping;\n\tareaMapping?: AreaMapping;\n}\n\nexport interface Mapping {\n\tdefaultValue?: number;\n\tlowerBound?: number;\n\tupperBound?: number;\n\t/**\n\t * QTI attribute on <mapping>. When \"false\", string mappings are case-insensitive by default.\n\t * Stored as raw string to match XML attribute values (\"true\"/\"false\").\n\t */\n\tcaseSensitive?: string;\n\tentries: Record<string, MapEntry>;\n}\n\nexport interface MapEntry {\n\tmapKey: string;\n\tmappedValue: number;\n\tcaseSensitive?: string;\n}\n\nexport interface AreaMapping {\n\tdefaultValue?: number;\n\tlowerBound?: number;\n\tupperBound?: number;\n\tentries: AreaMapEntry[];\n}\n\nexport interface AreaMapEntry {\n\tshape: 'circle' | 'rect' | 'poly' | 'ellipse' | 'default';\n\tcoords: string;\n\tmappedValue: number;\n}\n\nexport interface ResponseDeclaration extends VariableDeclaration {\n\tcorrectResponse?: any;\n}\n\nexport interface OutcomeDeclaration extends VariableDeclaration {\n\tinterpretation?: string;\n\tlongInterpretation?: string;\n\tnormalMaximum?: number;\n\tnormalMinimum?: number;\n\tmasteryValue?: number;\n\tviews?: string[];\n}\n\n/** @internal Private engine snapshot shape; use SerializedItemSessionState. */\nexport interface ItemSessionState {\n\t[variableId: string]: any;\n}\n\nexport type ItemLifecycleStatus = 'initial' | 'interacting' | 'suspended' | 'closed' | 'review' | 'solution' | 'answer';\n\nexport type SerializedVariableKind = 'response' | 'outcome' | 'template' | 'context';\n\nexport interface SerializedItemSessionVariable {\n\tidentifier: string;\n\tkind: SerializedVariableKind;\n\t/** Omitted for record cardinality. */\n\tbaseType?: VariableBaseType;\n\tcardinality: VariableCardinality;\n\tvalue: any;\n\tdefaultValue?: any;\n}\n\nexport interface SerializedItemSessionState {\n\titemIdentifier?: string;\n\tsessionGuid: string;\n\tlifecycleStatus: ItemLifecycleStatus;\n\tcompletionStatus: CompletionStatus;\n\tnumAttempts: number;\n\t/**\n\t * Time-on-task in milliseconds, stored as the QTI built-in duration variable value.\n\t */\n\tduration: number;\n\tresponseVariables: Record<string, SerializedItemSessionVariable>;\n\toutcomeVariables: Record<string, SerializedItemSessionVariable>;\n\ttemplateVariables: Record<string, SerializedItemSessionVariable>;\n\tcontextVariables: Record<string, SerializedItemSessionVariable>;\n\tvalidationMessages: ResponseValidationResult['issues'];\n\tsavedAt: string;\n}\n\nexport type ItemSessionAction =\n\t| 'suspendAttempt'\n\t| 'endAttempt'\n\t| 'scoreAttempt'\n\t| 'newTemplate'\n\t| 'submitAttempt';\n\nexport type ItemSessionActionCommand =\n\t| { action: 'suspendAttempt' }\n\t| { action: 'endAttempt'; countAttempt?: boolean; validateResponses?: boolean }\n\t| { action: 'scoreAttempt' }\n\t| { action: 'newTemplate'; resetResponses?: boolean }\n\t| { action: 'submitAttempt'; countAttempt?: boolean };\n\nexport interface ItemSessionActionResult {\n\taction: ItemSessionAction;\n\tlifecycleStatus: ItemLifecycleStatus;\n\tcompletionStatus: CompletionStatus;\n\tnumAttempts: number;\n\tduration: number;\n\tcompleted: boolean;\n\tsessionState: SerializedItemSessionState;\n\tvalidation?: ResponseValidationResult;\n\tscoring?: ScoringResult;\n}\n\n/** @internal Private engine response map. */\nexport interface InteractionResponse {\n\t[responseId: string]: any;\n}\n\n/**\n * Serializable representation of a QTI baseType=\"file\" response.\n * (We cannot store a browser File object in session state / JSON exports.)\n */\nexport interface QTIFileResponse {\n\tname: string;\n\ttype: string;\n\tsize: number;\n\tlastModified: number;\n\t/** Base64 data URL, e.g. data:application/pdf;base64,... */\n\tdataUrl: string;\n\t/**\n\t * Optional ImageData extracted from canvas (for drawing interactions).\n\t * This allows custom operators to analyze drawing content synchronously\n\t * without needing to decode the dataUrl asynchronously.\n\t */\n\timageData?: {\n\t\tdata: Uint8ClampedArray;\n\t\twidth: number;\n\t\theight: number;\n\t};\n}\n\nexport interface ModalFeedback {\n\t/** Unique identifier for this feedback block */\n\tidentifier: string;\n\t/** Outcome variable identifier this feedback is tied to */\n\toutcomeIdentifier: string;\n\t/** When to show: 'show' means display when outcome matches identifier */\n\tshowHide: 'show' | 'hide';\n\t/** HTML content to display */\n\tcontent: HtmlContent;\n\t/** Optional title for the feedback */\n\ttitle?: string;\n}\n\nexport interface ScoringResult {\n\tscore: number;\n\tmaxScore: number;\n\tcompleted: boolean;\n\toutcomeValues: Record<string, any>;\n\t/**\n\t * Whether every declared response matches its correct response; absent when the item has no\n\t * response or one declares no correct response.\n\t */\n\tcorrect?: boolean;\n\t/** Modal feedback elements that should be displayed based on outcome values */\n\tmodalFeedback?: ModalFeedback[];\n}\n\n/**\n * QTI 2.2 completionStatus values for adaptive items\n * - not_attempted: No interaction has occurred yet\n * - unknown: Response exists but hasn't been scored/evaluated\n * - incomplete: Item has been scored but is still active (can submit again)\n * - completed: Item is finished (final state)\n */\nexport type CompletionStatus = 'not_attempted' | 'unknown' | 'incomplete' | 'completed';\n\n/**\n * Extended scoring result for adaptive items with multi-attempt support\n */\nexport interface AdaptiveAttemptResult extends ScoringResult {\n\t/** Number of attempts made so far */\n\tnumAttempts: number;\n\t/** Current completion status of the item */\n\tcompletionStatus: CompletionStatus;\n\t/** Whether the item can accept more submissions */\n\tcanContinue: boolean;\n}\n\n/**\n * QTI role/view actors used for audience filtering (for example rubric/outcome visibility).\n * Runtime interaction behavior (readonly vs editable, correct-answer visibility) is a player\n * policy layered on top of these roles.\n */\nexport type QTIRole = 'candidate' | 'scorer' | 'proctor' | 'testConstructor' | 'tutor' | 'author';\n\nexport type RubricBlockScope = 'direct' | 'itemBody';\n\n/** @internal Private engine rubric query. */\nexport interface RubricBlockOptions {\n\t/**\n\t * `direct` rubrics are assessment-item children and are intended for host placement.\n\t * `itemBody` rubrics are authored in the visible item body flow.\n\t */\n\tscope?: RubricBlockScope | 'all';\n}\n\nexport interface RubricBlock {\n\tview: string[]; // Array of role strings that can see this rubric\n\thtml: HtmlContent; // HTML content of the rubric\n\tscope: RubricBlockScope;\n\tuse?: string;\n}\n\n/**\n * QTI specification compliance configuration.\n * Controls whether the player enforces strict QTI 2.2 spec or allows vendor extensions.\n */\nexport interface QTIComplianceConfig {\n\t/** Enable strict QTI 2.2 compliance mode. Default: false (lenient) */\n\tenabled?: boolean;\n\n\t/** Reject items with unknown or non-standard elements. Default: false */\n\trejectUnknownExtensions?: boolean;\n\n\t/** Log warnings for spec deviations and vendor extensions. Default: true */\n\tlogDeviations?: boolean;\n}\n\n/** @internal Configuration for the private item-session engine. */\nexport interface ItemSessionEngineConfig {\n\titemXml: string;\n\t/**\n\t * QTI 3.0 §6.2 Personal Needs and Preferences profile.\n\t * Display needs are applied as attributes and custom properties on the player root.\n\t * Use player.updatePnp() to change mid-session without re-parsing the item.\n\t */\n\tpnp?: import('../pnp/types.js').PnpProfile;\n\t/**\n\t * Optional shared catalog XML string (QTI 3.0 §6.3).\n\t * Parsed and merged with any catalog embedded in the item XML.\n\t * Item-level catalog entries take precedence over shared entries with the same identifier.\n\t * Deferred: external catalog files from IMS manifest (G-15) are not yet supported.\n\t */\n\tcatalogXml?: string;\n\t/**\n\t * Optional resolved delivery context produced by IMS package/assessment layers.\n\t * This is additive to catalogXml: shared catalog sources are merged first, then\n\t * catalogXml, then item-embedded catalog entries so item-local entries win.\n\t */\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\trole?: QTIRole;\n\t/**\n\t * Values for the item's context variables, set before template processing: `QTI_CONTEXT`, a\n\t * record, and any declared by `contextDeclaration` (`qti-context-declaration`).\n\t */\n\tcontextVariables?: Readonly<Record<string, unknown>>;\n\t/**\n\t * Default values for template variables, set before template processing and kept by\n\t * `newTemplate`, as an assessmentItemRef's `templateDefault` requires.\n\t */\n\ttemplateDefaults?: Readonly<Record<string, unknown>>;\n\t/** Optional seed for deterministic random operations (e.g. templateProcessing randomInteger) */\n\tseed?: number;\n\t/** Optional RNG override (takes precedence over seed if provided) */\n\trng?: () => number;\n\t/**\n\t * Optional element name mapper for handling different QTI versions.\n\t * Defaults to Qti2xElementNameMapper (primary supported QTI format).\n\t * @since 0.2.0\n\t */\n\telementNameMapper?: any; // Will be ElementNameMapper from @pie-qti/qti-common\n\t/**\n\t * Optional attribute name mapper for handling different QTI versions.\n\t * Defaults to Qti2xAttributeNameMapper (primary supported QTI format).\n\t * @since 0.3.0\n\t */\n\tattributeNameMapper?: any; // Will be AttributeNameMapper from @pie-qti/qti-common\n\t/** Optional web component registry for custom interaction components */\n\tcomponentRegistry?: any; // Will be ComponentRegistry, but avoiding circular dependency\n\t/** Optional extraction registry for custom element extractors */\n\textractionRegistry?: any; // Will be ExtractionRegistry, but avoiding circular dependency\n\t/**\n\t * Optional i18n provider for internationalization.\n\t * If not provided, defaults to DefaultI18nProvider with English messages.\n\t */\n\ti18nProvider?: any; // Will be I18nProvider from @pie-qti/i18n\n\t/**\n\t * Optional registry for executing QTI <customOperator> expressions.\n\t * Keyed by operator `class` (preferred) or `definition` URI.\n\t */\n\tcustomOperators?: Record<string, (args: QtiValue[], meta: { class?: string; definition?: string }) => QtiValue>;\n\t/**\n\t * Host-controlled resolver for xi:include processing fragments.\n\t * The player never fetches an authored href directly; package hosts must resolve\n\t * and containment-check it, then return XML synchronously.\n\t */\n\tresolveProcessingFragment?: ProcessingFragmentResolver;\n\t/** Resource limits applied cumulatively while compiling external processing fragments. */\n\tprocessingFragmentLimits?: {\n\t\t/** Maximum nested xi:include depth. Default: 16. */\n\t\tmaxDepth?: number;\n\t\t/** Maximum cumulative XML characters. Default: 2 MiB. */\n\t\tmaxCharacters?: number;\n\t};\n\t/**\n\t * Portable Custom Interaction runtime configuration.\n\t * A moduleResolver is required before any authored PCI code can execute.\n\t */\n\tpci?: PciConfiguration;\n\t/**\n\t * Security-related controls for untrusted QTI rendered into the host DOM.\n\t * Defaults are conservative for same-DOM embedding.\n\t */\n\tsecurity?: PlayerSecurityConfig;\n\n\t/**\n\t * QTI specification compliance settings.\n\t * Set strictQtiCompliance.enabled = true for strict QTI 2.2 validation.\n\t */\n\tstrictQtiCompliance?: QTIComplianceConfig;\n}\n\nexport interface UrlPolicyConfig {\n\t/**\n\t * Optional base URL used to resolve relative asset URLs (e.g. images/media).\n\t * If omitted, relative URLs are preserved as-is.\n\t */\n\tassetBaseUrl?: string;\n\t/** Allow https: URLs */\n\tallowHttps?: boolean;\n\t/** Allow http: URLs (default false; prefer https) */\n\tallowHttp?: boolean;\n\t/** Allow protocol-relative URLs (e.g. //cdn.example/asset). Default false. */\n\tallowProtocolRelative?: boolean;\n\t/** Allow data:image/* for <img src>. */\n\tallowDataImages?: boolean;\n\t/** Allow data:image/svg+xml (default false) */\n\tallowSvgDataImages?: boolean;\n\t/** Allow blob: URLs for package-resolved images (default false). */\n\tallowBlobImages?: boolean;\n\t/** Allow blob: URLs for package-resolved audio/video media (default false). */\n\tallowBlobMedia?: boolean;\n\t/** Optional allowlist of hostnames for absolute URLs (exact match). */\n\tallowedHosts?: string[];\n}\n\n/**\n * Trusted Types support:\n * - When enabled and supported by the host browser + CSP, HTML-returning APIs may return TrustedHTML instead of string.\n * - When not enabled (default), APIs return plain strings as before.\n */\nexport type TrustedTypesHtml = typeof globalThis extends { TrustedHTML: infer T } ? T : never;\nexport type HtmlContent = string | TrustedTypesHtml;\n\nexport interface PlayerSecurityConfig {\n\t/** URL policy applied to extracted URL fields and HTML attribute URLs */\n\turlPolicy?: UrlPolicyConfig;\n\t/** Allow <object>/<embed> usage (default false) */\n\tallowObjectEmbeds?: boolean;\n\t/** Allow <iframe> usage (default false) */\n\tallowIframes?: boolean;\n\t/**\n\t * Optional parsing/processing guardrails to reduce DoS risk from untrusted QTI.\n\t * Disabled by default for compatibility.\n\t */\n\tparsingLimits?: ParsingLimitsConfig;\n\t/**\n\t * Optional Trusted Types policy name (host-controlled).\n\t * When set, and Trusted Types is available, the player will produce TrustedHTML for HTML injection sinks.\n\t *\n\t * Note: this is only effective when the host enables Trusted Types via CSP.\n\t */\n\ttrustedTypesPolicyName?: string;\n}\n\nexport interface ParsingLimitsConfig {\n\t/**\n\t * Enables parsing limits. When false/undefined, the player behaves exactly as before (compat default).\n\t */\n\tenabled?: boolean;\n\t/**\n\t * Reject any XML containing <!DOCTYPE ...> (case-insensitive) when enabled.\n\t * Helps reduce entity-expansion and other parser edge-case risks.\n\t */\n\trejectDoctype?: boolean;\n\t/**\n\t * Maximum bytes for `itemXml` input (UTF-8). Enforced when enabled.\n\t */\n\tmaxItemXmlBytes?: number;\n\t/**\n\t * Maximum bytes for HTML strings passed to sanitizer (UTF-8). Enforced when enabled.\n\t */\n\tmaxHtmlBytes?: number;\n\t/**\n\t * Maximum number of element nodes sanitized per HTML input. Enforced when enabled.\n\t */\n\tmaxHtmlNodes?: number;\n\t/**\n\t * Maximum element depth sanitized per HTML input. Enforced when enabled.\n\t */\n\tmaxHtmlDepth?: number;\n}\n\nexport interface InteractionContext {\n\tresponseIdentifier: string;\n\tmaxChoices?: number;\n\tminChoices?: number;\n\tshuffle?: boolean;\n\torientation?: 'horizontal' | 'vertical';\n}\n\nexport * from './responseValidation.js';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAgcH,cAAc,yBAAyB,CAAC","sourcesContent":["/**\n * Core QTI types for the player\n */\n\nimport type {\n\tBaseType as ProcessingBaseType,\n\tCardinality as ProcessingCardinality,\n\tProcessingFragmentResolver,\n\tQtiValue,\n} from '@pie-qti/qti-processing';\nimport type {\n\tAttributeNameMapper,\n\tElementNameMapper,\n} from '@pie-qti/qti-common';\nimport type { I18nProvider } from '@pie-qti/i18n';\nimport type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\nimport type { PciConfiguration } from '../pci/types.js';\nimport type { ComponentRegistry } from '../core/ComponentRegistry.js';\nimport type { ExtractionRegistry } from '../extraction/ExtractionRegistry.js';\nimport type { ResponseValidationResult } from './responseValidation.js';\n\n/**\n * QTI base type identifier\n * Extensible string type allows custom base types\n */\nexport type VariableBaseType = ProcessingBaseType;\n\n/**\n * QTI cardinality identifier\n * Extensible string type allows custom cardinality values\n */\nexport type VariableCardinality = ProcessingCardinality;\n\nexport interface VariableDeclaration {\n\tidentifier: string;\n\t/** Omitted for record cardinality. */\n\tbaseType?: VariableBaseType;\n\tcardinality: VariableCardinality;\n\tvalue: any;\n\tdefaultValue?: any;\n\tmapping?: Mapping;\n\tareaMapping?: AreaMapping;\n}\n\nexport interface Mapping {\n\tdefaultValue?: number;\n\tlowerBound?: number;\n\tupperBound?: number;\n\t/**\n\t * QTI attribute on <mapping>. When \"false\", string mappings are case-insensitive by default.\n\t * Stored as raw string to match XML attribute values (\"true\"/\"false\").\n\t */\n\tcaseSensitive?: string;\n\tentries: Record<string, MapEntry>;\n}\n\nexport interface MapEntry {\n\tmapKey: string;\n\tmappedValue: number;\n\tcaseSensitive?: string;\n}\n\nexport interface AreaMapping {\n\tdefaultValue?: number;\n\tlowerBound?: number;\n\tupperBound?: number;\n\tentries: AreaMapEntry[];\n}\n\nexport interface AreaMapEntry {\n\tshape: 'circle' | 'rect' | 'poly' | 'ellipse' | 'default';\n\tcoords: string;\n\tmappedValue: number;\n}\n\nexport interface ResponseDeclaration extends VariableDeclaration {\n\tcorrectResponse?: any;\n}\n\nexport interface OutcomeDeclaration extends VariableDeclaration {\n\tinterpretation?: string;\n\tlongInterpretation?: string;\n\tnormalMaximum?: number;\n\tnormalMinimum?: number;\n\tmasteryValue?: number;\n\tviews?: string[];\n}\n\n/** @internal Private engine snapshot shape; use SerializedItemSessionState. */\nexport interface ItemSessionState {\n\t[variableId: string]: any;\n}\n\nexport type ItemLifecycleStatus = 'initial' | 'interacting' | 'suspended' | 'closed' | 'review' | 'solution' | 'answer';\n\nexport type SerializedVariableKind = 'response' | 'outcome' | 'template' | 'context';\n\nexport interface SerializedItemSessionVariable {\n\tidentifier: string;\n\tkind: SerializedVariableKind;\n\t/** Omitted for record cardinality. */\n\tbaseType?: VariableBaseType;\n\tcardinality: VariableCardinality;\n\tvalue: any;\n\tdefaultValue?: any;\n}\n\nexport interface SerializedItemSessionState {\n\titemIdentifier?: string;\n\tsessionGuid: string;\n\tlifecycleStatus: ItemLifecycleStatus;\n\tcompletionStatus: CompletionStatus;\n\tnumAttempts: number;\n\t/**\n\t * Time-on-task in milliseconds, stored as the QTI built-in duration variable value.\n\t */\n\tduration: number;\n\tresponseVariables: Record<string, SerializedItemSessionVariable>;\n\toutcomeVariables: Record<string, SerializedItemSessionVariable>;\n\ttemplateVariables: Record<string, SerializedItemSessionVariable>;\n\tcontextVariables: Record<string, SerializedItemSessionVariable>;\n\tvalidationMessages: ResponseValidationResult['issues'];\n\tsavedAt: string;\n}\n\nexport type ItemSessionAction =\n\t| 'suspendAttempt'\n\t| 'endAttempt'\n\t| 'scoreAttempt'\n\t| 'newTemplate'\n\t| 'submitAttempt';\n\nexport type ItemSessionActionCommand =\n\t| { action: 'suspendAttempt' }\n\t| { action: 'endAttempt'; countAttempt?: boolean; validateResponses?: boolean }\n\t| { action: 'scoreAttempt' }\n\t| { action: 'newTemplate'; resetResponses?: boolean }\n\t| { action: 'submitAttempt'; countAttempt?: boolean };\n\nexport interface ItemSessionActionResult {\n\taction: ItemSessionAction;\n\tlifecycleStatus: ItemLifecycleStatus;\n\tcompletionStatus: CompletionStatus;\n\tnumAttempts: number;\n\tduration: number;\n\tcompleted: boolean;\n\tsessionState: SerializedItemSessionState;\n\tvalidation?: ResponseValidationResult;\n\tscoring?: ScoringResult;\n}\n\n/** @internal Private engine response map. */\nexport interface InteractionResponse {\n\t[responseId: string]: any;\n}\n\n/**\n * Serializable representation of a QTI baseType=\"file\" response.\n * (We cannot store a browser File object in session state / JSON exports.)\n */\nexport interface QTIFileResponse {\n\tname: string;\n\ttype: string;\n\tsize: number;\n\tlastModified: number;\n\t/** Base64 data URL, e.g. data:application/pdf;base64,... */\n\tdataUrl: string;\n\t/**\n\t * Optional ImageData extracted from canvas (for drawing interactions).\n\t * This allows custom operators to analyze drawing content synchronously\n\t * without needing to decode the dataUrl asynchronously.\n\t */\n\timageData?: {\n\t\tdata: Uint8ClampedArray;\n\t\twidth: number;\n\t\theight: number;\n\t};\n}\n\nexport interface ModalFeedback {\n\t/** Unique identifier for this feedback block */\n\tidentifier: string;\n\t/** Outcome variable identifier this feedback is tied to */\n\toutcomeIdentifier: string;\n\t/** When to show: 'show' means display when outcome matches identifier */\n\tshowHide: 'show' | 'hide';\n\t/** HTML content to display */\n\tcontent: HtmlContent;\n\t/** Optional title for the feedback */\n\ttitle?: string;\n}\n\nexport interface ScoringResult {\n\tscore: number;\n\tmaxScore: number;\n\tcompleted: boolean;\n\toutcomeValues: Record<string, any>;\n\t/**\n\t * Whether every declared response matches its correct response; absent when the item has no\n\t * response or one declares no correct response.\n\t */\n\tcorrect?: boolean;\n\t/** Modal feedback elements that should be displayed based on outcome values */\n\tmodalFeedback?: ModalFeedback[];\n}\n\n/**\n * QTI 2.2 completionStatus values for adaptive items\n * - not_attempted: No interaction has occurred yet\n * - unknown: Response exists but hasn't been scored/evaluated\n * - incomplete: Item has been scored but is still active (can submit again)\n * - completed: Item is finished (final state)\n */\nexport type CompletionStatus = 'not_attempted' | 'unknown' | 'incomplete' | 'completed';\n\n/**\n * Extended scoring result for adaptive items with multi-attempt support\n */\nexport interface AdaptiveAttemptResult extends ScoringResult {\n\t/** Number of attempts made so far */\n\tnumAttempts: number;\n\t/** Current completion status of the item */\n\tcompletionStatus: CompletionStatus;\n\t/** Whether the item can accept more submissions */\n\tcanContinue: boolean;\n}\n\n/**\n * QTI role/view actors used for audience filtering (for example rubric/outcome visibility).\n * Runtime interaction behavior (readonly vs editable, correct-answer visibility) is a player\n * policy layered on top of these roles.\n */\nexport type QTIRole = 'candidate' | 'scorer' | 'proctor' | 'testConstructor' | 'tutor' | 'author';\n\nexport type RubricBlockScope = 'direct' | 'itemBody';\n\n/** @internal Private engine rubric query. */\nexport interface RubricBlockOptions {\n\t/**\n\t * `direct` rubrics are assessment-item children and are intended for host placement.\n\t * `itemBody` rubrics are authored in the visible item body flow.\n\t */\n\tscope?: RubricBlockScope | 'all';\n}\n\nexport interface RubricBlock {\n\tview: string[]; // Array of role strings that can see this rubric\n\thtml: HtmlContent; // HTML content of the rubric\n\tscope: RubricBlockScope;\n\tuse?: string;\n}\n\n/**\n * QTI specification compliance configuration.\n * Controls whether the player enforces strict QTI 2.2 spec or allows vendor extensions.\n */\nexport interface QTIComplianceConfig {\n\t/** Enable strict QTI 2.2 compliance mode. Default: false (lenient) */\n\tenabled?: boolean;\n\n\t/** Reject items with unknown or non-standard elements. Default: false */\n\trejectUnknownExtensions?: boolean;\n\n\t/** Log warnings for spec deviations and vendor extensions. Default: true */\n\tlogDeviations?: boolean;\n}\n\n/** @internal Configuration for the private item-session engine. */\nexport interface ItemSessionEngineConfig {\n\titemXml: string;\n\t/**\n\t * QTI 3.0 §6.2 Personal Needs and Preferences profile.\n\t * Display needs are applied as attributes and custom properties on the player root.\n\t * Use player.updatePnp() to change mid-session without re-parsing the item.\n\t */\n\tpnp?: import('../pnp/types.js').PnpProfile;\n\t/**\n\t * Optional shared catalog XML string (QTI 3.0 §6.3).\n\t * Parsed and merged with any catalog embedded in the item XML.\n\t * Item-level catalog entries take precedence over shared entries with the same identifier.\n\t * Deferred: external catalog files from IMS manifest (G-15) are not yet supported.\n\t */\n\tcatalogXml?: string;\n\t/**\n\t * Optional resolved delivery context produced by IMS package/assessment layers.\n\t * This is additive to catalogXml: shared catalog sources are merged first, then\n\t * catalogXml, then item-embedded catalog entries so item-local entries win.\n\t */\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\trole?: QTIRole;\n\t/**\n\t * Values for the item's context variables, set before template processing: `QTI_CONTEXT`, a\n\t * record, and any declared by `contextDeclaration` (`qti-context-declaration`).\n\t */\n\tcontextVariables?: Readonly<Record<string, unknown>>;\n\t/**\n\t * Default values for template variables, set before template processing and kept by\n\t * `newTemplate`, as an assessmentItemRef's `templateDefault` requires.\n\t */\n\ttemplateDefaults?: Readonly<Record<string, unknown>>;\n\t/** Optional seed for deterministic random operations (e.g. templateProcessing randomInteger) */\n\tseed?: number;\n\t/** Optional RNG override (takes precedence over seed if provided) */\n\trng?: () => number;\n\t/**\n\t * Optional element name mapper for handling different QTI versions.\n\t * Defaults to Qti2xElementNameMapper (primary supported QTI format).\n\t * @since 0.2.0\n\t */\n\telementNameMapper?: ElementNameMapper;\n\t/**\n\t * Optional attribute name mapper for handling different QTI versions.\n\t * Defaults to Qti2xAttributeNameMapper (primary supported QTI format).\n\t * @since 0.3.0\n\t */\n\tattributeNameMapper?: AttributeNameMapper;\n\t/** Optional web component registry for custom interaction components */\n\tcomponentRegistry?: ComponentRegistry;\n\t/** Optional extraction registry for custom element extractors */\n\textractionRegistry?: ExtractionRegistry;\n\t/**\n\t * Optional i18n provider for internationalization.\n\t * If not provided, defaults to DefaultI18nProvider with English messages.\n\t */\n\ti18nProvider?: I18nProvider;\n\t/**\n\t * Optional registry for executing QTI <customOperator> expressions.\n\t * Keyed by operator `class` (preferred) or `definition` URI.\n\t */\n\tcustomOperators?: Record<string, (args: QtiValue[], meta: { class?: string; definition?: string }) => QtiValue>;\n\t/**\n\t * Host-controlled resolver for xi:include processing fragments.\n\t * The player never fetches an authored href directly; package hosts must resolve\n\t * and containment-check it, then return XML synchronously.\n\t */\n\tresolveProcessingFragment?: ProcessingFragmentResolver;\n\t/** Resource limits applied cumulatively while compiling external processing fragments. */\n\tprocessingFragmentLimits?: {\n\t\t/** Maximum nested xi:include depth. Default: 16. */\n\t\tmaxDepth?: number;\n\t\t/** Maximum cumulative XML characters. Default: 2 MiB. */\n\t\tmaxCharacters?: number;\n\t};\n\t/**\n\t * Portable Custom Interaction runtime configuration.\n\t * A moduleResolver is required before any authored PCI code can execute.\n\t */\n\tpci?: PciConfiguration;\n\t/**\n\t * Security-related controls for untrusted QTI rendered into the host DOM.\n\t * Defaults are conservative for same-DOM embedding.\n\t */\n\tsecurity?: PlayerSecurityConfig;\n\n\t/**\n\t * QTI specification compliance settings.\n\t * Set strictQtiCompliance.enabled = true for strict QTI 2.2 validation.\n\t */\n\tstrictQtiCompliance?: QTIComplianceConfig;\n}\n\nexport interface UrlPolicyConfig {\n\t/**\n\t * Optional base URL used to resolve relative asset URLs (e.g. images/media).\n\t * If omitted, relative URLs are preserved as-is.\n\t */\n\tassetBaseUrl?: string;\n\t/** Allow https: URLs */\n\tallowHttps?: boolean;\n\t/** Allow http: URLs (default false; prefer https) */\n\tallowHttp?: boolean;\n\t/** Allow protocol-relative URLs (e.g. //cdn.example/asset). Default false. */\n\tallowProtocolRelative?: boolean;\n\t/** Allow data:image/* for <img src>. */\n\tallowDataImages?: boolean;\n\t/** Allow data:image/svg+xml (default false) */\n\tallowSvgDataImages?: boolean;\n\t/** Allow blob: URLs for package-resolved images (default false). */\n\tallowBlobImages?: boolean;\n\t/** Allow blob: URLs for package-resolved audio/video media (default false). */\n\tallowBlobMedia?: boolean;\n\t/** Optional allowlist of hostnames for absolute URLs (exact match). */\n\tallowedHosts?: string[];\n}\n\n/**\n * Trusted Types support:\n * - When enabled and supported by the host browser + CSP, HTML-returning APIs may return TrustedHTML instead of string.\n * - When not enabled (default), APIs return plain strings as before.\n */\nexport type TrustedTypesHtml = typeof globalThis extends { TrustedHTML: infer T } ? T : never;\nexport type HtmlContent = string | TrustedTypesHtml;\n\nexport interface PlayerSecurityConfig {\n\t/** URL policy applied to extracted URL fields and HTML attribute URLs */\n\turlPolicy?: UrlPolicyConfig;\n\t/** Allow <object>/<embed> usage (default false) */\n\tallowObjectEmbeds?: boolean;\n\t/** Allow <iframe> usage (default false) */\n\tallowIframes?: boolean;\n\t/**\n\t * Optional parsing/processing guardrails to reduce DoS risk from untrusted QTI.\n\t * Disabled by default for compatibility.\n\t */\n\tparsingLimits?: ParsingLimitsConfig;\n\t/**\n\t * Optional Trusted Types policy name (host-controlled).\n\t * When set, and Trusted Types is available, the player will produce TrustedHTML for HTML injection sinks.\n\t *\n\t * Note: this is only effective when the host enables Trusted Types via CSP.\n\t */\n\ttrustedTypesPolicyName?: string;\n}\n\nexport interface ParsingLimitsConfig {\n\t/**\n\t * Enables parsing limits. When false/undefined, the player behaves exactly as before (compat default).\n\t */\n\tenabled?: boolean;\n\t/**\n\t * Reject any XML containing <!DOCTYPE ...> (case-insensitive) when enabled.\n\t * Helps reduce entity-expansion and other parser edge-case risks.\n\t */\n\trejectDoctype?: boolean;\n\t/**\n\t * Maximum bytes for `itemXml` input (UTF-8). Enforced when enabled.\n\t */\n\tmaxItemXmlBytes?: number;\n\t/**\n\t * Maximum bytes for HTML strings passed to sanitizer (UTF-8). Enforced when enabled.\n\t */\n\tmaxHtmlBytes?: number;\n\t/**\n\t * Maximum number of element nodes sanitized per HTML input. Enforced when enabled.\n\t */\n\tmaxHtmlNodes?: number;\n\t/**\n\t * Maximum element depth sanitized per HTML input. Enforced when enabled.\n\t */\n\tmaxHtmlDepth?: number;\n}\n\nexport interface InteractionContext {\n\tresponseIdentifier: string;\n\tmaxChoices?: number;\n\tminChoices?: number;\n\tshuffle?: boolean;\n\torientation?: 'horizontal' | 'vertical';\n}\n\nexport * from './responseValidation.js';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pie-qti/item-player",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.4",
|
|
4
4
|
"description": "Modern QTI player supporting QTI 2.2 and 3.0 - Client-side with optional backend hooks",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -27,10 +27,10 @@
|
|
|
27
27
|
],
|
|
28
28
|
"license": "MIT",
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@pie-qti/i18n": "1.0.0-beta.
|
|
31
|
-
"@pie-qti/ims-cp-core": "1.0.0-beta.
|
|
32
|
-
"@pie-qti/qti-common": "1.0.0-beta.
|
|
33
|
-
"@pie-qti/qti-processing": "1.0.0-beta.
|
|
30
|
+
"@pie-qti/i18n": "1.0.0-beta.4",
|
|
31
|
+
"@pie-qti/ims-cp-core": "1.0.0-beta.4",
|
|
32
|
+
"@pie-qti/qti-common": "1.0.0-beta.4",
|
|
33
|
+
"@pie-qti/qti-processing": "1.0.0-beta.4",
|
|
34
34
|
"mathlive": "^0.111.1",
|
|
35
35
|
"node-html-parser": "^9.0.5"
|
|
36
36
|
},
|
|
@@ -69,10 +69,6 @@
|
|
|
69
69
|
"types": "./dist/pci/index.d.ts",
|
|
70
70
|
"import": "./dist/pci/index.js"
|
|
71
71
|
},
|
|
72
|
-
"./components/utils": {
|
|
73
|
-
"types": "./dist/components/utils/index.d.ts",
|
|
74
|
-
"import": "./dist/components/utils/index.js"
|
|
75
|
-
},
|
|
76
72
|
"./element": {
|
|
77
73
|
"types": "./dist/element.d.ts",
|
|
78
74
|
"import": "./dist/element.js"
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Feedback text utilities for QTI items
|
|
3
|
-
*
|
|
4
|
-
* NOTE: The cleanFeedbackText function contains vendor-specific transforms
|
|
5
|
-
* for content that uses semicolons after "Correct" and "Incorrect" labels.
|
|
6
|
-
* This is common in some QTI authoring tools but not part of the QTI specification.
|
|
7
|
-
*
|
|
8
|
-
* To customize this behavior for your vendor's content, you can:
|
|
9
|
-
* 1. Modify the patterns in this file
|
|
10
|
-
* 2. Create a vendor-specific transform plugin (see VENDOR-TRANSFORM-PLUGIN-GUIDE.md)
|
|
11
|
-
* 3. Pass custom transforms via the feedbackTransforms option
|
|
12
|
-
*/
|
|
13
|
-
/**
|
|
14
|
-
* Text pattern replacement for feedback content
|
|
15
|
-
*/
|
|
16
|
-
export interface FeedbackTransform {
|
|
17
|
-
/** Regular expression to match the pattern */
|
|
18
|
-
pattern: RegExp;
|
|
19
|
-
/** Replacement string (can use capture groups like $1, $2) */
|
|
20
|
-
replacement: string;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Default feedback text transforms
|
|
24
|
-
* These are vendor-specific patterns commonly found in certain QTI authoring tools
|
|
25
|
-
*/
|
|
26
|
-
export declare const DEFAULT_FEEDBACK_TRANSFORMS: FeedbackTransform[];
|
|
27
|
-
/**
|
|
28
|
-
* Clean up feedback text formatting using configurable transforms
|
|
29
|
-
*
|
|
30
|
-
* @param content - The feedback content HTML string
|
|
31
|
-
* @param transforms - Optional custom transforms (defaults to DEFAULT_FEEDBACK_TRANSFORMS)
|
|
32
|
-
* @returns Cleaned feedback content
|
|
33
|
-
*/
|
|
34
|
-
export declare function cleanFeedbackText(content: string, transforms?: FeedbackTransform[]): string;
|
|
35
|
-
/**
|
|
36
|
-
* Default outcome identifier for feedback display
|
|
37
|
-
* This can be overridden if your QTI content uses a different identifier
|
|
38
|
-
*/
|
|
39
|
-
export declare const DEFAULT_FEEDBACK_OUTCOME_ID = "FEEDBACK";
|
|
40
|
-
/**
|
|
41
|
-
* Options for processing feedbackInline elements
|
|
42
|
-
*/
|
|
43
|
-
export interface ProcessFeedbackInlineOptions {
|
|
44
|
-
/** Outcome values from response processing */
|
|
45
|
-
outcomeValues: Record<string, any>;
|
|
46
|
-
/** Whether to apply feedback text cleaning heuristics */
|
|
47
|
-
applyHeuristics?: boolean;
|
|
48
|
-
/** Whether to wrap inline feedback content with qti-feedback-inline span */
|
|
49
|
-
wrapWithSpan?: boolean;
|
|
50
|
-
/** Custom feedback transforms (defaults to DEFAULT_FEEDBACK_TRANSFORMS) */
|
|
51
|
-
transforms?: FeedbackTransform[];
|
|
52
|
-
/** Drop every feedback element whatever the outcomes. */
|
|
53
|
-
hideAll?: boolean;
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Process feedbackInline and feedbackBlock elements in QTI content
|
|
57
|
-
*
|
|
58
|
-
* Shows or hides each `feedbackInline` and `feedbackBlock` (`qti-feedback-inline` and
|
|
59
|
-
* `qti-feedback-block` in QTI 3) by the shared visibility rule: its `identifier` against the
|
|
60
|
-
* outcome value, by membership for a container, inverted by `showHide="hide"`. Nested feedback
|
|
61
|
-
* resolves inside shown feedback; hidden feedback drops with everything inside it. Markup outside
|
|
62
|
-
* feedback elements is left as it is.
|
|
63
|
-
*
|
|
64
|
-
* @param html - The HTML content containing feedbackInline elements
|
|
65
|
-
* @param options - Processing options
|
|
66
|
-
* @returns Modified HTML with processed feedbackInline elements
|
|
67
|
-
*
|
|
68
|
-
* @example
|
|
69
|
-
* ```typescript
|
|
70
|
-
* const html = processFeedbackInline(content, {
|
|
71
|
-
* outcomeValues: { FEEDBACK: 'choiceA' },
|
|
72
|
-
* applyHeuristics: true,
|
|
73
|
-
* wrapWithSpan: true
|
|
74
|
-
* });
|
|
75
|
-
* ```
|
|
76
|
-
*/
|
|
77
|
-
export declare function processFeedbackInline(html: string, options: ProcessFeedbackInlineOptions): string;
|
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Feedback text utilities for QTI items
|
|
3
|
-
*
|
|
4
|
-
* NOTE: The cleanFeedbackText function contains vendor-specific transforms
|
|
5
|
-
* for content that uses semicolons after "Correct" and "Incorrect" labels.
|
|
6
|
-
* This is common in some QTI authoring tools but not part of the QTI specification.
|
|
7
|
-
*
|
|
8
|
-
* To customize this behavior for your vendor's content, you can:
|
|
9
|
-
* 1. Modify the patterns in this file
|
|
10
|
-
* 2. Create a vendor-specific transform plugin (see VENDOR-TRANSFORM-PLUGIN-GUIDE.md)
|
|
11
|
-
* 3. Pass custom transforms via the feedbackTransforms option
|
|
12
|
-
*/
|
|
13
|
-
import { isShownByIdentifier } from '@pie-qti/qti-common';
|
|
14
|
-
/**
|
|
15
|
-
* Default feedback text transforms
|
|
16
|
-
* These are vendor-specific patterns commonly found in certain QTI authoring tools
|
|
17
|
-
*/
|
|
18
|
-
export const DEFAULT_FEEDBACK_TRANSFORMS = [
|
|
19
|
-
// Remove semicolons after "Incorrect" (with or without <strong> tags)
|
|
20
|
-
{ pattern: /<strong>Incorrect;<\/strong>/gi, replacement: '<strong>Incorrect</strong> ' },
|
|
21
|
-
{ pattern: /Incorrect;/gi, replacement: 'Incorrect ' },
|
|
22
|
-
// Remove semicolons after "Correct" (with or without <strong> tags)
|
|
23
|
-
{ pattern: /<strong>Correct;<\/strong>/gi, replacement: '<strong>Correct</strong> ' },
|
|
24
|
-
{ pattern: /Correct;/gi, replacement: 'Correct ' },
|
|
25
|
-
];
|
|
26
|
-
/**
|
|
27
|
-
* Clean up feedback text formatting using configurable transforms
|
|
28
|
-
*
|
|
29
|
-
* @param content - The feedback content HTML string
|
|
30
|
-
* @param transforms - Optional custom transforms (defaults to DEFAULT_FEEDBACK_TRANSFORMS)
|
|
31
|
-
* @returns Cleaned feedback content
|
|
32
|
-
*/
|
|
33
|
-
export function cleanFeedbackText(content, transforms = DEFAULT_FEEDBACK_TRANSFORMS) {
|
|
34
|
-
if (!content)
|
|
35
|
-
return content;
|
|
36
|
-
let result = content;
|
|
37
|
-
for (const transform of transforms) {
|
|
38
|
-
result = result.replace(transform.pattern, transform.replacement);
|
|
39
|
-
}
|
|
40
|
-
return result;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Default outcome identifier for feedback display
|
|
44
|
-
* This can be overridden if your QTI content uses a different identifier
|
|
45
|
-
*/
|
|
46
|
-
export const DEFAULT_FEEDBACK_OUTCOME_ID = 'FEEDBACK';
|
|
47
|
-
/**
|
|
48
|
-
* Process feedbackInline and feedbackBlock elements in QTI content
|
|
49
|
-
*
|
|
50
|
-
* Shows or hides each `feedbackInline` and `feedbackBlock` (`qti-feedback-inline` and
|
|
51
|
-
* `qti-feedback-block` in QTI 3) by the shared visibility rule: its `identifier` against the
|
|
52
|
-
* outcome value, by membership for a container, inverted by `showHide="hide"`. Nested feedback
|
|
53
|
-
* resolves inside shown feedback; hidden feedback drops with everything inside it. Markup outside
|
|
54
|
-
* feedback elements is left as it is.
|
|
55
|
-
*
|
|
56
|
-
* @param html - The HTML content containing feedbackInline elements
|
|
57
|
-
* @param options - Processing options
|
|
58
|
-
* @returns Modified HTML with processed feedbackInline elements
|
|
59
|
-
*
|
|
60
|
-
* @example
|
|
61
|
-
* ```typescript
|
|
62
|
-
* const html = processFeedbackInline(content, {
|
|
63
|
-
* outcomeValues: { FEEDBACK: 'choiceA' },
|
|
64
|
-
* applyHeuristics: true,
|
|
65
|
-
* wrapWithSpan: true
|
|
66
|
-
* });
|
|
67
|
-
* ```
|
|
68
|
-
*/
|
|
69
|
-
export function processFeedbackInline(html, options) {
|
|
70
|
-
if (!html)
|
|
71
|
-
return html;
|
|
72
|
-
const feedback = feedbackElements(html);
|
|
73
|
-
if (feedback.length === 0)
|
|
74
|
-
return html;
|
|
75
|
-
const { outcomeValues, applyHeuristics = false, wrapWithSpan = false, transforms, hideAll = false } = options;
|
|
76
|
-
const render = (start, end, elements) => {
|
|
77
|
-
let out = '';
|
|
78
|
-
let position = start;
|
|
79
|
-
for (const element of elements) {
|
|
80
|
-
out += html.slice(position, element.openStart);
|
|
81
|
-
position = element.closeEnd;
|
|
82
|
-
const outcomeId = feedbackInlineAttr(element.attrs, 'outcomeIdentifier');
|
|
83
|
-
const feedbackId = feedbackInlineAttr(element.attrs, 'identifier');
|
|
84
|
-
if (hideAll || outcomeId === null || feedbackId === null)
|
|
85
|
-
continue;
|
|
86
|
-
const showHide = feedbackInlineAttr(element.attrs, 'showHide');
|
|
87
|
-
if (!isShownByIdentifier(outcomeValues[outcomeId], feedbackId, showHide))
|
|
88
|
-
continue;
|
|
89
|
-
let content = render(element.openEnd, element.closeStart, element.children);
|
|
90
|
-
if (applyHeuristics)
|
|
91
|
-
content = cleanFeedbackText(content, transforms);
|
|
92
|
-
out += wrapWithSpan && !element.block ? ` <span class="qti-feedback-inline">${content}</span>` : content;
|
|
93
|
-
}
|
|
94
|
-
return out + html.slice(position, end);
|
|
95
|
-
};
|
|
96
|
-
return render(0, html.length, feedback);
|
|
97
|
-
}
|
|
98
|
-
const FEEDBACK_TAG = /<(\/?)(feedbackInline|qti-feedback-inline|feedbackBlock|qti-feedback-block)\b([^>]*?)(\/?)>/gi;
|
|
99
|
-
/** The top-level feedback elements in `html`, each with the feedback nested inside it. */
|
|
100
|
-
function feedbackElements(html) {
|
|
101
|
-
const roots = [];
|
|
102
|
-
const open = [];
|
|
103
|
-
const add = (element) => (open[open.length - 1]?.children ?? roots).push(element);
|
|
104
|
-
for (const match of html.matchAll(FEEDBACK_TAG)) {
|
|
105
|
-
const [tag, closing, name = '', attrs = '', selfClosing] = match;
|
|
106
|
-
const start = match.index;
|
|
107
|
-
const end = start + tag.length;
|
|
108
|
-
if (closing) {
|
|
109
|
-
const element = open.pop();
|
|
110
|
-
if (!element)
|
|
111
|
-
continue;
|
|
112
|
-
element.closeStart = start;
|
|
113
|
-
element.closeEnd = end;
|
|
114
|
-
add(element);
|
|
115
|
-
}
|
|
116
|
-
else {
|
|
117
|
-
const block = /block$/i.test(name);
|
|
118
|
-
const element = { block, attrs, openStart: start, openEnd: end, closeStart: end, closeEnd: end, children: [] };
|
|
119
|
-
if (selfClosing)
|
|
120
|
-
add(element);
|
|
121
|
-
else
|
|
122
|
-
open.push(element);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
// An unclosed element is left as written, with any feedback inside it.
|
|
126
|
-
return roots;
|
|
127
|
-
}
|
|
128
|
-
/** An attribute in either QTI spelling, e.g. `outcomeIdentifier` or `outcome-identifier`. */
|
|
129
|
-
function feedbackInlineAttr(attrs, name) {
|
|
130
|
-
const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
131
|
-
for (const spelling of kebab === name ? [name] : [name, kebab]) {
|
|
132
|
-
const match = new RegExp(`(?:^|\\s)${spelling}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i').exec(attrs);
|
|
133
|
-
if (match)
|
|
134
|
-
return match[1] ?? match[2] ?? '';
|
|
135
|
-
}
|
|
136
|
-
return null;
|
|
137
|
-
}
|
|
138
|
-
//# sourceMappingURL=feedbackUtils.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"feedbackUtils.js","sourceRoot":"","sources":["../../../src/components/utils/feedbackUtils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAY1D;;;GAGG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAwB;IAC/D,sEAAsE;IACtE,EAAE,OAAO,EAAE,gCAAgC,EAAE,WAAW,EAAE,6BAA6B,EAAE;IACzF,EAAE,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,YAAY,EAAE;IAEtD,oEAAoE;IACpE,EAAE,OAAO,EAAE,8BAA8B,EAAE,WAAW,EAAE,2BAA2B,EAAE;IACrF,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE;CAClD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAChC,OAAe,EACf,aAAkC,2BAA2B;IAE7D,IAAI,CAAC,OAAO;QAAE,OAAO,OAAO,CAAC;IAE7B,IAAI,MAAM,GAAG,OAAO,CAAC;IACrB,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACpC,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,OAAO,EAAE,SAAS,CAAC,WAAW,CAAC,CAAC;IACnE,CAAC;IAED,OAAO,MA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CAAC;AACb,CAAC","sourcesContent":["/**\n * Feedback text utilities for QTI items\n *\n * NOTE: The cleanFeedbackText function contains vendor-specific transforms\n * for content that uses semicolons after \"Correct\" and \"Incorrect\" labels.\n * This is common in some QTI authoring tools but not part of the QTI specification.\n *\n * To customize this behavior for your vendor's content, you can:\n * 1. Modify the patterns in this file\n * 2. Create a vendor-specific transform plugin (see VENDOR-TRANSFORM-PLUGIN-GUIDE.md)\n * 3. Pass custom transforms via the feedbackTransforms option\n */\n\nimport { isShownByIdentifier } from '@pie-qti/qti-common';\n\n/**\n * Text pattern replacement for feedback content\n */\nexport interface FeedbackTransform {\n\t/** Regular expression to match the pattern */\n\tpattern: RegExp;\n\t/** Replacement string (can use capture groups like $1, $2) */\n\treplacement: string;\n}\n\n/**\n * Default feedback text transforms\n * These are vendor-specific patterns commonly found in certain QTI authoring tools\n */\nexport const DEFAULT_FEEDBACK_TRANSFORMS: FeedbackTransform[] = [\n\t// Remove semicolons after \"Incorrect\" (with or without <strong> tags)\n\t{ pattern: /<strong>Incorrect;<\\/strong>/gi, replacement: '<strong>Incorrect</strong> ' },\n\t{ pattern: /Incorrect;/gi, replacement: 'Incorrect ' },\n\n\t// Remove semicolons after \"Correct\" (with or without <strong> tags)\n\t{ pattern: /<strong>Correct;<\\/strong>/gi, replacement: '<strong>Correct</strong> ' },\n\t{ pattern: /Correct;/gi, replacement: 'Correct ' },\n];\n\n/**\n * Clean up feedback text formatting using configurable transforms\n *\n * @param content - The feedback content HTML string\n * @param transforms - Optional custom transforms (defaults to DEFAULT_FEEDBACK_TRANSFORMS)\n * @returns Cleaned feedback content\n */\nexport function cleanFeedbackText(\n\tcontent: string,\n\ttransforms: FeedbackTransform[] = DEFAULT_FEEDBACK_TRANSFORMS\n): string {\n\tif (!content) return content;\n\n\tlet result = content;\n\tfor (const transform of transforms) {\n\t\tresult = result.replace(transform.pattern, transform.replacement);\n\t}\n\n\treturn result;\n}\n\n/**\n * Default outcome identifier for feedback display\n * This can be overridden if your QTI content uses a different identifier\n */\nexport const DEFAULT_FEEDBACK_OUTCOME_ID = 'FEEDBACK';\n\n/**\n * Options for processing feedbackInline elements\n */\nexport interface ProcessFeedbackInlineOptions {\n\t/** Outcome values from response processing */\n\toutcomeValues: Record<string, any>;\n\t/** Whether to apply feedback text cleaning heuristics */\n\tapplyHeuristics?: boolean;\n\t/** Whether to wrap inline feedback content with qti-feedback-inline span */\n\twrapWithSpan?: boolean;\n\t/** Custom feedback transforms (defaults to DEFAULT_FEEDBACK_TRANSFORMS) */\n\ttransforms?: FeedbackTransform[];\n\t/** Drop every feedback element whatever the outcomes. */\n\thideAll?: boolean;\n}\n\n/**\n * Process feedbackInline and feedbackBlock elements in QTI content\n *\n * Shows or hides each `feedbackInline` and `feedbackBlock` (`qti-feedback-inline` and\n * `qti-feedback-block` in QTI 3) by the shared visibility rule: its `identifier` against the\n * outcome value, by membership for a container, inverted by `showHide=\"hide\"`. Nested feedback\n * resolves inside shown feedback; hidden feedback drops with everything inside it. Markup outside\n * feedback elements is left as it is.\n *\n * @param html - The HTML content containing feedbackInline elements\n * @param options - Processing options\n * @returns Modified HTML with processed feedbackInline elements\n *\n * @example\n * ```typescript\n * const html = processFeedbackInline(content, {\n * outcomeValues: { FEEDBACK: 'choiceA' },\n * applyHeuristics: true,\n * wrapWithSpan: true\n * });\n * ```\n */\nexport function processFeedbackInline(\n\thtml: string,\n\toptions: ProcessFeedbackInlineOptions\n): string {\n\tif (!html) return html;\n\tconst feedback = feedbackElements(html);\n\tif (feedback.length === 0) return html;\n\n\tconst { outcomeValues, applyHeuristics = false, wrapWithSpan = false, transforms, hideAll = false } = options;\n\tconst render = (start: number, end: number, elements: readonly FeedbackElement[]): string => {\n\t\tlet out = '';\n\t\tlet position = start;\n\t\tfor (const element of elements) {\n\t\t\tout += html.slice(position, element.openStart);\n\t\t\tposition = element.closeEnd;\n\t\t\tconst outcomeId = feedbackInlineAttr(element.attrs, 'outcomeIdentifier');\n\t\t\tconst feedbackId = feedbackInlineAttr(element.attrs, 'identifier');\n\t\t\tif (hideAll || outcomeId === null || feedbackId === null) continue;\n\t\t\tconst showHide = feedbackInlineAttr(element.attrs, 'showHide');\n\t\t\tif (!isShownByIdentifier(outcomeValues[outcomeId], feedbackId, showHide)) continue;\n\n\t\t\tlet content = render(element.openEnd, element.closeStart, element.children);\n\t\t\tif (applyHeuristics) content = cleanFeedbackText(content, transforms);\n\t\t\tout += wrapWithSpan && !element.block ? ` <span class=\"qti-feedback-inline\">${content}</span>` : content;\n\t\t}\n\t\treturn out + html.slice(position, end);\n\t};\n\treturn render(0, html.length, feedback);\n}\n\nconst FEEDBACK_TAG = /<(\\/?)(feedbackInline|qti-feedback-inline|feedbackBlock|qti-feedback-block)\\b([^>]*?)(\\/?)>/gi;\n\ninterface FeedbackElement {\n\treadonly block: boolean;\n\treadonly attrs: string;\n\treadonly openStart: number;\n\treadonly openEnd: number;\n\tcloseStart: number;\n\tcloseEnd: number;\n\treadonly children: FeedbackElement[];\n}\n\n/** The top-level feedback elements in `html`, each with the feedback nested inside it. */\nfunction feedbackElements(html: string): FeedbackElement[] {\n\tconst roots: FeedbackElement[] = [];\n\tconst open: FeedbackElement[] = [];\n\tconst add = (element: FeedbackElement) => (open[open.length - 1]?.children ?? roots).push(element);\n\tfor (const match of html.matchAll(FEEDBACK_TAG)) {\n\t\tconst [tag, closing, name = '', attrs = '', selfClosing] = match;\n\t\tconst start = match.index;\n\t\tconst end = start + tag.length;\n\t\tif (closing) {\n\t\t\tconst element = open.pop();\n\t\t\tif (!element) continue;\n\t\t\telement.closeStart = start;\n\t\t\telement.closeEnd = end;\n\t\t\tadd(element);\n\t\t} else {\n\t\t\tconst block = /block$/i.test(name);\n\t\t\tconst element: FeedbackElement = { block, attrs, openStart: start, openEnd: end, closeStart: end, closeEnd: end, children: [] };\n\t\t\tif (selfClosing) add(element);\n\t\t\telse open.push(element);\n\t\t}\n\t}\n\t// An unclosed element is left as written, with any feedback inside it.\n\treturn roots;\n}\n\n/** An attribute in either QTI spelling, e.g. `outcomeIdentifier` or `outcome-identifier`. */\nfunction feedbackInlineAttr(attrs: string, name: string): string | null {\n\tconst kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n\tfor (const spelling of kebab === name ? [name] : [name, kebab]) {\n\t\tconst match = new RegExp(`(?:^|\\\\s)${spelling}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)')`, 'i').exec(attrs);\n\t\tif (match) return match[1] ?? match[2] ?? '';\n\t}\n\treturn null;\n}\n"]}
|