@pie-qti/assessment-player 0.1.1

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 (74) hide show
  1. package/.turbo/turbo-build.log +1 -0
  2. package/BACKEND-INTEGRATION.md +620 -0
  3. package/CHANGELOG.md +11 -0
  4. package/EXTENSIBILITY.md +551 -0
  5. package/README.md +1137 -0
  6. package/dist/core/AssessmentPlayer.d.ts +151 -0
  7. package/dist/core/AssessmentPlayer.d.ts.map +1 -0
  8. package/dist/core/AssessmentPlayer.js +595 -0
  9. package/dist/core/ItemSessionController.d.ts +119 -0
  10. package/dist/core/ItemSessionController.d.ts.map +1 -0
  11. package/dist/core/ItemSessionController.js +227 -0
  12. package/dist/core/NavigationManager.d.ts +59 -0
  13. package/dist/core/NavigationManager.d.ts.map +1 -0
  14. package/dist/core/NavigationManager.js +104 -0
  15. package/dist/core/StatePersistenceManager.d.ts +126 -0
  16. package/dist/core/StatePersistenceManager.d.ts.map +1 -0
  17. package/dist/core/StatePersistenceManager.js +267 -0
  18. package/dist/core/TimeManager.d.ts +123 -0
  19. package/dist/core/TimeManager.d.ts.map +1 -0
  20. package/dist/core/TimeManager.js +217 -0
  21. package/dist/core/index.d.ts +10 -0
  22. package/dist/core/index.d.ts.map +1 -0
  23. package/dist/core/index.js +5 -0
  24. package/dist/index.d.ts +6 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +7 -0
  27. package/dist/integration/ReferenceBackendAdapter.d.ts +128 -0
  28. package/dist/integration/ReferenceBackendAdapter.d.ts.map +1 -0
  29. package/dist/integration/ReferenceBackendAdapter.js +735 -0
  30. package/dist/integration/api-contract.d.ts +319 -0
  31. package/dist/integration/api-contract.d.ts.map +1 -0
  32. package/dist/integration/api-contract.js +19 -0
  33. package/dist/integration/index.d.ts +47 -0
  34. package/dist/integration/index.d.ts.map +1 -0
  35. package/dist/integration/index.js +46 -0
  36. package/dist/types/index.d.ts +51 -0
  37. package/dist/types/index.d.ts.map +1 -0
  38. package/dist/types/index.js +7 -0
  39. package/dist/utils/PerformanceMonitor.d.ts +115 -0
  40. package/dist/utils/PerformanceMonitor.d.ts.map +1 -0
  41. package/dist/utils/PerformanceMonitor.js +171 -0
  42. package/package.json +82 -0
  43. package/src/ambient.d.ts +55 -0
  44. package/src/components/AccessibilityAnnouncer.svelte +102 -0
  45. package/src/components/AssessmentHeader.svelte +76 -0
  46. package/src/components/AssessmentShell.svelte +485 -0
  47. package/src/components/AssessmentTimer.svelte +228 -0
  48. package/src/components/ItemRenderer.svelte +147 -0
  49. package/src/components/ItemSessionInfo.svelte +241 -0
  50. package/src/components/NavigationBar.svelte +142 -0
  51. package/src/components/RubricDisplay.svelte +185 -0
  52. package/src/components/SectionMenu.svelte +206 -0
  53. package/src/components/SplitPaneResizer.svelte +288 -0
  54. package/src/components/TestFeedback.svelte +147 -0
  55. package/src/components/index.ts +19 -0
  56. package/src/core/AssessmentPlayer.ts +720 -0
  57. package/src/core/ItemSessionController.ts +287 -0
  58. package/src/core/NavigationManager.ts +126 -0
  59. package/src/core/StatePersistenceManager.ts +344 -0
  60. package/src/core/TimeManager.ts +289 -0
  61. package/src/core/index.ts +15 -0
  62. package/src/index.ts +13 -0
  63. package/src/integration/ReferenceBackendAdapter.ts +861 -0
  64. package/src/integration/api-contract.ts +377 -0
  65. package/src/integration/index.ts +70 -0
  66. package/src/svelte-shims.d.ts +7 -0
  67. package/src/types/index.ts +56 -0
  68. package/src/utils/PerformanceMonitor.ts +222 -0
  69. package/svelte.config.js +8 -0
  70. package/tests/ReferenceBackendAdapter.spec.ts +309 -0
  71. package/tests/setup.ts +103 -0
  72. package/tests/smoke.test.ts +7 -0
  73. package/tsconfig.json +20 -0
  74. package/tsconfig.svelte.json +10 -0
package/README.md ADDED
@@ -0,0 +1,1137 @@
1
+ # @pie-qti/assessment-player
2
+
3
+ QTI 2.x Assessment Player - Multi-item test player with navigation, sections, and rubric blocks.
4
+
5
+ ## Features
6
+
7
+ - ✅ **Multi-item assessments** - Support for complete QTI assessmentTest structures
8
+ - ✅ **Navigation modes** - Linear (sequential) and nonlinear (free navigation)
9
+ - ✅ **Sections & hierarchy** - Nested sections with navigation
10
+ - ✅ **Rubric blocks** - Reading passages, instructions, and rubrics
11
+ - ✅ **Progress tracking** - Visual progress indicators
12
+ - ✅ **Section menu** - Quick navigation between sections
13
+ - ✅ **Outcome Processing** - QTI 2.x scoring with total/weighted/percentage/pass-fail templates
14
+ - ✅ **Test Feedback** - Conditional feedback based on outcome variables
15
+ - ✅ **Time Limits** - Assessment-level countdown timers with warnings and auto-submission
16
+ - ✅ **Item Session Control** - Max attempts, review/skip controls, response validation
17
+ - ✅ **State Persistence** - Auto-save with resume capability and optional backend integration
18
+ - ✅ **Selection & Ordering** - Random item selection and shuffling per QTI 2.x spec
19
+ - ✅ **QTI 2.x Standard Roles** - Candidate, scorer, tutor, author, proctor, testConstructor
20
+ - ✅ **Backend Integration** - Optional secure backend API (client-side by default)
21
+ - ✅ **Svelte 5 components** - Modern reactive UI
22
+ - ✅ **TypeScript** - Full type safety
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ bun add @pie-qti/assessment-player
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ### Basic Usage with Svelte
33
+
34
+ ```svelte
35
+ <script lang="ts">
36
+ import AssessmentShell from '@pie-qti/assessment-player/components/AssessmentShell.svelte';
37
+ import type { QtiAssessmentTest } from '@pie-qti/assessment-player';
38
+
39
+ const assessment: QtiAssessmentTest = {
40
+ identifier: 'my-assessment',
41
+ title: 'Sample Assessment',
42
+ testParts: [
43
+ {
44
+ identifier: 'part-1',
45
+ navigationMode: 'nonlinear',
46
+ submissionMode: 'simultaneous',
47
+ sections: [
48
+ {
49
+ identifier: 'section-1',
50
+ title: 'Section 1',
51
+ questionRefs: [
52
+ {
53
+ identifier: 'q1',
54
+ itemXml: '...' // QTI item XML
55
+ }
56
+ ]
57
+ }
58
+ ]
59
+ }
60
+ ]
61
+ };
62
+ </script>
63
+
64
+ <AssessmentShell
65
+ {assessment}
66
+ config={{
67
+ role: 'candidate',
68
+ showSections: true,
69
+ allowSectionNavigation: true,
70
+ showProgress: true,
71
+ onComplete: () => {
72
+ console.log('Assessment completed!');
73
+ }
74
+ }}
75
+ />
76
+ ```
77
+
78
+ ### Programmatic Usage (JavaScript/TypeScript)
79
+
80
+ ```typescript
81
+ import { AssessmentPlayer } from '@pie-qti/assessment-player';
82
+
83
+ const player = new AssessmentPlayer({
84
+ assessment: myAssessment,
85
+ role: 'candidate',
86
+ navigationMode: 'nonlinear',
87
+ showSections: true,
88
+ allowSectionNavigation: true,
89
+ });
90
+
91
+ // Navigate to first item
92
+ await player.navigateTo(0);
93
+
94
+ // Get navigation state
95
+ const navState = player.getNavigationState();
96
+ console.log(`Item ${navState.currentIndex + 1} of ${navState.totalItems}`);
97
+
98
+ // Get current rubric blocks (passages)
99
+ const rubrics = player.getCurrentRubricBlocks();
100
+
101
+ // Navigate next/previous
102
+ await player.next();
103
+ await player.previous();
104
+
105
+ // Navigate to section
106
+ await player.navigateToSection('section-1');
107
+
108
+ // Submit assessment
109
+ const results = await player.submit();
110
+ console.log('Total score:', results.totalScore, '/', results.maxScore);
111
+ ```
112
+
113
+ ## Assessment Format
114
+
115
+ The player uses a QTI 2.x-compliant JSON format:
116
+
117
+ ```typescript
118
+ interface QtiAssessmentTest {
119
+ identifier?: string;
120
+ title?: string;
121
+ testParts?: TestPart[];
122
+ }
123
+
124
+ interface TestPart {
125
+ identifier: string;
126
+ navigationMode: 'linear' | 'nonlinear';
127
+ submissionMode: 'individual' | 'simultaneous';
128
+ sections: AssessmentSection[];
129
+ }
130
+
131
+ interface AssessmentSection {
132
+ identifier: string;
133
+ title?: string;
134
+ visible?: boolean;
135
+ rubricBlocks?: RubricBlock[];
136
+ questionRefs?: QuestionRef[];
137
+ sections?: AssessmentSection[]; // Nested sections
138
+ }
139
+
140
+ interface QuestionRef {
141
+ identifier: string;
142
+ href?: string; // URL to item XML
143
+ title?: string;
144
+ itemXml?: string; // Loaded item XML (convenience property)
145
+ }
146
+
147
+ interface RubricBlock {
148
+ view: string[]; // QTI roles: ['candidate', 'scorer', 'author', 'tutor', 'proctor', 'testConstructor']
149
+ use?: 'passage' | 'instructions' | 'rubric';
150
+ content: string; // HTML content
151
+ }
152
+ ```
153
+
154
+ ## Backend Integration
155
+
156
+ **By default**, the player runs 100% client-side with no backend required. This is perfect for demos, development, and non-critical assessments.
157
+
158
+ **For production**, integrate with a secure backend for:
159
+ - Server-side scoring (prevent score manipulation)
160
+ - Role-based data filtering (hide correct answers from candidates)
161
+ - Persistent session storage
162
+ - Authentication and authorization
163
+
164
+ ### Quick Start
165
+
166
+ ```typescript
167
+ import { ReferenceBackendAdapter } from '@pie-qti/assessment-player/integration';
168
+
169
+ // Development/demo mode - uses localStorage
170
+ const adapter = new ReferenceBackendAdapter();
171
+
172
+ const player = new AssessmentPlayer({
173
+ backend: adapter,
174
+ assessmentId: 'test-001',
175
+ candidateId: 'student-123'
176
+ });
177
+ ```
178
+
179
+ ### Production Implementation
180
+
181
+ Implement the `BackendAdapter` interface for your backend:
182
+
183
+ ```typescript
184
+ import type { BackendAdapter } from '@pie-qti/assessment-player/integration';
185
+
186
+ class MyBackendAdapter implements BackendAdapter {
187
+ async initSession(request) {
188
+ const response = await fetch('/api/qti/sessions/init', {
189
+ method: 'POST',
190
+ headers: { 'Authorization': `Bearer ${token}` },
191
+ body: JSON.stringify(request)
192
+ });
193
+ return response.json();
194
+ }
195
+
196
+ async submitResponses(request) {
197
+ // Server performs scoring and returns results
198
+ const response = await fetch('/api/qti/responses/submit', {
199
+ method: 'POST',
200
+ body: JSON.stringify(request)
201
+ });
202
+ return response.json();
203
+ }
204
+
205
+ // ... implement other methods
206
+ }
207
+ ```
208
+
209
+ **See [BACKEND-INTEGRATION.md](./BACKEND-INTEGRATION.md) for complete implementation guide.**
210
+
211
+ ## QTI 2.x Standard Roles
212
+
213
+ The player implements QTI 2.x standard roles to control behavior:
214
+
215
+ | Role | Behavior |
216
+ |------|----------|
217
+ | `candidate` | Test-taker - inputs editable, no correct answers shown |
218
+ | `scorer` | Grader - inputs readonly, correct answers shown |
219
+ | `author` | Content author - inputs readonly, correct answers shown |
220
+ | `tutor` | Instructional mode - inputs readonly, correct answers shown |
221
+ | `proctor` | Test administrator - inputs readonly, limited feedback |
222
+ | `testConstructor` | Test developer - inputs readonly, correct answers shown |
223
+
224
+ ```typescript
225
+ // For test-takers
226
+ <AssessmentShell {assessment} config={{ role: 'candidate' }} />
227
+
228
+ // For grading/review
229
+ <AssessmentShell {assessment} config={{ role: 'scorer' }} />
230
+ ```
231
+
232
+ ## Time Limits
233
+
234
+ QTI 2.x supports time limits at assessment, test part, section, and item levels. The player provides:
235
+
236
+ - **Countdown timer** - Displays remaining time to candidates
237
+ - **Warning threshold** - Alert before time expires (default: 60 seconds)
238
+ - **Auto-submission** - Automatically submits when time expires (configurable)
239
+ - **Late submission** - Optional allow submission after time expires
240
+
241
+ ### Usage
242
+
243
+ ```typescript
244
+ const assessment: QtiAssessmentTest = {
245
+ identifier: 'timed-test',
246
+ timeLimits: {
247
+ maxTime: 3600, // 1 hour in seconds
248
+ allowLateSubmission: false // Auto-submit when time expires
249
+ },
250
+ testParts: [/* ... */]
251
+ };
252
+
253
+ const player = new AssessmentPlayer({
254
+ assessment,
255
+ timeWarningThreshold: 300 // Warn at 5 minutes remaining
256
+ });
257
+
258
+ // Listen for time events
259
+ player.onTimeWarning((remainingSeconds) => {
260
+ console.log(`Warning: ${remainingSeconds} seconds remaining`);
261
+ });
262
+
263
+ player.onTimeExpired(() => {
264
+ console.log('Time expired!');
265
+ });
266
+
267
+ player.onTimeTick((remaining, elapsed) => {
268
+ console.log(`${remaining}s remaining, ${elapsed}s elapsed`);
269
+ });
270
+
271
+ // Pause/resume timer (e.g., for breaks)
272
+ player.pauseTimer();
273
+ player.resumeTimer();
274
+
275
+ // Check time status
276
+ const remaining = player.getRemainingTime(); // seconds or null if no limit
277
+ const elapsed = player.getElapsedTime(); // seconds
278
+ const isExpired = player.isTimeExpired(); // boolean
279
+ ```
280
+
281
+ ### AssessmentTimer Component
282
+
283
+ Visual timer component that displays countdown:
284
+
285
+ ```svelte
286
+ <script>
287
+ import { AssessmentTimer } from '@pie-qti/assessment-player/components';
288
+ </script>
289
+
290
+ <AssessmentTimer
291
+ {player}
292
+ showElapsed={false}
293
+ position="top-right"
294
+ />
295
+ ```
296
+
297
+ **Props:**
298
+ - `player: AssessmentPlayer` - The assessment player instance
299
+ - `showElapsed?: boolean` - Show elapsed time instead of remaining (default: false)
300
+ - `position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'` - Timer position
301
+
302
+ ## Item Session Control
303
+
304
+ QTI itemSessionControl determines how candidates interact with items:
305
+
306
+ | Setting | Description |
307
+ |---------|-------------|
308
+ | `maxAttempts` | Maximum submission attempts (0 = unlimited) |
309
+ | `showFeedback` | Show feedback after submission |
310
+ | `showSolution` | Show correct answers |
311
+ | `allowReview` | Allow returning to submitted items |
312
+ | `allowSkipping` | Allow skipping items without answering |
313
+ | `validateResponses` | Require valid responses before navigation |
314
+
315
+ ### Usage
316
+
317
+ ```typescript
318
+ const assessment: QtiAssessmentTest = {
319
+ testParts: [{
320
+ identifier: 'part-1',
321
+ navigationMode: 'nonlinear',
322
+ submissionMode: 'individual',
323
+ itemSessionControl: {
324
+ maxAttempts: 3, // 3 attempts per item
325
+ showFeedback: true,
326
+ showSolution: false,
327
+ allowReview: true,
328
+ allowSkipping: false, // Must answer before moving
329
+ validateResponses: true
330
+ },
331
+ sections: [/* ... */]
332
+ }]
333
+ };
334
+
335
+ // Get session info for current item
336
+ const info = player.getItemSessionInfo();
337
+ console.log(`Can submit: ${info.canSubmit}`);
338
+ console.log(`Attempts remaining: ${info.remainingAttempts}`);
339
+ console.log(`Attempt count: ${info.attemptCount}`);
340
+ console.log(`Show feedback: ${info.showFeedback}`);
341
+ console.log(`Can skip: ${info.canSkip}`);
342
+ ```
343
+
344
+ ### ItemSessionInfo Component
345
+
346
+ Visual display of session control information:
347
+
348
+ ```svelte
349
+ <script>
350
+ import { ItemSessionInfo } from '@pie-qti/assessment-player/components';
351
+ </script>
352
+
353
+ <ItemSessionInfo
354
+ {player}
355
+ position="inline"
356
+ showDetails={true}
357
+ />
358
+ ```
359
+
360
+ **Props:**
361
+ - `player: AssessmentPlayer` - The assessment player instance
362
+ - `position?: 'inline' | 'floating'` - Display mode (default: 'inline')
363
+ - `showDetails?: boolean` - Show detailed session information (default: false)
364
+
365
+ ## State Persistence
366
+
367
+ The assessment player supports automatic state persistence for save/resume functionality. This allows candidates to continue their assessment across sessions.
368
+
369
+ ### Capabilities
370
+
371
+ - **Auto-save**: Automatic debounced saves (default: 2000ms)
372
+ - **State capture**: Current item, responses, session states, time tracking
373
+ - **Storage fallback**: localStorage → sessionStorage → memory
374
+ - **Resume capability**: Restore exact position and state
375
+ - **Optional backend**: Integrate with server-side storage
376
+
377
+ ### Basic Usage
378
+
379
+ Enable state persistence by providing a `sessionId`:
380
+
381
+ ```typescript
382
+ const player = new AssessmentPlayer({
383
+ assessment: myAssessment,
384
+ role: 'candidate',
385
+
386
+ // State persistence config
387
+ sessionId: 'candidate-123-assessment-456', // Unique session identifier
388
+ enableAutoSave: true, // Default: true when sessionId provided
389
+ autoSaveDelay: 2000, // Debounce delay in ms (default: 2000)
390
+ storage: 'localStorage', // 'localStorage' | 'sessionStorage' | 'memory'
391
+
392
+ // Callbacks
393
+ onStateSaved: (timestamp) => {
394
+ console.log('State saved at:', new Date(timestamp));
395
+ },
396
+ onStateRestored: (timestamp) => {
397
+ console.log('State restored from:', new Date(timestamp));
398
+ }
399
+ });
400
+
401
+ // Check if saved state exists
402
+ const hasSaved = await player.hasSavedState();
403
+
404
+ // Load and resume from saved state
405
+ if (hasSaved) {
406
+ const restored = await player.loadSavedState();
407
+ console.log('Resumed assessment:', restored);
408
+ }
409
+
410
+ // Manually trigger immediate save (bypasses debounce)
411
+ await player.forceSaveState();
412
+
413
+ // Get last save timestamp
414
+ const lastSave = player.getLastSaveTime();
415
+
416
+ // Clear saved state
417
+ await player.clearSavedState();
418
+ ```
419
+
420
+ ### Backend Integration
421
+
422
+ Integrate with your backend for server-side persistence:
423
+
424
+ ```typescript
425
+ import { StatePersistenceManager } from '@pie-qti/assessment-player';
426
+ import type { PersistableState } from '@pie-qti/assessment-player';
427
+
428
+ const persistenceManager = new StatePersistenceManager({
429
+ sessionId: 'candidate-123-assessment-456',
430
+ assessmentId: 'my-assessment',
431
+ autoSave: true,
432
+ autoSaveDelay: 2000,
433
+ storage: 'localStorage', // Fallback if backend fails
434
+
435
+ // Optional backend save callback
436
+ onBackendSave: async (state: PersistableState) => {
437
+ await fetch('/api/assessment/save', {
438
+ method: 'POST',
439
+ headers: { 'Content-Type': 'application/json' },
440
+ body: JSON.stringify(state)
441
+ });
442
+ },
443
+
444
+ onSaveSuccess: (state) => {
445
+ console.log('Saved at:', state.savedAt);
446
+ },
447
+
448
+ onSaveError: (error) => {
449
+ console.error('Save failed:', error);
450
+ }
451
+ });
452
+
453
+ // Update state (triggers auto-save)
454
+ persistenceManager.updateState({
455
+ assessmentId: 'my-assessment',
456
+ currentItemIndex: 5,
457
+ visitedItems: [0, 1, 2, 3, 4, 5],
458
+ responses: { 'RESPONSE_1': 'answer' },
459
+ itemSessionStates: {},
460
+ savedAt: Date.now()
461
+ });
462
+
463
+ // Load state
464
+ const savedState = await persistenceManager.load();
465
+
466
+ // Manual save
467
+ await persistenceManager.forceSave();
468
+
469
+ // Pause/resume auto-save (useful during navigation transitions)
470
+ persistenceManager.pauseAutoSave();
471
+ persistenceManager.resumeAutoSave();
472
+
473
+ // Cleanup
474
+ persistenceManager.destroy();
475
+ ```
476
+
477
+ ### State Structure
478
+
479
+ The `PersistableState` interface captures all necessary data:
480
+
481
+ ```typescript
482
+ interface PersistableState {
483
+ assessmentId: string;
484
+ currentItemIndex: number;
485
+ visitedItems: number[];
486
+ responses: Record<string, unknown>;
487
+ itemSessionStates: Record<string, {
488
+ attemptCount: number;
489
+ isAnswered: boolean;
490
+ isSubmitted: boolean;
491
+ lastSubmissionTime?: number;
492
+ }>;
493
+ timeTracking?: {
494
+ startedAt: number;
495
+ totalElapsed: number;
496
+ itemTimes: Record<string, number>;
497
+ sectionTimes: Record<string, number>;
498
+ };
499
+ savedAt: number;
500
+ }
501
+ ```
502
+
503
+ ## Selection & Ordering
504
+
505
+ The assessment player supports QTI 2.x selection and ordering rules for creating randomized assessments and item pools.
506
+
507
+ ### Selection Rules
508
+
509
+ Randomly select a subset of items from a pool:
510
+
511
+ ```typescript
512
+ const assessment: QtiAssessmentTest = {
513
+ identifier: 'random-assessment',
514
+ title: 'Random Item Assessment',
515
+ testParts: [{
516
+ identifier: 'part-1',
517
+ navigationMode: 'nonlinear',
518
+ submissionMode: 'individual',
519
+ sections: [{
520
+ identifier: 'item-pool',
521
+ title: 'Question Pool',
522
+
523
+ // Selection rule: Pick 5 items from pool of 10
524
+ selection: {
525
+ select: 5, // Number of items to select
526
+ withReplacement: false // Don't allow same item twice (default)
527
+ },
528
+
529
+ questionRefs: [
530
+ // Pool of 10 items - 5 will be randomly selected
531
+ { identifier: 'q1', itemXml: '...' },
532
+ { identifier: 'q2', itemXml: '...' },
533
+ { identifier: 'q3', itemXml: '...' },
534
+ // ... 7 more items
535
+ ]
536
+ }]
537
+ }]
538
+ };
539
+
540
+ // Optional: Provide seed for consistent randomization
541
+ const player = new AssessmentPlayer({
542
+ assessment,
543
+ randomSeed: 12345 // Same seed = same item selection
544
+ });
545
+ ```
546
+
547
+ **Selection Options:**
548
+ - `select: number` - Number of items to select from the pool
549
+ - `withReplacement?: boolean` - Allow selecting same item multiple times (default: false)
550
+ - `fromBank?: string` - Reference to external item bank (not yet implemented)
551
+
552
+ **Behavior:**
553
+ - If `select >= pool size`, all items are included
554
+ - Without replacement: Fisher-Yates shuffle, take first N items
555
+ - With replacement: Can select same item multiple times
556
+
557
+ ### Ordering Rules
558
+
559
+ Shuffle items while optionally keeping some in fixed positions:
560
+
561
+ ```typescript
562
+ const assessment: QtiAssessmentTest = {
563
+ testParts: [{
564
+ identifier: 'part-1',
565
+ navigationMode: 'nonlinear',
566
+ submissionMode: 'individual',
567
+ sections: [{
568
+ identifier: 'section-1',
569
+ title: 'Mixed Questions',
570
+
571
+ // Ordering rule: Shuffle items except fixed ones
572
+ ordering: {
573
+ shuffle: true,
574
+ fixed: ['intro-question', 'summary-question'] // Keep these in place
575
+ },
576
+
577
+ questionRefs: [
578
+ { identifier: 'intro-question', fixed: true, itemXml: '...' }, // Always first
579
+ { identifier: 'q1', itemXml: '...' }, // Will be shuffled
580
+ { identifier: 'q2', itemXml: '...' }, // Will be shuffled
581
+ { identifier: 'q3', itemXml: '...' }, // Will be shuffled
582
+ { identifier: 'summary-question', fixed: true, itemXml: '...' } // Always last
583
+ ]
584
+ }]
585
+ }]
586
+ };
587
+ ```
588
+
589
+ **Ordering Options:**
590
+ - `shuffle?: boolean` - Shuffle items (default: false)
591
+ - `fixed?: string[]` - Item identifiers that should not be shuffled
592
+
593
+ **Per-Item Fixed Flag:**
594
+ Items can also be marked as fixed directly:
595
+
596
+ ```typescript
597
+ questionRefs: [
598
+ { identifier: 'q1', fixed: true, itemXml: '...' }, // Won't shuffle
599
+ { identifier: 'q2', itemXml: '...' } // Will shuffle
600
+ ]
601
+ ```
602
+
603
+ ### Combined Selection & Ordering
604
+
605
+ You can use both rules together:
606
+
607
+ ```typescript
608
+ sections: [{
609
+ identifier: 'random-shuffled-pool',
610
+
611
+ // First select 10 items from pool of 20
612
+ selection: {
613
+ select: 10,
614
+ withReplacement: false
615
+ },
616
+
617
+ // Then shuffle the selected items
618
+ ordering: {
619
+ shuffle: true,
620
+ fixed: ['anchor-item'] // But keep anchor item in place
621
+ },
622
+
623
+ questionRefs: [
624
+ { identifier: 'anchor-item', fixed: true, itemXml: '...' },
625
+ // ... 19 more items in pool
626
+ ]
627
+ }]
628
+ ```
629
+
630
+ **Processing Order:**
631
+ 1. Selection is applied first (if specified)
632
+ 2. Ordering is applied to the selected items (if specified)
633
+ 3. Fixed items maintain their relative positions
634
+
635
+ ### Random Seed
636
+
637
+ Control randomization for reproducibility or testing:
638
+
639
+ ```typescript
640
+ // Different candidates get different randomizations
641
+ const player = new AssessmentPlayer({
642
+ assessment,
643
+ randomSeed: candidateId // Each candidate gets unique seed
644
+ });
645
+
646
+ // Or generate session-specific seed
647
+ const sessionSeed = Date.now();
648
+ const player = new AssessmentPlayer({
649
+ assessment,
650
+ randomSeed: sessionSeed // Same items for whole session
651
+ });
652
+ ```
653
+
654
+ **Seed Behavior:**
655
+ - Default: `Date.now()` (different each time)
656
+ - Same seed = same item selection and order
657
+ - Used internally for consistency (resume preserves order)
658
+ - Uses Linear Congruential Generator (LCG) for seeded randomness
659
+
660
+ ### Use Cases
661
+
662
+ **1. Item Pools**
663
+ ```typescript
664
+ // Create large pool, select subset per candidate
665
+ selection: { select: 20 }, // From pool of 100
666
+ questionRefs: [...100 items...]
667
+ ```
668
+
669
+ **2. Randomized Exams**
670
+ ```typescript
671
+ // Shuffle all questions to prevent cheating
672
+ ordering: { shuffle: true }
673
+ ```
674
+
675
+ **3. Fixed Start/End**
676
+ ```typescript
677
+ // Instructions first, reflection last, shuffle middle
678
+ ordering: {
679
+ shuffle: true,
680
+ fixed: ['instructions', 'reflection']
681
+ }
682
+ ```
683
+
684
+ **4. Practice Mode**
685
+ ```typescript
686
+ // Random subset, shuffled order, new each time
687
+ selection: { select: 10 },
688
+ ordering: { shuffle: true }
689
+ // No randomSeed = different each load
690
+ ```
691
+
692
+ **5. Consistent Test Forms**
693
+ ```typescript
694
+ // Same questions for all candidates taking "Form A"
695
+ randomSeed: 'form-a'.hashCode(), // Consistent seed
696
+ selection: { select: 50 },
697
+ ordering: { shuffle: true }
698
+ ```
699
+
700
+ ## Outcome Processing & Scoring
701
+
702
+ The assessment player implements QTI 2.x outcome processing for aggregating item scores into assessment-level outcomes.
703
+
704
+ ### Scoring Templates
705
+
706
+ The `outcomeProcessing.template` field determines how item scores are combined:
707
+
708
+ #### Total Score (Default)
709
+
710
+ Simple sum of all item scores.
711
+
712
+ ```typescript
713
+ const assessment: QtiAssessmentTest = {
714
+ identifier: 'test-1',
715
+ outcomeProcessing: {
716
+ template: 'total_score' // or omit for default
717
+ },
718
+ testParts: [/* ... */]
719
+ };
720
+
721
+ // Results:
722
+ // SCORE = sum of item scores
723
+ // MAXSCORE = sum of item max scores
724
+ ```
725
+
726
+ #### Weighted Score
727
+
728
+ Applies weights to individual items. Use `weight` property on `questionRef` to specify item weights (default: 1).
729
+
730
+ ```typescript
731
+ const assessment: QtiAssessmentTest = {
732
+ identifier: 'test-1',
733
+ outcomeProcessing: {
734
+ template: 'weighted_score'
735
+ },
736
+ testParts: [{
737
+ identifier: 'part-1',
738
+ navigationMode: 'nonlinear',
739
+ submissionMode: 'simultaneous',
740
+ sections: [{
741
+ identifier: 'section-1',
742
+ questionRefs: [
743
+ {
744
+ identifier: 'q1',
745
+ weight: 2, // Worth 2x other items
746
+ itemXml: '...'
747
+ },
748
+ {
749
+ identifier: 'q2',
750
+ weight: 1,
751
+ itemXml: '...'
752
+ },
753
+ {
754
+ identifier: 'q3',
755
+ weight: 3, // Worth 3x other items
756
+ itemXml: '...'
757
+ }
758
+ ]
759
+ }]
760
+ }]
761
+ };
762
+
763
+ // Results:
764
+ // SCORE = (q1.score * 2) + (q2.score * 1) + (q3.score * 3)
765
+ // MAXSCORE = (q1.maxScore * 2) + (q2.maxScore * 1) + (q3.maxScore * 3)
766
+ ```
767
+
768
+ #### Percentage Score
769
+
770
+ Calculates percentage of total possible points (0-100).
771
+
772
+ ```typescript
773
+ const assessment: QtiAssessmentTest = {
774
+ outcomeProcessing: {
775
+ template: 'percentage_score'
776
+ }
777
+ };
778
+
779
+ // Results:
780
+ // SCORE = (total earned / total possible) * 100
781
+ // MAXSCORE = 100
782
+ // PERCENTAGE = same as SCORE
783
+ ```
784
+
785
+ #### Pass/Fail
786
+
787
+ Determines pass/fail based on a threshold.
788
+
789
+ ```typescript
790
+ const assessment: QtiAssessmentTest = {
791
+ outcomeDeclarations: [
792
+ {
793
+ identifier: 'PASSING_THRESHOLD',
794
+ baseType: 'float',
795
+ cardinality: 'single',
796
+ defaultValue: 0.7 // 70% threshold
797
+ }
798
+ ],
799
+ outcomeProcessing: {
800
+ template: 'pass_fail'
801
+ }
802
+ };
803
+
804
+ // Results:
805
+ // SCORE = total earned points
806
+ // MAXSCORE = total possible points
807
+ // PASSED = true/false (based on threshold)
808
+ // PERCENTAGE = percentage score
809
+ ```
810
+
811
+ ### Outcome Variables
812
+
813
+ Define custom outcome variables with `outcomeDeclarations`:
814
+
815
+ ```typescript
816
+ const assessment: QtiAssessmentTest = {
817
+ outcomeDeclarations: [
818
+ {
819
+ identifier: 'SCORE',
820
+ baseType: 'float',
821
+ cardinality: 'single',
822
+ defaultValue: 0
823
+ },
824
+ {
825
+ identifier: 'MAXSCORE',
826
+ baseType: 'float',
827
+ cardinality: 'single',
828
+ defaultValue: 0
829
+ },
830
+ {
831
+ identifier: 'PASSING_THRESHOLD',
832
+ baseType: 'float',
833
+ cardinality: 'single',
834
+ defaultValue: 0.75
835
+ },
836
+ {
837
+ identifier: 'GRADE_LEVEL',
838
+ baseType: 'string',
839
+ cardinality: 'single',
840
+ defaultValue: 'Not Graded'
841
+ }
842
+ ]
843
+ };
844
+ ```
845
+
846
+ ### Accessing Outcomes
847
+
848
+ After submission, access outcome variables:
849
+
850
+ ```typescript
851
+ const results = await player.submit();
852
+
853
+ console.log('Total Score:', results.totalScore);
854
+ console.log('Max Score:', results.maxScore);
855
+ console.log('Item Results:', results.itemResults);
856
+
857
+ // Access outcome processor directly
858
+ const outcomeProcessor = player.getOutcomeProcessor();
859
+ const allOutcomes = outcomeProcessor.getOutcomes();
860
+ const passed = outcomeProcessor.getOutcome('PASSED');
861
+ const percentage = outcomeProcessor.getOutcome('PERCENTAGE');
862
+
863
+ console.log('All outcomes:', allOutcomes);
864
+ console.log('Passed:', passed);
865
+ console.log('Percentage:', percentage);
866
+ ```
867
+
868
+ ### Test Feedback
869
+
870
+ Display feedback based on outcome conditions:
871
+
872
+ ```typescript
873
+ const assessment: QtiAssessmentTest = {
874
+ outcomeProcessing: {
875
+ template: 'pass_fail'
876
+ },
877
+ testFeedback: [
878
+ {
879
+ identifier: 'pass-feedback',
880
+ outcomeIdentifier: 'PASSED',
881
+ showHide: 'show', // Show when PASSED is true
882
+ access: 'atEnd',
883
+ content: '<p>Congratulations! You passed the test.</p>'
884
+ },
885
+ {
886
+ identifier: 'fail-feedback',
887
+ outcomeIdentifier: 'PASSED',
888
+ showHide: 'hide', // Show when PASSED is false
889
+ access: 'atEnd',
890
+ content: '<p>Unfortunately, you did not pass. Please review the material and try again.</p>'
891
+ }
892
+ ]
893
+ };
894
+
895
+ // After submission
896
+ const feedback = player.getVisibleFeedback();
897
+ for (const fb of feedback) {
898
+ console.log('Feedback:', fb.content);
899
+ }
900
+ ```
901
+
902
+ ### Custom Outcome Processing
903
+
904
+ The four standard templates (total_score, weighted_score, percentage_score, pass_fail) cover 95%+ of real-world assessment needs. For advanced custom scoring logic, you can provide your own outcome processor:
905
+
906
+ ```typescript
907
+ import { OutcomeProcessor, AssessmentPlayer } from '@pie-qti/assessment-player';
908
+ import type { AssessmentPlayerConfig } from '@pie-qti/assessment-player';
909
+
910
+ // Option 1: Extend the built-in OutcomeProcessor
911
+ class CustomOutcomeProcessor extends OutcomeProcessor {
912
+ processResults(itemResults) {
913
+ // Call parent to get standard scoring
914
+ const results = super.processResults(itemResults);
915
+
916
+ // Add your custom logic
917
+ // Example: Bonus points for perfect scores
918
+ const perfectCount = itemResults.filter(r => r.score === r.maxScore).length;
919
+ results.outcomes.SCORE += perfectCount * 5; // 5 bonus points per perfect item
920
+ results.outcomes.BONUS_POINTS = perfectCount * 5;
921
+
922
+ return results;
923
+ }
924
+ }
925
+
926
+ // Option 2: Implement your own from scratch
927
+ class AdvancedOutcomeProcessor {
928
+ constructor(assessment) {
929
+ this.assessment = assessment;
930
+ }
931
+
932
+ processResults(itemResults) {
933
+ // Your completely custom scoring logic
934
+ // Must return an AssessmentResults object
935
+ return {
936
+ outcomes: {
937
+ SCORE: /* your calculation */,
938
+ MAXSCORE: /* your calculation */,
939
+ // ... any custom outcome variables
940
+ },
941
+ feedback: []
942
+ };
943
+ }
944
+
945
+ getVisibleFeedback() {
946
+ // Return feedback based on outcomes
947
+ return [];
948
+ }
949
+ }
950
+
951
+ // Use your custom processor
952
+ const config: AssessmentPlayerConfig = {
953
+ assessment,
954
+ outcomeProcessor: new CustomOutcomeProcessor(assessment),
955
+ // ... other config
956
+ };
957
+
958
+ const player = new AssessmentPlayer(config);
959
+ ```
960
+
961
+ **Note:** The player does NOT include a full QTI rule interpreter for complex `setOutcomeValue`, `responseCondition`, etc. This is an intentional design decision to avoid unnecessary complexity. The pluggable outcome processor architecture allows you to implement any custom scoring logic you need while keeping the core framework simple and maintainable.
962
+
963
+ ### Scoring Use Cases
964
+
965
+ #### 1. Simple Quiz
966
+
967
+ ```typescript
968
+ // Just sum the scores
969
+ outcomeProcessing: { template: 'total_score' }
970
+ ```
971
+
972
+ #### 2. Weighted Exam
973
+
974
+ ```typescript
975
+ // Essay questions worth more than multiple choice
976
+ outcomeProcessing: { template: 'weighted_score' }
977
+ // Set weight: 5 on essay questionRefs, weight: 1 on MC
978
+ ```
979
+
980
+ #### 3. Pass/Fail Certification
981
+
982
+ ```typescript
983
+ // Must score 80% to pass
984
+ outcomeDeclarations: [
985
+ { identifier: 'PASSING_THRESHOLD', baseType: 'float', cardinality: 'single', defaultValue: 0.8 }
986
+ ],
987
+ outcomeProcessing: { template: 'pass_fail' }
988
+ ```
989
+
990
+ #### 4. Grade Levels
991
+
992
+ ```typescript
993
+ // Use percentage_score and map to letter grades in your app
994
+ outcomeProcessing: { template: 'percentage_score' }
995
+ // Then: A = 90-100, B = 80-89, etc.
996
+ ```
997
+
998
+ #### 5. Adaptive Feedback
999
+
1000
+ ```typescript
1001
+ // Show different feedback based on score ranges
1002
+ testFeedback: [
1003
+ { outcomeIdentifier: 'HIGH_SCORE', showHide: 'show', content: 'Excellent work!' },
1004
+ { outcomeIdentifier: 'MEDIUM_SCORE', showHide: 'show', content: 'Good effort!' },
1005
+ { outcomeIdentifier: 'LOW_SCORE', showHide: 'show', content: 'Keep practicing!' }
1006
+ ]
1007
+ ```
1008
+
1009
+ ## Components
1010
+
1011
+ ### AssessmentShell
1012
+
1013
+ Main component that orchestrates the entire assessment experience.
1014
+
1015
+ **Props:**
1016
+ - `assessment: QtiAssessmentTest` - The assessment data
1017
+ - `config?: AssessmentPlayerConfig` - Configuration options
1018
+
1019
+ ### NavigationBar
1020
+
1021
+ Navigation controls with progress indicator.
1022
+
1023
+ **Props:**
1024
+ - `navState: NavigationState` - Current navigation state
1025
+ - `onPrevious?: () => void` - Previous button handler
1026
+ - `onNext?: () => void` - Next button handler
1027
+ - `onSubmit?: () => void` - Submit button handler
1028
+ - `showProgress?: boolean` - Show progress bar (default: true)
1029
+
1030
+ ### SectionMenu
1031
+
1032
+ Dropdown menu for section navigation.
1033
+
1034
+ **Props:**
1035
+ - `sections: Section[]` - List of sections
1036
+ - `currentSectionIndex?: number` - Active section index
1037
+ - `onSectionSelect?: (index: number) => void` - Section selection handler
1038
+ - `disabled?: boolean` - Disable navigation
1039
+
1040
+ ### RubricDisplay
1041
+
1042
+ Displays rubric blocks (passages, instructions).
1043
+
1044
+ **Props:**
1045
+ - `blocks: RubricBlock[]` - Array of rubric blocks
1046
+ - `collapsed?: boolean` - Initial collapsed state
1047
+
1048
+ ### ItemRenderer
1049
+
1050
+ Renders individual QTI items within the assessment.
1051
+
1052
+ **Props:**
1053
+ - `questionRef: QuestionRef` - Question reference with item XML
1054
+ - `role?: QTIRole` - QTI 2.x standard role (default: 'candidate')
1055
+ - `extendedTextEditor?: 'tiptap' | 'textarea'` - Editor type for extended text
1056
+ - `responses?: Record<string, unknown>` - Response data
1057
+ - `onResponseChange?: (responseId: string, value: unknown) => void` - Response handler
1058
+
1059
+ ## Navigation Modes
1060
+
1061
+ ### Linear Navigation
1062
+
1063
+ Sequential navigation only. Students must proceed through items in order but can review previous items.
1064
+
1065
+ ```typescript
1066
+ {
1067
+ navigationMode: 'linear'
1068
+ }
1069
+ ```
1070
+
1071
+ ### Nonlinear Navigation
1072
+
1073
+ Free navigation. Students can jump to any item at any time.
1074
+
1075
+ ```typescript
1076
+ {
1077
+ navigationMode: 'nonlinear'
1078
+ }
1079
+ ```
1080
+
1081
+ ## Events
1082
+
1083
+ ```typescript
1084
+ player.onItemChange((index, total) => {
1085
+ console.log(`Item ${index + 1} of ${total}`);
1086
+ });
1087
+
1088
+ player.onSectionChange((sectionIndex, totalSections) => {
1089
+ console.log(`Section ${sectionIndex + 1} of ${totalSections}`);
1090
+ });
1091
+
1092
+ player.onResponseChange((responses) => {
1093
+ console.log('Responses:', responses);
1094
+ });
1095
+
1096
+ player.onComplete(() => {
1097
+ console.log('Assessment completed!');
1098
+ });
1099
+ ```
1100
+
1101
+ ## State Management
1102
+
1103
+ Save and restore assessment state for continuity:
1104
+
1105
+ ```typescript
1106
+ // Save state
1107
+ const state = player.getState();
1108
+ localStorage.setItem('assessment-state', JSON.stringify(state));
1109
+
1110
+ // Restore state
1111
+ const savedState = JSON.parse(localStorage.getItem('assessment-state'));
1112
+ player.restoreState(savedState);
1113
+ ```
1114
+
1115
+ ## Styling
1116
+
1117
+ Components use DaisyUI classes and can be styled with Tailwind CSS or custom CSS variables.
1118
+
1119
+ ## Development
1120
+
1121
+ ```bash
1122
+ # Build
1123
+ bun run build
1124
+
1125
+ # Watch mode
1126
+ bun run dev
1127
+
1128
+ # Type check
1129
+ bun run typecheck
1130
+
1131
+ # Lint
1132
+ bun run lint
1133
+ ```
1134
+
1135
+ ## License
1136
+
1137
+ ISC