@readium/guided-navigation 1.1.2 → 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 (134) 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/dom.js +1 -1
  5. package/dist/elementHandlers.js +1 -1
  6. package/dist/emptyPairs.js +1 -0
  7. package/dist/language.js +1 -0
  8. package/dist/object.js +1 -1
  9. package/dist/prescan.js +1 -1
  10. package/dist/roles.js +1 -1
  11. package/dist/text.js +1 -1
  12. package/dist/textrefFragment.js +1 -1
  13. package/fixtures/ROLES_COVERAGE.md +5 -4
  14. package/fixtures/abbreviation-acronym-html-native/gnd.json +9 -0
  15. package/fixtures/abbreviation-acronym-html-native/input.html +1 -0
  16. package/fixtures/abbreviation-acronym-html-native/meta.json +11 -0
  17. package/fixtures/abbreviation-before-formatting/gnd.json +9 -0
  18. package/fixtures/abbreviation-before-formatting/input.html +1 -0
  19. package/fixtures/abbreviation-before-formatting/meta.json +11 -0
  20. package/fixtures/abbreviation-before-image/gnd.json +24 -0
  21. package/fixtures/abbreviation-before-image/input.html +1 -0
  22. package/fixtures/abbreviation-before-image/meta.json +12 -0
  23. package/fixtures/abbreviation-html-native/gnd.json +9 -0
  24. package/fixtures/abbreviation-html-native/input.html +1 -0
  25. package/fixtures/abbreviation-html-native/meta.json +11 -0
  26. package/fixtures/abbreviation-language/gnd.json +9 -0
  27. package/fixtures/abbreviation-language/input.html +1 -0
  28. package/fixtures/abbreviation-language/meta.json +11 -0
  29. package/fixtures/abbreviation-line-break/gnd.json +9 -0
  30. package/fixtures/abbreviation-line-break/input.html +1 -0
  31. package/fixtures/abbreviation-line-break/meta.json +11 -0
  32. package/fixtures/abbreviation-nested/gnd.json +9 -0
  33. package/fixtures/abbreviation-nested/input.html +1 -0
  34. package/fixtures/abbreviation-nested/meta.json +11 -0
  35. package/fixtures/abbreviation-nested-emphasis/gnd.json +9 -0
  36. package/fixtures/abbreviation-nested-emphasis/input.html +1 -0
  37. package/fixtures/abbreviation-nested-emphasis/meta.json +11 -0
  38. package/fixtures/abbreviation-nested-term/gnd.json +21 -0
  39. package/fixtures/abbreviation-nested-term/input.html +1 -0
  40. package/fixtures/abbreviation-nested-term/meta.json +12 -0
  41. package/fixtures/abbreviation-nested-term-punctuation/gnd.json +26 -0
  42. package/fixtures/abbreviation-nested-term-punctuation/input.html +1 -0
  43. package/fixtures/abbreviation-nested-term-punctuation/meta.json +12 -0
  44. package/fixtures/abbreviation-no-title/gnd.json +8 -0
  45. package/fixtures/abbreviation-no-title/input.html +1 -0
  46. package/fixtures/abbreviation-no-title/meta.json +11 -0
  47. package/fixtures/abbreviation-spanning-terms/gnd.json +33 -0
  48. package/fixtures/abbreviation-spanning-terms/input.html +1 -0
  49. package/fixtures/abbreviation-spanning-terms/meta.json +12 -0
  50. package/fixtures/abbreviation-with-image/gnd.json +24 -0
  51. package/fixtures/abbreviation-with-image/input.html +1 -0
  52. package/fixtures/abbreviation-with-image/meta.json +12 -0
  53. package/fixtures/abbreviation-with-svg-and-math/gnd.json +39 -0
  54. package/fixtures/abbreviation-with-svg-and-math/input.html +1 -0
  55. package/fixtures/abbreviation-with-svg-and-math/meta.json +13 -0
  56. package/fixtures/biblioref-target-descendant-ids/gnd.json +90 -0
  57. package/fixtures/biblioref-target-descendant-ids/input.html +1 -0
  58. package/fixtures/biblioref-target-descendant-ids/meta.json +14 -0
  59. package/fixtures/biblioref-target-in-bibliography-role-aria/gnd.json +59 -0
  60. package/fixtures/biblioref-target-in-bibliography-role-aria/input.html +6 -0
  61. package/fixtures/biblioref-target-in-bibliography-role-aria/meta.json +14 -0
  62. package/fixtures/biblioref-target-mixed-content/gnd.json +63 -0
  63. package/fixtures/biblioref-target-mixed-content/input.html +1 -0
  64. package/fixtures/biblioref-target-mixed-content/meta.json +11 -0
  65. package/fixtures/glossref-target-in-glossary-role-aria/gnd.json +76 -0
  66. package/fixtures/glossref-target-in-glossary-role-aria/input.html +5 -0
  67. package/fixtures/glossref-target-in-glossary-role-aria/meta.json +14 -0
  68. package/fixtures/glossref-target-percent-encoded/gnd.json +68 -0
  69. package/fixtures/glossref-target-percent-encoded/input.html +1 -0
  70. package/fixtures/glossref-target-percent-encoded/meta.json +14 -0
  71. package/fixtures/manifest.json +330 -0
  72. package/fixtures/noteref-after-closing-straight-quote/gnd.json +32 -0
  73. package/fixtures/noteref-after-closing-straight-quote/input.html +1 -0
  74. package/fixtures/noteref-after-closing-straight-quote/meta.json +13 -0
  75. package/fixtures/noteref-after-closing-straight-quote-split/gnd.json +38 -0
  76. package/fixtures/noteref-after-closing-straight-quote-split/input.html +1 -0
  77. package/fixtures/noteref-after-closing-straight-quote-split/meta.json +12 -0
  78. package/fixtures/noteref-enclosed-across-formatting/gnd.json +32 -0
  79. package/fixtures/noteref-enclosed-across-formatting/input.html +1 -0
  80. package/fixtures/noteref-enclosed-across-formatting/meta.json +13 -0
  81. package/fixtures/noteref-enclosed-adjacent-pairs/gnd.json +108 -0
  82. package/fixtures/noteref-enclosed-adjacent-pairs/input.html +1 -0
  83. package/fixtures/noteref-enclosed-adjacent-pairs/meta.json +13 -0
  84. package/fixtures/noteref-enclosed-adjacent-text/gnd.json +34 -0
  85. package/fixtures/noteref-enclosed-adjacent-text/input.html +1 -0
  86. package/fixtures/noteref-enclosed-adjacent-text/meta.json +13 -0
  87. package/fixtures/noteref-enclosed-before-formatting/gnd.json +34 -0
  88. package/fixtures/noteref-enclosed-before-formatting/input.html +1 -0
  89. package/fixtures/noteref-enclosed-before-formatting/meta.json +13 -0
  90. package/fixtures/noteref-enclosed-guillemets-french/gnd.json +103 -0
  91. package/fixtures/noteref-enclosed-guillemets-french/input.html +1 -0
  92. package/fixtures/noteref-enclosed-guillemets-french/meta.json +13 -0
  93. package/fixtures/noteref-enclosed-quotes-chinese/gnd.json +47 -0
  94. package/fixtures/noteref-enclosed-quotes-chinese/input.html +1 -0
  95. package/fixtures/noteref-enclosed-quotes-chinese/meta.json +13 -0
  96. package/fixtures/noteref-enclosed-quotes-german/gnd.json +124 -0
  97. package/fixtures/noteref-enclosed-quotes-german/input.html +1 -0
  98. package/fixtures/noteref-enclosed-quotes-german/meta.json +13 -0
  99. package/fixtures/noteref-enclosed-quotes-swedish/gnd.json +70 -0
  100. package/fixtures/noteref-enclosed-quotes-swedish/input.html +1 -0
  101. package/fixtures/noteref-enclosed-quotes-swedish/meta.json +13 -0
  102. package/fixtures/noteref-enclosed-straight-quotes/gnd.json +32 -0
  103. package/fixtures/noteref-enclosed-straight-quotes/input.html +1 -0
  104. package/fixtures/noteref-enclosed-straight-quotes/meta.json +13 -0
  105. package/fixtures/noteref-in-lone-block/gnd.json +29 -0
  106. package/fixtures/noteref-in-lone-block/input.html +1 -0
  107. package/fixtures/noteref-in-lone-block/meta.json +12 -0
  108. package/fixtures/noteref-target-malformed-escape/gnd.json +32 -0
  109. package/fixtures/noteref-target-malformed-escape/input.html +1 -0
  110. package/fixtures/noteref-target-malformed-escape/meta.json +13 -0
  111. package/fixtures/noteref-target-percent-encoded/gnd.json +32 -0
  112. package/fixtures/noteref-target-percent-encoded/input.html +1 -0
  113. package/fixtures/noteref-target-percent-encoded/meta.json +13 -0
  114. package/package.json +1 -1
  115. package/src/a11y.ts +50 -39
  116. package/src/converter.ts +140 -50
  117. package/src/dom.ts +0 -10
  118. package/src/elementHandlers.ts +76 -22
  119. package/src/emptyPairs.ts +74 -0
  120. package/src/language.ts +37 -0
  121. package/src/object.ts +11 -1
  122. package/src/prescan.ts +2 -1
  123. package/src/roles.ts +2 -0
  124. package/src/text.ts +5 -2
  125. package/src/textrefFragment.ts +9 -1
  126. package/types/src/a11y.d.ts +9 -4
  127. package/types/src/converter.d.ts +4 -0
  128. package/types/src/dom.d.ts +0 -1
  129. package/types/src/elementHandlers.d.ts +3 -2
  130. package/types/src/emptyPairs.d.ts +3 -0
  131. package/types/src/language.d.ts +4 -0
  132. package/types/src/object.d.ts +2 -0
  133. package/types/src/text.d.ts +2 -1
  134. 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.2",
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
@@ -1,5 +1,6 @@
1
1
  import { normalizeWhitespace } from "./text.ts";
2
2
  import { hasExplicitRole } from "./roles.ts";
3
+ import { nodeLanguage, sharedLanguage } from "./language.ts";
3
4
 
4
5
  function nodeIsHidden(el: Element): boolean {
5
6
  if (el.getAttribute("aria-hidden") === "true") return true;
@@ -7,42 +8,44 @@ function nodeIsHidden(el: Element): boolean {
7
8
  return false;
8
9
  }
9
10
 
10
- function nodeText(el: Node): string {
11
- let text = "";
12
- const walk = (n: Node) => {
13
- if (n.nodeType === 3 /* TEXT_NODE */) {
14
- text += n.nodeValue ?? "";
15
- }
16
- for (let c = n.firstChild; c; c = c.nextSibling) walk(c);
17
- };
18
- walk(el);
19
- return text;
11
+ export interface NodeText {
12
+ text: string;
13
+ // Shared by all of the text, unknown ("") when parts of it are in different languages.
14
+ language: string;
20
15
  }
21
16
 
22
- /** Normalized (whitespace-coalesced and trimmed) text content of a node's subtree. */
23
- export function normalizedNodeText(el: Node): string {
24
- return normalizeWhitespace(nodeText(el), true).trim();
25
- }
26
-
27
- // Same as `nodeText`, skipping descendants with an explicit role — those are
28
- // walked/spoken separately, so folding their text in here would double it up.
29
- function nodeTextExcludingExplicitRoles(root: Node): string {
17
+ // Raw text of a subtree, adding each non-blank text node's language to `languages`. Explicit-role
18
+ // descendants can be skipped: they're spoken separately, so their text would be doubled up.
19
+ function nodeText(root: Node, excludeExplicitRoles: boolean, languages: Set<string>): string {
30
20
  let text = "";
31
21
  const walk = (n: Node, isRoot: boolean) => {
32
22
  if (n.nodeType === 3 /* TEXT_NODE */) {
33
- text += n.nodeValue ?? "";
23
+ const value = n.nodeValue ?? "";
24
+ text += value;
25
+ if (value.trim()) languages.add(nodeLanguage(n.parentElement));
34
26
  return;
35
27
  }
36
- if (n.nodeType === 1 /* ELEMENT_NODE */ && !isRoot && hasExplicitRole(n as Element)) return;
28
+ if (excludeExplicitRoles && n.nodeType === 1 /* ELEMENT_NODE */ && !isRoot && hasExplicitRole(n as Element)) return;
37
29
  for (let c = n.firstChild; c; c = c.nextSibling) walk(c, false);
38
30
  };
39
31
  walk(root, true);
40
32
  return text;
41
33
  }
42
34
 
35
+ function normalizedText(root: Node, excludeExplicitRoles: boolean): NodeText {
36
+ const languages = new Set<string>();
37
+ const text = normalizeWhitespace(nodeText(root, excludeExplicitRoles, languages), true).trim();
38
+ return { text, language: sharedLanguage(languages) };
39
+ }
40
+
41
+ /** Normalized (whitespace-coalesced and trimmed) text content of a node's subtree, and its language. */
42
+ export function normalizedNodeText(el: Node): NodeText {
43
+ return normalizedText(el, false);
44
+ }
45
+
43
46
  /** Same as `normalizedNodeText`, excluding explicitly-role-bearing descendants. */
44
- export function normalizedNodeTextExcludingExplicitRoles(el: Node): string {
45
- return normalizeWhitespace(nodeTextExcludingExplicitRoles(el), true).trim();
47
+ export function normalizedNodeTextExcludingExplicitRoles(el: Node): NodeText {
48
+ return normalizedText(el, true);
46
49
  }
47
50
 
48
51
  /**
@@ -51,11 +54,12 @@ export function normalizedNodeTextExcludingExplicitRoles(el: Node): string {
51
54
  * precedence order (https://www.w3.org/TR/accname/#terminology, 2.A-2.D)
52
55
  * for its accessible-name sources, with a non-AccName `aria-describedby`
53
56
  * fallback spliced in between 2.C and 2.D — see that branch below.
57
+ * Also returns that text's language.
54
58
  */
55
- export function extractNodeAria(el: Element): [string | null, boolean] {
59
+ export function extractNodeAria(el: Element): [string | null, boolean, string] {
56
60
  // 2.A
57
61
  if (nodeIsHidden(el)) {
58
- return [null, false];
62
+ return [null, false, ""];
59
63
  }
60
64
 
61
65
  // 2.B
@@ -69,23 +73,29 @@ export function extractNodeAria(el: Element): [string | null, boolean] {
69
73
 
70
74
  if (labelNodes.length > 0) {
71
75
  let text = "";
76
+ const languages = new Set<string>();
72
77
  // Directly-referenced label nodes count even when hidden (AccName 2.A).
73
78
  labelNodes.forEach((n, i) => {
74
79
  const label = n.getAttribute("aria-label");
75
- text += label ? label : nodeTextExcludingExplicitRoles(n);
80
+ if (label) {
81
+ text += label;
82
+ languages.add(nodeLanguage(n));
83
+ } else {
84
+ text += nodeText(n, true, languages);
85
+ }
76
86
  if (i < labelNodes.length - 1) text += " ";
77
87
  });
78
88
  const normalized = normalizeWhitespace(text, true).trim();
79
89
  if (normalized !== "") {
80
- return [normalized, true];
90
+ return [normalized, true, sharedLanguage(languages)];
81
91
  }
82
92
  }
83
93
  }
84
94
 
85
95
  // 2.C
86
- const label = (el.getAttribute("aria-label") ?? "").trim();
96
+ const label = normalizeWhitespace(el.getAttribute("aria-label") ?? "", true).trim();
87
97
  if (label) {
88
- return [label, true];
98
+ return [label, true, nodeLanguage(el)];
89
99
  }
90
100
 
91
101
  // Not part of the AccName algorithm proper (which computes a name, not a
@@ -99,10 +109,11 @@ export function extractNodeAria(el: Element): [string | null, boolean] {
99
109
  .map((id) => el.ownerDocument.getElementById(id))
100
110
  .filter((n): n is HTMLElement => n !== null);
101
111
  if (nodes.length > 0) {
102
- const text = nodes.map((n) => nodeTextExcludingExplicitRoles(n)).join(" ");
112
+ const languages = new Set<string>();
113
+ const text = nodes.map((n) => nodeText(n, true, languages)).join(" ");
103
114
  const normalized = normalizeWhitespace(text, true).trim();
104
115
  if (normalized !== "") {
105
- return [normalized, true];
116
+ return [normalized, true, sharedLanguage(languages)];
106
117
  }
107
118
  }
108
119
  }
@@ -110,25 +121,25 @@ export function extractNodeAria(el: Element): [string | null, boolean] {
110
121
  // 2.D (partial support)
111
122
  const tagName = el.tagName.toLowerCase();
112
123
  if (tagName === "img") {
113
- const alt = (el.getAttribute("alt") ?? "").trim();
114
- if (alt) return [alt, true];
124
+ const alt = normalizeWhitespace(el.getAttribute("alt") ?? "", true).trim();
125
+ if (alt) return [alt, true, nodeLanguage(el)];
115
126
  // 2.I fallback for images: the title attribute
116
- const title = (el.getAttribute("title") ?? "").trim();
117
- if (title) return [title, true];
127
+ const title = normalizeWhitespace(el.getAttribute("title") ?? "", true).trim();
128
+ if (title) return [title, true, nodeLanguage(el)];
118
129
  } else if (tagName === "svg") {
119
130
  // The accessible name of an SVG comes from its <title> child
120
131
  const title = el.querySelector(":scope > title");
121
132
  if (title) {
122
- const text = normalizedNodeText(title);
123
- if (text) return [text, true];
133
+ const { text, language } = normalizedNodeText(title);
134
+ if (text) return [text, true, language];
124
135
  }
125
136
  } else if (tagName === "math") {
126
137
  // MathML Core's spoken-form fallback (not part of the ARIA AccName algorithm)
127
- const alttext = (el.getAttribute("alttext") ?? "").trim();
128
- if (alttext) return [alttext, true];
138
+ const alttext = normalizeWhitespace(el.getAttribute("alttext") ?? "", true).trim();
139
+ if (alttext) return [alttext, true, nodeLanguage(el)];
129
140
  }
130
141
 
131
- return [null, true];
142
+ return [null, true, ""];
132
143
  }
133
144
 
134
145
  const ssmlTags: Record<string, [string, Record<string, string>?]> = {
package/src/converter.ts CHANGED
@@ -14,9 +14,10 @@ import {
14
14
  ctxEqual,
15
15
  normalizeWhitespace,
16
16
  } from "./text.ts";
17
- import { ssmlAttrEscape, ssmlTextEscape, startsWithBindingPunct } from "@readium/helpers";
18
- import { type ObjBuilder, NavObject, isEmptyObj, finalizeToGuidedNavigationObject } from "./object.ts";
19
- import { type GndMediaType, nodeLanguage, isInlineTag, sniffMediaType } from "./dom.ts";
17
+ import { ssmlAttrEscape, ssmlTextEscape } from "@readium/helpers";
18
+ import { type ObjBuilder, NavObject, isEmptyObj, finalizeToGuidedNavigationObject, setDescription } from "./object.ts";
19
+ import { type GndMediaType, isAncestorOf, isInlineTag, sniffMediaType } from "./dom.ts";
20
+ import { declaredLanguage, nodeLanguage, sameLanguage } from "./language.ts";
20
21
  import { encodeDomRangeFragment, encodeTextFragmentDirective } from "./textrefFragment.ts";
21
22
  import { resolveRefs } from "./href.ts";
22
23
  import { rootAnchorSelector, selectorForElement, textrefForSelector } from "./selectorGenerator.ts";
@@ -25,7 +26,8 @@ import { textFragmentDirectiveFor } from "./textFragmentGenerator.ts";
25
26
  import { type GndGenerationOptions, normalizeTextrefOptions } from "./options.ts";
26
27
  import { IdAllocator } from "./idAllocator.ts";
27
28
  import { prescan as prescanImpl } from "./prescan.ts";
28
- import { pagebreak, noteref, link } from "./elementHandlers.ts";
29
+ import { pagebreak, noteref, reference, link } from "./elementHandlers.ts";
30
+ import { DROPPED, bindsToPrevious, removeDropped } from "./emptyPairs.ts";
29
31
 
30
32
  const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
31
33
 
@@ -78,6 +80,8 @@ export class Converter {
78
80
  selectorRoot: Element | null = null;
79
81
  // Prefixed onto every generated selector — see selectorGenerator.ts's rootAnchorSelector().
80
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;
81
85
 
82
86
  private root = new NavObject();
83
87
  private current = this.root;
@@ -89,7 +93,7 @@ export class Converter {
89
93
 
90
94
  private segments: Segment[] = [];
91
95
  private textAcc = "";
92
- private currentCtx: SSMLContext = { lang: "", tag: "" };
96
+ private currentCtx: SSMLContext = { lang: undefined, tag: "" };
93
97
  private flowEndsWithSpace = true;
94
98
  private pendingChildren: NavObject[] = [];
95
99
 
@@ -128,6 +132,7 @@ export class Converter {
128
132
  child.domRangeEnabled = this.domRangeEnabled;
129
133
  child.textFragmentEnabled = this.textFragmentEnabled;
130
134
  child.leafTextEnabled = this.leafTextEnabled;
135
+ child.copy = this.copy;
131
136
  return child;
132
137
  }
133
138
 
@@ -155,7 +160,8 @@ export class Converter {
155
160
 
156
161
  resultBuilders(): ObjBuilder[] {
157
162
  const res = this.root.finalize((el) => textrefForSelector(selectorForElement(el, this.selectorRoot, this.selectorRootAnchor), el));
158
- 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) {
159
165
  if (isEmptyObj(res)) return [];
160
166
  return [res];
161
167
  }
@@ -209,7 +215,7 @@ export class Converter {
209
215
  if (skippedElements.has(tagName)) return true;
210
216
  if (this.suppressed.has(el) && el !== this.allowNode) return true;
211
217
 
212
- const [aria, visible] = extractNodeAria(el);
218
+ const [aria, visible, ariaLanguage] = extractNodeAria(el);
213
219
  if (!visible && el !== this.allowNode) return true;
214
220
 
215
221
  const roles = extractNodeRoles(el);
@@ -223,7 +229,8 @@ export class Converter {
223
229
  }
224
230
 
225
231
  if (tagName === "br") {
226
- 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) {
227
234
  this.closeSegment();
228
235
  this.segments.push({ kind: "break" });
229
236
  this.flowEndsWithSpace = true;
@@ -232,27 +239,31 @@ export class Converter {
232
239
  }
233
240
 
234
241
  if (roles.includes("pagebreak")) {
235
- return !pagebreak(this, el, aria, roles);
242
+ return !pagebreak(this, el, aria, ariaLanguage, roles);
236
243
  }
237
244
  if (tagName === "a" && roles.includes("noteref") && el.getAttribute("href")) {
238
245
  noteref(this, el, roles);
239
246
  return true;
240
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
+ }
241
252
  if (tagName === "a" && el.getAttribute("href")) {
242
- // Any other link — backlink/biblioref/glossref, or a plain navigational
253
+ // Any other link — a backlink, or a plain navigational
243
254
  // link with no specific role (e.g. a TOC entry) — carries its href as
244
255
  // textref. When it's the sole content of its enclosing block (the usual
245
256
  // case for list items), the hoist rule promotes it onto that block;
246
257
  // otherwise it becomes an inline SSML placeholder like any other
247
258
  // embedded object.
248
- link(this, el, roles, aria);
259
+ link(this, el, roles, aria, ariaLanguage);
249
260
  return true;
250
261
  }
251
262
  if (tagName === "img") {
252
263
  const obj: ObjBuilder = { role: roles };
253
264
  const src = el.getAttribute("src");
254
265
  if (src) obj.imgref = src;
255
- if (aria) obj.description = aria;
266
+ if (aria) setDescription(obj, aria, ariaLanguage);
256
267
  this.placeholder(el, "image", obj);
257
268
  return true;
258
269
  }
@@ -268,7 +279,7 @@ export class Converter {
268
279
  } else if (src) {
269
280
  obj.videoref = src;
270
281
  }
271
- if (aria) obj.description = aria;
282
+ if (aria) setDescription(obj, aria, ariaLanguage);
272
283
  this.placeholder(el, tagName, obj);
273
284
  return true;
274
285
  }
@@ -276,14 +287,14 @@ export class Converter {
276
287
  // Elements acting as images without being one, e.g. <span role="img">:
277
288
  // their content is replaced by their accessible name.
278
289
  const obj: ObjBuilder = { role: roles };
279
- if (aria) obj.description = aria;
290
+ if (aria) setDescription(obj, aria, ariaLanguage);
280
291
  if (roles.includes("math")) {
281
292
  // MathML is carried as-is in SSML, other math markup as plain text.
282
293
  if (el.namespaceURI === MATHML_NS) {
283
- obj.text = { plain: "", ssml: new XMLSerializer().serializeToString(el), language: "" };
294
+ obj.text = { plain: "", ssml: new XMLSerializer().serializeToString(el), language: nodeLanguage(el) };
284
295
  } else {
285
- const text = normalizedNodeText(el);
286
- if (text) obj.text = { plain: text, ssml: "", language: "" };
296
+ const { text, language } = normalizedNodeText(el);
297
+ if (text) obj.text = { plain: text, ssml: "", language };
287
298
  }
288
299
  obj.textref = textrefForSelector(selectorForElement(el, this.selectorRoot, this.selectorRootAnchor), el);
289
300
  }
@@ -301,7 +312,7 @@ export class Converter {
301
312
  const cur = this.current.object;
302
313
  if (roles.length > 0) cur.role = roles;
303
314
  if (aria) {
304
- cur.description = aria;
315
+ setDescription(cur, aria, ariaLanguage);
305
316
  if (roles.includes("figure")) {
306
317
  this.current.noText = true;
307
318
  }
@@ -310,18 +321,18 @@ export class Converter {
310
321
  if (caption) {
311
322
  // Not suppressed — walked normally so a nested explicit-role
312
323
  // descendant (e.g. a credit) still speaks.
313
- const text = normalizedNodeTextExcludingExplicitRoles(caption);
324
+ const { text, language } = normalizedNodeTextExcludingExplicitRoles(caption);
314
325
  if (text) {
315
- cur.description = text;
326
+ setDescription(cur, text, language);
316
327
  this.current.noText = true;
317
328
  }
318
329
  }
319
330
  } else if (roles.includes("table")) {
320
331
  const caption = this.implicitCaptionOf(el);
321
332
  if (caption) {
322
- const text = normalizedNodeTextExcludingExplicitRoles(caption);
333
+ const { text, language } = normalizedNodeTextExcludingExplicitRoles(caption);
323
334
  if (text) {
324
- cur.description = text;
335
+ setDescription(cur, text, language);
325
336
  this.foldedCaptions.add(caption);
326
337
  }
327
338
  }
@@ -422,7 +433,21 @@ export class Converter {
422
433
  }
423
434
 
424
435
  private textContext(node: Node): SSMLContext {
425
- const ctx: SSMLContext = { lang: nodeLanguage(node.parentElement), tag: "" };
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;
450
+ const ctx: SSMLContext = { lang: declaredLanguage(node.parentElement), tag: "" };
426
451
  for (let p = node.parentElement; p && p !== this.current.el; p = p.parentElement) {
427
452
  const [tag, attrs] = convertElementToSSMLTag(p.tagName.toLowerCase());
428
453
  if (tag && tag !== "break") {
@@ -434,6 +459,30 @@ export class Converter {
434
459
  return ctx;
435
460
  }
436
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
+
437
486
  private updateFlowSpace() {
438
487
  if (this.textAcc.length > 0) {
439
488
  this.flowEndsWithSpace = this.textAcc.endsWith(" ");
@@ -449,7 +498,7 @@ export class Converter {
449
498
  private resetFlow() {
450
499
  this.segments = [];
451
500
  this.textAcc = "";
452
- this.currentCtx = { lang: "", tag: "" };
501
+ this.currentCtx = { lang: undefined, tag: "" };
453
502
  this.flowEndsWithSpace = true;
454
503
  this.pendingChildren = [];
455
504
  this.flowFirstNode = null;
@@ -526,27 +575,55 @@ export class Converter {
526
575
  break;
527
576
  }
528
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
+
529
606
  const hasText = segments.some((s) => s.kind === "text" && s.text!.trim() !== "");
530
607
  if (!hasText) {
531
608
  for (const child of pending) this.appendChild(child);
532
609
  return;
533
610
  }
534
611
 
535
- const textLangs: string[] = [];
612
+ const textLangs: (string | undefined)[] = [];
536
613
  for (const seg of segments) {
537
614
  if (seg.kind === "text" && seg.text!.trim() !== "") {
538
615
  const lang = seg.ctx!.lang;
539
- if (!textLangs.includes(lang)) textLangs.push(lang);
616
+ if (!textLangs.some((other) => sameLanguage(other, lang))) textLangs.push(lang);
540
617
  }
541
618
  }
542
- let baseLang = nodeLanguage(this.current.el ?? null);
543
- if (textLangs.length === 1 && textLangs[0] !== "") {
619
+ let baseLang = declaredLanguage(this.current.el ?? null);
620
+ if (textLangs.length === 1) {
544
621
  baseLang = textLangs[0];
545
622
  }
546
623
 
547
624
  let needSSML = false;
548
625
  for (const seg of segments) {
549
- if (seg.kind !== "text" || seg.ctx!.tag !== "" || seg.ctx!.lang !== baseLang) {
626
+ if (seg.kind !== "text" || seg.ctx!.tag !== "" || !sameLanguage(seg.ctx!.lang, baseLang)) {
550
627
  needSSML = true;
551
628
  break;
552
629
  }
@@ -555,14 +632,16 @@ export class Converter {
555
632
  // Default to English when an SSML representation is required (mixed
556
633
  // formatting, embedded objects, or a language shift) but no explicit
557
634
  // language was declared anywhere in the document.
558
- if (needSSML && baseLang === "") {
635
+ if (needSSML && baseLang === undefined) {
559
636
  baseLang = "en";
560
637
  }
638
+ // Undeclared text is in the base language; an empty declaration is a shift to an unknown one.
639
+ const shiftsLanguage = (lang: string | undefined): lang is string => lang !== undefined && !sameLanguage(lang, baseLang);
561
640
 
562
641
  if (needSSML) {
563
642
  for (const seg of segments) {
564
643
  if (seg.kind !== "placeholder") continue;
565
- let id = seg.candidateID;
644
+ let id = this.copy ? undefined : seg.candidateID;
566
645
  if (!id || !this.idAlloc.claim(id)) {
567
646
  id = this.idAlloc.allocate(seg.tag!, (candidate) => this.ids.has(candidate));
568
647
  }
@@ -587,7 +666,7 @@ export class Converter {
587
666
  if (plainB.length > 0) {
588
667
  const spaced = prevTrail || midSpace || lead;
589
668
  if (sawBreak) join = true;
590
- else if (sawPlaceholder) join = spaced && !startsWithBindingPunct(t);
669
+ else if (sawPlaceholder) join = spaced && !bindsToPrevious(t, baseLang);
591
670
  else join = spaced;
592
671
  }
593
672
  if (join) plainB += " ";
@@ -599,9 +678,11 @@ export class Converter {
599
678
  } else if (seg.kind === "break") {
600
679
  sawBreak = true;
601
680
  } else if (seg.kind === "placeholder") {
681
+ plainB += DROPPED;
602
682
  sawPlaceholder = true;
603
683
  }
604
684
  }
685
+ plainB = removeDropped(plainB, baseLang);
605
686
 
606
687
  // Plain text is only worth keeping alongside SSML when it diverges from
607
688
  // what stripping tags from the SSML would produce — i.e. when a
@@ -613,33 +694,31 @@ export class Converter {
613
694
  const text: TextBuilder = {
614
695
  plain: needSSML && !hasPlaceholder ? "" : plainB.trim(),
615
696
  ssml: "",
616
- language: baseLang,
697
+ language: baseLang ?? "",
617
698
  };
618
699
 
619
700
  if (needSSML) {
620
701
  let sb = "";
621
702
  for (const seg of segments) {
622
703
  if (seg.kind === "text") {
623
- let tag = seg.ctx!.tag;
624
- let attrs = seg.ctx!.attrs;
625
- if (seg.ctx!.lang !== baseLang && seg.ctx!.lang !== "") {
626
- // A language shift takes priority over whatever SSML tag the
627
- // shifting element would otherwise map to.
628
- tag = "lang";
629
- 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;
630
712
  }
631
- if (tag) {
632
- sb += `<${tag}`;
633
- for (const [k, v] of Object.entries(attrs ?? {})) {
634
- sb += ` ${k}="${ssmlAttrEscape(v)}"`;
635
- }
636
- if (seg.ctx!.lang !== baseLang && seg.ctx!.lang !== "") {
637
- sb += ` xml:lang="${ssmlAttrEscape(seg.ctx!.lang)}"`;
638
- }
639
- 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>`;
640
718
  } else {
641
- sb += ssmlTextEscape(seg.text!);
719
+ sb += tag ? ssmlElement(tag, attrs, segText) : ssmlTextEscape(segText);
642
720
  }
721
+ sb += edges?.[3] ?? "";
643
722
  } else if (seg.kind === "break") {
644
723
  sb += "<break/>";
645
724
  } else if (seg.kind === "placeholder") {
@@ -662,6 +741,17 @@ export class Converter {
662
741
  }
663
742
  }
664
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
+
665
755
  // A DOM <body> only counts as real content when the input actually wrote
666
756
  // one — text/html parsing synthesizes a <body> around any fragment
667
757
  // regardless of what was passed in, and that synthesized wrapper was
package/src/dom.ts CHANGED
@@ -1,15 +1,5 @@
1
1
  const ELEMENT_NODE = 1;
2
2
 
3
- export function nodeLanguage(el: Element | null): string {
4
- for (let n: Element | null = el; n; n = n.parentElement) {
5
- const xmlLang = n.getAttribute("xml:lang");
6
- if (xmlLang) return xmlLang;
7
- const lang = n.getAttribute("lang");
8
- if (lang) return lang;
9
- }
10
- return "";
11
- }
12
-
13
3
  export function hasElementChild(el: Element): boolean {
14
4
  for (let c = el.firstChild; c; c = c.nextSibling) {
15
5
  if (c.nodeType === ELEMENT_NODE) return true;