@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
@@ -0,0 +1,595 @@
1
+ /**
2
+ * AssessmentPlayer (backend-authoritative)
3
+ *
4
+ * Client responsibilities:
5
+ * - Render items using @pie-qti/item-player
6
+ * - Collect candidate responses
7
+ * - Submit responses to BackendAdapter
8
+ * - Apply backend navigation decisions + session state
9
+ */
10
+ import { Player } from '@pie-qti/item-player';
11
+ import { ItemSessionController } from './ItemSessionController.js';
12
+ import { NavigationManager } from './NavigationManager.js';
13
+ import { TimeManager } from './TimeManager.js';
14
+ export class AssessmentPlayer {
15
+ static async create(config) {
16
+ const init = await config.backend.initSession(config.initSession);
17
+ return new AssessmentPlayer(config, init);
18
+ }
19
+ constructor(config, init) {
20
+ this.config = config;
21
+ this.timeManager = null;
22
+ this.questions = [];
23
+ this.currentItemIndex = -1;
24
+ this.currentItemPlayer = null;
25
+ this.responses = {};
26
+ this.itemResults = new Map();
27
+ this.visibleFeedback = [];
28
+ // Event listeners
29
+ this.itemChangeListeners = new Set();
30
+ this.sectionChangeListeners = new Set();
31
+ this.responseChangeListeners = new Set();
32
+ this.completeListeners = new Set();
33
+ this.timeWarningListeners = new Set();
34
+ this.timeExpiredListeners = new Set();
35
+ this.timeTickListeners = new Set();
36
+ this.backend = config.backend;
37
+ this.sessionId = init.sessionId;
38
+ this.assessment = init.assessment;
39
+ this.i18nProvider = config.i18nProvider ?? this.createDefaultI18nProvider();
40
+ this.state =
41
+ init.restoredState ??
42
+ {
43
+ currentItemIdentifier: '',
44
+ visitedItems: [],
45
+ itemResponses: {},
46
+ itemScores: {},
47
+ timing: { startedAt: Date.now(), itemTimes: {}, totalTime: 0 },
48
+ };
49
+ this.questions = this.flattenQuestions(this.assessment);
50
+ const navigationMode = this.assessment.navigationMode || 'nonlinear';
51
+ this.navigationManager = new NavigationManager(navigationMode, this.questions.length);
52
+ // Item session control is a UI hint; backend remains authoritative.
53
+ const itemSessionControl = this.assessment.testParts?.[0]?.itemSessionControl;
54
+ this.sessionController = new ItemSessionController(itemSessionControl);
55
+ // Initialize per-item session state so itemSessionControl checks work immediately.
56
+ for (const q of this.questions) {
57
+ this.sessionController.initializeItem(q.identifier);
58
+ }
59
+ // Initialize time manager if time limits exist
60
+ if (this.assessment.timeLimits?.maxTime) {
61
+ this.timeManager = new TimeManager({
62
+ assessmentTimeLimits: this.assessment.timeLimits,
63
+ warningThreshold: config.timeWarningThreshold || 60,
64
+ onWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),
65
+ onExpired: () => this.notifyTimeExpired(),
66
+ onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
67
+ });
68
+ }
69
+ // Restore to backend-provided current item if present
70
+ const startId = this.state.currentItemIdentifier;
71
+ const idx = startId ? this.questions.findIndex((q) => q.identifier === startId) : -1;
72
+ if (idx >= 0) {
73
+ this.navigateTo(idx).catch(() => { });
74
+ }
75
+ }
76
+ hasAnyResponse(responses) {
77
+ for (const v of Object.values(responses)) {
78
+ if (v == null)
79
+ continue;
80
+ if (Array.isArray(v)) {
81
+ if (v.length > 0)
82
+ return true;
83
+ continue;
84
+ }
85
+ if (typeof v === 'string') {
86
+ if (v.trim().length > 0)
87
+ return true;
88
+ continue;
89
+ }
90
+ // object / number / boolean etc.
91
+ return true;
92
+ }
93
+ return false;
94
+ }
95
+ flattenQuestions(assessment) {
96
+ const out = [];
97
+ const testParts = assessment.testParts || [];
98
+ let idx = 0;
99
+ let secIdx = 0;
100
+ for (const tp of testParts) {
101
+ for (const section of tp.sections || []) {
102
+ for (const item of section.items || []) {
103
+ out.push({
104
+ identifier: item.identifier,
105
+ item,
106
+ section,
107
+ testPart: tp,
108
+ index: idx++,
109
+ sectionIndex: secIdx,
110
+ });
111
+ }
112
+ secIdx++;
113
+ }
114
+ }
115
+ return out;
116
+ }
117
+ // ---------------------------------------------------------------------------
118
+ // Public API used by components
119
+ // ---------------------------------------------------------------------------
120
+ getAllSections() {
121
+ const out = [];
122
+ let idx = 0;
123
+ for (const tp of this.assessment.testParts || []) {
124
+ for (const s of tp.sections || []) {
125
+ out.push({ id: s.identifier, title: s.title, visible: s.visible, index: idx++ });
126
+ }
127
+ }
128
+ return out;
129
+ }
130
+ getNavigationState() {
131
+ const total = this.questions.length;
132
+ const canPrevious = this.canPrevious();
133
+ const canNext = this.canNext();
134
+ const q = this.questions[this.currentItemIndex];
135
+ const totalSections = this.getAllSections().length;
136
+ return {
137
+ currentIndex: this.currentItemIndex,
138
+ totalItems: total,
139
+ canNext,
140
+ canPrevious,
141
+ isLoading: false,
142
+ currentSection: q
143
+ ? { id: q.section.identifier, title: q.section.title, index: q.sectionIndex }
144
+ : undefined,
145
+ totalSections,
146
+ };
147
+ }
148
+ getCurrentQuestion() {
149
+ const q = this.questions[this.currentItemIndex];
150
+ if (!q)
151
+ return null;
152
+ // Keep the legacy QuestionRef-ish shape expected by ItemRenderer.svelte
153
+ return {
154
+ identifier: q.item.identifier,
155
+ title: q.section.title,
156
+ required: q.item.required,
157
+ itemXml: q.item.itemXml,
158
+ };
159
+ }
160
+ getCurrentRubricBlocks() {
161
+ const q = this.questions[this.currentItemIndex];
162
+ if (!q)
163
+ return [];
164
+ return q.section.rubrics || q.testPart.rubrics || [];
165
+ }
166
+ getVisibleFeedback() {
167
+ return this.visibleFeedback;
168
+ }
169
+ updateResponse(responseId, value) {
170
+ this.responses = { ...this.responses, [responseId]: value };
171
+ const q = this.questions[this.currentItemIndex];
172
+ if (q) {
173
+ this.state.itemResponses[q.identifier] = this.responses;
174
+ this.sessionController.markAnswered(q.identifier, this.hasAnyResponse(this.responses));
175
+ }
176
+ this.notifyResponseChange();
177
+ }
178
+ /**
179
+ * Update a response for a specific item.
180
+ * Useful when response events are observed outside the current-item renderer and we
181
+ * want to be explicit about which item receives the response (some assessments reuse
182
+ * the same responseIdentifier like "RESPONSE" across items).
183
+ */
184
+ updateResponseForItem(itemIdentifier, responseId, value) {
185
+ const prev = (this.state.itemResponses?.[itemIdentifier] || {});
186
+ const next = { ...prev, [responseId]: value };
187
+ this.state.itemResponses[itemIdentifier] = next;
188
+ // If this is the active item, keep the live response state + UI hints in sync.
189
+ const active = this.questions[this.currentItemIndex];
190
+ if (active?.identifier === itemIdentifier) {
191
+ this.responses = next;
192
+ this.sessionController.markAnswered(itemIdentifier, this.hasAnyResponse(this.responses));
193
+ this.currentItemPlayer?.setResponses(this.responses);
194
+ this.notifyResponseChange();
195
+ }
196
+ }
197
+ /**
198
+ * Get current unsaved responses for the active item.
199
+ * (Useful for host integrations / web components.)
200
+ */
201
+ getResponses() {
202
+ return { ...this.responses };
203
+ }
204
+ /**
205
+ * Get the current session state snapshot (client-side view).
206
+ * Note: backend remains authoritative; this is intended for simple save/resume.
207
+ */
208
+ getState() {
209
+ // Shallow clone to avoid accidental external mutation.
210
+ return {
211
+ ...this.state,
212
+ visitedItems: [...this.state.visitedItems],
213
+ itemResponses: { ...this.state.itemResponses },
214
+ itemScores: this.state.itemScores ? { ...this.state.itemScores } : undefined,
215
+ timing: {
216
+ ...this.state.timing,
217
+ itemTimes: { ...this.state.timing.itemTimes },
218
+ },
219
+ };
220
+ }
221
+ /**
222
+ * Restore a previously saved session state.
223
+ */
224
+ async restoreState(state) {
225
+ this.state = state;
226
+ // Restore visited state for UI navigation hints.
227
+ const visitedIdx = (state.visitedItems || [])
228
+ .map((id) => this.questions.findIndex((q) => q.identifier === id))
229
+ .filter((i) => i >= 0);
230
+ this.navigationManager.restoreState(visitedIdx);
231
+ // Rehydrate itemResults from scores if present, so submit() can behave sensibly.
232
+ this.itemResults.clear();
233
+ if (state.itemScores) {
234
+ for (const [itemIdentifier, scoring] of Object.entries(state.itemScores)) {
235
+ this.itemResults.set(itemIdentifier, {
236
+ itemIdentifier,
237
+ score: scoring.score,
238
+ maxScore: scoring.maxScore,
239
+ responses: state.itemResponses?.[itemIdentifier] || {},
240
+ });
241
+ }
242
+ }
243
+ const currentId = state.currentItemIdentifier;
244
+ const idx = currentId ? this.questions.findIndex((q) => q.identifier === currentId) : -1;
245
+ if (idx >= 0) {
246
+ await this.navigateTo(idx);
247
+ }
248
+ else if (this.questions.length > 0) {
249
+ await this.navigateTo(0);
250
+ }
251
+ }
252
+ async navigateTo(index) {
253
+ if (index < 0 || index >= this.questions.length)
254
+ throw new Error(`Invalid item index: ${index}`);
255
+ // Enforce navigation rules (UI hints, still backend-authoritative for real deployments).
256
+ if (this.currentItemIndex >= 0 && !this.navigationManager.canNavigateTo(index, this.currentItemIndex)) {
257
+ if (this.navigationManager.getMode() === 'linear' && index > this.currentItemIndex + 1) {
258
+ throw new Error('In linear navigation mode, you can only move to the next question.');
259
+ }
260
+ throw new Error('Navigation is not allowed.');
261
+ }
262
+ const target = this.questions[index];
263
+ if (target && !this.sessionController.canReview(target.identifier)) {
264
+ throw new Error('You cannot go back to previous questions in this assessment.');
265
+ }
266
+ this.currentItemIndex = index;
267
+ const q = this.questions[index];
268
+ this.state.currentItemIdentifier = q.identifier;
269
+ // Restore responses
270
+ this.responses = { ...(this.state.itemResponses[q.identifier] || {}) };
271
+ // Create item player
272
+ this.currentItemPlayer = new Player({
273
+ itemXml: q.item.itemXml,
274
+ role: q.item.role,
275
+ i18nProvider: this.i18nProvider,
276
+ });
277
+ this.currentItemPlayer.setResponses(this.responses);
278
+ this.notifyItemChange();
279
+ this.notifySectionChange();
280
+ }
281
+ async navigateToSection(sectionId) {
282
+ const idx = this.questions.findIndex((q) => q.section.identifier === sectionId);
283
+ if (idx >= 0)
284
+ await this.navigateTo(idx);
285
+ }
286
+ async next() {
287
+ const state = this.getNavigationState();
288
+ if (!state.canNext)
289
+ return;
290
+ const q = this.questions[this.currentItemIndex];
291
+ if (q) {
292
+ const hasResponses = this.hasAnyResponse(this.responses);
293
+ this.sessionController.markAnswered(q.identifier, hasResponses);
294
+ const navAway = this.sessionController.canNavigateAway(q.identifier, hasResponses);
295
+ if (!navAway.allowed) {
296
+ throw new Error(navAway.reason || 'You must answer this question before continuing.');
297
+ }
298
+ // In individual submission mode, submit current item before moving forward.
299
+ if (this.assessment.submissionMode === 'individual') {
300
+ const before = this.currentItemIndex;
301
+ await this.submitCurrentItem();
302
+ // submitCurrentItem may branch/navigate; if it did, we're done.
303
+ if (this.currentItemIndex !== before)
304
+ return;
305
+ }
306
+ }
307
+ await this.navigateTo(this.currentItemIndex + 1);
308
+ }
309
+ async previous() {
310
+ const state = this.getNavigationState();
311
+ if (!state.canPrevious)
312
+ return;
313
+ await this.navigateTo(this.currentItemIndex - 1);
314
+ }
315
+ /** Submit current item (server-side scoring) */
316
+ async submitCurrentItem() {
317
+ const q = this.questions[this.currentItemIndex];
318
+ if (!q)
319
+ throw new Error('No current item');
320
+ const submittedAt = Date.now();
321
+ const res = await this.backend.submitResponses({
322
+ sessionId: this.sessionId,
323
+ itemIdentifier: q.identifier,
324
+ responses: this.responses,
325
+ submittedAt,
326
+ });
327
+ if (!res.success || !res.result) {
328
+ throw new Error(res.error || 'Submit failed');
329
+ }
330
+ if (res.updatedState) {
331
+ this.state = res.updatedState;
332
+ }
333
+ else {
334
+ // Minimal state update when backend doesn't return full state.
335
+ this.state.itemScores = this.state.itemScores || {};
336
+ this.state.itemScores[q.identifier] = res.result;
337
+ if (!this.state.visitedItems.includes(q.identifier))
338
+ this.state.visitedItems.push(q.identifier);
339
+ this.state.itemResponses[q.identifier] = this.responses;
340
+ }
341
+ const itemResult = {
342
+ itemIdentifier: q.identifier,
343
+ score: res.result.score,
344
+ maxScore: res.result.maxScore,
345
+ responses: { ...this.responses },
346
+ };
347
+ this.itemResults.set(q.identifier, itemResult);
348
+ // Track item session rules (review/attempts) and visited items for navigation hints.
349
+ try {
350
+ this.sessionController.recordAttempt(q.identifier);
351
+ }
352
+ catch {
353
+ // ignore
354
+ }
355
+ this.sessionController.markAnswered(q.identifier, this.hasAnyResponse(this.responses));
356
+ this.navigationManager.markVisited(this.currentItemIndex);
357
+ // Apply backend branching decision if provided
358
+ if (res.nextItemIdentifier) {
359
+ const nextIdx = this.questions.findIndex((x) => x.identifier === res.nextItemIdentifier);
360
+ if (nextIdx >= 0) {
361
+ await this.navigateTo(nextIdx);
362
+ }
363
+ }
364
+ return itemResult;
365
+ }
366
+ canPrevious() {
367
+ if (this.currentItemIndex <= 0)
368
+ return false;
369
+ const prev = this.questions[this.currentItemIndex - 1];
370
+ if (!prev)
371
+ return false;
372
+ if (!this.navigationManager.canNavigateTo(this.currentItemIndex - 1, this.currentItemIndex))
373
+ return false;
374
+ return this.sessionController.canReview(prev.identifier);
375
+ }
376
+ canNext() {
377
+ if (this.currentItemIndex < 0)
378
+ return false;
379
+ const nextIdx = this.currentItemIndex + 1;
380
+ if (nextIdx >= this.questions.length)
381
+ return false;
382
+ if (!this.navigationManager.canNavigateTo(nextIdx, this.currentItemIndex))
383
+ return false;
384
+ // Note: itemSessionControl constraints on leaving current item are enforced in next().
385
+ return true;
386
+ }
387
+ /** Submit entire assessment (finalize on backend) */
388
+ async submit() {
389
+ // For simultaneous submission, ensure all items are submitted before finalize so
390
+ // the backend can compute a complete test score.
391
+ if (this.assessment.submissionMode === 'simultaneous') {
392
+ // Preserve client-collected responses across backend state updates.
393
+ // Some backend adapters return an updatedState snapshot that may only include
394
+ // responses for items that have been submitted so far, which would otherwise
395
+ // wipe out responses for later items during this loop.
396
+ const allItemResponses = { ...(this.state.itemResponses || {}) };
397
+ for (const q of this.questions) {
398
+ if (this.itemResults.has(q.identifier))
399
+ continue;
400
+ const submittedAt = Date.now();
401
+ const responsesForItem = (allItemResponses?.[q.identifier] || {});
402
+ const res = await this.backend.submitResponses({
403
+ sessionId: this.sessionId,
404
+ itemIdentifier: q.identifier,
405
+ responses: responsesForItem,
406
+ submittedAt,
407
+ });
408
+ if (!res.success || !res.result) {
409
+ throw new Error(res.error || `Submit failed for item ${q.identifier}`);
410
+ }
411
+ if (res.updatedState) {
412
+ this.state = res.updatedState;
413
+ // Restore full response map captured on the client.
414
+ this.state.itemResponses = allItemResponses;
415
+ }
416
+ else {
417
+ this.state.itemScores = this.state.itemScores || {};
418
+ this.state.itemScores[q.identifier] = res.result;
419
+ if (!this.state.visitedItems.includes(q.identifier))
420
+ this.state.visitedItems.push(q.identifier);
421
+ this.state.itemResponses[q.identifier] = responsesForItem;
422
+ }
423
+ this.itemResults.set(q.identifier, {
424
+ itemIdentifier: q.identifier,
425
+ score: res.result.score,
426
+ maxScore: res.result.maxScore,
427
+ responses: this.state.itemResponses[q.identifier] || {},
428
+ });
429
+ }
430
+ }
431
+ else {
432
+ // Ensure current item is submitted (individual submission mode)
433
+ const q = this.questions[this.currentItemIndex];
434
+ if (q && !this.itemResults.has(q.identifier)) {
435
+ await this.submitCurrentItem();
436
+ }
437
+ }
438
+ const finalized = await this.backend.finalizeAssessment({
439
+ sessionId: this.sessionId,
440
+ });
441
+ if (!finalized.success)
442
+ throw new Error('Finalize failed');
443
+ // Map backend itemScores to ItemResult[]
444
+ const itemScores = finalized.itemScores || {};
445
+ const itemResults = Object.values(itemScores).map((r) => ({
446
+ itemIdentifier: r.itemIdentifier,
447
+ score: r.score,
448
+ maxScore: r.maxScore,
449
+ responses: this.state.itemResponses[r.itemIdentifier] || {},
450
+ }));
451
+ this.visibleFeedback = finalized.feedback
452
+ ? [{ identifier: 'testFeedback', content: finalized.feedback, access: 'atEnd' }]
453
+ : [];
454
+ this.notifyComplete();
455
+ if (this.config.onComplete)
456
+ this.config.onComplete();
457
+ return {
458
+ totalScore: finalized.totalScore,
459
+ maxScore: finalized.maxScore,
460
+ itemResults,
461
+ completedAt: new Date(finalized.finalizedAt),
462
+ };
463
+ }
464
+ // ---------------------------------------------------------------------------
465
+ // Session info + time helpers
466
+ // ---------------------------------------------------------------------------
467
+ getItemSessionInfo(_itemIdentifier) {
468
+ const q = this.questions[this.currentItemIndex];
469
+ if (!q)
470
+ return null;
471
+ const id = q.identifier;
472
+ const state = this.sessionController.getItemState(id);
473
+ if (!state) {
474
+ this.sessionController.initializeItem(id);
475
+ }
476
+ const st = this.sessionController.getItemState(id);
477
+ return {
478
+ canSubmit: this.sessionController.canSubmit(id),
479
+ remainingAttempts: this.sessionController.getRemainingAttempts(id),
480
+ attemptCount: st?.attemptCount ?? 0,
481
+ showFeedback: this.sessionController.shouldShowFeedback(id),
482
+ showSolution: this.sessionController.shouldShowSolution(id),
483
+ canReview: this.sessionController.canReview(id),
484
+ canSkip: this.sessionController.canSkip(id),
485
+ };
486
+ }
487
+ getRemainingTime() {
488
+ // TimeManager exposes seconds getters.
489
+ return this.timeManager?.getRemainingSeconds() ?? 0;
490
+ }
491
+ getElapsedTime() {
492
+ return this.timeManager?.getElapsedSeconds() ?? 0;
493
+ }
494
+ isTimeExpired() {
495
+ return this.timeManager?.isExpired() ?? false;
496
+ }
497
+ // ---------------------------------------------------------------------------
498
+ // Event subscriptions
499
+ // ---------------------------------------------------------------------------
500
+ onItemChange(listener) {
501
+ this.itemChangeListeners.add(listener);
502
+ return () => this.itemChangeListeners.delete(listener);
503
+ }
504
+ onSectionChange(listener) {
505
+ this.sectionChangeListeners.add(listener);
506
+ return () => this.sectionChangeListeners.delete(listener);
507
+ }
508
+ onResponseChange(listener) {
509
+ this.responseChangeListeners.add(listener);
510
+ return () => this.responseChangeListeners.delete(listener);
511
+ }
512
+ onComplete(listener) {
513
+ this.completeListeners.add(listener);
514
+ return () => this.completeListeners.delete(listener);
515
+ }
516
+ onTimeWarning(listener) {
517
+ this.timeWarningListeners.add(listener);
518
+ return () => this.timeWarningListeners.delete(listener);
519
+ }
520
+ onTimeExpired(listener) {
521
+ this.timeExpiredListeners.add(listener);
522
+ return () => this.timeExpiredListeners.delete(listener);
523
+ }
524
+ onTimeTick(listener) {
525
+ this.timeTickListeners.add(listener);
526
+ return () => this.timeTickListeners.delete(listener);
527
+ }
528
+ destroy() {
529
+ this.itemChangeListeners.clear();
530
+ this.sectionChangeListeners.clear();
531
+ this.responseChangeListeners.clear();
532
+ this.completeListeners.clear();
533
+ this.timeWarningListeners.clear();
534
+ this.timeExpiredListeners.clear();
535
+ this.timeTickListeners.clear();
536
+ this.currentItemPlayer = null;
537
+ }
538
+ // ---------------------------------------------------------------------------
539
+ // Internal notify helpers
540
+ // ---------------------------------------------------------------------------
541
+ notifyItemChange() {
542
+ for (const l of this.itemChangeListeners)
543
+ l(this.currentItemIndex, this.questions.length);
544
+ this.config.onItemChange?.(this.currentItemIndex, this.questions.length);
545
+ }
546
+ notifySectionChange() {
547
+ const q = this.questions[this.currentItemIndex];
548
+ const sectionIndex = q?.sectionIndex ?? 0;
549
+ const totalSections = this.getAllSections().length;
550
+ for (const l of this.sectionChangeListeners)
551
+ l(sectionIndex, totalSections);
552
+ this.config.onSectionChange?.(sectionIndex, totalSections);
553
+ }
554
+ notifyResponseChange() {
555
+ for (const l of this.responseChangeListeners)
556
+ l(this.responses);
557
+ this.config.onResponseChange?.(this.responses);
558
+ }
559
+ notifyComplete() {
560
+ for (const l of this.completeListeners)
561
+ l();
562
+ }
563
+ notifyTimeWarning(remainingSeconds) {
564
+ for (const l of this.timeWarningListeners)
565
+ l(remainingSeconds);
566
+ }
567
+ notifyTimeExpired() {
568
+ for (const l of this.timeExpiredListeners)
569
+ l();
570
+ }
571
+ notifyTimeTick(remainingSeconds, elapsedSeconds) {
572
+ for (const l of this.timeTickListeners)
573
+ l(remainingSeconds, elapsedSeconds);
574
+ }
575
+ /**
576
+ * Get the i18n provider instance
577
+ * @returns I18nProvider instance
578
+ */
579
+ getI18nProvider() {
580
+ return this.i18nProvider;
581
+ }
582
+ /**
583
+ * Create a simple fallback i18n provider when none is provided
584
+ */
585
+ createDefaultI18nProvider() {
586
+ return {
587
+ getLocale: () => 'en-US',
588
+ setLocale: () => { },
589
+ t: (key) => key, // Fallback to key
590
+ plural: (key) => key,
591
+ formatNumber: (value) => value.toString(),
592
+ formatDate: (date) => date.toISOString(),
593
+ };
594
+ }
595
+ }