@pie-qti/player-elements 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 (55) hide show
  1. package/.turbo/turbo-build.log +14 -0
  2. package/CHANGELOG.md +10 -0
  3. package/README.md +111 -0
  4. package/bunfig.toml +2 -0
  5. package/dist/constants.d.ts +3 -0
  6. package/dist/constants.d.ts.map +1 -0
  7. package/dist/define.d.ts +2 -0
  8. package/dist/define.d.ts.map +1 -0
  9. package/dist/elements/BaseSvelteMountElement.d.ts +12 -0
  10. package/dist/elements/BaseSvelteMountElement.d.ts.map +1 -0
  11. package/dist/elements/QtiAssessmentPlayerElement.d.ts +54 -0
  12. package/dist/elements/QtiAssessmentPlayerElement.d.ts.map +1 -0
  13. package/dist/elements/QtiItemPlayerElement.d.ts +49 -0
  14. package/dist/elements/QtiItemPlayerElement.d.ts.map +1 -0
  15. package/dist/index-B1sHDWWn.js +30415 -0
  16. package/dist/index-B1sHDWWn.js.map +1 -0
  17. package/dist/index-C_WHHKJ8.js +34157 -0
  18. package/dist/index-C_WHHKJ8.js.map +1 -0
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +13 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/mathlive.min-B8mv5Blc.js +15374 -0
  24. package/dist/mathlive.min-B8mv5Blc.js.map +1 -0
  25. package/dist/player-elements.css +1 -0
  26. package/dist/qti/parseAssessmentTest.d.ts +3 -0
  27. package/dist/qti/parseAssessmentTest.d.ts.map +1 -0
  28. package/dist/qti/resolveItems.d.ts +8 -0
  29. package/dist/qti/resolveItems.d.ts.map +1 -0
  30. package/dist/qti/types.d.ts +28 -0
  31. package/dist/qti/types.d.ts.map +1 -0
  32. package/dist/register.d.ts +2 -0
  33. package/dist/register.d.ts.map +1 -0
  34. package/dist/register.js +6 -0
  35. package/dist/register.js.map +1 -0
  36. package/dist/utils/json.d.ts +2 -0
  37. package/dist/utils/json.d.ts.map +1 -0
  38. package/package.json +39 -0
  39. package/src/constants.ts +4 -0
  40. package/src/define.ts +9 -0
  41. package/src/elements/BaseSvelteMountElement.ts +63 -0
  42. package/src/elements/QtiAssessmentPlayerElement.ts +384 -0
  43. package/src/elements/QtiItemPlayerElement.ts +197 -0
  44. package/src/index.ts +26 -0
  45. package/src/qti/parseAssessmentTest.ts +174 -0
  46. package/src/qti/resolveItems.ts +94 -0
  47. package/src/qti/types.ts +33 -0
  48. package/src/register.ts +7 -0
  49. package/src/utils/json.ts +10 -0
  50. package/svelte.config.js +14 -0
  51. package/tests/qti-assessment-test-parsing.test.ts +125 -0
  52. package/tests/setup.ts +29 -0
  53. package/tsconfig.build.json +15 -0
  54. package/tsconfig.json +18 -0
  55. package/vite.config.ts +25 -0
@@ -0,0 +1 @@
1
+ .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}
@@ -0,0 +1,3 @@
1
+ import type { ParsedAssessmentTest } from './types.js';
2
+ export declare function parseAssessmentTestXml(xml: string): ParsedAssessmentTest;
3
+ //# sourceMappingURL=parseAssessmentTest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parseAssessmentTest.d.ts","sourceRoot":"","sources":["../../src/qti/parseAssessmentTest.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAA2B,oBAAoB,EAAqC,MAAM,YAAY,CAAC;AA6HnH,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,GAAG,oBAAoB,CA4CxE"}
@@ -0,0 +1,8 @@
1
+ import type { ParsedAssessmentTest } from './types.js';
2
+ export type QtiItemMap = Record<string, string>;
3
+ export declare function resolveItemsForAssessment(options: {
4
+ assessment: ParsedAssessmentTest;
5
+ itemBaseUrl?: string;
6
+ items?: QtiItemMap;
7
+ }): Promise<ParsedAssessmentTest>;
8
+ //# sourceMappingURL=resolveItems.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveItems.d.ts","sourceRoot":"","sources":["../../src/qti/resolveItems.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA2B,oBAAoB,EAAqC,MAAM,YAAY,CAAC;AAEnH,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAoDhD,wBAAsB,yBAAyB,CAAC,OAAO,EAAE;IACxD,UAAU,EAAE,oBAAoB,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,UAAU,CAAC;CACnB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAiChC"}
@@ -0,0 +1,28 @@
1
+ import type { RubricBlock } from '@pie-qti/assessment-player';
2
+ export interface ParsedQuestionRef {
3
+ identifier: string;
4
+ title?: string;
5
+ href?: string;
6
+ required?: boolean;
7
+ itemXml?: string;
8
+ }
9
+ export interface ParsedAssessmentSection {
10
+ identifier: string;
11
+ title?: string;
12
+ visible?: boolean;
13
+ rubricBlocks?: RubricBlock[];
14
+ questionRefs?: ParsedQuestionRef[];
15
+ sections?: ParsedAssessmentSection[];
16
+ }
17
+ export interface ParsedTestPart {
18
+ identifier: string;
19
+ navigationMode: 'linear' | 'nonlinear';
20
+ submissionMode: 'individual' | 'simultaneous';
21
+ sections: ParsedAssessmentSection[];
22
+ }
23
+ export interface ParsedAssessmentTest {
24
+ identifier?: string;
25
+ title?: string;
26
+ testParts: ParsedTestPart[];
27
+ }
28
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/qti/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAE9D,MAAM,WAAW,iBAAiB;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,uBAAuB;IACvC,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,YAAY,CAAC,EAAE,WAAW,EAAE,CAAC;IAC7B,YAAY,CAAC,EAAE,iBAAiB,EAAE,CAAC;IACnC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,CAAC;CACrC;AAED,MAAM,WAAW,cAAc;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,QAAQ,GAAG,WAAW,CAAC;IACvC,cAAc,EAAE,YAAY,GAAG,cAAc,CAAC;IAC9C,QAAQ,EAAE,uBAAuB,EAAE,CAAC;CACpC;AAED,MAAM,WAAW,oBAAoB;IACpC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,cAAc,EAAE,CAAC;CAC5B"}
@@ -0,0 +1,2 @@
1
+ export { defineQtiPlayerElements } from './define.js';
2
+ //# sourceMappingURL=register.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../src/register.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { d as e } from "./index-B1sHDWWn.js";
2
+ e();
3
+ export {
4
+ e as defineQtiPlayerElements
5
+ };
6
+ //# sourceMappingURL=register.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register.js","sources":["../src/register.ts"],"sourcesContent":["import { defineQtiPlayerElements } from './define.js';\n\ndefineQtiPlayerElements();\n\nexport { defineQtiPlayerElements } from './define.js';\n\n\n"],"names":["defineQtiPlayerElements"],"mappings":";AAEAA,EAAA;"}
@@ -0,0 +1,2 @@
1
+ export declare function safeJsonParse<T>(value: string | null | undefined): T | undefined;
2
+ //# sourceMappingURL=json.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../../src/utils/json.ts"],"names":[],"mappings":"AAAA,wBAAgB,aAAa,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,CAAC,GAAG,SAAS,CAOhF"}
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@pie-qti/player-elements",
3
+ "version": "0.1.1",
4
+ "description": "QTI (2.x and 3.0) player web components (custom elements) for framework-agnostic embedding",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./register": {
14
+ "types": "./dist/register.d.ts",
15
+ "import": "./dist/register.js"
16
+ }
17
+ },
18
+ "scripts": {
19
+ "build": "vite build && tsc -p ./tsconfig.build.json",
20
+ "test": "bun test",
21
+ "typecheck": "tsc --noEmit",
22
+ "lint": "biome check .",
23
+ "lint:fix": "biome check --write .",
24
+ "format": "biome format --write ."
25
+ },
26
+ "license": "MIT",
27
+ "dependencies": {
28
+ "@pie-qti/assessment-player": "workspace:*",
29
+ "@pie-qti/item-player": "workspace:*",
30
+ "svelte": "^5.46.1"
31
+ },
32
+ "devDependencies": {
33
+ "@biomejs/biome": "^2.3.11",
34
+ "@sveltejs/vite-plugin-svelte": "^6.2.3",
35
+ "linkedom": "^0.18.12",
36
+ "typescript": "^5.9.3",
37
+ "vite": "^7.3.1"
38
+ }
39
+ }
@@ -0,0 +1,4 @@
1
+ export const QTI_ITEM_PLAYER_TAG = 'pie-qti-item-player';
2
+ export const QTI_ASSESSMENT_PLAYER_TAG = 'pie-qti-assessment-player';
3
+
4
+
package/src/define.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { defineQtiAssessmentPlayerElement } from './elements/QtiAssessmentPlayerElement.js';
2
+ import { defineQtiItemPlayerElement } from './elements/QtiItemPlayerElement.js';
3
+
4
+ export function defineQtiPlayerElements() {
5
+ defineQtiItemPlayerElement();
6
+ defineQtiAssessmentPlayerElement();
7
+ }
8
+
9
+
@@ -0,0 +1,63 @@
1
+ import type { Component } from 'svelte';
2
+ import { mount, unmount } from 'svelte';
3
+
4
+ export abstract class BaseSvelteMountElement<TProps extends Record<string, unknown>> extends HTMLElement {
5
+ protected abstract Component: Component<any>;
6
+ protected abstract getProps(): TProps;
7
+
8
+ #container: HTMLDivElement | null = null;
9
+ protected _instance: any = null;
10
+
11
+ connectedCallback() {
12
+ this._mountOrUpdate();
13
+ }
14
+
15
+ disconnectedCallback() {
16
+ this._teardownInstance();
17
+
18
+ if (this.#container) {
19
+ this.#container.remove();
20
+ this.#container = null;
21
+ }
22
+ }
23
+
24
+ protected _mountOrUpdate() {
25
+ if (!this.#container) {
26
+ this.#container = document.createElement('div');
27
+ this.#container.style.display = 'contents';
28
+ this.appendChild(this.#container);
29
+ }
30
+
31
+ const props = this.getProps();
32
+
33
+ if (!this._instance) {
34
+ this._instance = mount(this.Component, {
35
+ target: this.#container as HTMLDivElement,
36
+ props,
37
+ });
38
+ return;
39
+ }
40
+
41
+ // Svelte 5 `mount` returns an instance that may or may not have `$set`.
42
+ // If it doesn't, remount.
43
+ if (typeof this._instance?.$set === 'function') {
44
+ this._instance.$set(props);
45
+ } else {
46
+ this._teardownInstance();
47
+ this._mountOrUpdate();
48
+ }
49
+ }
50
+
51
+ protected _teardownInstance() {
52
+ if (this._instance) {
53
+ try {
54
+ unmount(this._instance);
55
+ } catch {
56
+ // ignore
57
+ }
58
+ this._instance = null;
59
+ }
60
+ }
61
+ }
62
+
63
+
@@ -0,0 +1,384 @@
1
+ import type { AssessmentResults, BackendAdapter, BackendAssessmentPlayerConfig, InitSessionRequest, SecureAssessment } from '@pie-qti/assessment-player';
2
+ import { ReferenceBackendAdapter } from '@pie-qti/assessment-player';
3
+ import AssessmentShell from '@pie-qti/assessment-player/components/AssessmentShell.svelte';
4
+ import type { PlayerSecurityConfig } from '@pie-qti/item-player';
5
+ import { QTI_ASSESSMENT_PLAYER_TAG } from '../constants.js';
6
+ import { parseAssessmentTestXml } from '../qti/parseAssessmentTest.js';
7
+ import { type QtiItemMap, resolveItemsForAssessment } from '../qti/resolveItems.js';
8
+ import type { ParsedAssessmentSection, ParsedAssessmentTest } from '../qti/types.js';
9
+ import { safeJsonParse } from '../utils/json.js';
10
+ import { BaseSvelteMountElement } from './BaseSvelteMountElement.js';
11
+
12
+ export type QtiAssessmentResponseChangeDetail = {
13
+ responses: Record<string, unknown>;
14
+ };
15
+
16
+ export type QtiAssessmentItemChangeDetail = {
17
+ itemIndex: number;
18
+ totalItems: number;
19
+ };
20
+
21
+ export type QtiAssessmentSectionChangeDetail = {
22
+ sectionIndex: number;
23
+ totalSections: number;
24
+ };
25
+
26
+ export type QtiAssessmentSubmitDetail = {
27
+ results: AssessmentResults;
28
+ };
29
+
30
+ export class QtiAssessmentPlayerElement extends BaseSvelteMountElement<Record<string, unknown>> {
31
+ static get observedAttributes() {
32
+ return [
33
+ // Pure-QTI inputs
34
+ 'assessment-test-xml',
35
+ 'assessment-id',
36
+ 'candidate-id',
37
+ 'item-base-url',
38
+ 'items-json',
39
+ // Common
40
+ 'config-json',
41
+ 'security-json',
42
+ ];
43
+ }
44
+
45
+ protected Component = AssessmentShell;
46
+
47
+ #assessmentTestXml: string | null = null;
48
+ #assessmentId: string | undefined;
49
+ #candidateId: string | undefined;
50
+ #itemBaseUrl: string | undefined;
51
+ #items: QtiItemMap | undefined;
52
+ #config: Partial<BackendAssessmentPlayerConfig> = {};
53
+ #security: PlayerSecurityConfig | undefined;
54
+
55
+ #backend: BackendAdapter = {
56
+ async initSession(_request) {
57
+ throw new Error('No assessment loaded. Provide `assessment-test-xml`.');
58
+ },
59
+ async submitResponses(_request) {
60
+ return { success: false, error: 'No assessment loaded.' };
61
+ },
62
+ async finalizeAssessment(_request) {
63
+ return { success: false, totalScore: 0, maxScore: 0, itemScores: {}, finalizedAt: Date.now() };
64
+ },
65
+ async saveState(_request) {
66
+ return { success: false, savedAt: Date.now() };
67
+ },
68
+ async queryItemBank(_request) {
69
+ return { items: [], selectedAt: Date.now() };
70
+ },
71
+ };
72
+ #initSession: InitSessionRequest = { assessmentId: 'assessment', candidateId: 'candidate' };
73
+
74
+ #loadSeq = 0;
75
+ #allowMount = false;
76
+
77
+ connectedCallback() {
78
+ super.connectedCallback();
79
+ queueMicrotask(() => {
80
+ this.dispatchEvent(new CustomEvent('ready', { bubbles: true, composed: true }));
81
+ });
82
+ }
83
+
84
+ protected override _mountOrUpdate() {
85
+ // Prevent mounting until assessment is loaded or no XML is provided
86
+ if (!this.#allowMount && this.#assessmentTestXml) {
87
+ return;
88
+ }
89
+ super._mountOrUpdate();
90
+ }
91
+
92
+ attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null) {
93
+ if (name === 'assessment-test-xml') {
94
+ this.#assessmentTestXml = newValue;
95
+ }
96
+
97
+ if (name === 'assessment-id') {
98
+ this.#assessmentId = newValue ?? undefined;
99
+ }
100
+
101
+ if (name === 'candidate-id') {
102
+ this.#candidateId = newValue ?? undefined;
103
+ }
104
+
105
+ if (name === 'item-base-url') {
106
+ this.#itemBaseUrl = newValue ?? undefined;
107
+ }
108
+
109
+ if (name === 'items-json') {
110
+ const parsed = safeJsonParse<QtiItemMap>(newValue);
111
+ if (parsed) this.#items = parsed;
112
+ }
113
+
114
+ if (name === 'config-json') {
115
+ const parsed = safeJsonParse<Partial<BackendAssessmentPlayerConfig>>(newValue);
116
+ if (parsed) this.#config = parsed;
117
+ }
118
+
119
+ if (name === 'security-json') {
120
+ const parsed = safeJsonParse<PlayerSecurityConfig>(newValue);
121
+ if (parsed) this.#security = parsed;
122
+ }
123
+
124
+ void this.#syncFromQti();
125
+ // Don't call _mountOrUpdate here - let #syncFromQti handle it when done
126
+ }
127
+
128
+ get config() {
129
+ return this.#config;
130
+ }
131
+ set config(value: Partial<BackendAssessmentPlayerConfig>) {
132
+ this.#config = value ?? {};
133
+ // Don't call _mountOrUpdate here - let #syncFromQti handle it when done
134
+ // If assessment is not being loaded (no XML), then update immediately
135
+ if (!this.#assessmentTestXml) {
136
+ this._mountOrUpdate();
137
+ }
138
+ }
139
+
140
+ get security() {
141
+ return this.#security;
142
+ }
143
+ set security(value: PlayerSecurityConfig | undefined) {
144
+ this.#security = value;
145
+ // Don't call _mountOrUpdate here - let #syncFromQti handle it when done
146
+ // If assessment is not being loaded (no XML), then update immediately
147
+ if (!this.#assessmentTestXml) {
148
+ this._mountOrUpdate();
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Pure-QTI API (preferred): supply an assessmentTest XML string and let the element
154
+ * resolve itemRefs via either an item map (A) or base URL fetching (B).
155
+ */
156
+ get assessmentTestXml() {
157
+ return this.#assessmentTestXml;
158
+ }
159
+ set assessmentTestXml(value: string | null) {
160
+ this.#assessmentTestXml = value;
161
+ void this.#syncFromQti();
162
+ // Don't call _mountOrUpdate here - let #syncFromQti handle it when done
163
+ }
164
+
165
+ get itemBaseUrl() {
166
+ return this.#itemBaseUrl;
167
+ }
168
+ set itemBaseUrl(value: string | undefined) {
169
+ this.#itemBaseUrl = value;
170
+ void this.#syncFromQti();
171
+ // Don't call _mountOrUpdate here - let #syncFromQti handle it when done
172
+ }
173
+
174
+ get items() {
175
+ return this.#items;
176
+ }
177
+ set items(value: QtiItemMap | undefined) {
178
+ this.#items = value;
179
+ void this.#syncFromQti();
180
+ // Don't call _mountOrUpdate here - let #syncFromQti handle it when done
181
+ }
182
+
183
+ /**
184
+ * Imperative API (proxied through `AssessmentShell` exports)
185
+ */
186
+ async next() {
187
+ return this._instance?.next?.();
188
+ }
189
+ async previous() {
190
+ return this._instance?.previous?.();
191
+ }
192
+ async navigateTo(index: number) {
193
+ return this._instance?.navigateTo?.(index);
194
+ }
195
+ async navigateToSection(sectionIdentifier: string) {
196
+ return this._instance?.navigateToSection?.(sectionIdentifier);
197
+ }
198
+ async submit() {
199
+ return this._instance?.submit?.();
200
+ }
201
+ getResponses() {
202
+ return this._instance?.getResponses?.();
203
+ }
204
+ getState() {
205
+ return this._instance?.getState?.();
206
+ }
207
+ restoreState(state: unknown) {
208
+ return this._instance?.restoreState?.(state);
209
+ }
210
+
211
+ async #syncFromQti() {
212
+ if (!this.#assessmentTestXml) return;
213
+
214
+ const seq = ++this.#loadSeq;
215
+ this.dispatchEvent(new CustomEvent('load-start', { bubbles: true, composed: true }));
216
+
217
+ try {
218
+ const parsed = parseAssessmentTestXml(this.#assessmentTestXml);
219
+ await resolveItemsForAssessment({
220
+ assessment: parsed,
221
+ itemBaseUrl: this.#itemBaseUrl,
222
+ items: this.#items,
223
+ });
224
+
225
+ if (seq !== this.#loadSeq) return; // superseded
226
+ const assessmentId = this.#assessmentId ?? parsed.identifier ?? 'assessment';
227
+ const candidateId = this.#candidateId ?? 'candidate';
228
+
229
+ const secure = this.#toSecureAssessment(parsed, this.#config.role ?? 'candidate');
230
+ const backend = new ReferenceBackendAdapter();
231
+ backend.registerAssessment(assessmentId, secure);
232
+ this.#backend = backend;
233
+ this.#initSession = { assessmentId, candidateId };
234
+
235
+ this.dispatchEvent(new CustomEvent('load-end', { bubbles: true, composed: true }));
236
+
237
+ // Allow mounting now that backend is ready
238
+ this.#allowMount = true;
239
+ this._mountOrUpdate();
240
+ } catch (e) {
241
+ if (seq !== this.#loadSeq) return;
242
+ // Keep current backend/initSession; component will display error.
243
+ this.dispatchEvent(
244
+ new CustomEvent('load-error', {
245
+ detail: { message: e instanceof Error ? e.message : String(e) },
246
+ bubbles: true,
247
+ composed: true,
248
+ }),
249
+ );
250
+ this._mountOrUpdate(); // Mount/update even on error (will show fallback)
251
+ }
252
+ }
253
+
254
+ #toSecureAssessment(parsed: ParsedAssessmentTest, role: BackendAssessmentPlayerConfig['role']): SecureAssessment {
255
+ const testParts = parsed.testParts ?? [];
256
+ const first = testParts[0];
257
+
258
+ if (!first) {
259
+ return {
260
+ identifier: parsed.identifier ?? 'assessment',
261
+ title: parsed.title ?? 'Assessment',
262
+ navigationMode: 'nonlinear',
263
+ submissionMode: 'simultaneous',
264
+ testParts: [],
265
+ };
266
+ }
267
+
268
+ const flattenSections = (roots: ParsedAssessmentSection[]): ParsedAssessmentSection[] => {
269
+ const out: ParsedAssessmentSection[] = [];
270
+ const stack = [...roots].reverse();
271
+ while (stack.length) {
272
+ const s = stack.pop()!;
273
+ out.push(s);
274
+ if (s.sections && s.sections.length) {
275
+ // depth-first, preserve original order
276
+ for (const child of [...s.sections].reverse()) stack.push(child);
277
+ }
278
+ }
279
+ return out;
280
+ };
281
+
282
+ const mapSection = (s: ParsedAssessmentSection) => {
283
+ const items =
284
+ s.questionRefs?.map((q) => {
285
+ if (!q.itemXml) {
286
+ throw new Error(`Missing itemXml for item "${q.identifier}" (provide items-json or item-base-url).`);
287
+ }
288
+ return {
289
+ identifier: q.identifier,
290
+ itemXml: q.itemXml,
291
+ role: role ?? 'candidate',
292
+ required: q.required,
293
+ };
294
+ }) ?? [];
295
+
296
+ return {
297
+ identifier: s.identifier,
298
+ title: s.title,
299
+ visible: s.visible ?? true,
300
+ items,
301
+ rubrics: s.rubricBlocks,
302
+ };
303
+ };
304
+
305
+ return {
306
+ identifier: parsed.identifier ?? 'assessment',
307
+ title: parsed.title ?? 'Assessment',
308
+ navigationMode: first.navigationMode ?? 'nonlinear',
309
+ submissionMode: first.submissionMode ?? 'simultaneous',
310
+ testParts: testParts.map((p) => ({
311
+ identifier: p.identifier,
312
+ sections: flattenSections(p.sections).map(mapSection),
313
+ })),
314
+ };
315
+ }
316
+
317
+ getProps() {
318
+ // Ensure we never expose callback-style config as the public API.
319
+ // Consumers should listen to DOM events instead.
320
+ const baseConfig: Partial<BackendAssessmentPlayerConfig> = {
321
+ ...this.#config,
322
+ security: this.#security,
323
+ onItemChange: (itemIndex: number, totalItems: number) => {
324
+ const detail: QtiAssessmentItemChangeDetail = { itemIndex, totalItems };
325
+ this.dispatchEvent(
326
+ new CustomEvent<QtiAssessmentItemChangeDetail>('item-change', {
327
+ detail,
328
+ bubbles: true,
329
+ composed: true,
330
+ }),
331
+ );
332
+ },
333
+ onSectionChange: (sectionIndex: number, totalSections: number) => {
334
+ const detail: QtiAssessmentSectionChangeDetail = { sectionIndex, totalSections };
335
+ this.dispatchEvent(
336
+ new CustomEvent<QtiAssessmentSectionChangeDetail>('section-change', {
337
+ detail,
338
+ bubbles: true,
339
+ composed: true,
340
+ }),
341
+ );
342
+ },
343
+ onResponseChange: (responses: Record<string, unknown>) => {
344
+ const detail: QtiAssessmentResponseChangeDetail = { responses: { ...responses } };
345
+ this.dispatchEvent(
346
+ new CustomEvent<QtiAssessmentResponseChangeDetail>('response-change', {
347
+ detail,
348
+ bubbles: true,
349
+ composed: true,
350
+ }),
351
+ );
352
+ },
353
+ onComplete: () => {
354
+ this.dispatchEvent(new CustomEvent('complete', { bubbles: true, composed: true }));
355
+ },
356
+ };
357
+
358
+ const props: any = {
359
+ backend: this.#backend,
360
+ initSession: this.#initSession,
361
+ config: baseConfig,
362
+ onSubmit: (results: AssessmentResults) => {
363
+ const detail: QtiAssessmentSubmitDetail = { results };
364
+ this.dispatchEvent(
365
+ new CustomEvent<QtiAssessmentSubmitDetail>('submit', {
366
+ detail,
367
+ bubbles: true,
368
+ composed: true,
369
+ }),
370
+ );
371
+ },
372
+ };
373
+ // Don't pass typeset at all if not provided (passing undefined can cause issues)
374
+ return props;
375
+ }
376
+ }
377
+
378
+ export function defineQtiAssessmentPlayerElement() {
379
+ if (!customElements.get(QTI_ASSESSMENT_PLAYER_TAG)) {
380
+ customElements.define(QTI_ASSESSMENT_PLAYER_TAG, QtiAssessmentPlayerElement);
381
+ }
382
+ }
383
+
384
+