@pie-qti/item-player 0.1.28 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +35 -6
  2. package/dist/catalog/applyGlossaryTriggers.js +8 -2
  3. package/dist/catalog/applyGlossaryTriggers.js.map +1 -1
  4. package/dist/catalog/catalogExtractor.js +44 -7
  5. package/dist/catalog/catalogExtractor.js.map +1 -1
  6. package/dist/catalog/catalogLookup.d.ts +8 -0
  7. package/dist/catalog/catalogLookup.js +17 -0
  8. package/dist/catalog/catalogLookup.js.map +1 -1
  9. package/dist/catalog/types.d.ts +3 -3
  10. package/dist/catalog/types.js.map +1 -1
  11. package/dist/components/utils/feedbackUtils.d.ts +9 -4
  12. package/dist/components/utils/feedbackUtils.js +67 -34
  13. package/dist/components/utils/feedbackUtils.js.map +1 -1
  14. package/dist/core/AssessmentItemDefinition.js +35 -0
  15. package/dist/core/AssessmentItemDefinition.js.map +1 -1
  16. package/dist/core/ItemSession.d.ts +19 -1
  17. package/dist/core/ItemSession.js +12 -2
  18. package/dist/core/ItemSession.js.map +1 -1
  19. package/dist/core/Player.d.ts +41 -1
  20. package/dist/core/Player.js +216 -48
  21. package/dist/core/Player.js.map +1 -1
  22. package/dist/core/sanitizer.js +16 -3
  23. package/dist/core/sanitizer.js.map +1 -1
  24. package/dist/document/AssessmentItemDocument.d.ts +12 -5
  25. package/dist/document/AssessmentItemDocument.js +28 -19
  26. package/dist/document/AssessmentItemDocument.js.map +1 -1
  27. package/dist/document/contentPass.d.ts +17 -0
  28. package/dist/document/contentPass.js +40 -0
  29. package/dist/document/contentPass.js.map +1 -0
  30. package/dist/document/printedVariable.d.ts +35 -0
  31. package/dist/document/printedVariable.js +215 -0
  32. package/dist/document/printedVariable.js.map +1 -0
  33. package/dist/{element-class-BzATCyhV.js → element-class-D-kJi_w9.js} +3211 -2125
  34. package/dist/element-class-D-kJi_w9.js.map +1 -0
  35. package/dist/element-class.js +1 -1
  36. package/dist/element.js +1 -1
  37. package/dist/extraction/interactionAccessibility.d.ts +14 -0
  38. package/dist/extraction/interactionAccessibility.js +58 -0
  39. package/dist/extraction/interactionAccessibility.js.map +1 -0
  40. package/dist/extraction/interactionExtractionPipeline.d.ts +4 -1
  41. package/dist/extraction/interactionExtractionPipeline.js +7 -2
  42. package/dist/extraction/interactionExtractionPipeline.js.map +1 -1
  43. package/dist/extraction/utils.js +20 -1
  44. package/dist/extraction/utils.js.map +1 -1
  45. package/dist/index.d.ts +9 -3
  46. package/dist/index.js +4 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/interactions/order/extractor.js +2 -0
  49. package/dist/interactions/order/extractor.js.map +1 -1
  50. package/dist/interactions/portable-custom/extractor.js +47 -11
  51. package/dist/interactions/portable-custom/extractor.js.map +1 -1
  52. package/dist/interactions/shared/types.d.ts +16 -0
  53. package/dist/interactions/shared/types.js.map +1 -1
  54. package/dist/pci/PciHost.d.ts +85 -43
  55. package/dist/pci/PciHost.js +229 -148
  56. package/dist/pci/PciHost.js.map +1 -1
  57. package/dist/pci/allowlistResolver.d.ts +10 -1
  58. package/dist/pci/allowlistResolver.js +43 -4
  59. package/dist/pci/allowlistResolver.js.map +1 -1
  60. package/dist/pci/amdLoader.d.ts +23 -0
  61. package/dist/pci/amdLoader.js +190 -0
  62. package/dist/pci/amdLoader.js.map +1 -0
  63. package/dist/pci/index.d.ts +14 -3
  64. package/dist/pci/index.js +8 -1
  65. package/dist/pci/index.js.map +1 -1
  66. package/dist/pci/moduleSession.d.ts +41 -0
  67. package/dist/pci/moduleSession.js +2 -0
  68. package/dist/pci/moduleSession.js.map +1 -0
  69. package/dist/pci/pageRealmSession.d.ts +49 -0
  70. package/dist/pci/pageRealmSession.js +193 -0
  71. package/dist/pci/pageRealmSession.js.map +1 -0
  72. package/dist/pci/qtiVariableJson.d.ts +7 -0
  73. package/dist/pci/qtiVariableJson.js +93 -0
  74. package/dist/pci/qtiVariableJson.js.map +1 -0
  75. package/dist/pci/registry.d.ts +15 -0
  76. package/dist/pci/registry.js +77 -0
  77. package/dist/pci/registry.js.map +1 -0
  78. package/dist/pci/resolutionConfig.d.ts +23 -0
  79. package/dist/pci/resolutionConfig.js +63 -0
  80. package/dist/pci/resolutionConfig.js.map +1 -0
  81. package/dist/pci/sandbox/SandboxedPciSession.d.ts +78 -0
  82. package/dist/pci/sandbox/SandboxedPciSession.js +332 -0
  83. package/dist/pci/sandbox/SandboxedPciSession.js.map +1 -0
  84. package/dist/pci/sandbox/iframeConnector.d.ts +13 -0
  85. package/dist/pci/sandbox/iframeConnector.js +94 -0
  86. package/dist/pci/sandbox/iframeConnector.js.map +1 -0
  87. package/dist/pci/sandbox/protocol.d.ts +117 -0
  88. package/dist/pci/sandbox/protocol.js +49 -0
  89. package/dist/pci/sandbox/protocol.js.map +1 -0
  90. package/dist/pci/types.d.ts +213 -30
  91. package/dist/pci/types.js +8 -1
  92. package/dist/pci/types.js.map +1 -1
  93. package/dist/pnp/applyPnp.d.ts +3 -4
  94. package/dist/pnp/applyPnp.js +54 -8
  95. package/dist/pnp/applyPnp.js.map +1 -1
  96. package/dist/pnp/parsePnpXml.d.ts +2 -2
  97. package/dist/pnp/parsePnpXml.js +146 -4
  98. package/dist/pnp/parsePnpXml.js.map +1 -1
  99. package/dist/pnp/types.d.ts +57 -0
  100. package/dist/pnp/types.js.map +1 -1
  101. package/dist/presentation/itemPresentationPlan.d.ts +12 -1
  102. package/dist/presentation/itemPresentationPlan.js +11 -3
  103. package/dist/presentation/itemPresentationPlan.js.map +1 -1
  104. package/dist/server.d.ts +5 -0
  105. package/dist/server.js.map +1 -1
  106. package/dist/types/index.d.ts +5 -0
  107. package/dist/types/index.js.map +1 -1
  108. package/package.json +6 -6
  109. package/dist/element-class-BzATCyhV.js.map +0 -1
@@ -1,6 +1,8 @@
1
1
  import { buildOutcomeProcessingAst, buildResponseProcessingAst, buildTemplateProcessingAst, coerceBaseValue, DeclarationContext, evalExpr, execProgram, findDescendants, findFirstDescendant, getAttr, OperatorRegistry, qtiNull, qtiValue, toBoolean, toNumber, toStringValue, } from '@pie-qti/qti-processing';
2
- import { Qti2xElementNameMapper, Qti2xAttributeNameMapper, Qti3ElementNameMapper, Qti3AttributeNameMapper, detectQtiVersion, } from '@pie-qti/qti-common';
2
+ import { prepareContentMarkup } from '@pie-qti/qti-common/accessibility';
3
+ import { Qti2xElementNameMapper, Qti2xAttributeNameMapper, Qti3ElementNameMapper, Qti3AttributeNameMapper, detectQtiVersion, isShownByIdentifier, } from '@pie-qti/qti-common';
3
4
  import { parseAssessmentItemDocument } from '../document/AssessmentItemDocument.js';
5
+ import { printVariable, readPrintedVariableOptions } from '../document/printedVariable.js';
4
6
  import { createExtractionRegistry, registerFrameworkDeliveryFields, } from '../extraction/ExtractionRegistry.js';
5
7
  import { extractInteractionData } from '../extraction/interactionExtractionPipeline.js';
6
8
  import { getStandardInteractionModules } from '../interactions/modules.js';
@@ -9,11 +11,24 @@ import { createSeededRng } from './random.js';
9
11
  import { sanitizeHtml } from './sanitizer.js';
10
12
  import { toTrustedHtml } from './trustedTypes.js';
11
13
  import { sanitizeResourceUrl } from './urlPolicy.js';
14
+ import { enforceItemXmlLimits } from './parsingLimits.js';
12
15
  import { applyPnpToRoot } from '../pnp/applyPnp.js';
13
16
  import { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';
14
- import { getCatalogEntry } from '../catalog/catalogLookup.js';
17
+ import { getCatalogEntryWithAliases } from '../catalog/catalogLookup.js';
15
18
  import { PciHost } from '../pci/PciHost.js';
16
19
  import { createExtendedTextNumericRecord, EXTENDED_TEXT_RECORD_FIELD_TYPES, } from '../interactions/extended-text/response.js';
20
+ /** Choices a template variable can show or hide, by canonical name. */
21
+ const TEMPLATE_CHOICES = [
22
+ 'simplechoice',
23
+ 'simpleassociablechoice',
24
+ 'gaptext',
25
+ 'gapimg',
26
+ 'gap',
27
+ 'hottext',
28
+ 'inlinechoice',
29
+ 'hotspotchoice',
30
+ 'associablehotspot',
31
+ ];
17
32
  /** @internal Used by AssessmentItemDefinition; deliberately absent from the package root API. */
18
33
  export function preparePlayerDefinitionInternal(config) {
19
34
  const compiler = new Player(config, undefined, { compileOnly: true });
@@ -33,6 +48,8 @@ export function createPlayerFromPreparedInternal(config, prepared, skipTemplateP
33
48
  export class Player {
34
49
  constructor(config, prepared, construction = {}) {
35
50
  this.interactionDataCache = null;
51
+ /** Template variables declared with `mathVariable`, substituted into MathML. */
52
+ this.mathVariableIds = null;
36
53
  this.warnedImpliedZeroMaxScore = false;
37
54
  this.responseProcessingProgram = null;
38
55
  this.templateProcessingProgram = null;
@@ -80,6 +97,11 @@ export class Player {
80
97
  this.decls = cloneDeclarationMap(prepared.declarations);
81
98
  }
82
99
  else {
100
+ // Read-aloud markup: suppression restated as the attribute the PIE tools read, and SSML
101
+ // docked as catalog idrefs and unwrapped from the visible body. The section player derives
102
+ // the same `spoken` cards from the same XML.
103
+ enforceItemXmlLimits(this.itemXml, this.config.security);
104
+ this.itemXml = prepareContentMarkup(this.itemXml, [], { hidingStyles: false }).xml;
83
105
  this.itemDocument = parseAssessmentItemDocument({
84
106
  itemXml: this.itemXml,
85
107
  elementNameMapper: this.mapper,
@@ -89,6 +111,8 @@ export class Player {
89
111
  this.decls = this.buildDeclarations();
90
112
  this.ensureBuiltinDeclarations(this.decls);
91
113
  }
114
+ this.applyContextVariables(config.contextVariables);
115
+ this.applyTemplateDefaults(config.templateDefaults);
92
116
  this.sourceDeclarations = cloneDeclarationMap(this.decls);
93
117
  this.ctx = new DeclarationContext(this.decls);
94
118
  this.ops = new OperatorRegistry();
@@ -157,6 +181,8 @@ export class Player {
157
181
  // Build the catalog index from shared catalog XML, item XML, and resolved delivery context.
158
182
  // Sanitized item-level delivery context entries win over raw item XML on collisions.
159
183
  // Stimulus entries are kept separately so rendered stimulus terms can avoid ID collisions.
184
+ // Package (shared catalog file) entries merge first: they hold the lowest
185
+ // precedence, below catalogXml and the item's own catalogs (QTI 3.0 §6.3).
160
186
  if (prepared) {
161
187
  this._catalogIndex = prepared.catalogIndex;
162
188
  this._stimulusCatalogIndexes = prepared.stimulusCatalogIndexes;
@@ -170,6 +196,9 @@ export class Player {
170
196
  const existing = this._stimulusCatalogIndexes.get(source.stimulusIdentifier) ?? new Map();
171
197
  this._stimulusCatalogIndexes.set(source.stimulusIdentifier, mergeCatalogs(existing, sourceCatalog));
172
198
  }
199
+ else if (source.scope === 'package') {
200
+ mergedCatalog = mergeCatalogs(mergedCatalog, sourceCatalog);
201
+ }
173
202
  else {
174
203
  deliveryItemCatalog = mergeCatalogs(deliveryItemCatalog, sourceCatalog);
175
204
  }
@@ -227,6 +256,10 @@ export class Player {
227
256
  listener(this._pnp);
228
257
  }
229
258
  }
259
+ /** The language the item's content is written in, from the nearest `xml:lang` on its body. */
260
+ getContentLanguage() {
261
+ return this.itemDocument.getContentLanguage();
262
+ }
230
263
  /** Return the current resolved PNP profile. */
231
264
  getPnp() {
232
265
  return this._pnp;
@@ -247,9 +280,9 @@ export class Player {
247
280
  */
248
281
  getCatalogEntry(idref, usage, lang, options) {
249
282
  const stimulusHtml = options?.stimulusIdentifier
250
- ? getCatalogEntry(this._stimulusCatalogIndexes.get(options.stimulusIdentifier) ?? new Map(), idref, usage, lang)
283
+ ? getCatalogEntryWithAliases(this._stimulusCatalogIndexes.get(options.stimulusIdentifier) ?? new Map(), idref, usage, lang)
251
284
  : null;
252
- const html = stimulusHtml ?? getCatalogEntry(this._catalogIndex, idref, usage, lang);
285
+ const html = stimulusHtml ?? getCatalogEntryWithAliases(this._catalogIndex, idref, usage, lang);
253
286
  if (html === null)
254
287
  return null;
255
288
  if (looksLikeCatalogUrl(html)) {
@@ -270,6 +303,13 @@ export class Player {
270
303
  const host = new PciHost(data, {
271
304
  baseUrl: this.config.pci?.baseUrl,
272
305
  moduleResolver: this.config.pci?.moduleResolver,
306
+ sandbox: this.config.pci?.sandbox,
307
+ modulePolicy: this.config.pci?.modulePolicy,
308
+ responseDeclaration: (() => {
309
+ const d = this.decls[data.responseIdentifier];
310
+ return d ? { baseType: d.baseType, cardinality: d.cardinality } : undefined;
311
+ })(),
312
+ status: () => this.pciInteractionStatus(),
273
313
  });
274
314
  // Wire response changes back into the player's declaration context
275
315
  host.onResponseChange((responseId, value) => {
@@ -310,6 +350,19 @@ export class Player {
310
350
  host.enable();
311
351
  }
312
352
  }
353
+ /**
354
+ * The QTI 3.0 §6.1 interaction status a PCI instantiates with: 'solution' when
355
+ * correct responses are exposed, 'review' for non-candidate roles otherwise,
356
+ * 'closed' once the attempt finished, 'interacting' while the candidate works.
357
+ * Hosts that know better pass their own `status` to the PciHost options.
358
+ */
359
+ pciInteractionStatus() {
360
+ if (this.role !== 'candidate')
361
+ return 'review';
362
+ if (this.lifecycleStatus === 'closed')
363
+ return 'closed';
364
+ return 'interacting';
365
+ }
313
366
  /**
314
367
  * Destroy all PCI hosts. Call on player teardown.
315
368
  */
@@ -634,11 +687,29 @@ export class Player {
634
687
  maxScore,
635
688
  completed,
636
689
  outcomeValues: outcomes,
690
+ correct: this.responsesMatchCorrect(),
637
691
  modalFeedback: this.getModalFeedback(outcomes),
638
692
  };
639
693
  }
694
+ /**
695
+ * QTI item correctness, as test-level `numberCorrect` reads it: every declared response matches
696
+ * its correct response. Undefined when the item has no response or one declares no correct
697
+ * response.
698
+ */
699
+ responsesMatchCorrect() {
700
+ const responses = Object.values(this.decls).filter((d) => d.__kind === 'response');
701
+ if (responses.length === 0 || responses.some((d) => d.correctResponse?.kind !== 'value'))
702
+ return undefined;
703
+ const env = { ctx: this.ctx, ops: this.ops, rng: this.rng, customOperators: this.config.customOperators };
704
+ return responses.every((d) => toBoolean(evalExpr(env, {
705
+ kind: 'expr.match',
706
+ id: `correct-${d.identifier}`,
707
+ a: { kind: 'expr.variable', id: `correct-${d.identifier}-response`, identifier: d.identifier },
708
+ b: { kind: 'expr.correct', id: `correct-${d.identifier}-correct`, identifier: d.identifier },
709
+ })));
710
+ }
640
711
  getItemBodyHtml() {
641
- const inner = this.itemDocument.serializeItemBodyChildren();
712
+ const inner = this.itemDocument.serializeItemBodyChildren(this.contentHandlers({ feedback: false }));
642
713
  if (!inner)
643
714
  return '';
644
715
  return this.renderHtmlContent(inner);
@@ -653,7 +724,7 @@ export class Player {
653
724
  */
654
725
  getRubrics(options = {}) {
655
726
  const role = this.role;
656
- const rubrics = this.itemDocument.readRubricBlocks();
727
+ const rubrics = this.itemDocument.readRubricBlocks(this.contentHandlers());
657
728
  if (rubrics.length === 0)
658
729
  return [];
659
730
  const blocks = [];
@@ -665,9 +736,7 @@ export class Player {
665
736
  // If view is specified, show only when it includes the current role.
666
737
  if (view.length > 0 && role && !view.includes(role))
667
738
  continue;
668
- const printed = this.renderPrintedVariables(rubric.content);
669
- const sanitized = sanitizeHtml(printed, { security: this.config.security });
670
- const html = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
739
+ const html = this.renderHtmlContent(rubric.content);
671
740
  blocks.push({ view, html, scope, use: rubric.use });
672
741
  }
673
742
  return blocks;
@@ -693,6 +762,9 @@ export class Player {
693
762
  // resumed session reproduces the order the candidate already saw, while a
694
763
  // different candidate or a new attempt gets a different one.
695
764
  sessionGuid: this.sessionGuid,
765
+ // Template content resolves before extraction, so interactions are extracted again
766
+ // when template values change. Choice feedback resolves in presentation.
767
+ contentHandlers: this.contentHandlers({ feedback: false }),
696
768
  });
697
769
  return this.interactionDataCache;
698
770
  }
@@ -814,6 +886,7 @@ export class Player {
814
886
  return out;
815
887
  }
816
888
  setTemplateVariables(vars) {
889
+ this.interactionDataCache = null;
817
890
  for (const [id, raw] of Object.entries(vars)) {
818
891
  const d = this.decls[id];
819
892
  if (!d?.isTemplate)
@@ -1000,6 +1073,7 @@ export class Player {
1000
1073
  // Execution
1001
1074
  // ----------------------------------------------------------------------------
1002
1075
  execTemplateProcessing() {
1076
+ this.interactionDataCache = null;
1003
1077
  if (!this.templateProcessingProgram)
1004
1078
  return;
1005
1079
  execProgram({
@@ -1186,14 +1260,33 @@ export class Player {
1186
1260
  addDecl('outcome', el);
1187
1261
  for (const el of this.itemDocument.findDeclarationElements('template'))
1188
1262
  addDecl('template', el);
1263
+ for (const el of this.itemDocument.findDeclarationElements('context'))
1264
+ addDecl('context', el);
1189
1265
  return decls;
1190
1266
  }
1267
+ /** Host-supplied context values, e.g. `QTI_CONTEXT`; identifiers that are not context variables are ignored. */
1268
+ applyContextVariables(values) {
1269
+ for (const [id, raw] of Object.entries(values ?? {})) {
1270
+ const d = this.decls[id];
1271
+ if (d?.__kind !== 'context')
1272
+ continue;
1273
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);
1274
+ }
1275
+ }
1276
+ /** Test-supplied template defaults; identifiers that are not template variables are ignored. */
1277
+ applyTemplateDefaults(values) {
1278
+ for (const [id, raw] of Object.entries(values ?? {})) {
1279
+ const d = this.decls[id];
1280
+ if (!d?.isTemplate)
1281
+ continue;
1282
+ d.defaultValue = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);
1283
+ d.value = d.defaultValue;
1284
+ }
1285
+ }
1191
1286
  parseMatchTable(el) {
1192
- const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();
1193
- const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;
1194
1287
  return {
1195
1288
  kind: 'table.matchTable',
1196
- defaultValue: Number.isFinite(defaultValue) ? defaultValue : undefined,
1289
+ defaultValue: (getAttr(el, 'defaultValue') || '').trim() || undefined,
1197
1290
  entries: findDescendants(el, this.mapper.toNative('matchtableentry')).map((e) => ({
1198
1291
  sourceValue: (getAttr(e, 'sourceValue') || '').trim(),
1199
1292
  targetValue: (getAttr(e, 'targetValue') || '').trim(),
@@ -1201,19 +1294,16 @@ export class Player {
1201
1294
  };
1202
1295
  }
1203
1296
  parseInterpolationTable(el) {
1204
- const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();
1205
- const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;
1206
- const interpolationMethod = (getAttr(el, 'interpolationMethod') || 'linear').trim();
1207
1297
  return {
1208
1298
  kind: 'table.interpolationTable',
1209
- defaultValue: Number.isFinite(defaultValue) ? defaultValue : undefined,
1210
- interpolationMethod,
1299
+ defaultValue: (getAttr(el, 'defaultValue') || '').trim() || undefined,
1211
1300
  entries: findDescendants(el, this.mapper.toNative('interpolationtableentry'))
1212
1301
  .map((e) => ({
1213
- sourceValue: Number((getAttr(e, 'sourceValue') || '').trim()),
1214
- targetValue: Number((getAttr(e, 'targetValue') || '').trim()),
1302
+ sourceValue: Number((getAttr(e, 'sourceValue') || '').trim() || Number.NaN),
1303
+ targetValue: (getAttr(e, 'targetValue') || '').trim(),
1304
+ includeBoundary: (getAttr(e, 'includeBoundary') || '').trim() !== 'false',
1215
1305
  }))
1216
- .filter((e) => Number.isFinite(e.sourceValue) && Number.isFinite(e.targetValue)),
1306
+ .filter((e) => Number.isFinite(e.sourceValue)),
1217
1307
  };
1218
1308
  }
1219
1309
  ensureBuiltinDeclarations(decls) {
@@ -1254,6 +1344,18 @@ export class Player {
1254
1344
  __kind: 'outcome',
1255
1345
  };
1256
1346
  }
1347
+ // QTI 3 built-in context variable, set by the delivery system.
1348
+ if (!decls.QTI_CONTEXT) {
1349
+ decls.QTI_CONTEXT = {
1350
+ identifier: 'QTI_CONTEXT',
1351
+ cardinality: 'record',
1352
+ defaultValue: qtiNull(undefined, 'record'),
1353
+ value: qtiNull(undefined, 'record'),
1354
+ isTemplate: false,
1355
+ // @ts-expect-error internal marker
1356
+ __kind: 'context',
1357
+ };
1358
+ }
1257
1359
  // Common scoring defaults
1258
1360
  if (!decls.SCORE) {
1259
1361
  decls.SCORE = {
@@ -1314,7 +1416,7 @@ export class Player {
1314
1416
  if (d.isTemplate) {
1315
1417
  templateVariables[d.identifier] = { ...variable, kind: 'template' };
1316
1418
  }
1317
- else if (contextIds.has(d.identifier)) {
1419
+ else if (contextIds.has(d.identifier) || d.__kind === 'context') {
1318
1420
  contextVariables[d.identifier] = { ...variable, kind: 'context' };
1319
1421
  }
1320
1422
  else if (d.__kind === 'response') {
@@ -1626,41 +1728,106 @@ export class Player {
1626
1728
  return out;
1627
1729
  }
1628
1730
  // ----------------------------------------------------------------------------
1629
- // printedVariable + feedback
1731
+ // Item content pass: printedVariable, feedback, templates
1630
1732
  // ----------------------------------------------------------------------------
1631
- renderPrintedVariables(html) {
1632
- const readIdentifier = (attrs) => {
1633
- const m = attrs.match(/identifier\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);
1634
- return (m?.[1] || m?.[2] || m?.[3] || '').trim() || null;
1635
- };
1636
- const renderId = (id) => {
1637
- if (!id)
1638
- return '';
1639
- const v = this.ctx.getValue(id);
1640
- if (v.kind !== 'value')
1641
- return '';
1642
- if (Array.isArray(v.value))
1643
- return v.value.map(String).join(', ');
1644
- return String(v.value);
1645
- };
1646
- let out = html.replace(/<printedVariable\b([^>]*)>([\s\S]*?)<\/printedVariable>/gi, (_m, attrs) => renderId(readIdentifier(String(attrs))));
1647
- out = out.replace(/<printedVariable\b([^>]*)\/>/gi, (_m, attrs) => renderId(readIdentifier(String(attrs))));
1648
- return out;
1733
+ /**
1734
+ * The item content pass's handlers, reading the session's current variable values. QTI 3 wraps
1735
+ * rubric content in `qti-content-body`, which is unwrapped so a rubric renders as in QTI 2.2.
1736
+ * Feedback resolves here for rubric and modal feedback content; item body and choice feedback
1737
+ * resolve in presentation, which takes the outcome values to present as input.
1738
+ */
1739
+ contentHandlers({ feedback = true } = {}) {
1740
+ const conditional = (variable) => (element) => this.isShownByVariable(element, variable, getAttr(element, 'identifier')) ? Array.from(element.childNodes) : [];
1741
+ const handlers = new Map([
1742
+ ['printedvariable', (element) => this.printedVariableNodes(element)],
1743
+ ['contentbody', (element) => Array.from(element.childNodes)],
1744
+ ['templateinline', conditional('templateIdentifier')],
1745
+ ['templateblock', conditional('templateIdentifier')],
1746
+ ]);
1747
+ for (const choice of TEMPLATE_CHOICES) {
1748
+ handlers.set(choice, (element) => !getAttr(element, 'templateIdentifier') ||
1749
+ this.isShownByVariable(element, 'templateIdentifier', getAttr(element, 'identifier'))
1750
+ ? undefined
1751
+ : []);
1752
+ }
1753
+ if (this.mathVariables().size > 0) {
1754
+ handlers.set('mi', (element) => this.mathVariableNodes(element, 'mn'));
1755
+ handlers.set('ci', (element) => this.mathVariableNodes(element, 'cn'));
1756
+ }
1757
+ if (feedback) {
1758
+ handlers.set('feedbackinline', conditional('outcomeIdentifier'));
1759
+ handlers.set('feedbackblock', conditional('outcomeIdentifier'));
1760
+ }
1761
+ return handlers;
1762
+ }
1763
+ /**
1764
+ * Whether `element` shows: the variable named by its `variableAttribute` against `identifier`,
1765
+ * by the shared visibility rule. A missing variable or identifier hides it.
1766
+ */
1767
+ isShownByVariable(element, variableAttribute, identifier) {
1768
+ const variable = (getAttr(element, variableAttribute) || '').trim();
1769
+ const id = (identifier || '').trim();
1770
+ if (!variable || !id)
1771
+ return false;
1772
+ const current = this.ctx.getValue(variable);
1773
+ return isShownByIdentifier(current.kind === 'value' ? current.value : null, id, getAttr(element, 'showHide'));
1774
+ }
1775
+ mathVariables() {
1776
+ this.mathVariableIds ?? (this.mathVariableIds = new Set(this.itemDocument
1777
+ .findDeclarationElements('template')
1778
+ .filter((el) => getAttr(el, 'mathVariable')?.trim() === 'true')
1779
+ .map((el) => (getAttr(el, 'identifier') || '').trim())));
1780
+ return this.mathVariableIds;
1781
+ }
1782
+ /**
1783
+ * A MathML `mi` or `ci` naming a math variable, with the variable's single value in its place:
1784
+ * a number as `mn` or `cn` (`numberName`), any other value as the element's text. NULL and
1785
+ * container values leave the element as authored.
1786
+ */
1787
+ mathVariableNodes(element, numberName) {
1788
+ const identifier = (element.textContent || '').trim();
1789
+ const document = element.ownerDocument;
1790
+ if (!document || !this.mathVariables().has(identifier))
1791
+ return undefined;
1792
+ const value = this.ctx.getValue(identifier);
1793
+ if (value.kind !== 'value' || value.cardinality !== 'single')
1794
+ return undefined;
1795
+ const text = String(value.value);
1796
+ if (value.baseType !== 'integer' && value.baseType !== 'float') {
1797
+ // The pass resolves a copy, and the element is not walked again, so this cannot cycle.
1798
+ element.textContent = text;
1799
+ return undefined;
1800
+ }
1801
+ const name = element.prefix ? `${element.prefix}:${numberName}` : numberName;
1802
+ const replacement = document.createElementNS(element.namespaceURI, name);
1803
+ replacement.appendChild(document.createTextNode(text));
1804
+ return [replacement];
1805
+ }
1806
+ printedVariableNodes(element) {
1807
+ const identifier = (getAttr(element, 'identifier') || '').trim();
1808
+ const document = element.ownerDocument;
1809
+ if (!identifier || !document)
1810
+ return [];
1811
+ const variable = (id) => this.ctx.getValue(id);
1812
+ const printed = printVariable(variable(identifier), readPrintedVariableOptions(element, variable));
1813
+ return printed.map((segment) => {
1814
+ if (typeof segment === 'string')
1815
+ return document.createTextNode(segment);
1816
+ const sup = document.createElementNS(element.namespaceURI, 'sup');
1817
+ sup.appendChild(document.createTextNode(segment.superscript));
1818
+ return sup;
1819
+ });
1649
1820
  }
1650
1821
  renderHtmlContent(html) {
1651
- const printed = this.renderPrintedVariables(html);
1652
- const sanitized = sanitizeHtml(printed, { security: this.config.security });
1822
+ const sanitized = sanitizeHtml(html, { security: this.config.security });
1653
1823
  return toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
1654
1824
  }
1655
1825
  getModalFeedback(outcomes) {
1656
1826
  const active = [];
1657
- for (const feedback of this.itemDocument.readModalFeedback()) {
1827
+ for (const feedback of this.itemDocument.readModalFeedback(this.contentHandlers())) {
1658
1828
  const { identifier, outcomeIdentifier, showHide, title } = feedback;
1659
- const sanitized = sanitizeHtml(feedback.content, { security: this.config.security });
1660
- const content = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
1661
- const outcomeValue = outcomes[outcomeIdentifier];
1662
- const shouldShow = showHide === 'show' ? outcomeValue === identifier : outcomeValue !== identifier;
1663
- if (shouldShow && content) {
1829
+ const content = this.renderHtmlContent(feedback.content);
1830
+ if (isShownByIdentifier(outcomes[outcomeIdentifier], identifier, showHide) && content) {
1664
1831
  active.push({ identifier, outcomeIdentifier, showHide, content, title });
1665
1832
  }
1666
1833
  }
@@ -1675,6 +1842,7 @@ function mergePnp(base, partial) {
1675
1842
  display: { ...(base?.display ?? {}), ...(partial.display ?? {}) },
1676
1843
  content: { ...(base?.content ?? {}), ...(partial.content ?? {}) },
1677
1844
  cognitive: { ...(base?.cognitive ?? {}), ...(partial.cognitive ?? {}) },
1845
+ ...(base?.tools || partial.tools ? { tools: { ...(base?.tools ?? {}), ...(partial.tools ?? {}) } } : {}),
1678
1846
  };
1679
1847
  }
1680
1848
  function createSessionGuid() {