@pie-qti/qti-common 0.1.28 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +31 -86
  2. package/package.json +2 -3
  3. package/dist/accessibility/apip.d.ts +0 -66
  4. package/dist/accessibility/apip.js +0 -576
  5. package/dist/accessibility/apip.js.map +0 -1
  6. package/dist/accessibility/catalog-info.d.ts +0 -17
  7. package/dist/accessibility/catalog-info.js +0 -60
  8. package/dist/accessibility/catalog-info.js.map +0 -1
  9. package/dist/accessibility/catalog.d.ts +0 -53
  10. package/dist/accessibility/catalog.js +0 -68
  11. package/dist/accessibility/catalog.js.map +0 -1
  12. package/dist/accessibility/index.d.ts +0 -3
  13. package/dist/accessibility/index.js +0 -4
  14. package/dist/accessibility/index.js.map +0 -1
  15. package/dist/dom/assignProps.d.ts +0 -4
  16. package/dist/dom/assignProps.js +0 -9
  17. package/dist/dom/assignProps.js.map +0 -1
  18. package/dist/dom/svelteMountController.d.ts +0 -25
  19. package/dist/dom/svelteMountController.js +0 -131
  20. package/dist/dom/svelteMountController.js.map +0 -1
  21. package/dist/dom/touchDrag.d.ts +0 -10
  22. package/dist/dom/touchDrag.js +0 -141
  23. package/dist/dom/touchDrag.js.map +0 -1
  24. package/dist/element-mapper/AttributeNameMapper.d.ts +0 -66
  25. package/dist/element-mapper/AttributeNameMapper.js +0 -2
  26. package/dist/element-mapper/AttributeNameMapper.js.map +0 -1
  27. package/dist/element-mapper/ElementNameMapper.d.ts +0 -66
  28. package/dist/element-mapper/ElementNameMapper.js +0 -2
  29. package/dist/element-mapper/ElementNameMapper.js.map +0 -1
  30. package/dist/element-mapper/Qti2xAttributeNameMapper.d.ts +0 -27
  31. package/dist/element-mapper/Qti2xAttributeNameMapper.js +0 -38
  32. package/dist/element-mapper/Qti2xAttributeNameMapper.js.map +0 -1
  33. package/dist/element-mapper/Qti2xElementNameMapper.d.ts +0 -37
  34. package/dist/element-mapper/Qti2xElementNameMapper.js +0 -47
  35. package/dist/element-mapper/Qti2xElementNameMapper.js.map +0 -1
  36. package/dist/element-mapper/Qti3AttributeNameMapper.d.ts +0 -40
  37. package/dist/element-mapper/Qti3AttributeNameMapper.js +0 -87
  38. package/dist/element-mapper/Qti3AttributeNameMapper.js.map +0 -1
  39. package/dist/element-mapper/Qti3ElementNameMapper.d.ts +0 -14
  40. package/dist/element-mapper/Qti3ElementNameMapper.js +0 -39
  41. package/dist/element-mapper/Qti3ElementNameMapper.js.map +0 -1
  42. package/dist/element-mapper/index.d.ts +0 -8
  43. package/dist/element-mapper/index.js +0 -7
  44. package/dist/element-mapper/index.js.map +0 -1
  45. package/dist/element-mapper/qti2-to-qti3.d.ts +0 -36
  46. package/dist/element-mapper/qti2-to-qti3.js +0 -228
  47. package/dist/element-mapper/qti2-to-qti3.js.map +0 -1
  48. package/dist/element-mapper/qti3-attribute-map.d.ts +0 -8
  49. package/dist/element-mapper/qti3-attribute-map.js +0 -115
  50. package/dist/element-mapper/qti3-attribute-map.js.map +0 -1
  51. package/dist/element-mapper/qti3-element-mappings.d.ts +0 -538
  52. package/dist/element-mapper/qti3-element-mappings.js +0 -381
  53. package/dist/element-mapper/qti3-element-mappings.js.map +0 -1
  54. package/dist/index.d.ts +0 -15
  55. package/dist/index.js +0 -17
  56. package/dist/index.js.map +0 -1
  57. package/dist/parser-factory.d.ts +0 -137
  58. package/dist/parser-factory.js +0 -146
  59. package/dist/parser-factory.js.map +0 -1
  60. package/dist/version-detection/detectQtiVersion.d.ts +0 -23
  61. package/dist/version-detection/detectQtiVersion.js +0 -129
  62. package/dist/version-detection/detectQtiVersion.js.map +0 -1
  63. package/dist/version-detection/index.d.ts +0 -2
  64. package/dist/version-detection/index.js +0 -2
  65. package/dist/version-detection/index.js.map +0 -1
  66. package/dist/xml/attributes.d.ts +0 -77
  67. package/dist/xml/attributes.js +0 -120
  68. package/dist/xml/attributes.js.map +0 -1
@@ -1,576 +0,0 @@
1
- /**
2
- * APIP accessibility
3
- *
4
- * QTI 2.x carries accessibility content as APIP 1.0: an `apip:apipAccessibility` element whose
5
- * `accessElement`s each link content elements, by `id`, to the supports that describe them. A
6
- * catalog is the same thing in QTI 3's terms, so an access element maps to one catalog by its
7
- * `identifier`, its supports to cards under the support names QTI 3 uses, as 1EdTech's
8
- * APIP-to-QTI 3 migration guide maps them:
9
- *
10
- * - `spoken`: one script card, the first of `textToSpeechPronunciationSSML` (as `<speak>`),
11
- * `textToSpeechPronunciation` and `spokenText`, the others kept as `ext:custom-` cards, and a
12
- * card per `audioFileInfo` recording, its `startTime` and `duration` the time range;
13
- * - `brailleText` as `braille`, `tactileFile` as `tactile`;
14
- * - `signing` as `sign-language` video, `ase` for ASL and `eng-US` for Signed English, with the
15
- * cues as the time range;
16
- * - `keyWordTranslation` as `keyword-translation`, one card per language;
17
- * - `guidance`'s `languageLearnerSupport` as `linguistic-guidance`.
18
- *
19
- * QTI 3 has no counterpart for the other supports, which the reader reports as unmapped;
20
- * `voiceType`, `voiceSpeed` and `supportOrder` are dropped, the last because document order is the
21
- * order.
22
- *
23
- * The writer maps the other way. A card APIP has no element for, a card past the one an element
24
- * holds, and a card missing what its element requires (a `tactile` recording without its text, an
25
- * audio file whose MIME type is unknown) are unwritten, and the result names their supports.
26
- * SSML elements APIP does not admit are unwrapped to their content. Plain-text APIP elements take
27
- * the card's text, its markup dropped.
28
- */
29
- import { NodeType, parse, TextNode } from 'node-html-parser';
30
- import { clockSeconds, mediaKind, mediaMimeType, } from './catalog.js';
31
- export const APIP_NAMESPACE = 'http://www.imsglobal.org/xsd/apip/apipv1p0/imsapip_qtiv1p0';
32
- export const SSML_NAMESPACE = 'http://www.w3.org/2001/10/synthesis';
33
- const SPOKEN = 'spoken';
34
- const SIGN_LANGUAGE = 'sign-language';
35
- const TTS_PRONUNCIATION = 'ext:custom-text-to-speech-pronunciation';
36
- const SPOKEN_TEXT = 'ext:custom-spoken-text';
37
- const TACTILE_BRAILLE_TEXT = 'ext:custom-tactile-braille-text';
38
- /** The sign language a `signing` file is in: ASL, and Signed English as the guide codes it. */
39
- const SIGN_FILE_LANGUAGES = {
40
- signFileASL: 'ase',
41
- signFileSignedEnglish: 'eng-US',
42
- };
43
- /** The SSML elements `textToSpeechPronunciationSSML` admits. */
44
- const APIP_SSML_ELEMENTS = new Set([
45
- 'p',
46
- 's',
47
- 'say-as',
48
- 'phoneme',
49
- 'sub',
50
- 'voice',
51
- 'emphasis',
52
- 'break',
53
- 'prosody',
54
- 'mark',
55
- 'audio',
56
- ]);
57
- const APIP_SUPPORTS = {
58
- spoken: spokenSupport,
59
- brailleText: (support) => ({ cards: textCards('braille', textOf(support, 'brailleTextString')) }),
60
- tactileFile: (support) => {
61
- const audio = firstChild(support, 'tactileAudioFile');
62
- const payload = audio && audioPayload(audio);
63
- return {
64
- cards: [
65
- ...textCards('tactile', textOf(support, 'tactileAudioText')),
66
- ...(payload ? [{ catalog: 'tactile', payload }] : []),
67
- ...textCards(TACTILE_BRAILLE_TEXT, textOf(support, 'tactileBrailleText')),
68
- ],
69
- };
70
- },
71
- signing: (support) => {
72
- const cards = [];
73
- const unmapped = [];
74
- for (const signFile of allChildElements(support)) {
75
- const language = SIGN_FILE_LANGUAGES[localName(signFile)];
76
- const video = firstChild(signFile, 'videoFileInfo');
77
- const payload = language && video ? videoPayload(video) : undefined;
78
- if (payload)
79
- cards.push({ catalog: SIGN_LANGUAGE, language, payload });
80
- if (!language)
81
- unmapped.push(localName(signFile));
82
- else if (firstChild(signFile, 'boneAnimationVideoFile'))
83
- unmapped.push('boneAnimationVideoFile');
84
- }
85
- return { cards, unmapped };
86
- },
87
- keyWordTranslation: (support) => ({
88
- cards: childElements(support, 'definitionId').flatMap((definition) => {
89
- const language = definition.getAttribute('xml:lang')?.trim();
90
- return textCards('keyword-translation', textOf(definition, 'textString')).map((card) => language ? { ...card, language } : card);
91
- }),
92
- }),
93
- guidance: (support) => {
94
- const learner = firstChild(support, 'languageLearnerSupport');
95
- return {
96
- cards: learner ? textCards('linguistic-guidance', textOf(learner, 'textString')) : [],
97
- unmapped: firstChild(support, 'cognitiveGuidanceSupport') ? ['cognitiveGuidanceSupport'] : [],
98
- };
99
- },
100
- };
101
- /**
102
- * The APIP access elements a QTI 2.x document declares, in document order. A string is parsed
103
- * with its CDATA sections unwrapped; a parsed root must keep tag names as authored.
104
- */
105
- export function readApipAccessElements(source) {
106
- const root = typeof source === 'string'
107
- ? parse(source.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1'), {
108
- lowerCaseTagName: false,
109
- comment: false,
110
- })
111
- : source;
112
- return root
113
- .querySelectorAll('*')
114
- .filter((element) => localName(element) === 'accessElement')
115
- .map((element) => {
116
- const cards = [];
117
- const unmapped = [];
118
- for (const info of childElements(element, 'relatedElementInfo')) {
119
- for (const support of allChildElements(info)) {
120
- const read = APIP_SUPPORTS[localName(support)];
121
- if (!read) {
122
- unmapped.push(localName(support));
123
- continue;
124
- }
125
- const mapped = read(support);
126
- cards.push(...mapped.cards);
127
- unmapped.push(...(mapped.unmapped ?? []));
128
- }
129
- }
130
- return {
131
- identifier: element.getAttribute('identifier')?.trim() ?? '',
132
- links: childElements(element, 'contentLinkInfo').map(contentLink),
133
- cards,
134
- unmapped,
135
- };
136
- });
137
- }
138
- /** Write access elements as `apip:apipAccessibility`, for the end of an item or stimulus. */
139
- export function writeApipAccessibility(elements, options = {}) {
140
- const ids = new IdAllocator(options.reservedIds);
141
- const unwritten = new Map();
142
- const written = [];
143
- let ssml = false;
144
- for (const element of elements) {
145
- const links = element.links.flatMap((link) => {
146
- const xml = contentLinkXml(link);
147
- return xml ? [xml] : [];
148
- });
149
- const identifier = ids.take(ncName(element.identifier));
150
- const label = () => ids.take(`${identifier}-${ids.next(identifier)}`);
151
- const supports = links.length > 0 ? supportsXml(element.cards, label) : undefined;
152
- const skipped = supports ? supports.unwritten : element.cards.map((card) => card.catalog);
153
- if (skipped.length > 0)
154
- unwritten.set(element.identifier, [...new Set(skipped)]);
155
- if (!supports || supports.xml.length === 0)
156
- continue;
157
- ssml ||= supports.ssml;
158
- written.push(`<apip:accessElement identifier="${escapeAttribute(identifier)}">${links.join('')}` +
159
- `<apip:relatedElementInfo>${supports.xml.join('')}</apip:relatedElementInfo></apip:accessElement>`);
160
- }
161
- if (written.length === 0)
162
- return { unwritten };
163
- const namespaces = `xmlns:apip="${APIP_NAMESPACE}"${ssml ? ` xmlns:ssml="${SSML_NAMESPACE}"` : ''}`;
164
- return {
165
- xml: `<apip:apipAccessibility ${namespaces}><apip:accessibilityInfo>${written.join('')}</apip:accessibilityInfo></apip:apipAccessibility>`,
166
- unwritten,
167
- };
168
- }
169
- // ---------------------------------------------------------------------------
170
- // Reading
171
- // ---------------------------------------------------------------------------
172
- function spokenSupport(spoken) {
173
- const ssml = firstChild(spoken, 'textToSpeechPronunciationSSML');
174
- // The first script present is the spoken card; the ones it outranks keep their own names.
175
- const scripts = [
176
- [SPOKEN, ssml && speakMarkup(ssml)],
177
- [TTS_PRONUNCIATION, textOf(spoken, 'textToSpeechPronunciation')],
178
- [SPOKEN_TEXT, textOf(spoken, 'spokenText')],
179
- ].filter((script) => Boolean(script[1]));
180
- const recordings = childElements(spoken, 'audioFileInfo').flatMap((audio) => {
181
- const payload = audioPayload(audio);
182
- return payload ? [{ catalog: SPOKEN, payload }] : [];
183
- });
184
- return {
185
- cards: [
186
- ...scripts.map(([catalog, content], index) => ({
187
- catalog: index === 0 ? SPOKEN : catalog,
188
- content,
189
- })),
190
- ...recordings,
191
- ],
192
- };
193
- }
194
- /** `textToSpeechPronunciationSSML` as a `<speak>` document, its elements without prefixes. */
195
- function speakMarkup(ssml) {
196
- const markup = ssml.innerHTML
197
- .replace(/<(\/?)[\w.-]+:/g, '<$1')
198
- .replace(/\s+xmlns(?::[\w.-]+)?\s*=\s*(?:"[^"]*"|'[^']*')/g, '')
199
- .replace(/\s+/g, ' ')
200
- .trim();
201
- if (!markup)
202
- return undefined;
203
- return /^<speak[\s>]/.test(markup) ? markup : `<speak>${markup}</speak>`;
204
- }
205
- function audioPayload(info) {
206
- const start = timeOf(info, 'startTime');
207
- const duration = timeOf(info, 'duration');
208
- const startSeconds = start ?? 0;
209
- return filePayload(info, 'audio', start === undefined && duration === undefined
210
- ? undefined
211
- : {
212
- startSeconds,
213
- ...(duration === undefined ? {} : { endSeconds: milliseconds(startSeconds + duration) }),
214
- });
215
- }
216
- function videoPayload(info) {
217
- const start = timeOf(info, 'startCue');
218
- const end = timeOf(info, 'endCue');
219
- return filePayload(info, 'video', start === undefined && end === undefined
220
- ? undefined
221
- : { startSeconds: start ?? 0, ...(end === undefined ? {} : { endSeconds: end }) });
222
- }
223
- function filePayload(info, fallback, fragment) {
224
- const src = firstChild(info, 'fileHref')?.textContent.trim();
225
- if (!src)
226
- return undefined;
227
- const type = info.getAttribute('mimeType')?.trim();
228
- return {
229
- media: {
230
- version: 1,
231
- id: src,
232
- kind: mediaKind(type, src, fallback),
233
- sources: [{ src, ...(type ? { type } : {}) }],
234
- },
235
- ...(fragment ? { fragment } : {}),
236
- };
237
- }
238
- /** An `xs:time` child as seconds; its time zone, which a media offset has no use for, ignored. */
239
- function timeOf(parent, name) {
240
- const value = firstChild(parent, name)
241
- ?.textContent.trim()
242
- .replace(/(?:Z|[+-]\d{2}:\d{2})$/, '');
243
- return value ? clockSeconds(value) : undefined;
244
- }
245
- function milliseconds(value) {
246
- return Math.round(value * 1000) / 1000;
247
- }
248
- function contentLink(link) {
249
- const target = link.getAttribute('qtiLinkIdentifierRef')?.trim() ?? '';
250
- const textLink = firstChild(link, 'textLink');
251
- const word = textLink && firstChild(textLink, 'wordLink');
252
- const character = textLink && firstChild(textLink, 'characterLink');
253
- const characters = textLink && firstChild(textLink, 'characterStringLink');
254
- let range;
255
- if (word) {
256
- range = { unit: 'word', start: count(word), stop: count(word) };
257
- }
258
- else if (character) {
259
- range = { unit: 'character', start: count(character), stop: count(character) };
260
- }
261
- else if (characters) {
262
- range = {
263
- unit: 'character',
264
- start: count(firstChild(characters, 'startCharacter')),
265
- stop: count(firstChild(characters, 'stopCharacter')),
266
- };
267
- }
268
- return {
269
- target,
270
- ...(range ? { range } : {}),
271
- ...(firstChild(link, 'objectLink') ? { object: true } : {}),
272
- };
273
- }
274
- /** A link's word or character number; not a number when absent, so it locates nothing. */
275
- function count(element) {
276
- return Number(element?.textContent.trim() || Number.NaN);
277
- }
278
- /** A text child as card content: its text, escaped as HTML. */
279
- function textOf(parent, name) {
280
- const text = firstChild(parent, name)?.textContent.trim();
281
- return text ? escapeText(text) : undefined;
282
- }
283
- function textCards(catalog, content) {
284
- return content ? [{ catalog, content }] : [];
285
- }
286
- /** Hands out unique NCName `id`s. */
287
- class IdAllocator {
288
- used;
289
- counters = new Map();
290
- constructor(reserved = []) {
291
- this.used = new Set(reserved);
292
- }
293
- take(base) {
294
- let id = base;
295
- for (let suffix = 2; this.used.has(id); suffix += 1)
296
- id = `${base}-${suffix}`;
297
- this.used.add(id);
298
- return id;
299
- }
300
- /** The next number in `base`'s sequence, from 1. */
301
- next(base) {
302
- const value = (this.counters.get(base) ?? 0) + 1;
303
- this.counters.set(base, value);
304
- return value;
305
- }
306
- }
307
- function supportsXml(cards, label) {
308
- const unwritten = [];
309
- const byCatalog = (...catalogs) => cards.filter((card) => catalogs.includes(card.catalog));
310
- const handled = new Set([
311
- SPOKEN,
312
- TTS_PRONUNCIATION,
313
- SPOKEN_TEXT,
314
- 'braille',
315
- 'tactile',
316
- TACTILE_BRAILLE_TEXT,
317
- SIGN_LANGUAGE,
318
- 'keyword-translation',
319
- 'linguistic-guidance',
320
- ]);
321
- unwritten.push(...cards.filter((card) => !handled.has(card.catalog)).map((card) => card.catalog));
322
- const xml = [];
323
- const spoken = spokenXml(byCatalog(SPOKEN, TTS_PRONUNCIATION, SPOKEN_TEXT), label);
324
- unwritten.push(...spoken.unwritten);
325
- if (spoken.xml)
326
- xml.push(spoken.xml);
327
- for (const card of byCatalog('braille')) {
328
- const text = card.content === undefined ? undefined : plainText(card.content);
329
- if (text)
330
- xml.push(`<apip:brailleText>${labelled('brailleTextString', label(), text)}</apip:brailleText>`);
331
- else
332
- unwritten.push(card.catalog);
333
- }
334
- const tactile = tactileXml(byCatalog('tactile', TACTILE_BRAILLE_TEXT), label);
335
- unwritten.push(...tactile.unwritten);
336
- if (tactile.xml)
337
- xml.push(tactile.xml);
338
- const signFiles = { signFileASL: [], signFileSignedEnglish: [] };
339
- for (const card of byCatalog(SIGN_LANGUAGE)) {
340
- const element = Object.keys(SIGN_FILE_LANGUAGES).find((name) => SIGN_FILE_LANGUAGES[name]?.toLowerCase() === card.language?.toLowerCase());
341
- const video = element && card.payload ? fileInfoXml('videoFileInfo', card.payload, label) : undefined;
342
- if (element && video)
343
- signFiles[element]?.push(`<apip:${element}>${video}</apip:${element}>`);
344
- else
345
- unwritten.push(card.catalog);
346
- }
347
- const signing = Object.values(signFiles).flat();
348
- if (signing.length > 0)
349
- xml.push(`<apip:signing>${signing.join('')}</apip:signing>`);
350
- const definitions = byCatalog('keyword-translation').flatMap((card) => {
351
- const text = card.content === undefined ? undefined : plainText(card.content);
352
- if (!text || !card.language) {
353
- unwritten.push(card.catalog);
354
- return [];
355
- }
356
- return [
357
- `<apip:definitionId xml:lang="${escapeAttribute(card.language)}">${labelled('textString', label(), text)}</apip:definitionId>`,
358
- ];
359
- });
360
- if (definitions.length > 0)
361
- xml.push(`<apip:keyWordTranslation>${definitions.join('')}</apip:keyWordTranslation>`);
362
- const [guidance, ...extraGuidance] = byCatalog('linguistic-guidance');
363
- const guidanceText = guidance?.content === undefined ? undefined : plainText(guidance.content);
364
- if (guidance && guidanceText) {
365
- xml.push(`<apip:guidance><apip:languageLearnerSupport><apip:supportOrder>1</apip:supportOrder>${labelled('textString', label(), guidanceText)}</apip:languageLearnerSupport></apip:guidance>`);
366
- }
367
- else if (guidance) {
368
- unwritten.push(guidance.catalog);
369
- }
370
- unwritten.push(...extraGuidance.map((card) => card.catalog));
371
- return { xml, unwritten, ssml: spoken.ssml };
372
- }
373
- /**
374
- * One `spoken`: its recordings, then its scripts. A `<speak>` card is the SSML script; the
375
- * `ext:custom-` cards take their own elements, and a plain-text `spoken` card the first of
376
- * `textToSpeechPronunciation` and `spokenText` they leave free.
377
- */
378
- function spokenXml(cards, label) {
379
- const unwritten = [];
380
- const audio = [];
381
- const slots = {};
382
- const plain = [];
383
- for (const card of cards) {
384
- if (card.payload) {
385
- const info = card.catalog === SPOKEN ? fileInfoXml('audioFileInfo', card.payload, label) : undefined;
386
- if (info)
387
- audio.push(info);
388
- else
389
- unwritten.push(card.catalog);
390
- continue;
391
- }
392
- const content = card.content ?? '';
393
- const ssml = card.catalog === SPOKEN && !slots.ssml ? ssmlScript(content) : undefined;
394
- const text = plainText(content);
395
- if (ssml)
396
- slots.ssml = ssml;
397
- else if (card.catalog === TTS_PRONUNCIATION && !slots.tts && text)
398
- slots.tts = text;
399
- else if (card.catalog === SPOKEN_TEXT && !slots.text && text)
400
- slots.text = text;
401
- else if (card.catalog === SPOKEN && text)
402
- plain.push(card);
403
- else
404
- unwritten.push(card.catalog);
405
- }
406
- for (const card of plain) {
407
- const text = plainText(card.content ?? '');
408
- if (!slots.tts)
409
- slots.tts = text;
410
- else if (!slots.text)
411
- slots.text = text;
412
- else
413
- unwritten.push(card.catalog);
414
- }
415
- const scripts = [
416
- slots.text && labelled('spokenText', label(), slots.text),
417
- slots.tts && labelled('textToSpeechPronunciation', label(), slots.tts),
418
- slots.ssml &&
419
- `<apip:textToSpeechPronunciationSSML>${slots.ssml}</apip:textToSpeechPronunciationSSML>`,
420
- ].filter(Boolean);
421
- if (audio.length === 0 && scripts.length === 0)
422
- return { unwritten, ssml: false };
423
- return {
424
- xml: `<apip:spoken>${audio.join('')}${scripts.join('')}</apip:spoken>`,
425
- unwritten,
426
- ssml: Boolean(slots.ssml),
427
- };
428
- }
429
- /** One `tactileFile`: it needs the `tactile` text, so the cards beside it go unwritten without one. */
430
- function tactileXml(cards, label) {
431
- const unwritten = [];
432
- let text;
433
- let audio;
434
- let braille;
435
- for (const card of cards) {
436
- const value = card.content === undefined ? undefined : plainText(card.content);
437
- if (card.catalog === TACTILE_BRAILLE_TEXT && value && !braille)
438
- braille = value;
439
- else if (card.catalog === 'tactile' && card.payload && !audio) {
440
- audio = fileInfoXml('tactileAudioFile', card.payload, label);
441
- if (!audio)
442
- unwritten.push(card.catalog);
443
- }
444
- else if (card.catalog === 'tactile' && value && !text)
445
- text = value;
446
- else
447
- unwritten.push(card.catalog);
448
- }
449
- if (!text)
450
- return { unwritten: cards.map((card) => card.catalog) };
451
- return {
452
- xml: `<apip:tactileFile>${audio ?? ''}${labelled('tactileAudioText', label(), text)}` +
453
- `${braille ? labelled('tactileBrailleText', label(), braille) : ''}</apip:tactileFile>`,
454
- unwritten,
455
- };
456
- }
457
- /** An `audioFileInfo` or `videoFileInfo` for a payload's first source whose MIME type is known. */
458
- function fileInfoXml(name, payload, label) {
459
- const video = name === 'videoFileInfo';
460
- const source = payload.media.sources
461
- .map((candidate) => ({ ...candidate, mimeType: mediaMimeType(candidate) }))
462
- .find((candidate) => candidate.src && candidate.mimeType);
463
- if (!source)
464
- return undefined;
465
- const { fragment } = payload;
466
- let times = '';
467
- if (fragment && video) {
468
- times =
469
- `<apip:startCue>${xsTime(fragment.startSeconds)}</apip:startCue>` +
470
- (fragment.endSeconds === undefined ? '' : `<apip:endCue>${xsTime(fragment.endSeconds)}</apip:endCue>`);
471
- }
472
- else if (fragment) {
473
- times =
474
- `<apip:startTime>${xsTime(fragment.startSeconds)}</apip:startTime>` +
475
- (fragment.endSeconds === undefined
476
- ? ''
477
- : `<apip:duration>${xsTime(fragment.endSeconds - fragment.startSeconds)}</apip:duration>`);
478
- }
479
- return (`<apip:${name} contentLinkIdentifier="${escapeAttribute(label())}" mimeType="${escapeAttribute(source.mimeType)}">` +
480
- `<apip:fileHref>${escapeText(source.src)}</apip:fileHref>${times}</apip:${name}>`);
481
- }
482
- /** Seconds as an `xs:time`, to the millisecond. */
483
- function xsTime(seconds) {
484
- const total = Math.max(0, Math.round(seconds * 1000));
485
- const pad = (value) => String(value).padStart(2, '0');
486
- const fraction = total % 1000;
487
- const clock = `${pad(Math.floor(total / 3_600_000))}:${pad(Math.floor(total / 60_000) % 60)}:${pad(Math.floor(total / 1000) % 60)}`;
488
- return fraction === 0 ? clock : `${clock}.${String(fraction).padStart(3, '0').replace(/0+$/, '')}`;
489
- }
490
- function contentLinkXml(link) {
491
- if (!link.target)
492
- return undefined;
493
- const { range } = link;
494
- let body;
495
- if (link.object) {
496
- body = '<apip:objectLink/>';
497
- }
498
- else if (!range) {
499
- body = '<apip:textLink><apip:fullString/></apip:textLink>';
500
- }
501
- else if (!Number.isInteger(range.start) || !Number.isInteger(range.stop)) {
502
- return undefined;
503
- }
504
- else if (range.unit === 'character' && range.start !== range.stop) {
505
- body = `<apip:textLink><apip:characterStringLink><apip:startCharacter>${range.start}</apip:startCharacter><apip:stopCharacter>${range.stop}</apip:stopCharacter></apip:characterStringLink></apip:textLink>`;
506
- }
507
- else if (range.start === range.stop) {
508
- const element = range.unit === 'word' ? 'wordLink' : 'characterLink';
509
- body = `<apip:textLink><apip:${element}>${range.start}</apip:${element}></apip:textLink>`;
510
- }
511
- else {
512
- // APIP links one word, never a run of them.
513
- return undefined;
514
- }
515
- return `<apip:contentLinkInfo qtiLinkIdentifierRef="${escapeAttribute(link.target)}">${body}</apip:contentLinkInfo>`;
516
- }
517
- /** A `<speak>` card's content as APIP SSML, prefixed, or `undefined` when it is not SSML. */
518
- function ssmlScript(content) {
519
- if (!/^\s*<(?:[\w.-]+:)?speak[\s>/]/.test(content))
520
- return undefined;
521
- const root = parse(content, { lowerCaseTagName: false, comment: false });
522
- const speak = allChildElements(root).find((element) => localName(element) === 'speak');
523
- const script = speak ? speak.childNodes.map(ssmlNode).join('').trim() : '';
524
- return script || undefined;
525
- }
526
- function ssmlNode(node) {
527
- if (node instanceof TextNode)
528
- return escapeText(node.text);
529
- if (node.nodeType !== NodeType.ELEMENT_NODE)
530
- return '';
531
- const element = node;
532
- const children = element.childNodes.map(ssmlNode).join('');
533
- const name = localName(element);
534
- if (!APIP_SSML_ELEMENTS.has(name))
535
- return children;
536
- const attributes = Object.entries(element.attributes)
537
- .filter(([attribute]) => attribute !== 'xmlns' && !attribute.startsWith('xmlns:'))
538
- .map(([attribute, value]) => ` ${attribute}="${escapeAttribute(value)}"`)
539
- .join('');
540
- return children ? `<ssml:${name}${attributes}>${children}</ssml:${name}>` : `<ssml:${name}${attributes}/>`;
541
- }
542
- /** Card content as the text a plain-text APIP element holds. */
543
- function plainText(content) {
544
- return parse(content).textContent.trim();
545
- }
546
- function labelled(name, identifier, text) {
547
- return `<apip:${name} contentLinkIdentifier="${escapeAttribute(identifier)}">${escapeText(text)}</apip:${name}>`;
548
- }
549
- /** `value` as an `xs:ID`: characters an NCName cannot hold become `-`, and a leading non-letter gains `_`. */
550
- function ncName(value) {
551
- const name = value.trim().replace(/[^\w.-]/g, '-');
552
- return /^[A-Za-z_]/.test(name) ? name : `_${name}`;
553
- }
554
- // ---------------------------------------------------------------------------
555
- // Shared
556
- // ---------------------------------------------------------------------------
557
- function escapeText(text) {
558
- return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
559
- }
560
- function escapeAttribute(value) {
561
- return escapeText(value).replace(/"/g, '&quot;');
562
- }
563
- function childElements(parent, name) {
564
- return allChildElements(parent).filter((child) => localName(child) === name);
565
- }
566
- function allChildElements(parent) {
567
- return parent.childNodes.filter((child) => child.nodeType === NodeType.ELEMENT_NODE);
568
- }
569
- function firstChild(parent, name) {
570
- return childElements(parent, name)[0];
571
- }
572
- function localName(element) {
573
- const raw = element.rawTagName ?? '';
574
- return raw.slice(raw.indexOf(':') + 1);
575
- }
576
- //# sourceMappingURL=apip.js.map