@pie-qti/assessment-player 0.1.4 → 0.1.6

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 (32) hide show
  1. package/README.md +19 -16
  2. package/dist/core/AssessmentPlayer.d.ts +21 -2
  3. package/dist/core/AssessmentPlayer.d.ts.map +1 -1
  4. package/dist/core/AssessmentPlayer.js +144 -15
  5. package/dist/core/TimeManager.d.ts +9 -0
  6. package/dist/core/TimeManager.d.ts.map +1 -1
  7. package/dist/core/TimeManager.js +16 -3
  8. package/dist/integration/ReferenceBackendAdapter.d.ts +28 -8
  9. package/dist/integration/ReferenceBackendAdapter.d.ts.map +1 -1
  10. package/dist/integration/ReferenceBackendAdapter.js +409 -51
  11. package/dist/integration/api-contract.d.ts +82 -2
  12. package/dist/integration/api-contract.d.ts.map +1 -1
  13. package/dist/integration/assessment-item-scorer.d.ts +12 -0
  14. package/dist/integration/assessment-item-scorer.d.ts.map +1 -0
  15. package/dist/integration/assessment-item-scorer.js +40 -0
  16. package/dist/integration/index.d.ts +1 -0
  17. package/dist/integration/index.d.ts.map +1 -1
  18. package/dist/integration/index.js +1 -0
  19. package/package.json +6 -6
  20. package/src/components/AccessibilityAnnouncer.svelte +13 -2
  21. package/src/components/AssessmentShell.svelte +13 -8
  22. package/src/components/AssessmentTimer.svelte +23 -0
  23. package/src/components/ItemRenderer.svelte +7 -3
  24. package/src/components/NavigationBar.svelte +2 -0
  25. package/src/components/SectionMenu.svelte +72 -5
  26. package/src/components/index.ts +1 -1
  27. package/src/core/AssessmentPlayer.ts +162 -17
  28. package/src/core/TimeManager.ts +20 -3
  29. package/src/integration/ReferenceBackendAdapter.ts +467 -54
  30. package/src/integration/api-contract.ts +84 -2
  31. package/src/integration/assessment-item-scorer.ts +53 -0
  32. package/src/integration/index.ts +5 -0
@@ -8,7 +8,7 @@
8
8
  * - Apply backend navigation decisions + session state
9
9
  */
10
10
 
11
- import type { QTIRole } from '@pie-qti/item-player';
11
+ import type { QTIRole, PnpProfile } from '@pie-qti/item-player';
12
12
  import { Player } from '@pie-qti/item-player';
13
13
  import type {
14
14
  AssessmentRubricBlock,
@@ -29,7 +29,7 @@ import type {
29
29
  ItemResult,
30
30
  NavigationState,
31
31
  } from '../types/index.js';
32
- import { ItemSessionController } from './ItemSessionController.js';
32
+ import { ItemSessionController, type ItemSessionState } from './ItemSessionController.js';
33
33
  import { NavigationManager } from './NavigationManager.js';
34
34
  import { TimeManager } from './TimeManager.js';
35
35
 
@@ -37,6 +37,8 @@ export interface BackendAssessmentPlayerConfig {
37
37
  backend: BackendAdapter;
38
38
  initSession: InitSessionRequest;
39
39
  role?: QTIRole;
40
+ /** Optional RNG for deterministic shuffling in selection/ordering. Defaults to Math.random. */
41
+ rng?: () => number;
40
42
  /**
41
43
  * Optional hint for item renderers that support multiple extended text editors.
42
44
  * (Plumbed through the shell; the item player remains authoritative for behavior.)
@@ -58,6 +60,13 @@ export interface BackendAssessmentPlayerConfig {
58
60
  showProgress?: boolean;
59
61
  // Time management
60
62
  timeWarningThreshold?: number;
63
+ /**
64
+ * QTI 3.0 §6.2 Personal Needs and Preferences profile.
65
+ * Extended time (pnp.content.extendedTime) is applied to assessment timeLimits.
66
+ * The full profile is passed down to each item player for component-level features
67
+ * (color scheme, elimination tool).
68
+ */
69
+ pnp?: PnpProfile;
61
70
  // Callbacks
62
71
  onItemChange?: (itemIndex: number, totalItems: number) => void;
63
72
  onSectionChange?: (sectionIndex: number, totalSections: number) => void;
@@ -134,6 +143,7 @@ export class AssessmentPlayer {
134
143
  this.navigationManager = new NavigationManager(navigationMode, this.items.length);
135
144
 
136
145
  // Item session control is a UI hint; backend remains authoritative.
146
+ // Start with testPart-level defaults; section-level overrides are applied per item in navigateTo().
137
147
  const itemSessionControl = this.assessment.testParts?.[0]?.itemSessionControl;
138
148
  this.sessionController = new ItemSessionController(itemSessionControl);
139
149
 
@@ -141,12 +151,14 @@ export class AssessmentPlayer {
141
151
  for (const q of this.items) {
142
152
  this.sessionController.initializeItem(q.identifier);
143
153
  }
154
+ this.restoreItemSessionsFromState(this.state);
144
155
 
145
156
  // Initialize time manager if time limits exist
146
157
  if (this.assessment.timeLimits?.maxTime) {
147
158
  this.timeManager = new TimeManager({
148
159
  assessmentTimeLimits: this.assessment.timeLimits,
149
160
  warningThreshold: config.timeWarningThreshold || 60,
161
+ extendedTime: config.pnp?.content?.extendedTime,
150
162
  onWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),
151
163
  onExpired: () => this.notifyTimeExpired(),
152
164
  onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
@@ -157,10 +169,33 @@ export class AssessmentPlayer {
157
169
  const startId = this.state.currentItemIdentifier;
158
170
  const idx = startId ? this.items.findIndex((q) => q.identifier === startId) : -1;
159
171
  if (idx >= 0) {
160
- this.navigateTo(idx).catch(() => {});
172
+ this.navigateTo(idx, { restoring: true }).catch(() => {});
161
173
  }
162
174
  }
163
175
 
176
+ /**
177
+ * Compute effective itemSessionControl for a given item using three-level fallback:
178
+ * section-level (highest priority) → testPart-level → defaults.
179
+ * Section-level values override testPart-level when present.
180
+ */
181
+ private getEffectiveItemSessionControl(flat: FlatItem): SecureSection['itemSessionControl'] {
182
+ const testPartControl = flat.testPart.itemSessionControl;
183
+ const sectionControl = flat.section.itemSessionControl;
184
+
185
+ if (!sectionControl) return testPartControl;
186
+ if (!testPartControl) return sectionControl;
187
+
188
+ return {
189
+ maxAttempts: sectionControl.maxAttempts ?? testPartControl.maxAttempts,
190
+ showFeedback: sectionControl.showFeedback ?? testPartControl.showFeedback,
191
+ allowReview: sectionControl.allowReview ?? testPartControl.allowReview,
192
+ showSolution: sectionControl.showSolution ?? testPartControl.showSolution,
193
+ allowComment: sectionControl.allowComment ?? testPartControl.allowComment,
194
+ allowSkipping: sectionControl.allowSkipping ?? testPartControl.allowSkipping,
195
+ validateResponses: sectionControl.validateResponses ?? testPartControl.validateResponses,
196
+ };
197
+ }
198
+
164
199
  private hasAnyResponse(responses: Record<string, unknown>): boolean {
165
200
  for (const v of Object.values(responses)) {
166
201
  if (v == null) continue;
@@ -178,15 +213,65 @@ export class AssessmentPlayer {
178
213
  return false;
179
214
  }
180
215
 
216
+ private restoreItemSessionsFromState(state: AssessmentSessionState): void {
217
+ const restoredStates = new Map<string, ItemSessionState>();
218
+ for (const item of this.items) {
219
+ const persisted = state.itemSessionStates?.[item.identifier];
220
+ if (persisted) {
221
+ restoredStates.set(item.identifier, {
222
+ itemIdentifier: item.identifier,
223
+ attemptCount: Math.max(0, persisted.attemptCount),
224
+ isAnswered: persisted.isAnswered,
225
+ isSubmitted: persisted.isSubmitted,
226
+ lastSubmissionTime: persisted.lastSubmissionTime,
227
+ });
228
+ continue;
229
+ }
230
+
231
+ const responses = state.itemResponses?.[item.identifier] ?? {};
232
+ const isSubmitted = Boolean(state.itemScores?.[item.identifier]);
233
+ restoredStates.set(item.identifier, {
234
+ itemIdentifier: item.identifier,
235
+ attemptCount: isSubmitted ? 1 : 0,
236
+ isAnswered: this.hasAnyResponse(responses),
237
+ isSubmitted,
238
+ });
239
+ }
240
+ this.sessionController.restoreStates(restoredStates);
241
+ }
242
+
243
+ private getItemSessionStateSnapshot(): Record<string, ItemSessionState> {
244
+ return Object.fromEntries(
245
+ [...this.sessionController.getAllStates().entries()].map(([itemIdentifier, state]) => [
246
+ itemIdentifier,
247
+ { ...state },
248
+ ])
249
+ );
250
+ }
251
+
181
252
  private flattenItems(assessment: SecureAssessment): FlatItem[] {
182
253
  const out: FlatItem[] = [];
183
254
  const testParts = assessment.testParts || [];
184
255
  let idx = 0;
185
256
  let secIdx = 0;
257
+ const rng = this.config.rng ?? Math.random;
186
258
 
187
259
  for (const tp of testParts) {
188
260
  for (const section of tp.sections || []) {
189
- for (const item of section.assessmentItemRefs || []) {
261
+ let refs = [...(section.assessmentItemRefs || [])];
262
+
263
+ // QTI ordering: shuffle items within the section when requested.
264
+ // The server may have already shuffled; if not (e.g. reference adapter), do it client-side.
265
+ if (section.ordering?.shuffle) {
266
+ refs = shuffleArray(refs, rng);
267
+ }
268
+
269
+ // QTI selection: take only `select` items from the (possibly shuffled) list.
270
+ if (section.selection && section.selection.select > 0 && section.selection.select < refs.length) {
271
+ refs = refs.slice(0, section.selection.select);
272
+ }
273
+
274
+ for (const item of refs) {
190
275
  out.push({
191
276
  identifier: item.identifier,
192
277
  item,
@@ -277,12 +362,12 @@ export class AssessmentPlayer {
277
362
  const prev = (this.state.itemResponses?.[itemIdentifier] || {}) as Record<string, unknown>;
278
363
  const next = { ...prev, [responseId]: value };
279
364
  this.state.itemResponses[itemIdentifier] = next as any;
365
+ this.sessionController.markAnswered(itemIdentifier, this.hasAnyResponse(next));
280
366
 
281
367
  // If this is the active item, keep the live response state + UI hints in sync.
282
368
  const active = this.items[this.currentItemIndex];
283
369
  if (active?.identifier === itemIdentifier) {
284
370
  this.responses = next;
285
- this.sessionController.markAnswered(itemIdentifier, this.hasAnyResponse(this.responses));
286
371
  this.currentItemPlayer?.setResponses(this.responses as any);
287
372
  this.notifyResponseChange();
288
373
  }
@@ -307,6 +392,7 @@ export class AssessmentPlayer {
307
392
  visitedItems: [...this.state.visitedItems],
308
393
  itemResponses: { ...this.state.itemResponses },
309
394
  itemScores: this.state.itemScores ? { ...this.state.itemScores } : undefined,
395
+ itemSessionStates: this.getItemSessionStateSnapshot(),
310
396
  timing: {
311
397
  ...this.state.timing,
312
398
  itemTimes: { ...this.state.timing.itemTimes },
@@ -325,6 +411,7 @@ export class AssessmentPlayer {
325
411
  .map((id) => this.items.findIndex((q) => q.identifier === id))
326
412
  .filter((i) => i >= 0);
327
413
  this.navigationManager.restoreState(visitedIdx);
414
+ this.restoreItemSessionsFromState(state);
328
415
 
329
416
  // Rehydrate itemResults from scores if present, so submit() can behave sensibly.
330
417
  this.itemResults.clear();
@@ -342,24 +429,24 @@ export class AssessmentPlayer {
342
429
  const currentId = state.currentItemIdentifier;
343
430
  const idx = currentId ? this.items.findIndex((q) => q.identifier === currentId) : -1;
344
431
  if (idx >= 0) {
345
- await this.navigateTo(idx);
432
+ await this.navigateTo(idx, { restoring: true });
346
433
  } else if (this.items.length > 0) {
347
- await this.navigateTo(0);
434
+ await this.navigateTo(0, { restoring: true });
348
435
  }
349
436
  }
350
437
 
351
- public async navigateTo(index: number): Promise<void> {
438
+ public async navigateTo(index: number, options: { restoring?: boolean } = {}): Promise<void> {
352
439
  if (index < 0 || index >= this.items.length) throw new Error(`Invalid item index: ${index}`);
353
440
 
354
441
  // Enforce navigation rules (UI hints, still backend-authoritative for real deployments).
355
- if (this.currentItemIndex >= 0 && !this.navigationManager.canNavigateTo(index, this.currentItemIndex)) {
442
+ if (!options.restoring && this.currentItemIndex >= 0 && !this.navigationManager.canNavigateTo(index, this.currentItemIndex)) {
356
443
  if (this.navigationManager.getMode() === 'linear' && index > this.currentItemIndex + 1) {
357
444
  throw new Error('In linear navigation mode, you can only move to the next question.');
358
445
  }
359
446
  throw new Error('Navigation is not allowed.');
360
447
  }
361
448
  const target = this.items[index];
362
- if (target && !this.sessionController.canReview(target.identifier)) {
449
+ if (!options.restoring && target && !this.sessionController.canReview(target.identifier)) {
363
450
  throw new Error('You cannot go back to previous questions in this assessment.');
364
451
  }
365
452
 
@@ -367,6 +454,12 @@ export class AssessmentPlayer {
367
454
  const q = this.items[index]!;
368
455
  this.state.currentItemIdentifier = q.identifier;
369
456
 
457
+ // Apply three-level itemSessionControl fallback for this item's section (S1).
458
+ const effectiveControl = this.getEffectiveItemSessionControl(q);
459
+ if (effectiveControl) {
460
+ this.sessionController.updateSettings(effectiveControl);
461
+ }
462
+
370
463
  // Restore responses
371
464
  this.responses = { ...(this.state.itemResponses[q.identifier] || {}) };
372
465
 
@@ -463,11 +556,36 @@ export class AssessmentPlayer {
463
556
  this.sessionController.markAnswered(q.identifier, this.hasAnyResponse(this.responses));
464
557
  this.navigationManager.markVisited(this.currentItemIndex);
465
558
 
466
- // Apply backend branching decision if provided
559
+ // Apply backend branching decision if provided.
560
+ // Special QTI targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION trigger finalization.
467
561
  if (res.nextItemIdentifier) {
468
- const nextIdx = this.items.findIndex((x) => x.identifier === res.nextItemIdentifier);
469
- if (nextIdx >= 0) {
470
- await this.navigateTo(nextIdx);
562
+ const special = res.nextItemIdentifier;
563
+ if (special === 'EXIT_TEST') {
564
+ // Finalize immediately — no further navigation
565
+ for (const l of this.completeListeners) l();
566
+ this.config.onComplete?.();
567
+ } else if (special === 'EXIT_TESTPART' || special === 'EXIT_SECTION') {
568
+ // Advance past all remaining items in the current testPart or section
569
+ const currentItem = this.items[this.currentItemIndex];
570
+ const isSection = special === 'EXIT_SECTION';
571
+ const nextIdx = this.items.findIndex((item, i) =>
572
+ i > this.currentItemIndex &&
573
+ (isSection
574
+ ? item.section.identifier !== currentItem?.section.identifier
575
+ : item.testPart.identifier !== currentItem?.testPart.identifier)
576
+ );
577
+ if (nextIdx >= 0) {
578
+ await this.navigateTo(nextIdx);
579
+ } else {
580
+ // No further items — signal completion
581
+ for (const l of this.completeListeners) l();
582
+ this.config.onComplete?.();
583
+ }
584
+ } else {
585
+ const nextIdx = this.items.findIndex((x) => x.identifier === special);
586
+ if (nextIdx >= 0) {
587
+ await this.navigateTo(nextIdx);
588
+ }
471
589
  }
472
590
  }
473
591
 
@@ -554,9 +672,26 @@ export class AssessmentPlayer {
554
672
  responses: this.state.itemResponses[r.itemIdentifier] || {},
555
673
  }));
556
674
 
557
- this.visibleFeedback = finalized.feedback
558
- ? [{ identifier: 'testFeedback', content: finalized.feedback, access: 'atEnd' }]
559
- : [];
675
+ // Evaluate testFeedback visibility using QTI string equality:
676
+ // show when outcomeIdentifier's value equals feedback.identifier (for showHide='show'),
677
+ // or does NOT equal it (for showHide='hide').
678
+ const structuredFeedback = this.assessment.testFeedback ?? [];
679
+ const outcomes = finalized.outcomes ?? {};
680
+ if (structuredFeedback.length > 0) {
681
+ this.visibleFeedback = structuredFeedback
682
+ .filter((fb) => fb.access === 'atEnd')
683
+ .filter((fb) => {
684
+ const outcomeValue = String(outcomes[fb.outcomeIdentifier] ?? '');
685
+ const matches = outcomeValue === fb.identifier;
686
+ return fb.showHide === 'show' ? matches : !matches;
687
+ })
688
+ .map((fb) => ({ identifier: fb.identifier, content: fb.content, access: fb.access }));
689
+ } else {
690
+ // Legacy: backend returns a plain feedback string
691
+ this.visibleFeedback = finalized.feedback
692
+ ? [{ identifier: 'testFeedback', content: finalized.feedback, access: 'atEnd' }]
693
+ : [];
694
+ }
560
695
 
561
696
  this.notifyComplete();
562
697
  if (this.config.onComplete) this.config.onComplete();
@@ -725,3 +860,13 @@ export class AssessmentPlayer {
725
860
  };
726
861
  }
727
862
  }
863
+
864
+ /** Fisher-Yates shuffle using a provided RNG (returns a new array). */
865
+ function shuffleArray<T>(arr: T[], rng: () => number): T[] {
866
+ const out = [...arr];
867
+ for (let i = out.length - 1; i > 0; i--) {
868
+ const j = Math.floor(rng() * (i + 1));
869
+ [out[i], out[j]] = [out[j], out[i]];
870
+ }
871
+ return out;
872
+ }
@@ -25,6 +25,12 @@ export interface TimeManagerConfig {
25
25
  onExpired?: () => void;
26
26
  /** Callback for time updates (fires every second) */
27
27
  onTick?: (remainingSeconds: number, elapsedSeconds: number) => void;
28
+ /**
29
+ * QTI 3.0 PNP extended time accommodation.
30
+ * When active, multiplies assessmentTimeLimits.maxTime by the given multiplier.
31
+ * multiplier: Infinity removes the time limit entirely.
32
+ */
33
+ extendedTime?: { active: boolean; multiplier: number };
28
34
  }
29
35
 
30
36
  export interface TimeTrackingState {
@@ -63,10 +69,21 @@ export class TimeManager {
63
69
  isPaused: false,
64
70
  };
65
71
 
66
- // Initialize timer if time limit exists
72
+ // Initialize timer if time limit exists, applying PNP extended-time multiplier if set.
67
73
  if (config.assessmentTimeLimits?.maxTime) {
68
- this.maxTimeSeconds = config.assessmentTimeLimits.maxTime;
69
- this.startTimer();
74
+ const base = config.assessmentTimeLimits.maxTime;
75
+ const et = config.extendedTime;
76
+ if (et?.active && et.multiplier === Infinity) {
77
+ // multiplier: Infinity → unlimited time (no countdown)
78
+ this.maxTimeSeconds = null;
79
+ } else if (et?.active && et.multiplier > 0) {
80
+ this.maxTimeSeconds = base * et.multiplier;
81
+ } else {
82
+ this.maxTimeSeconds = base;
83
+ }
84
+ if (this.maxTimeSeconds !== null) {
85
+ this.startTimer();
86
+ }
70
87
  }
71
88
  }
72
89