@readium/guided-navigation 1.1.3 → 1.2.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 (126) hide show
  1. package/README.md +1 -1
  2. package/dist/a11y.js +1 -1
  3. package/dist/converter.js +1 -1
  4. package/dist/elementHandlers.js +1 -1
  5. package/dist/emptyPairs.js +1 -0
  6. package/dist/object.js +1 -1
  7. package/dist/prescan.js +1 -1
  8. package/dist/roles.js +1 -1
  9. package/dist/text.js +1 -1
  10. package/dist/textrefFragment.js +1 -1
  11. package/fixtures/ROLES_COVERAGE.md +5 -4
  12. package/fixtures/abbreviation-acronym-html-native/gnd.json +9 -0
  13. package/fixtures/abbreviation-acronym-html-native/input.html +1 -0
  14. package/fixtures/abbreviation-acronym-html-native/meta.json +11 -0
  15. package/fixtures/abbreviation-before-formatting/gnd.json +9 -0
  16. package/fixtures/abbreviation-before-formatting/input.html +1 -0
  17. package/fixtures/abbreviation-before-formatting/meta.json +11 -0
  18. package/fixtures/abbreviation-before-image/gnd.json +24 -0
  19. package/fixtures/abbreviation-before-image/input.html +1 -0
  20. package/fixtures/abbreviation-before-image/meta.json +12 -0
  21. package/fixtures/abbreviation-html-native/gnd.json +9 -0
  22. package/fixtures/abbreviation-html-native/input.html +1 -0
  23. package/fixtures/abbreviation-html-native/meta.json +11 -0
  24. package/fixtures/abbreviation-language/gnd.json +9 -0
  25. package/fixtures/abbreviation-language/input.html +1 -0
  26. package/fixtures/abbreviation-language/meta.json +11 -0
  27. package/fixtures/abbreviation-line-break/gnd.json +9 -0
  28. package/fixtures/abbreviation-line-break/input.html +1 -0
  29. package/fixtures/abbreviation-line-break/meta.json +11 -0
  30. package/fixtures/abbreviation-nested/gnd.json +9 -0
  31. package/fixtures/abbreviation-nested/input.html +1 -0
  32. package/fixtures/abbreviation-nested/meta.json +11 -0
  33. package/fixtures/abbreviation-nested-emphasis/gnd.json +9 -0
  34. package/fixtures/abbreviation-nested-emphasis/input.html +1 -0
  35. package/fixtures/abbreviation-nested-emphasis/meta.json +11 -0
  36. package/fixtures/abbreviation-nested-term/gnd.json +21 -0
  37. package/fixtures/abbreviation-nested-term/input.html +1 -0
  38. package/fixtures/abbreviation-nested-term/meta.json +12 -0
  39. package/fixtures/abbreviation-nested-term-punctuation/gnd.json +26 -0
  40. package/fixtures/abbreviation-nested-term-punctuation/input.html +1 -0
  41. package/fixtures/abbreviation-nested-term-punctuation/meta.json +12 -0
  42. package/fixtures/abbreviation-no-title/gnd.json +8 -0
  43. package/fixtures/abbreviation-no-title/input.html +1 -0
  44. package/fixtures/abbreviation-no-title/meta.json +11 -0
  45. package/fixtures/abbreviation-spanning-terms/gnd.json +33 -0
  46. package/fixtures/abbreviation-spanning-terms/input.html +1 -0
  47. package/fixtures/abbreviation-spanning-terms/meta.json +12 -0
  48. package/fixtures/abbreviation-with-image/gnd.json +24 -0
  49. package/fixtures/abbreviation-with-image/input.html +1 -0
  50. package/fixtures/abbreviation-with-image/meta.json +12 -0
  51. package/fixtures/abbreviation-with-svg-and-math/gnd.json +39 -0
  52. package/fixtures/abbreviation-with-svg-and-math/input.html +1 -0
  53. package/fixtures/abbreviation-with-svg-and-math/meta.json +13 -0
  54. package/fixtures/biblioref-target-descendant-ids/gnd.json +90 -0
  55. package/fixtures/biblioref-target-descendant-ids/input.html +1 -0
  56. package/fixtures/biblioref-target-descendant-ids/meta.json +14 -0
  57. package/fixtures/biblioref-target-in-bibliography-role-aria/gnd.json +59 -0
  58. package/fixtures/biblioref-target-in-bibliography-role-aria/input.html +6 -0
  59. package/fixtures/biblioref-target-in-bibliography-role-aria/meta.json +14 -0
  60. package/fixtures/biblioref-target-mixed-content/gnd.json +63 -0
  61. package/fixtures/biblioref-target-mixed-content/input.html +1 -0
  62. package/fixtures/biblioref-target-mixed-content/meta.json +11 -0
  63. package/fixtures/glossref-target-in-glossary-role-aria/gnd.json +76 -0
  64. package/fixtures/glossref-target-in-glossary-role-aria/input.html +5 -0
  65. package/fixtures/glossref-target-in-glossary-role-aria/meta.json +14 -0
  66. package/fixtures/glossref-target-percent-encoded/gnd.json +68 -0
  67. package/fixtures/glossref-target-percent-encoded/input.html +1 -0
  68. package/fixtures/glossref-target-percent-encoded/meta.json +14 -0
  69. package/fixtures/manifest.json +330 -0
  70. package/fixtures/noteref-after-closing-straight-quote/gnd.json +32 -0
  71. package/fixtures/noteref-after-closing-straight-quote/input.html +1 -0
  72. package/fixtures/noteref-after-closing-straight-quote/meta.json +13 -0
  73. package/fixtures/noteref-after-closing-straight-quote-split/gnd.json +38 -0
  74. package/fixtures/noteref-after-closing-straight-quote-split/input.html +1 -0
  75. package/fixtures/noteref-after-closing-straight-quote-split/meta.json +12 -0
  76. package/fixtures/noteref-enclosed-across-formatting/gnd.json +32 -0
  77. package/fixtures/noteref-enclosed-across-formatting/input.html +1 -0
  78. package/fixtures/noteref-enclosed-across-formatting/meta.json +13 -0
  79. package/fixtures/noteref-enclosed-adjacent-pairs/gnd.json +108 -0
  80. package/fixtures/noteref-enclosed-adjacent-pairs/input.html +1 -0
  81. package/fixtures/noteref-enclosed-adjacent-pairs/meta.json +13 -0
  82. package/fixtures/noteref-enclosed-adjacent-text/gnd.json +34 -0
  83. package/fixtures/noteref-enclosed-adjacent-text/input.html +1 -0
  84. package/fixtures/noteref-enclosed-adjacent-text/meta.json +13 -0
  85. package/fixtures/noteref-enclosed-before-formatting/gnd.json +34 -0
  86. package/fixtures/noteref-enclosed-before-formatting/input.html +1 -0
  87. package/fixtures/noteref-enclosed-before-formatting/meta.json +13 -0
  88. package/fixtures/noteref-enclosed-guillemets-french/gnd.json +103 -0
  89. package/fixtures/noteref-enclosed-guillemets-french/input.html +1 -0
  90. package/fixtures/noteref-enclosed-guillemets-french/meta.json +13 -0
  91. package/fixtures/noteref-enclosed-quotes-chinese/gnd.json +47 -0
  92. package/fixtures/noteref-enclosed-quotes-chinese/input.html +1 -0
  93. package/fixtures/noteref-enclosed-quotes-chinese/meta.json +13 -0
  94. package/fixtures/noteref-enclosed-quotes-german/gnd.json +124 -0
  95. package/fixtures/noteref-enclosed-quotes-german/input.html +1 -0
  96. package/fixtures/noteref-enclosed-quotes-german/meta.json +13 -0
  97. package/fixtures/noteref-enclosed-quotes-swedish/gnd.json +70 -0
  98. package/fixtures/noteref-enclosed-quotes-swedish/input.html +1 -0
  99. package/fixtures/noteref-enclosed-quotes-swedish/meta.json +13 -0
  100. package/fixtures/noteref-enclosed-straight-quotes/gnd.json +32 -0
  101. package/fixtures/noteref-enclosed-straight-quotes/input.html +1 -0
  102. package/fixtures/noteref-enclosed-straight-quotes/meta.json +13 -0
  103. package/fixtures/noteref-in-lone-block/gnd.json +29 -0
  104. package/fixtures/noteref-in-lone-block/input.html +1 -0
  105. package/fixtures/noteref-in-lone-block/meta.json +12 -0
  106. package/fixtures/noteref-target-malformed-escape/gnd.json +32 -0
  107. package/fixtures/noteref-target-malformed-escape/input.html +1 -0
  108. package/fixtures/noteref-target-malformed-escape/meta.json +13 -0
  109. package/fixtures/noteref-target-percent-encoded/gnd.json +32 -0
  110. package/fixtures/noteref-target-percent-encoded/input.html +1 -0
  111. package/fixtures/noteref-target-percent-encoded/meta.json +13 -0
  112. package/package.json +1 -1
  113. package/src/a11y.ts +4 -4
  114. package/src/converter.ts +112 -25
  115. package/src/elementHandlers.ts +64 -11
  116. package/src/emptyPairs.ts +74 -0
  117. package/src/object.ts +4 -0
  118. package/src/prescan.ts +2 -1
  119. package/src/roles.ts +2 -0
  120. package/src/text.ts +3 -1
  121. package/src/textrefFragment.ts +9 -1
  122. package/types/src/converter.d.ts +4 -0
  123. package/types/src/elementHandlers.d.ts +1 -0
  124. package/types/src/emptyPairs.d.ts +3 -0
  125. package/types/src/text.d.ts +1 -0
  126. package/types/src/textrefFragment.d.ts +4 -0
@@ -0,0 +1,13 @@
1
+ {
2
+ "id": "noteref-target-percent-encoded",
3
+ "description": "A noteref whose href is percent-encoded still finds and embeds its footnote, which isn't output again at its own location",
4
+ "role": "noteref",
5
+ "rolesCovered": [
6
+ "noteref",
7
+ "footnote",
8
+ "aside",
9
+ "paragraph"
10
+ ],
11
+ "sourceRef": "https://github.com/readium/guided-navigation/blob/main/roles.md",
12
+ "inputKind": "fragment"
13
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@readium/guided-navigation",
3
- "version": "1.1.3",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "description": "Guided Navigation document generation from HTML and XHTML content",
6
6
  "author": "readium",
package/src/a11y.ts CHANGED
@@ -93,7 +93,7 @@ export function extractNodeAria(el: Element): [string | null, boolean, string] {
93
93
  }
94
94
 
95
95
  // 2.C
96
- const label = (el.getAttribute("aria-label") ?? "").trim();
96
+ const label = normalizeWhitespace(el.getAttribute("aria-label") ?? "", true).trim();
97
97
  if (label) {
98
98
  return [label, true, nodeLanguage(el)];
99
99
  }
@@ -121,10 +121,10 @@ export function extractNodeAria(el: Element): [string | null, boolean, string] {
121
121
  // 2.D (partial support)
122
122
  const tagName = el.tagName.toLowerCase();
123
123
  if (tagName === "img") {
124
- const alt = (el.getAttribute("alt") ?? "").trim();
124
+ const alt = normalizeWhitespace(el.getAttribute("alt") ?? "", true).trim();
125
125
  if (alt) return [alt, true, nodeLanguage(el)];
126
126
  // 2.I fallback for images: the title attribute
127
- const title = (el.getAttribute("title") ?? "").trim();
127
+ const title = normalizeWhitespace(el.getAttribute("title") ?? "", true).trim();
128
128
  if (title) return [title, true, nodeLanguage(el)];
129
129
  } else if (tagName === "svg") {
130
130
  // The accessible name of an SVG comes from its <title> child
@@ -135,7 +135,7 @@ export function extractNodeAria(el: Element): [string | null, boolean, string] {
135
135
  }
136
136
  } else if (tagName === "math") {
137
137
  // MathML Core's spoken-form fallback (not part of the ARIA AccName algorithm)
138
- const alttext = (el.getAttribute("alttext") ?? "").trim();
138
+ const alttext = normalizeWhitespace(el.getAttribute("alttext") ?? "", true).trim();
139
139
  if (alttext) return [alttext, true, nodeLanguage(el)];
140
140
  }
141
141
 
package/src/converter.ts CHANGED
@@ -14,9 +14,9 @@ import {
14
14
  ctxEqual,
15
15
  normalizeWhitespace,
16
16
  } from "./text.ts";
17
- import { ssmlAttrEscape, ssmlTextEscape, startsWithBindingPunct } from "@readium/helpers";
17
+ import { ssmlAttrEscape, ssmlTextEscape } from "@readium/helpers";
18
18
  import { type ObjBuilder, NavObject, isEmptyObj, finalizeToGuidedNavigationObject, setDescription } from "./object.ts";
19
- import { type GndMediaType, isInlineTag, sniffMediaType } from "./dom.ts";
19
+ import { type GndMediaType, isAncestorOf, isInlineTag, sniffMediaType } from "./dom.ts";
20
20
  import { declaredLanguage, nodeLanguage, sameLanguage } from "./language.ts";
21
21
  import { encodeDomRangeFragment, encodeTextFragmentDirective } from "./textrefFragment.ts";
22
22
  import { resolveRefs } from "./href.ts";
@@ -26,7 +26,8 @@ import { textFragmentDirectiveFor } from "./textFragmentGenerator.ts";
26
26
  import { type GndGenerationOptions, normalizeTextrefOptions } from "./options.ts";
27
27
  import { IdAllocator } from "./idAllocator.ts";
28
28
  import { prescan as prescanImpl } from "./prescan.ts";
29
- import { pagebreak, noteref, link } from "./elementHandlers.ts";
29
+ import { pagebreak, noteref, reference, link } from "./elementHandlers.ts";
30
+ import { DROPPED, bindsToPrevious, removeDropped } from "./emptyPairs.ts";
30
31
 
31
32
  const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
32
33
 
@@ -79,6 +80,8 @@ export class Converter {
79
80
  selectorRoot: Element | null = null;
80
81
  // Prefixed onto every generated selector — see selectorGenerator.ts's rootAnchorSelector().
81
82
  selectorRootAnchor: string | null = null;
83
+ // Converting a copy of content also output at its own location, which keeps its elements' ids.
84
+ copy = false;
82
85
 
83
86
  private root = new NavObject();
84
87
  private current = this.root;
@@ -129,6 +132,7 @@ export class Converter {
129
132
  child.domRangeEnabled = this.domRangeEnabled;
130
133
  child.textFragmentEnabled = this.textFragmentEnabled;
131
134
  child.leafTextEnabled = this.leafTextEnabled;
135
+ child.copy = this.copy;
132
136
  return child;
133
137
  }
134
138
 
@@ -156,7 +160,8 @@ export class Converter {
156
160
 
157
161
  resultBuilders(): ObjBuilder[] {
158
162
  const res = this.root.finalize((el) => textrefForSelector(selectorForElement(el, this.selectorRoot, this.selectorRootAnchor), el));
159
- if (!res.children || res.children.length === 0) {
163
+ // Text of its own, from a flow hoisted onto it, makes the root content too, not just a container.
164
+ if (!res.children || res.children.length === 0 || res.text) {
160
165
  if (isEmptyObj(res)) return [];
161
166
  return [res];
162
167
  }
@@ -224,7 +229,8 @@ export class Converter {
224
229
  }
225
230
 
226
231
  if (tagName === "br") {
227
- if (!this.current.noText) {
232
+ // Within an abbreviation's expansion, a line break is only visual.
233
+ if (!this.current.noText && !this.textContext(el).abbr) {
228
234
  this.closeSegment();
229
235
  this.segments.push({ kind: "break" });
230
236
  this.flowEndsWithSpace = true;
@@ -239,8 +245,12 @@ export class Converter {
239
245
  noteref(this, el, roles);
240
246
  return true;
241
247
  }
248
+ if (tagName === "a" && (roles.includes("glossref") || roles.includes("biblioref")) && el.getAttribute("href")) {
249
+ reference(this, el, roles, aria, ariaLanguage);
250
+ return true;
251
+ }
242
252
  if (tagName === "a" && el.getAttribute("href")) {
243
- // Any other link — backlink/biblioref/glossref, or a plain navigational
253
+ // Any other link — a backlink, or a plain navigational
244
254
  // link with no specific role (e.g. a TOC entry) — carries its href as
245
255
  // textref. When it's the sole content of its enclosing block (the usual
246
256
  // case for list items), the hoist rule promotes it onto that block;
@@ -423,6 +433,20 @@ export class Converter {
423
433
  }
424
434
 
425
435
  private textContext(node: Node): SSMLContext {
436
+ // An abbreviation's text is replaced by its expansion as a whole, so it wins over any formatting inside it.
437
+ // It applies only if all its text is in one object, so its alias is never repeated or misplaced.
438
+ // The outermost one wins, its expansion covering any nested inside it.
439
+ let abbr: SSMLContext | undefined;
440
+ for (let p = node.parentElement, enclosing = false; p; p = p.parentElement) {
441
+ const alias = abbreviationExpansion(p);
442
+ if (alias) {
443
+ if (!enclosing && Converter.containsObject(p)) break;
444
+ abbr = { lang: declaredLanguage(p), tag: "sub", attrs: { alias }, abbr: p };
445
+ }
446
+ if (p === this.current.el) enclosing = true;
447
+ if (enclosing && !Converter.isSoleContent(p)) break;
448
+ }
449
+ if (abbr) return abbr;
426
450
  const ctx: SSMLContext = { lang: declaredLanguage(node.parentElement), tag: "" };
427
451
  for (let p = node.parentElement; p && p !== this.current.el; p = p.parentElement) {
428
452
  const [tag, attrs] = convertElementToSSMLTag(p.tagName.toLowerCase());
@@ -435,6 +459,30 @@ export class Converter {
435
459
  return ctx;
436
460
  }
437
461
 
462
+ private static containsObject(el: Element): boolean {
463
+ for (let c = el.firstElementChild; c; c = c.nextElementSibling) {
464
+ const tagName = c.tagName.toLowerCase();
465
+ const roles = extractNodeRoles(c);
466
+ if (skippedElements.has(tagName) || Converter.isPlaceholder(c, tagName, roles)) continue;
467
+ if (isBlockNode(tagName, roles) || Converter.containsObject(c)) return true;
468
+ }
469
+ return false;
470
+ }
471
+
472
+ // What head() embeds as a placeholder in the flow, rather than descending into.
473
+ private static isPlaceholder(el: Element, tagName: string, roles: GndRole[]): boolean {
474
+ if (roles.includes("pagebreak") || roles.includes("image") || roles.includes("math")) return true;
475
+ return ["img", "svg", "audio", "video"].includes(tagName) || (tagName === "a" && !!el.getAttribute("href"));
476
+ }
477
+
478
+ // Punctuation alongside doesn't count, e.g. the last period of <abbr><dfn>W.H.O</dfn>.</abbr>.
479
+ private static isSoleContent(el: Element): boolean {
480
+ for (let s = el.parentNode?.firstChild; s; s = s.nextSibling) {
481
+ if (s !== el && (s.nodeType === ELEMENT_NODE || (s.nodeType === TEXT_NODE && !/^[\s\p{P}]*$/u.test(s.nodeValue ?? "")))) return false;
482
+ }
483
+ return true;
484
+ }
485
+
438
486
  private updateFlowSpace() {
439
487
  if (this.textAcc.length > 0) {
440
488
  this.flowEndsWithSpace = this.textAcc.endsWith(" ");
@@ -527,6 +575,34 @@ export class Converter {
527
575
  break;
528
576
  }
529
577
 
578
+ // An abbreviation's expansion is spoken once, so its pieces become one segment, followed by any object within it.
579
+ const merged: Segment[] = [];
580
+ for (let i = 0; i < segments.length; i++) {
581
+ const seg = segments[i];
582
+ const abbr = seg.kind === "text" ? seg.ctx!.abbr : undefined;
583
+ if (!abbr) {
584
+ merged.push(seg);
585
+ continue;
586
+ }
587
+ let text = seg.text!;
588
+ const within: Segment[] = [];
589
+ let pending: Segment[] = [];
590
+ for (let j = i + 1; j < segments.length; j++) {
591
+ const next = segments[j];
592
+ if (next.kind === "placeholder" && isAncestorOf(abbr, next.child!.el!)) {
593
+ pending.push(next);
594
+ continue;
595
+ }
596
+ if (next.kind !== "text" || next.ctx!.abbr !== abbr) break;
597
+ text += next.text!;
598
+ within.push(...pending);
599
+ pending = [];
600
+ i = j;
601
+ }
602
+ merged.push({ ...seg, text }, ...within);
603
+ }
604
+ segments = merged;
605
+
530
606
  const hasText = segments.some((s) => s.kind === "text" && s.text!.trim() !== "");
531
607
  if (!hasText) {
532
608
  for (const child of pending) this.appendChild(child);
@@ -565,7 +641,7 @@ export class Converter {
565
641
  if (needSSML) {
566
642
  for (const seg of segments) {
567
643
  if (seg.kind !== "placeholder") continue;
568
- let id = seg.candidateID;
644
+ let id = this.copy ? undefined : seg.candidateID;
569
645
  if (!id || !this.idAlloc.claim(id)) {
570
646
  id = this.idAlloc.allocate(seg.tag!, (candidate) => this.ids.has(candidate));
571
647
  }
@@ -590,7 +666,7 @@ export class Converter {
590
666
  if (plainB.length > 0) {
591
667
  const spaced = prevTrail || midSpace || lead;
592
668
  if (sawBreak) join = true;
593
- else if (sawPlaceholder) join = spaced && !startsWithBindingPunct(t);
669
+ else if (sawPlaceholder) join = spaced && !bindsToPrevious(t, baseLang);
594
670
  else join = spaced;
595
671
  }
596
672
  if (join) plainB += " ";
@@ -602,9 +678,11 @@ export class Converter {
602
678
  } else if (seg.kind === "break") {
603
679
  sawBreak = true;
604
680
  } else if (seg.kind === "placeholder") {
681
+ plainB += DROPPED;
605
682
  sawPlaceholder = true;
606
683
  }
607
684
  }
685
+ plainB = removeDropped(plainB, baseLang);
608
686
 
609
687
  // Plain text is only worth keeping alongside SSML when it diverges from
610
688
  // what stripping tags from the SSML would produce — i.e. when a
@@ -623,26 +701,24 @@ export class Converter {
623
701
  let sb = "";
624
702
  for (const seg of segments) {
625
703
  if (seg.kind === "text") {
626
- let tag = seg.ctx!.tag;
627
- let attrs = seg.ctx!.attrs;
628
- if (shiftsLanguage(seg.ctx!.lang)) {
629
- // A language shift takes priority over whatever SSML tag the
630
- // shifting element would otherwise map to.
631
- tag = "lang";
632
- attrs = undefined;
704
+ const { tag, attrs, lang } = seg.ctx!;
705
+ // A `sub` replaces all of its text, so spaces at its edges stay outside it to keep separating words.
706
+ const edges = tag === "sub" ? /^( *)([^]*?)( *)$/.exec(seg.text!)! : null;
707
+ const segText = edges ? edges[2] : seg.text!;
708
+ // A `sub` around only whitespace would speak its expansion a second time.
709
+ if (edges && segText === "") {
710
+ sb += seg.text!;
711
+ continue;
633
712
  }
634
- if (tag) {
635
- sb += `<${tag}`;
636
- for (const [k, v] of Object.entries(attrs ?? {})) {
637
- sb += ` ${k}="${ssmlAttrEscape(v)}"`;
638
- }
639
- if (shiftsLanguage(seg.ctx!.lang)) {
640
- sb += ` xml:lang="${ssmlAttrEscape(seg.ctx!.lang)}"`;
641
- }
642
- sb += `>${ssmlTextEscape(seg.text!)}</${tag}>`;
713
+ sb += edges?.[1] ?? "";
714
+ if (shiftsLanguage(lang)) {
715
+ // A language shift replaces the element's own tag, except `sub`, which can't carry xml:lang.
716
+ const inner = tag === "sub" ? ssmlElement(tag, attrs, segText) : ssmlTextEscape(segText);
717
+ sb += `<lang xml:lang="${ssmlAttrEscape(lang)}">${inner}</lang>`;
643
718
  } else {
644
- sb += ssmlTextEscape(seg.text!);
719
+ sb += tag ? ssmlElement(tag, attrs, segText) : ssmlTextEscape(segText);
645
720
  }
721
+ sb += edges?.[3] ?? "";
646
722
  } else if (seg.kind === "break") {
647
723
  sb += "<break/>";
648
724
  } else if (seg.kind === "placeholder") {
@@ -665,6 +741,17 @@ export class Converter {
665
741
  }
666
742
  }
667
743
 
744
+ // An abbreviation's expansion, "" when it has none.
745
+ function abbreviationExpansion(el: Element): string {
746
+ if (!extractNodeRoles(el).includes("abbreviation")) return "";
747
+ return normalizeWhitespace(el.getAttribute("title") ?? "", true).trim();
748
+ }
749
+
750
+ function ssmlElement(tag: string, attrs: Record<string, string> | undefined, text: string): string {
751
+ const attrString = Object.entries(attrs ?? {}).map(([k, v]) => ` ${k}="${ssmlAttrEscape(v)}"`).join("");
752
+ return `<${tag}${attrString}>${ssmlTextEscape(text)}</${tag}>`;
753
+ }
754
+
668
755
  // A DOM <body> only counts as real content when the input actually wrote
669
756
  // one — text/html parsing synthesizes a <body> around any fragment
670
757
  // regardless of what was passed in, and that synthesized wrapper was
@@ -1,21 +1,23 @@
1
1
  // Handlers for element kinds that build one placeholder ObjBuilder each
2
- // (pagebreak/noteref/link), calling back into the converter for
3
- // placeholder() and, for noteref's footnote embedding, convert()/resultBuilders()
2
+ // (pagebreak/noteref/reference/link), calling back into the converter for
3
+ // placeholder() and, for noteref's and reference's target embedding, convert()/resultBuilders()
4
4
  // on a sub-Converter of its own.
5
5
  import type { GndRole } from "./types.ts";
6
+ import { ssmlAttrEscape } from "@readium/helpers";
6
7
  import { normalizedNodeText } from "./a11y.ts";
7
- import { textIsEmpty } from "./text.ts";
8
+ import { normalizeWhitespace, textIsEmpty } from "./text.ts";
8
9
  import { type ObjBuilder, ariaSubstitutedBuilders, substitutedOwnSelectorBuilders } from "./object.ts";
9
10
  import { hasElementChild, isAncestorOf } from "./dom.ts";
10
11
  import { nodeLanguage } from "./language.ts";
11
12
  import { Converter } from "./converter.ts";
12
13
  import { selectorForElement, textrefForSelector } from "./selectorGenerator.ts";
14
+ import { decodeIdFragment, detachSelfTextref } from "./textrefFragment.ts";
13
15
 
14
16
  // Returns true if el's children should still be descended into (a
15
17
  // pagebreak with element children of its own, in HTML parsing).
16
18
  export function pagebreak(converter: Converter, el: Element, aria: string | null, ariaLanguage: string, roles: GndRole[]): boolean {
17
19
  const obj: ObjBuilder = { role: roles };
18
- const title = (el.getAttribute("title") ?? "").trim();
20
+ const title = normalizeWhitespace(el.getAttribute("title") ?? "", true).trim();
19
21
  if (title) {
20
22
  obj.text = { plain: title, ssml: "", language: nodeLanguage(el) };
21
23
  } else if (aria) {
@@ -41,15 +43,15 @@ export function noteref(converter: Converter, el: Element, roles: GndRole[]): vo
41
43
  if (text) obj.text = { plain: text, ssml: "", language };
42
44
 
43
45
  const href = el.getAttribute("href") ?? "";
46
+ const fragment = href.startsWith("#") ? (decodeIdFragment(href) ?? href.slice(1)) : undefined;
44
47
  let candidateID = el.getAttribute("id") ?? "";
45
- if (!candidateID && href.startsWith("#")) {
48
+ if (!candidateID && fragment !== undefined) {
46
49
  // A target still output at its own location keeps its id there.
47
- const target = converter.ids.get(href.slice(1));
48
- if (!target || converter.suppressed.has(target)) candidateID = href.slice(1);
50
+ const target = converter.ids.get(fragment);
51
+ if (!target || converter.suppressed.has(target)) candidateID = fragment;
49
52
  }
50
53
 
51
- if (href.startsWith("#")) {
52
- const fragment = href.slice(1);
54
+ if (fragment !== undefined) {
53
55
  const target = converter.ids.get(fragment);
54
56
  if (target && !isAncestorOf(target, el) && converter.noterefDepth < 3) {
55
57
  const sub = converter.spawnChild(target);
@@ -59,7 +61,7 @@ export function noteref(converter: Converter, el: Element, roles: GndRole[]): vo
59
61
  // The target's own id already carries its meaning via this
60
62
  // noteref's own id — repeating it on the embedded content would
61
63
  // be redundant.
62
- for (const c of children) delete c.id;
64
+ for (const c of children) removeId(c);
63
65
  obj.children = children;
64
66
  }
65
67
  }
@@ -72,6 +74,31 @@ export function noteref(converter: Converter, el: Element, roles: GndRole[]): vo
72
74
  }
73
75
 
74
76
  export function link(converter: Converter, el: Element, roles: GndRole[], aria: string | null, ariaLanguage: string): void {
77
+ converter.placeholder(el, roles[0] ?? "link", linkObject(converter, el, roles, aria, ariaLanguage));
78
+ }
79
+
80
+ // A glossref or biblioref: a link that also embeds its same-document target, like a noteref its footnote.
81
+ export function reference(converter: Converter, el: Element, roles: GndRole[], aria: string | null, ariaLanguage: string): void {
82
+ const obj = linkObject(converter, el, roles, aria, ariaLanguage);
83
+ const href = el.getAttribute("href") ?? "";
84
+ if (href.startsWith("#")) {
85
+ const target = converter.ids.get(decodeIdFragment(href) ?? href.slice(1));
86
+ if (target && !isAncestorOf(target, el) && converter.noterefDepth < 3) {
87
+ const children = referencedContent(target).flatMap((content) => {
88
+ const sub = converter.spawnChild(content);
89
+ sub.copy = true;
90
+ sub.convert(content);
91
+ return sub.resultBuilders();
92
+ });
93
+ // Still output at its own location, which keeps its ids.
94
+ removeCopiedIds(children);
95
+ if (children.length > 0) obj.children = children;
96
+ }
97
+ }
98
+ converter.placeholder(el, roles[0], obj);
99
+ }
100
+
101
+ function linkObject(converter: Converter, el: Element, roles: GndRole[], aria: string | null, ariaLanguage: string): ObjBuilder {
75
102
  const obj: ObjBuilder = {};
76
103
  if (roles.length > 0) obj.role = roles;
77
104
  if (aria) {
@@ -85,5 +112,31 @@ export function link(converter: Converter, el: Element, roles: GndRole[], aria:
85
112
  }
86
113
  const href = el.getAttribute("href");
87
114
  if (href) obj.textref = href;
88
- converter.placeholder(el, roles[0] ?? "link", obj);
115
+ return obj;
116
+ }
117
+
118
+ function removeId(obj: ObjBuilder) {
119
+ const id = obj.id;
120
+ if (id === undefined) return;
121
+ delete obj.id;
122
+ detachSelfTextref(obj, id);
123
+ }
124
+
125
+ // Removes the ids a copy repeats from its original, keeping placeholders', allocated unique and referenced by their parent's SSML.
126
+ function removeCopiedIds(objs: ObjBuilder[], parent?: ObjBuilder) {
127
+ for (const obj of objs) {
128
+ if (obj.id === undefined || !parent?.text?.ssml.includes(`id="${ssmlAttrEscape(obj.id)}"`)) removeId(obj);
129
+ if (obj.children) removeCopiedIds(obj.children, obj);
130
+ }
131
+ }
132
+
133
+ // A glossary term and its definitions, else the target itself.
134
+ function referencedContent(target: Element): Element[] {
135
+ const term = target.tagName.toLowerCase() === "dt" ? target : target.closest("dt");
136
+ if (!term) return [target];
137
+ let n = term.nextElementSibling;
138
+ while (n && n.tagName.toLowerCase() === "dt") n = n.nextElementSibling;
139
+ const definitions: Element[] = [];
140
+ for (; n && n.tagName.toLowerCase() === "dd"; n = n.nextElementSibling) definitions.push(n);
141
+ return definitions.length > 0 ? [term, ...definitions] : [target];
89
142
  }
@@ -0,0 +1,74 @@
1
+ // Brackets and quotes left empty in plain text by the objects it drops, e.g. "1870s (◆) along".
2
+ import { startsWithBindingPunct } from "@readium/helpers";
3
+
4
+ // Stands in plain text for a dropped object, until removeDropped() takes it out.
5
+ export const DROPPED = "\u0000";
6
+
7
+ // Opening and closing marks, two characters per pair.
8
+ const BRACKET_PAIRS = "()[]{}()[]{}「」『』【】〔〕〈〉《》";
9
+ const STRAIGHT_QUOTE_PAIRS = "\"\"''";
10
+ // From CLDR's delimiters, plus guillemets: »…« in German and Danish books, «…» in Swiss German, »…» in Swedish and Finnish.
11
+ const QUOTE_PAIRS: Record<string, string> = {
12
+ ar: "”“’‘", bg: "„“", cs: "„“‚‘", da: "“”‘’»«›‹", de: "„“‚‘»«›‹«»‹›", el: "«»“”", en: "“”‘’", es: "“”‘’", et: "„“‚‘",
13
+ fi: "””’’»»››", fr: "«»", he: "””’’", hr: "„“‚‘", hu: "„”»«", hy: "«»", is: "„“‚‘", it: "«»“”", ja: "「」『』",
14
+ ka: "„“«»", ko: "“”‘’", lt: "„“", lv: "“”‘’", nb: "«»‘’", nl: "‘’", pl: "„”«»", pt: "“”‘’", ro: "„”«»", ru: "«»„“",
15
+ sk: "„“‚‘", sl: "„“‚‘", sr: "„”’’", sv: "””’’»»››", tr: "“”‘’", uk: "«»„“", zh: "“”‘’", "zh-hant": "「」『』",
16
+ };
17
+ // What may sit between a pair's marks and still leave it empty.
18
+ const FILLER = /[\s​-‍⁠,;、,\u0000]/;
19
+
20
+ interface Marks {
21
+ pairs: Set<string>;
22
+ opening: Set<string>;
23
+ closing: Set<string>;
24
+ }
25
+
26
+ const marksByLanguage = new Map<string, Marks>();
27
+
28
+ function marksFor(lang: string | undefined): Marks {
29
+ const tag = lang?.toLowerCase() ?? "";
30
+ let marks = marksByLanguage.get(tag);
31
+ if (marks) return marks;
32
+ const chars = BRACKET_PAIRS + STRAIGHT_QUOTE_PAIRS + (QUOTE_PAIRS[tag] ?? QUOTE_PAIRS[tag.split("-")[0]] ?? QUOTE_PAIRS.en);
33
+ marks = { pairs: new Set(), opening: new Set(), closing: new Set() };
34
+ for (let i = 0; i < chars.length; i += 2) {
35
+ marks.pairs.add(chars[i] + chars[i + 1]);
36
+ marks.opening.add(chars[i]);
37
+ marks.closing.add(chars[i + 1]);
38
+ }
39
+ marksByLanguage.set(tag, marks);
40
+ return marks;
41
+ }
42
+
43
+ // Whether text starts with punctuation attaching to what precedes it, unlike a quote it opens, e.g. German »Welt«.
44
+ // French spaces its closing guillemet and high punctuation instead.
45
+ export function bindsToPrevious(text: string, lang: string | undefined): boolean {
46
+ if (!startsWithBindingPunct(text)) return false;
47
+ if (lang?.toLowerCase().split("-")[0] === "fr" && "»;:!?".includes(text[0])) return false;
48
+ return !(marksFor(lang).opening.has(text[0]) && text.length > 1 && !/[\s\p{P}]/u.test(text[1]));
49
+ }
50
+
51
+ // Takes dropped objects out of plain text, with any bracket or quote pair they leave empty.
52
+ export function removeDropped(plain: string, lang: string | undefined): string {
53
+ const { pairs, opening, closing } = marksFor(lang);
54
+ for (let i = plain.indexOf(DROPPED); i !== -1; i = plain.indexOf(DROPPED, i + 1)) {
55
+ let start = i;
56
+ let end = i + 1;
57
+ while (start > 0 && FILLER.test(plain[start - 1])) start--;
58
+ while (end < plain.length && FILLER.test(plain[end])) end++;
59
+ const open = plain[start - 1];
60
+ const close = plain[end];
61
+ if (open === undefined || close === undefined || !pairs.has(open + close)) continue;
62
+ // A mark that both opens and closes must be placed as the one it is here.
63
+ if (closing.has(open) && start > 1 && !/[\s\p{Ps}\p{Pi}\p{Pd}]/u.test(plain[start - 2])) continue;
64
+ if (opening.has(close) && end < plain.length - 1 && !/[\s\p{P}]/u.test(plain[end + 1])) continue;
65
+ // The pair becomes one dropped object, which may leave an enclosing pair empty in turn.
66
+ plain = plain.slice(0, start - 1) + DROPPED + plain.slice(end + 1);
67
+ i = start - 2;
68
+ }
69
+ // A space is kept only where there was one around the dropped objects, and never before binding punctuation.
70
+ return plain.replace(/ *\u0000[\u0000 ]*/g, (match: string, offset: number) => {
71
+ const rest = plain.slice(offset + match.length);
72
+ return offset > 0 && rest !== "" && match.includes(" ") && !bindsToPrevious(rest, lang) ? " " : "";
73
+ });
74
+ }
package/src/object.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { GuidedNavigationDescription, GuidedNavigationObject, GuidedNavigationText } from "@readium/shared";
2
2
  import type { GndRole } from "./types.ts";
3
3
  import { type TextBuilder, textIsEmpty, finalizeText } from "./text.ts";
4
+ import { detachSelfTextref } from "./textrefFragment.ts";
4
5
 
5
6
  export interface ObjBuilder {
6
7
  id?: string;
@@ -143,6 +144,9 @@ export class NavObject {
143
144
  const textref = selfTextref(this.el);
144
145
  if (textref) result.textref = textref;
145
146
  }
147
+ // An object given another id than its element's references that element by selector.
148
+ const ownId = this.el?.getAttribute("id");
149
+ if (ownId && result.id !== ownId) detachSelfTextref(result, ownId);
146
150
 
147
151
  return result;
148
152
  }
package/src/prescan.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { extractNodeRoles } from "./roles.ts";
2
2
  import { isAncestorOf } from "./dom.ts";
3
+ import { decodeIdFragment } from "./textrefFragment.ts";
3
4
 
4
5
  function hasEndnotesAncestor(el: Element): boolean {
5
6
  for (let p: Element | null = el.parentElement; p; p = p.parentElement) {
@@ -22,7 +23,7 @@ export function prescan(root: Element, ids: Map<string, Element>, suppressed: Se
22
23
  if (roles.includes("noteref")) {
23
24
  const href = n.getAttribute("href") ?? "";
24
25
  if (href.startsWith("#")) {
25
- noterefTargets.push({ id: href.slice(1), ref: n });
26
+ noterefTargets.push({ id: decodeIdFragment(href) ?? href.slice(1), ref: n });
26
27
  }
27
28
  }
28
29
  }
package/src/roles.ts CHANGED
@@ -143,6 +143,8 @@ const epubTypeRoles: Record<string, GndRole> = {
143
143
 
144
144
  // Elements whose role depends only on their tag name.
145
145
  const simpleElementTypeRoles: Record<string, GndRole> = {
146
+ abbr: "abbreviation",
147
+ acronym: "abbreviation",
146
148
  article: "article",
147
149
  aside: "aside",
148
150
  audio: "audio",
package/src/text.ts CHANGED
@@ -24,10 +24,12 @@ export interface SSMLContext {
24
24
  lang: string | undefined;
25
25
  tag: string;
26
26
  attrs?: Record<string, string>;
27
+ // The abbreviation a `sub` expands, so adjacent identical ones stay separate segments.
28
+ abbr?: Element;
27
29
  }
28
30
 
29
31
  export function ctxEqual(a: SSMLContext, b: SSMLContext): boolean {
30
- if (a.lang !== b.lang || a.tag !== b.tag) return false;
32
+ if (a.lang !== b.lang || a.tag !== b.tag || a.abbr !== b.abbr) return false;
31
33
  const ae = Object.entries(a.attrs ?? {});
32
34
  const be = Object.entries(b.attrs ?? {});
33
35
  if (ae.length !== be.length) return false;
@@ -15,6 +15,14 @@ export function encodeCssSelectorFragment(selector: string): string {
15
15
  return `${CSS_PREFIX}${encodeURIComponent(selector)}${CSS_SUFFIX}`;
16
16
  }
17
17
 
18
+ // Without id as its own, node's bare "#id" textref would decode as a link, so it's re-expressed as that id's selector.
19
+ export function detachSelfTextref(node: { textref?: string }, id: string) {
20
+ const fragment = `#${encodeURIComponent(id)}`;
21
+ if (node.textref === fragment || node.textref?.startsWith(`${fragment}:~:`)) {
22
+ node.textref = encodeCssSelectorFragment(`#${CSS.escape(id)}`) + node.textref.slice(fragment.length);
23
+ }
24
+ }
25
+
18
26
  export function decodeCssSelectorFragment(textref: string | undefined): string | undefined {
19
27
  if (!textref || !textref.startsWith(CSS_PREFIX) || !textref.endsWith(CSS_SUFFIX)) return undefined;
20
28
  return decodeURIComponent(textref.slice(CSS_PREFIX.length, -CSS_SUFFIX.length));
@@ -131,7 +139,7 @@ export function combineDomRangeTextrefs(first: DecodedTextref, last: DecodedText
131
139
  return combined;
132
140
  }
133
141
 
134
- function decodeIdFragment(base: string): string | undefined {
142
+ export function decodeIdFragment(base: string): string | undefined {
135
143
  if (!base.startsWith("#")) return undefined;
136
144
  try {
137
145
  return decodeURIComponent(base.slice(1));
@@ -20,6 +20,7 @@ export declare class Converter {
20
20
  baseHref?: string;
21
21
  selectorRoot: Element | null;
22
22
  selectorRootAnchor: string | null;
23
+ copy: boolean;
23
24
  private root;
24
25
  private current;
25
26
  private foldedCaptions;
@@ -50,6 +51,9 @@ export declare class Converter {
50
51
  private applyTextref;
51
52
  private text;
52
53
  private textContext;
54
+ private static containsObject;
55
+ private static isPlaceholder;
56
+ private static isSoleContent;
53
57
  private updateFlowSpace;
54
58
  private closeSegment;
55
59
  private resetFlow;
@@ -3,3 +3,4 @@ import { Converter } from "./converter.ts";
3
3
  export declare function pagebreak(converter: Converter, el: Element, aria: string | null, ariaLanguage: string, roles: GndRole[]): boolean;
4
4
  export declare function noteref(converter: Converter, el: Element, roles: GndRole[]): void;
5
5
  export declare function link(converter: Converter, el: Element, roles: GndRole[], aria: string | null, ariaLanguage: string): void;
6
+ export declare function reference(converter: Converter, el: Element, roles: GndRole[], aria: string | null, ariaLanguage: string): void;
@@ -0,0 +1,3 @@
1
+ export declare const DROPPED = "\0";
2
+ export declare function bindsToPrevious(text: string, lang: string | undefined): boolean;
3
+ export declare function removeDropped(plain: string, lang: string | undefined): string;
@@ -10,6 +10,7 @@ export interface SSMLContext {
10
10
  lang: string | undefined;
11
11
  tag: string;
12
12
  attrs?: Record<string, string>;
13
+ abbr?: Element;
13
14
  }
14
15
  export declare function ctxEqual(a: SSMLContext, b: SSMLContext): boolean;
15
16
  export declare function isNoBreakSpace(ch: string): boolean;
@@ -1,4 +1,7 @@
1
1
  export declare function encodeCssSelectorFragment(selector: string): string;
2
+ export declare function detachSelfTextref(node: {
3
+ textref?: string;
4
+ }, id: string): void;
2
5
  export declare function decodeCssSelectorFragment(textref: string | undefined): string | undefined;
3
6
  export interface DomRangeJSON {
4
7
  start: {
@@ -35,6 +38,7 @@ export interface DecodedTextref {
35
38
  fragment?: string;
36
39
  }
37
40
  export declare function combineDomRangeTextrefs(first: DecodedTextref, last: DecodedTextref): DecodedTextref | undefined;
41
+ export declare function decodeIdFragment(base: string): string | undefined;
38
42
  export declare function decodeTextref(node: {
39
43
  id?: string;
40
44
  textref?: string;