@dita-viewer/core 0.2.0 → 0.2.2

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 (44) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +90 -58
  3. package/dist/editor/renderContext.d.ts +7 -0
  4. package/dist/editor/renderContext.js +24 -0
  5. package/dist/editor/topicRender.d.ts +9 -0
  6. package/dist/editor/topicRender.js +4 -2
  7. package/dist/index.js +3 -3
  8. package/dist/language/ditaLanguageUtils.js +2 -0
  9. package/dist/profiling.d.ts +9 -3
  10. package/dist/profiling.js +12 -6
  11. package/dist/render/baseTypeMap.js +28 -2
  12. package/dist/render/mapTypeMap.js +23 -23
  13. package/dist/render/renderer.d.ts +24 -0
  14. package/dist/render/renderer.js +36 -9
  15. package/dist-esm/bookRender.js +145 -0
  16. package/dist-esm/completion.js +142 -0
  17. package/dist-esm/completionData.js +155 -0
  18. package/dist-esm/diagnostics.js +378 -0
  19. package/dist-esm/editor/conkeyref.js +104 -0
  20. package/dist-esm/editor/keySpace.js +201 -0
  21. package/dist-esm/editor/refResolvers.js +633 -0
  22. package/dist-esm/editor/renderContext.js +138 -0
  23. package/dist-esm/editor/sourceText.js +142 -0
  24. package/dist-esm/editor/topicRender.js +328 -0
  25. package/dist-esm/index.js +66 -0
  26. package/dist-esm/keyMapForDocument.js +23 -0
  27. package/dist-esm/language/ditaLanguageUtils.js +659 -0
  28. package/dist-esm/language/referenceableFiles.js +108 -0
  29. package/dist-esm/mapRender.js +24 -0
  30. package/dist-esm/package.json +1 -0
  31. package/dist-esm/parser/ditaParser.js +409 -0
  32. package/dist-esm/parser/domTypes.js +1 -0
  33. package/dist-esm/parser/mapTagMap.js +77 -0
  34. package/dist-esm/parser/namedEntities.js +321 -0
  35. package/dist-esm/parser/standardTagMap.js +393 -0
  36. package/dist-esm/profiling.js +224 -0
  37. package/dist-esm/render/baseTypeMap.js +1057 -0
  38. package/dist-esm/render/cjkSpacing.js +94 -0
  39. package/dist-esm/render/mapTypeMap.js +568 -0
  40. package/dist-esm/render/renderer.js +519 -0
  41. package/dist-esm/siteRender.js +261 -0
  42. package/package.json +55 -53
  43. package/styles/TOKENS.md +59 -38
  44. package/styles/dita-content.css +1171 -1157
@@ -0,0 +1,1057 @@
1
+ // parentBaseType only reflects the immediate ancestor (entry sits under row,
2
+ // not thead), so header status is carried by an explicit ctx flag set when
3
+ // entering thead/sthead and cleared when entering tbody.
4
+ function isInTableHeader(ctx) {
5
+ return ctx.inTableHeader === true;
6
+ }
7
+ function getAttr(node, name) {
8
+ return node.attributes?.[name];
9
+ }
10
+ // Mirrors DEFAULT_NOTE_LABELS in src/editor/ditaRenderUtils.ts. Duplicated
11
+ // rather than imported to keep this module free of editor-layer
12
+ // dependencies (it's also used by the HTML export pipeline); update both
13
+ // if the label set changes.
14
+ const FALLBACK_NOTE_LABELS = {
15
+ note: 'Note', notice: 'Notice', warning: 'Warning', danger: 'Danger',
16
+ important: 'Important', tip: 'Tip', restriction: 'Restriction',
17
+ attention: 'Attention', caution: 'Caution', fastpath: 'Fastpath',
18
+ remember: 'Remember', trouble: 'Trouble',
19
+ };
20
+ function escapeAttr(s) {
21
+ return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
22
+ }
23
+ // CALS colwidth proportional notation: "N*" (e.g. "3*"), a bare "*" (= 1*),
24
+ // or "N.*"/"N.5*" with a decimal. A trailing dot with nothing after it
25
+ // ("3.*") is strictly malformed CALS, but Oxygen (and most DITA-OT
26
+ // transforms) tolerate it and just treat it as "3*" -- so this parses it
27
+ // the same way rather than silently falling through to "no colwidth", which
28
+ // used to make every column of a table with even ONE such colspec collapse
29
+ // to unweighted 'auto' sizing.
30
+ function parseColwidthStar(w) {
31
+ const m = w.match(/^(\d+(?:\.\d*)?)?\*$/);
32
+ if (!m)
33
+ return undefined;
34
+ return m[1] ? parseFloat(m[1]) : 1;
35
+ }
36
+ // Maps a CALS/DITA @align value to its direct CSS text-align equivalent.
37
+ // "char" (align relative to a specific character, e.g. lining up decimal
38
+ // points) has no simple CSS equivalent and is intentionally left
39
+ // unhandled -- falls back to whatever alignment the column/browser would
40
+ // otherwise use, rather than guessing at a character-alignment approximation.
41
+ function mapCalsAlign(value) {
42
+ return value === 'left' || value === 'right' || value === 'center' || value === 'justify' ? value : undefined;
43
+ }
44
+ // Recursively flattens an element's descendants to plain text, dropping all
45
+ // markup. Used for attribute-value contexts (alt/title) where HTML tags
46
+ // would just show up as literal escaped text if renderChildren() were used
47
+ // instead. Local to this module rather than imported from the editor/map
48
+ // layers' own copies of the same idea (extractTextFromNode/plainText) — see
49
+ // FALLBACK_NOTE_LABELS above for why src/render/ keeps its own copies.
50
+ function extractPlainText(node) {
51
+ if (node.type === 'text')
52
+ return node.text || '';
53
+ return (node.children || []).map(extractPlainText).join('');
54
+ }
55
+ function directTermText(node) {
56
+ return (node.children || [])
57
+ .filter((c) => c.type === 'text')
58
+ .map((c) => c.text || '')
59
+ .join('')
60
+ .trim();
61
+ }
62
+ /**
63
+ * Exported for the full-book search index (docsite design doc, 4.4):
64
+ * findTopLevelIndextermsInSubtree finds every independent indexterm tree in
65
+ * a topic (body and prolog/keywords alike), and this turns each one into
66
+ * its leaf-path chips -- the same two-step extraction the topic/indexterm
67
+ * renderer below already does for on-page display.
68
+ */
69
+ export function collectIndextermChips(node, ancestorPath = []) {
70
+ const ownTerm = directTermText(node);
71
+ const path = ownTerm ? [...ancestorPath, ownTerm] : ancestorPath;
72
+ const children = node.children || [];
73
+ const nestedTerms = children.filter((c) => c.type === 'element' && c.baseType === 'topic/indexterm');
74
+ const seeNodes = children.filter((c) => c.type === 'element' && (c.baseType === 'topic/index-see' || c.baseType === 'topic/index-see-also'));
75
+ const seeAnnotations = seeNodes
76
+ .map((s) => {
77
+ // index-see/index-see-also's own content is itself indexterm(s)
78
+ // naming the target entry, not plain text -- reuse the same
79
+ // extraction rather than a separate plain-text read so a
80
+ // multi-level "see" target (rare but valid) still reads correctly.
81
+ const targets = collectIndextermChips(s).map((c) => c.path.join(', '));
82
+ const label = s.baseType === 'topic/index-see-also' ? 'see also' : 'see';
83
+ return targets.length ? `${label}: ${targets.join('; ')}` : '';
84
+ })
85
+ .filter(Boolean);
86
+ if (nestedTerms.length === 0) {
87
+ return path.length > 0 ? [{ path, seeAnnotations }] : [];
88
+ }
89
+ const childChips = nestedTerms.flatMap((child) => collectIndextermChips(child, path));
90
+ // A see-annotation attached at an intermediate level (this node has both
91
+ // its own term text AND nested sub-entries) would otherwise be silently
92
+ // dropped -- surface it as its own chip alongside the leaf chips rather
93
+ // than losing it.
94
+ if (seeAnnotations.length > 0 && path.length > 0) {
95
+ return [{ path, seeAnnotations }, ...childChips];
96
+ }
97
+ return childChips;
98
+ }
99
+ /** Finds every topic/indexterm node in a subtree, but does NOT recurse
100
+ * into an indexterm's own children once found -- collectIndextermChips
101
+ * already walks that internal nesting (primary/secondary/... levels)
102
+ * itself, so recursing here too would double-collect the same entries.
103
+ * Used to pull indexterm chips out of <prolog><metadata><keywords>
104
+ * without also rendering the other, genuinely-private prolog content
105
+ * that happens to be a sibling of the keywords container. */
106
+ export function findTopLevelIndextermsInSubtree(node) {
107
+ const results = [];
108
+ for (const child of node.children || []) {
109
+ if (child.type !== 'element')
110
+ continue;
111
+ if (child.baseType === 'topic/indexterm') {
112
+ results.push(child);
113
+ continue;
114
+ }
115
+ results.push(...findTopLevelIndextermsInSubtree(child));
116
+ }
117
+ return results;
118
+ }
119
+ function renderIndextermChip(chip, ctx) {
120
+ const pathText = chip.path.map(escapeAttr).join(' \u203A ');
121
+ const seeText = chip.seeAnnotations.length
122
+ ? ` <span class="indexterm-chip__see">(${chip.seeAnnotations.map(escapeAttr).join('; ')})</span>`
123
+ : '';
124
+ const label = ctx.indexLabel || 'Index';
125
+ return `<span class="indexterm-chip" title="${escapeAttr(label)}: ${pathText}">\u{1F4D1} ${pathText}${seeText}</span>`;
126
+ }
127
+ function escapeHtml(text) {
128
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
129
+ }
130
+ // topic/foreign covers DITA's generic <foreign> element plus the MathML
131
+ // domain's <mathml> (and this project's own 'svg-container' convenience
132
+ // mapping) — see standardTagMap.ts. Its content is arbitrary raw markup
133
+ // from OUTSIDE the DITA vocabulary, so unlike every other renderer here
134
+ // (which maps a *specific known* DITA element to a *specific known* HTML
135
+ // shape), this one has to decide what to do with tag names it can't
136
+ // otherwise account for. Chromium (what VS Code's webview runs on) has
137
+ // supported MathML Core natively since Chrome 109 (Jan 2023), so real
138
+ // MathML markup — which is what DITA-OT/Oxygen actually emit here, per
139
+ // https://www.oxygenxml.com/dita/1.3/specs/langRef/technicalContent/mathml.html
140
+ // — can simply be serialized back out verbatim and left to the browser's
141
+ // own MathML renderer, rather than DITA Viewer needing to implement math
142
+ // typesetting itself.
143
+ //
144
+ // "Verbatim" is deliberately bounded, though: this is the one place in the
145
+ // renderer that takes a tag name and attribute set straight from the
146
+ // source XML and writes it into the HTML output without mapping it to a
147
+ // controlled shape first. Restricting to a real MathML tag allowlist, and
148
+ // stripping event-handler-shaped/URL-bearing attribute names regardless of
149
+ // tag, keeps a malformed or hand-edited <mathml> block from doing anything
150
+ // beyond "render as MathML (or not at all)" — it can't smuggle through an
151
+ // arbitrary tag the browser would treat as active content.
152
+ const MATHML_TAGS = new Set([
153
+ 'math', 'mrow', 'mi', 'mn', 'mo', 'mtext', 'mspace', 'ms', 'mglyph',
154
+ 'mfrac', 'msqrt', 'mroot', 'mstyle', 'merror', 'mpadded', 'mphantom',
155
+ 'mfenced', 'menclose', 'msub', 'msup', 'msubsup', 'munder', 'mover',
156
+ 'munderover', 'mmultiscripts', 'mprescripts', 'none', 'mtable', 'mtr',
157
+ 'mtd', 'mlabeledtr', 'maligngroup', 'malignmark', 'mstack', 'mlongdiv',
158
+ 'msgroup', 'msrow', 'mscarries', 'mscarry', 'msline', 'maction',
159
+ 'semantics', 'annotation', 'annotation-xml',
160
+ ]);
161
+ function isUnsafeForeignAttr(name) {
162
+ const n = name.toLowerCase();
163
+ return n.startsWith('on') || n === 'href' || n === 'src' || n === 'style' || n === 'xlink:href';
164
+ }
165
+ // Looks up a MathML attribute by its local (prefix-stripped) name -- the
166
+ // same tolerance serializeForeignContent's general attribute pass already
167
+ // applies, needed here too since <mfenced> (like everything else in this
168
+ // tree) may arrive as <m:mfenced separators="|" .../> with every attribute
169
+ // name unprefixed but the tag itself prefixed, or occasionally with a
170
+ // prefixed attribute as well.
171
+ function getForeignAttr(node, name) {
172
+ const attrs = node.attributes || {};
173
+ if (attrs[name] !== undefined)
174
+ return attrs[name];
175
+ for (const [k, v] of Object.entries(attrs)) {
176
+ if (localName(k) === name)
177
+ return v;
178
+ }
179
+ return undefined;
180
+ }
181
+ // Namespace-prefixed MathML (<mml:math>, <mml:msup>, ...) is extremely
182
+ // common in practice -- Oxygen's equation editor and MathType both export
183
+ // this shape by default -- but only the *local* part of the name is a real
184
+ // MathML tag; "mml:msup" itself will never match MATHML_TAGS. Browsers also
185
+ // don't recognize prefixed tags for the HTML math-integration point at
186
+ // all, so the prefix has to come off both for the allowlist check and for
187
+ // what actually gets written into the output, or the element silently
188
+ // falls through to the "unrecognized tag" branch below (dropping structure
189
+ // exactly like the un-fixed flatten-to-text bug this renderer exists to
190
+ // avoid).
191
+ function localName(tag) {
192
+ const i = tag.indexOf(':');
193
+ return i === -1 ? tag : tag.slice(i + 1);
194
+ }
195
+ // <mfenced> is real MathML 3, and it's how Oxygen/MathType export every
196
+ // parenthesized group and every |...| absolute-value bar -- but MathML
197
+ // Core (what Chromium, and therefore this webview and every "open in
198
+ // browser" WebHelp reader, actually implements) dropped it entirely.
199
+ // Passing it through verbatim renders as nothing: not "wrong brackets",
200
+ // the whole element and its fences silently disappear, which is exactly
201
+ // the "brackets and absolute values missing" symptom. The fix used by
202
+ // every engine that still wants mfenced to work under Core (MathJax
203
+ // included) is to expand it at serialization time into the primitives
204
+ // Core does support: an <mrow> with explicit <mo> fence/separator
205
+ // characters around the children, rather than relying on the browser to
206
+ // synthesize them from the mfenced attributes.
207
+ function expandMfenced(node) {
208
+ const openAttr = getForeignAttr(node, 'open');
209
+ const closeAttr = getForeignAttr(node, 'close');
210
+ const sepAttr = getForeignAttr(node, 'separators');
211
+ // Per the MathML 3 spec, an absent attribute gets the default fence/
212
+ // separator; an attribute present but explicitly empty (open="") means
213
+ // "no fence on this side" (used for one-sided constructs) and must stay
214
+ // empty rather than falling back to the default.
215
+ const open = openAttr !== undefined ? openAttr : '(';
216
+ const close = closeAttr !== undefined ? closeAttr : ')';
217
+ const separators = sepAttr !== undefined ? sepAttr : ',';
218
+ // Whitespace-only text nodes between tags (from source indentation/
219
+ // newlines, which the sax parser preserves as real text-node children)
220
+ // are not semantic arguments of mfenced -- only its element children
221
+ // (or text nodes with actual visible content) count as "items" that
222
+ // get fence/separator characters between them. Without this filter, a
223
+ // single-child mfenced formatted across multiple lines would pick up
224
+ // spurious extra separator characters for the whitespace "children"
225
+ // surrounding the real one.
226
+ const items = (node.children || [])
227
+ .filter((c) => c.type !== 'text' || (c.text || '').trim() !== '')
228
+ .map(serializeForeignContent);
229
+ let inner = '';
230
+ if (open !== '')
231
+ inner += `<mo>${escapeHtml(open)}</mo>`;
232
+ for (let i = 0; i < items.length; i++) {
233
+ inner += items[i];
234
+ if (i < items.length - 1 && separators !== '') {
235
+ // Fewer separator characters than gaps: the last one repeats for
236
+ // the rest, per spec. More than needed: the extras are unused.
237
+ const sepChar = separators[Math.min(i, separators.length - 1)];
238
+ inner += `<mo>${escapeHtml(sepChar)}</mo>`;
239
+ }
240
+ }
241
+ if (close !== '')
242
+ inner += `<mo>${escapeHtml(close)}</mo>`;
243
+ return `<mrow>${inner}</mrow>`;
244
+ }
245
+ function serializeForeignContent(node) {
246
+ if (node.type === 'text')
247
+ return escapeHtml(node.text || '');
248
+ const tag = localName((node.tagName || '').toLowerCase());
249
+ if (!MATHML_TAGS.has(tag)) {
250
+ // Not a tag we recognize as real MathML — don't trust it enough to
251
+ // emit as a live element, but keep any visible text rather than
252
+ // silently dropping the whole subtree.
253
+ return (node.children || []).map(serializeForeignContent).join('');
254
+ }
255
+ if (tag === 'mfenced')
256
+ return expandMfenced(node);
257
+ const attrs = Object.entries(node.attributes || {})
258
+ // xmlns / xmlns:* declarations are what produced the mml: prefix in
259
+ // the first place; now that the prefix is stripped from the tag name
260
+ // itself they're meaningless (and on re-serialized <math> would just
261
+ // be inert clutter), so drop them rather than carrying them through.
262
+ .filter(([name]) => {
263
+ const n = name.toLowerCase();
264
+ return n !== 'xmlns' && !n.startsWith('xmlns:') && !isUnsafeForeignAttr(localName(n));
265
+ })
266
+ .map(([name, value]) => safeAttr(localName(name), value))
267
+ .join('');
268
+ const inner = (node.children || []).map(serializeForeignContent).join('');
269
+ return `<${tag}${attrs}>${inner}</${tag}>`;
270
+ }
271
+ function safeAttr(name, value) {
272
+ if (value == null)
273
+ return '';
274
+ return ` ${name}="${escapeAttr(value)}"`;
275
+ }
276
+ // ── Utilities domain: image maps ─────────────────────────────────────────
277
+ // <imagemap> pairs one <image> with <area> hotspots, each declaring a
278
+ // region (<shape> + <coords>) and a destination (<xref>). The HTML
279
+ // translation is the native image-map construct the DITA element was
280
+ // designed around: the <img> carries usemap="#id", and a sibling
281
+ // <map name="id"> holds one <area shape coords href alt> per hotspot.
282
+ // Building that structure is what makes the region data clickable AND
283
+ // what keeps it off the page — the previous topic/fig + topic/figgroup
284
+ // mapping rendered the areas as visible "rect 0,0,10,10 Section 1"
285
+ // text lines with no click behavior at all.
286
+ // The <map> id needs to be unique per imagemap instance (two imagemaps
287
+ // in one rendered page would otherwise fight over the same map, and the
288
+ // browser only honors the first). A monotonic module-level counter keeps
289
+ // it deterministic and collision-free across a whole book render; it only
290
+ // needs uniqueness within one rendered document, which is also all it
291
+ // guarantees (re-renders restart the count, and separate documents never
292
+ // share a DOM).
293
+ let imagemapSequence = 0;
294
+ // Region geometry + destination for one <area>. Only shape/coords/xref
295
+ // are meaningful here (sort-as is authoring metadata for link-text
296
+ // generation and is deliberately not rendered); anything else the DTD
297
+ // allows is equally invisible in a hotspot.
298
+ function renderImageMapArea(area, ctx) {
299
+ const children = (area.children || []).filter((c) => c.type === 'element');
300
+ const shapeNode = children.find((c) => c.baseType === 'topic/shape');
301
+ const coordsNode = children.find((c) => c.baseType === 'topic/coords');
302
+ const xrefNode = children.find((c) => c.baseType === 'topic/xref');
303
+ // HTML shape keywords are case-insensitive; normalize to the canonical
304
+ // lowercase form so authoring style ("RECT", "Poly") doesn't leak into
305
+ // the markup. Whitespace between numbers is tolerated by browsers'
306
+ // coords parsing, so it's collapsed, not rejected.
307
+ const shape = shapeNode ? extractPlainText(shapeNode).trim().toLowerCase() : '';
308
+ const coords = coordsNode ? extractPlainText(coordsNode).trim().replace(/\s+/g, ' ') : '';
309
+ const rawHref = xrefNode ? getAttr(xrefNode, 'href') || '' : '';
310
+ // Three-way target resolution, mirroring topic/xref below so a hotspot
311
+ // behaves like the same link would outside an imagemap:
312
+ // same-page fragment -> real anchor; target inside the current
313
+ // book/docsite -> data-dita-book-xref (the site/book click handlers
314
+ // use closest(), which works on <area> like on any element);
315
+ // everything else -> the raw href kept on the area. Unlike topic/xref,
316
+ // which renders non-book targets as non-clickable hint spans, a
317
+ // hotspot can't opt out of being a link (an <area> without a usable
318
+ // href is a dead region, and clickable regions are the element's whole
319
+ // purpose), so the raw href stays and the webviews' image-map click
320
+ // guard (getImageMapSupportScript in ditaRenderUtils.ts) routes the
321
+ // click to the host, which resolves it like the map tree's openTopic
322
+ // handler does -- a bare relative href must never navigate the webview
323
+ // itself, that navigation is the white page.
324
+ let hrefAttr;
325
+ let bookXref;
326
+ if (rawHref) {
327
+ if (rawHref.startsWith('#')) {
328
+ hrefAttr = rawHref.includes('/') ? '#' + rawHref.split('/').pop() : rawHref;
329
+ }
330
+ else {
331
+ const bookTarget = ctx.isInCurrentBook?.(rawHref);
332
+ if (bookTarget) {
333
+ const hashIdx = rawHref.indexOf('#');
334
+ const idPart = hashIdx >= 0 ? rawHref.slice(hashIdx + 1) : '';
335
+ const anchorId = idPart ? (idPart.includes('/') ? idPart.split('/').pop() : idPart) : '';
336
+ bookXref = bookTarget + (anchorId ? '#' + anchorId : '');
337
+ // Same href="#" placeholder topic/xref uses for book-internal
338
+ // links: without an href the area isn't a link at all (no pointer
339
+ // cursor, no click), and the site/book click handlers key off
340
+ // data-dita-book-xref anyway.
341
+ hrefAttr = '#';
342
+ }
343
+ else {
344
+ hrefAttr = rawHref;
345
+ }
346
+ }
347
+ }
348
+ // Alternative text per the spec example: the <xref>'s own content is
349
+ // the link's alternative text ("Section 1 alternative text"). An empty
350
+ // xref (e.g. the spec's "pull title" comment case) falls back the same
351
+ // way topic/xref falls back for its visible text: keyref resolution,
352
+ // then the referenced document/element's title, then the raw href —
353
+ // an <area> must never end up with NO text hint at all.
354
+ let alt = xrefNode ? extractPlainText(xrefNode).trim() : '';
355
+ if (!alt && xrefNode) {
356
+ const keyref = getAttr(xrefNode, 'keyref');
357
+ if (keyref)
358
+ alt = ctx.resolveKey?.(keyref) || '';
359
+ }
360
+ if (!alt && rawHref) {
361
+ const titleId = rawHref.startsWith('#')
362
+ ? (rawHref.includes('/') ? rawHref.split('/').pop() : rawHref.slice(1))
363
+ : rawHref;
364
+ alt = ctx.resolveTitle?.(titleId) || '';
365
+ }
366
+ if (!alt)
367
+ alt = rawHref;
368
+ // title= doubles the alt text as a hover tooltip — the one affordance
369
+ // a hotspot has, since it renders no visible link text of its own.
370
+ // injectAttributes (renderer.ts) sees this title= and skips its
371
+ // generic tag-name tooltip for the element, as intended.
372
+ return `<area${safeAttr('shape', shape || undefined)}${safeAttr('coords', coords || undefined)}${safeAttr('href', hrefAttr)}${safeAttr('alt', alt || undefined)}${safeAttr('title', alt || undefined)}${bookXref ? ` data-dita-book-xref="${escapeAttr(bookXref)}"` : ''}>`;
373
+ }
374
+ export const BASE_TYPE_RENDERERS = {
375
+ 'topic/foreign': (node) => {
376
+ // No renderChildren() here — that would fall through to the generic
377
+ // "no handler for this baseType" path for every MathML tag underneath
378
+ // (none of them have a DITA baseType of their own), stripping all
379
+ // structure and leaving only flattened text. serializeForeignContent
380
+ // recurses on its own, bypassing the normal per-node baseType dispatch
381
+ // entirely for this subtree.
382
+ const inner = (node.children || []).map(serializeForeignContent).join('');
383
+ return `<span class="foreign-content">${inner}</span>`;
384
+ },
385
+ 'topic/topic': (node, ctx, renderChildren) => {
386
+ const id = getAttr(node, 'id');
387
+ return `<article${safeAttr('id', id)} class="topic">${renderChildren(node, ctx)}</article>`;
388
+ },
389
+ 'topic/title': (node, ctx, renderChildren) => {
390
+ const level = Math.min(Math.max(ctx.headingLevel, 1), 6);
391
+ // org.dita.html5 gives every title a `title` class plus a context marker:
392
+ // `topictitle{N}` for a topic's own title, `sectiontitle` for a title that
393
+ // heads a section/example. WebHelp template css keys on those, so add them
394
+ // (plan §2.4: only add, never remove). Branch on the real parent -- the
395
+ // overloaded ctx.parentBaseType would read back as 'topic/title' here.
396
+ const owner = ctx.ownerBaseType;
397
+ const titleClass = owner === 'topic/section' || owner === 'topic/example'
398
+ ? 'title sectiontitle'
399
+ : `title topictitle${level}`;
400
+ return `<h${level} class="${titleClass}">${renderChildren(node, ctx)}</h${level}>`;
401
+ },
402
+ 'topic/shortdesc': (node, ctx, renderChildren) => {
403
+ return `<p class="shortdesc">${renderChildren(node, ctx)}</p>`;
404
+ },
405
+ 'topic/body': (node, ctx, renderChildren) => {
406
+ return `<main class="body">${renderChildren(node, ctx)}</main>`;
407
+ },
408
+ 'topic/section': (node, ctx, renderChildren) => {
409
+ const id = getAttr(node, 'id');
410
+ return `<section${safeAttr('id', id)} class="section">${renderChildren(node, ctx)}</section>`;
411
+ },
412
+ 'topic/example': (node, ctx, renderChildren) => {
413
+ const id = getAttr(node, 'id');
414
+ return `<section${safeAttr('id', id)} class="example">${renderChildren(node, ctx)}</section>`;
415
+ },
416
+ 'topic/p': (_node, ctx, renderChildren) => {
417
+ return `<p class="p">${renderChildren(_node, ctx)}</p>`;
418
+ },
419
+ 'topic/itemgroup': (node, ctx, renderChildren) => {
420
+ return `<div class="itemgroup">${renderChildren(node, ctx)}</div>`;
421
+ },
422
+ 'topic/note': (node, ctx, renderChildren) => {
423
+ const type = getAttr(node, 'type') || 'note';
424
+ const spectitle = getAttr(node, 'spectitle');
425
+ const othertype = getAttr(node, 'othertype');
426
+ const labels = ctx.noteLabels || FALLBACK_NOTE_LABELS;
427
+ // spectitle always wins when present (DITA lets any note override its
428
+ // default title); otherwise type="other" falls back to @othertype
429
+ // (its label isn't a fixed string, unlike the other 12 note types);
430
+ // otherwise look up the type in the label map, or fall back to the
431
+ // raw attribute value for anything outside the known enumeration.
432
+ let label;
433
+ if (spectitle) {
434
+ label = spectitle;
435
+ }
436
+ else if (type === 'other' && othertype) {
437
+ label = othertype;
438
+ }
439
+ else {
440
+ label = labels[type] || type;
441
+ }
442
+ // Additive dual-classing (plan §2.2/§2.4): keep the own-mode `note--<type>`
443
+ // and `note__label` the built-in templates style, and add the org.dita.html5
444
+ // names WebHelp css expects -- the bare `{type}` token + `note_<type>` on the
445
+ // wrapper, `note__title` on the label, and a `note__body` wrapper around the
446
+ // content (the only structural addition, approved in the M2-8 audit).
447
+ return `<div class="note note--${escapeAttr(type)} ${escapeAttr(type)} note_${escapeAttr(type)}"><span class="note__label note__title">${escapeAttr(label)}:</span> <div class="note__body">${renderChildren(node, ctx)}</div></div>`;
448
+ },
449
+ 'topic/ul': (_node, ctx, renderChildren) => `<ul class="ul">${renderChildren(_node, ctx)}</ul>`,
450
+ 'topic/ol': (_node, ctx, renderChildren) => `<ol class="ol">${renderChildren(_node, ctx)}</ol>`,
451
+ 'topic/li': (_node, ctx, renderChildren) => `<li class="li">${renderChildren(_node, ctx)}</li>`,
452
+ 'topic/sl': (_node, ctx, renderChildren) => `<ul class="simple-list sl">${renderChildren(_node, ctx)}</ul>`,
453
+ 'topic/sli': (_node, ctx, renderChildren) => `<li class="li sli">${renderChildren(_node, ctx)}</li>`,
454
+ 'topic/dl': (_node, ctx, renderChildren) => `<dl class="dl">${renderChildren(_node, ctx)}</dl>`,
455
+ 'topic/dlentry': (_node, ctx, renderChildren) => `<div class="dlentry">${renderChildren(_node, ctx)}</div>`,
456
+ 'topic/dt': (_node, ctx, renderChildren) => `<dt class="dt dlterm">${renderChildren(_node, ctx)}</dt>`,
457
+ 'topic/dd': (_node, ctx, renderChildren) => `<dd class="dd">${renderChildren(_node, ctx)}</dd>`,
458
+ 'topic/table': (node, ctx, renderChildren) => {
459
+ const id = getAttr(node, 'id');
460
+ // If any tgroup declares colspecs, its <colgroup> gives every column an
461
+ // authoritative width -- but the default 'auto' table layout treats
462
+ // that width as only a hint: the browser still redistributes space
463
+ // based on each cell's own content (a long-unbroken run of CJK text or
464
+ // a single wide token can force its column wider than specified, at
465
+ // the expense of others), which is why some tables render with columns
466
+ // in roughly the proportions the author specified and others don't --
467
+ // it depends on what that particular table's cell content happens to
468
+ // do to the 'auto' algorithm's per-column min/max content width, not
469
+ // on anything wrong with the colspec/colwidth parsing itself. Forcing
470
+ // 'table-layout: fixed' (see styles.css's .cals-table--fixed-layout)
471
+ // makes the colgroup widths authoritative instead of a mere hint. Only
472
+ // applied when a colgroup actually exists -- tables with no colwidth
473
+ // hints at all should keep sizing themselves from content as before.
474
+ const hasColspec = (node.children || []).some((tgroup) => tgroup.type === 'element' &&
475
+ tgroup.baseType === 'topic/tgroup' &&
476
+ (tgroup.children || []).some((c) => c.type === 'element' && c.baseType === 'topic/colspec' && !!c.attributes?.colwidth));
477
+ const cls = hasColspec ? 'table cals-table cals-table--fixed-layout' : 'table cals-table';
478
+ return `<table${safeAttr('id', id)} class="${cls}">${renderChildren(node, ctx)}</table>`;
479
+ },
480
+ 'topic/tgroup': (node, ctx, renderChildren) => {
481
+ // Build column name → number map from colspec elements
482
+ const colspecs = (node.children || []).filter((c) => c.type === 'element' && c.baseType === 'topic/colspec');
483
+ const colMap = new Map();
484
+ colspecs.forEach((cs, i) => {
485
+ const colname = cs.attributes?.colname;
486
+ if (colname) {
487
+ const colnum = cs.attributes?.colnum
488
+ ? parseInt(cs.attributes.colnum, 10)
489
+ : i + 1;
490
+ colMap.set(colname, colnum);
491
+ }
492
+ });
493
+ // Table-wide default alignment (CALS @align on <tgroup>), overridden
494
+ // per-column by @align on that column's own <colspec>. Resolved once,
495
+ // up front, into an array indexed by colnum - 1, and applied per-cell
496
+ // below (an entry's own @align, when present, wins over this — see the
497
+ // cursor-tracking pass right below). NOTE: CSS explicitly restricts
498
+ // <col>/<colgroup> to only 'width', 'border', 'background' and
499
+ // 'visibility' — a <col style="text-align:...">, which an earlier
500
+ // version of this fix tried, is simply ignored by every browser, so
501
+ // this has to be threaded onto each individual <td>/<th> instead.
502
+ const tgroupAlign = mapCalsAlign(getAttr(node, 'align'));
503
+ const colAlignByIndex = colspecs.map((cs) => mapCalsAlign(cs.attributes?.align) || tgroupAlign);
504
+ // Pre-process entries: add colspan/rowspan attributes derived from
505
+ // CALS namest/nameend and morerows so the entry renderer can emit
506
+ // them as standard HTML attributes, and (when the entry has no @align
507
+ // of its own) fill in the alignment its column resolves to above, so
508
+ // the 'topic/entry' renderer's "own @align wins" check picks it up as
509
+ // if the source had declared it explicitly. Column position is
510
+ // tracked per row via a left-to-right cursor that advances by each
511
+ // entry's colspan -- this doesn't account for columns already
512
+ // occupied by an earlier row's @morerows/rowspan (CALS technically
513
+ // requires a full row/column occupancy grid for that), matching the
514
+ // same scope the existing colspan derivation below already had.
515
+ function addSpans(el) {
516
+ if (el.type !== 'element')
517
+ return el;
518
+ if (el.baseType === 'topic/row') {
519
+ let cursor = 1;
520
+ const children = (el.children || []).map((child) => {
521
+ const processed = addSpans(child);
522
+ if (processed.type !== 'element' || processed.baseType !== 'topic/entry') {
523
+ return processed;
524
+ }
525
+ const attrs = { ...processed.attributes };
526
+ const colStart = attrs.namest && colMap.has(attrs.namest) ? colMap.get(attrs.namest) : cursor;
527
+ const span = attrs.colspan ? parseInt(attrs.colspan, 10) : 1;
528
+ if (!attrs.align) {
529
+ const resolved = colAlignByIndex[colStart - 1];
530
+ if (resolved)
531
+ attrs.align = resolved;
532
+ }
533
+ cursor = colStart + (isNaN(span) || span < 1 ? 1 : span);
534
+ return { ...processed, attributes: attrs };
535
+ });
536
+ return { ...el, children };
537
+ }
538
+ const processedChildren = (el.children || []).map(addSpans);
539
+ if (el.baseType === 'topic/entry') {
540
+ const attrs = { ...el.attributes };
541
+ const { namest, nameend } = attrs;
542
+ if (namest && nameend && !attrs.colspan) {
543
+ const startCol = colMap.get(namest);
544
+ const endCol = colMap.get(nameend);
545
+ if (startCol !== undefined && endCol !== undefined) {
546
+ attrs.colspan = String(endCol - startCol + 1);
547
+ }
548
+ }
549
+ if (attrs.morerows !== undefined && !attrs.rowspan) {
550
+ const mr = parseInt(attrs.morerows, 10);
551
+ if (!isNaN(mr))
552
+ attrs.rowspan = String(mr + 1);
553
+ }
554
+ return { ...el, attributes: attrs, children: processedChildren };
555
+ }
556
+ return { ...el, children: processedChildren };
557
+ }
558
+ const processedNode = addSpans(node);
559
+ // Generate <colgroup> with column widths.
560
+ // CALS colwidth can be: "5*" or "1.5*" (proportional), "*" (= 1*),
561
+ // "50px", "30%", "2in", or a bare number (treated as pixels). Column
562
+ // alignment is handled per-cell above (in addSpans), not here -- CSS
563
+ // restricts <col> to only 'width', 'border', 'background', and
564
+ // 'visibility', so a <col style="text-align:...">, tried in an earlier
565
+ // version of this fix, is simply ignored by every browser.
566
+ let colgroup = '';
567
+ if (colspecs.length > 0) {
568
+ // Calculate total proportional parts for "*" notation
569
+ let totalStars = 0;
570
+ let hasStars = false;
571
+ for (const cs of colspecs) {
572
+ const w = cs.attributes?.colwidth;
573
+ const stars = w ? parseColwidthStar(w) : undefined;
574
+ if (stars !== undefined) {
575
+ hasStars = true;
576
+ totalStars += stars;
577
+ }
578
+ }
579
+ const cols = colspecs
580
+ .map((cs) => {
581
+ const w = cs.attributes?.colwidth;
582
+ if (!w)
583
+ return '<col>';
584
+ // Convert CALS proportional notation (N*) to percentage
585
+ const stars = parseColwidthStar(w);
586
+ if (stars !== undefined && hasStars && totalStars > 0) {
587
+ return `<col style="width: ${((stars / totalStars) * 100).toFixed(2)}%">`;
588
+ }
589
+ // Bare number → treat as pixels
590
+ if (/^\d+(?:\.\d+)?$/.test(w)) {
591
+ return `<col style="width: ${escapeAttr(w)}px">`;
592
+ }
593
+ // Pass through CSS-compatible values (px, %, em, in, cm, etc.)
594
+ return `<col style="width: ${escapeAttr(w)}">`;
595
+ })
596
+ .join('');
597
+ colgroup = `<colgroup>${cols}</colgroup>`;
598
+ }
599
+ // Render non-colspec children (thead, tbody, tfoot)
600
+ const childCtx = { ...ctx, parentBaseType: 'topic/tgroup' };
601
+ const nodeWithoutColspec = {
602
+ ...processedNode,
603
+ children: (processedNode.children || []).filter((c) => !(c.type === 'element' && c.baseType === 'topic/colspec')),
604
+ };
605
+ return colgroup + renderChildren(nodeWithoutColspec, childCtx);
606
+ },
607
+ 'topic/colspec': () => '',
608
+ 'topic/thead': (_node, ctx, renderChildren) => `<thead class="thead">${renderChildren(_node, { ...ctx, inTableHeader: true })}</thead>`,
609
+ 'topic/tbody': (_node, ctx, renderChildren) => `<tbody class="tbody">${renderChildren(_node, { ...ctx, inTableHeader: false })}</tbody>`,
610
+ 'topic/row': (_node, ctx, renderChildren) => `<tr class="row">${renderChildren(_node, ctx)}</tr>`,
611
+ 'topic/entry': (node, ctx, renderChildren) => {
612
+ const tag = isInTableHeader(ctx) ? 'th' : 'td';
613
+ const colspan = getAttr(node, 'colspan');
614
+ const rowspan = getAttr(node, 'rowspan');
615
+ // Overrides the column's own alignment (set via <colspec>/<tgroup>
616
+ // @align, see 'topic/tgroup' above) for just this cell, same as CALS
617
+ // precedence: entry > colspec > tgroup.
618
+ const align = mapCalsAlign(getAttr(node, 'align'));
619
+ const attrs = ` class="entry"${safeAttr('colspan', colspan)}${safeAttr('rowspan', rowspan)}${align ? ` style="text-align: ${align}"` : ''}`;
620
+ return `<${tag}${attrs}>${renderChildren(node, ctx)}</${tag}>`;
621
+ },
622
+ 'topic/simpletable': (node, ctx, renderChildren) => {
623
+ const id = getAttr(node, 'id');
624
+ return `<table${safeAttr('id', id)} class="simple-table simpletable">${renderChildren(node, ctx)}</table>`;
625
+ },
626
+ 'topic/sthead': (_node, ctx, renderChildren) => `<thead class="sthead">${renderChildren(_node, { ...ctx, inTableHeader: true })}</thead>`,
627
+ 'topic/strow': (_node, ctx, renderChildren) => `<tr class="strow">${renderChildren(_node, { ...ctx, inTableHeader: false })}</tr>`,
628
+ 'topic/stentry': (node, ctx, renderChildren) => {
629
+ const tag = isInTableHeader(ctx) ? 'th' : 'td';
630
+ return `<${tag} class="stentry">${renderChildren(node, ctx)}</${tag}>`;
631
+ },
632
+ 'topic/image': (node, ctx) => {
633
+ const href = getAttr(node, 'href') || '';
634
+ const placement = getAttr(node, 'placement') || 'inline';
635
+ let width = getAttr(node, 'width');
636
+ let height = getAttr(node, 'height');
637
+ const scale = getAttr(node, 'scale');
638
+ const scalefit = getAttr(node, 'scalefit');
639
+ // Captured before the natural-dimensions fallback below overwrites
640
+ // width/height for aspect-ratio reservation, so the @scale gate further
641
+ // down can still tell "the author actually gave a size" apart from "we
642
+ // filled one in ourselves" — see the bug this fixes at that gate.
643
+ const hadAuthorSize = !!(width || height);
644
+ // Author-specified @width/@height on the <image> element always wins;
645
+ // only fall back to the file's own natural dimensions (read from disk,
646
+ // not decoded from the loaded image — see readImageDimensions) when
647
+ // neither is given, purely to reserve the right aspect-ratio box
648
+ // before the browser has actually loaded the image (this project's
649
+ // own img{height:auto} means a bare width/height attribute doesn't
650
+ // force a fixed pixel size, it just informs the aspect ratio while
651
+ // max-width:100% still scales the box down responsively as usual).
652
+ if (!width && !height && href && ctx.getImageDimensions) {
653
+ const natural = ctx.getImageDimensions(href);
654
+ if (natural) {
655
+ width = String(natural.width);
656
+ height = String(natural.height);
657
+ }
658
+ }
659
+ // DITA allows alt text as both the @alt attribute and a richer <alt>
660
+ // child element (topic/alt) — the child can carry formatted content
661
+ // (ph, draft-comment, etc.) and takes precedence when present. Neither
662
+ // present -> alt stays undefined so safeAttr omits the attribute
663
+ // entirely, rather than always emitting alt="" regardless of whether
664
+ // the author gave any alt info at all.
665
+ const altChild = (node.children || []).find((c) => c.type === 'element' && c.baseType === 'topic/alt');
666
+ const altFromChild = altChild ? extractPlainText(altChild).trim() : '';
667
+ const alt = altFromChild || getAttr(node, 'alt');
668
+ const extra = `${safeAttr('width', width)}${safeAttr('height', height)}`;
669
+ const imgSrc = href ? ctx.asWebviewUri(href) : '';
670
+ const cls = placement === 'break' ? ' class="image image-break"' : ' class="image"';
671
+ // @scale sizes the image relative to its OWN natural dimensions, not
672
+ // the container — expressed via the CSS custom property --dita-scale,
673
+ // which styles.css combines with the toolbar's preview-only zoom via
674
+ // the CSS 'zoom' property (reflows the box, unlike transform:scale).
675
+ // Explicit width/height are a more specific instruction and win over
676
+ // scale when given. @scalefit="yes" means "prioritize fitting the
677
+ // available width", which this project already does by default for
678
+ // every image (img{max-width:100%}); so scalefit=yes just needs to
679
+ // suppress scale/width/height rather than actively doing anything.
680
+ let scaleStyle;
681
+ if (scalefit !== 'yes' && scale && !hadAuthorSize) {
682
+ const pct = parseFloat(scale);
683
+ if (!isNaN(pct) && pct > 0) {
684
+ scaleStyle = `--dita-scale:${pct / 100}`;
685
+ }
686
+ }
687
+ // Preview-default downscale flag: for an image with no @scale/@width/
688
+ // @height of its own, the preview should start smaller than full size
689
+ // -- but @scale's zoom-relative-to-natural-size mechanism above is the
690
+ // wrong tool for this, because zoom only shrinks what's already fitting
691
+ // under the container's max-width:100% clamp. A large image already
692
+ // being clamped down to the container's width stays clamped to that
693
+ // same width after a zoom<1 is applied (natural-size * zoom can still
694
+ // exceed the container), so "shrink by X%" would visibly do nothing
695
+ // for exactly the images most in need of shrinking. The actual pixel
696
+ // width of that clamped box is only known in the browser, at layout
697
+ // time -- see the webview script's use of this attribute, which reads
698
+ // getBoundingClientRect() (the same measurement the zoom toolbar's
699
+ // "100%" already means) and applies the reduction from there instead.
700
+ const useDefaultPreviewScale = scalefit !== 'yes' && !scale && !hadAuthorSize;
701
+ const altAttr = alt !== undefined ? safeAttr('alt', alt) : '';
702
+ const titleAttr = alt ? safeAttr('title', alt) : '';
703
+ const styleAttr = safeAttr('style', scaleStyle);
704
+ const defaultScaleAttr = useDefaultPreviewScale ? ' data-dita-default-scale="1"' : '';
705
+ return `<img src="${escapeAttr(imgSrc)}"${altAttr}${titleAttr}${extra}${cls}${styleAttr}${defaultScaleAttr} loading="lazy" data-dita-src="${escapeAttr(href)}">`;
706
+ },
707
+ 'topic/fig': (node, ctx, renderChildren) => {
708
+ const id = getAttr(node, 'id');
709
+ const titleNode = (node.children || []).find((c) => c.type === 'element' && c.baseType === 'topic/title');
710
+ const rest = (node.children || []).filter((c) => !(c.type === 'element' && c.baseType === 'topic/title'));
711
+ const figContent = renderChildren({ ...node, children: rest }, ctx);
712
+ const figCaption = titleNode
713
+ ? `<figcaption>${renderChildren(titleNode, { ...ctx, headingLevel: ctx.headingLevel + 1 })}</figcaption>`
714
+ : '';
715
+ return `<figure${safeAttr('id', id)} class="fig">${figContent}${figCaption}</figure>`;
716
+ },
717
+ // ── Utilities domain: image maps ── renderers below; the shared helpers
718
+ // (imagemapSequence + renderImageMapArea) live just above this object.
719
+ 'topic/imagemap': (node, ctx, renderChildren) => {
720
+ const id = getAttr(node, 'id');
721
+ const children = (node.children || []).filter((c) => c.type === 'element');
722
+ const titleNode = children.find((c) => c.baseType === 'topic/title');
723
+ const imageNode = children.find((c) => c.baseType === 'topic/image');
724
+ const areaNodes = children.filter((c) => c.baseType === 'topic/area');
725
+ imagemapSequence += 1;
726
+ const mapId = `dita-imagemap-${imagemapSequence}`;
727
+ // The hotspot image reuses the full topic/image renderer — webview URI
728
+ // resolution, natural-dimension reservation, @width/@height/@scale,
729
+ // <alt> handling — then gains the usemap binding. The renderer's
730
+ // data-dita-default-scale marker is stripped for imagemap images: that
731
+ // marker triggers the webview's cosmetic "start smaller" shrink, and a
732
+ // shrunken image would leave every <area> hit region misaligned with
733
+ // the pixels underneath (browsers don't rescale map coordinates for
734
+ // CSS-resized images). Keeping the image at its natural/author size is
735
+ // what keeps the coordinates honest; the zoom toolbar remains
736
+ // available for deliberate inspection.
737
+ let imgHtml = '';
738
+ if (imageNode) {
739
+ imgHtml = BASE_TYPE_RENDERERS['topic/image'](imageNode, ctx, renderChildren);
740
+ imgHtml = imgHtml.replace(/^<img/, `<img usemap="#${escapeAttr(mapId)}"`);
741
+ imgHtml = imgHtml.replace(/ data-dita-default-scale="1"/g, '');
742
+ }
743
+ const mapHtml = `<map${safeAttr('name', mapId)}${safeAttr('id', mapId)}>${areaNodes.map((a) => renderImageMapArea(a, ctx)).join('')}</map>`;
744
+ const figCaption = titleNode
745
+ ? `<figcaption>${renderChildren(titleNode, { ...ctx, headingLevel: ctx.headingLevel + 1 })}</figcaption>`
746
+ : '';
747
+ return `<figure${safeAttr('id', id)} class="fig imagemap">${imgHtml}${mapHtml}${figCaption}</figure>`;
748
+ },
749
+ // Standalone <area> (not inside an <imagemap>) has no image to attach
750
+ // its region to — any output would be an invisible no-op element or a
751
+ // stray link, so render nothing, same convention as the index-see family
752
+ // of parent-consumed elements. Valid markup never reaches here: the
753
+ // imagemap renderer above walks its own area children directly.
754
+ 'topic/area': () => '',
755
+ // shape/coords text is region data consumed by renderImageMapArea above;
756
+ // visited standalone they can only be malformed markup, and echoing
757
+ // "rect" / "0,0,10,10" into the page is exactly the bug this renderer
758
+ // pair exists to fix.
759
+ 'topic/shape': () => '',
760
+ 'topic/coords': () => '',
761
+ 'topic/codeblock': (node, ctx, renderChildren) => {
762
+ const outputClass = getAttr(node, 'outputclass') || '';
763
+ const lang = outputClass.replace(/^language-/, '');
764
+ const pre = `<pre class="pre codeblock ${escapeAttr(outputClass)}"><code>${renderChildren(node, ctx)}</code></pre>`;
765
+ if (!lang)
766
+ return pre;
767
+ // The label used to live *inside* <pre>, which has overflow-x:auto for
768
+ // wide code -- an absolutely-positioned child of a scrolling element
769
+ // scrolls along with that element's content, so the label drifted off
770
+ // to the left as soon as the user scrolled the code horizontally
771
+ // instead of staying pinned to the corner. Moving it to a sibling of
772
+ // <pre>, wrapped in a non-scrolling container, keeps it fixed in place;
773
+ // .codeblock-wrap in styles.css supplies the positioning context.
774
+ const langLabel = `<div class="codeblock-lang">${escapeAttr(lang)}</div>`;
775
+ return `<div class="codeblock-wrap">${pre}${langLabel}</div>`;
776
+ },
777
+ 'topic/pre': (_node, ctx, renderChildren) => `<pre class="pre preformatted">${renderChildren(_node, ctx)}</pre>`,
778
+ 'topic/xref': (node, ctx, renderChildren) => {
779
+ const href = getAttr(node, 'href') || '';
780
+ // No target at all: an xref with neither @href nor a keyref that
781
+ // resolves to one. Dropping the element silently (the old behaviour)
782
+ // hid both the author's text and the broken reference; keeping it
783
+ // visible -- its own content when it has any, an unresolved-key hint
784
+ // when it does not (the same treatment topic/ph gives an unresolved
785
+ // keyref) -- means a broken xref reads as one instead of vanishing.
786
+ if (!href) {
787
+ if (node.children.length > 0) {
788
+ const content = renderChildren(node, ctx);
789
+ const keyref = getAttr(node, 'keyref');
790
+ return keyref
791
+ ? `<span class="xref unresolved-keyref" title="Unresolved key: ${escapeAttr(keyref)}">${content}</span>`
792
+ : `<span class="xref">${content}</span>`;
793
+ }
794
+ const keyref = getAttr(node, 'keyref');
795
+ if (!keyref)
796
+ return '';
797
+ return `<span class="xref unresolved-keyref" title="Unresolved key: ${escapeAttr(keyref)}">[${escapeAttr(keyref)}]</span>`;
798
+ }
799
+ let content;
800
+ if (node.children.length > 0) {
801
+ content = renderChildren(node, ctx);
802
+ }
803
+ else if (href.startsWith('#')) {
804
+ const id = href.includes('/') ? href.split('/').pop() : href.slice(1);
805
+ content = escapeAttr(ctx.resolveTitle?.(id) ?? '') || escapeAttr(href);
806
+ }
807
+ else {
808
+ // Cross-file reference (with or without fragment):
809
+ // try to resolve the referenced document's title
810
+ content = escapeAttr(ctx.resolveTitle?.(href) ?? '') || escapeAttr(href);
811
+ }
812
+ if (href.startsWith('#')) {
813
+ const anchor = href.includes('/') ? '#' + href.split('/').pop() : href;
814
+ return `<a href="${escapeAttr(anchor)}" class="xref">${content}</a>`;
815
+ }
816
+ // Cross-file: when the target topic is part of the book/docsite this
817
+ // topic is itself being rendered as part of, isInCurrentBook resolves
818
+ // it to an absolute path and this becomes a real, clickable link
819
+ // instead of the plain hint text below -- the webview's click handler
820
+ // reads data-dita-book-xref to ask the extension host to switch pages
821
+ // (see getSiteNavClickHandlerScript in ditaRenderUtils.ts). The
822
+ // anchor id reuses the same "last path segment" convention the
823
+ // same-page branch above already uses, so a nested
824
+ // "topicId/elementId" fragment still resolves to the specific element
825
+ // to scroll to, not just the topic root.
826
+ const bookTarget = ctx.isInCurrentBook?.(href);
827
+ if (bookTarget) {
828
+ const hashIdx = href.indexOf('#');
829
+ const idPart = hashIdx >= 0 ? href.slice(hashIdx + 1) : '';
830
+ const anchorId = idPart ? (idPart.includes('/') ? idPart.split('/').pop() : idPart) : '';
831
+ const target = bookTarget + (anchorId ? '#' + anchorId : '');
832
+ return `<a href="#" class="xref" data-dita-book-xref="${escapeAttr(target)}">${content}</a>`;
833
+ }
834
+ // Standalone preview opt-in (clickableExternalXrefs, no book context):
835
+ // keep the target's own href and let the webview hand it to the host,
836
+ // which opens DITA targets in their preview and everything else in the
837
+ // right place (see openHrefTarget) -- instead of the dead hint span.
838
+ // Without the opt-in (export, diff, book/site, the second host) the
839
+ // historical non-clickable hint below is kept exactly as it was.
840
+ if (ctx.clickableExternalXrefs) {
841
+ return `<a href="#" class="xref" data-dita-href="${escapeAttr(href)}">${content}</a>`;
842
+ }
843
+ return `<span class="xref-external">→ ${content}</span>`;
844
+ },
845
+ 'topic/link': (node, ctx, renderChildren) => {
846
+ const href = getAttr(node, 'href');
847
+ const keyref = getAttr(node, 'keyref');
848
+ const target = href || keyref || '';
849
+ if (!target)
850
+ return renderChildren(node, ctx);
851
+ return `<a href="${escapeAttr(target)}" class="link">${renderChildren(node, ctx)}</a>`;
852
+ },
853
+ 'topic/linktext': (_node, ctx, renderChildren) => renderChildren(_node, ctx),
854
+ 'topic/related-links': (_node, ctx, renderChildren) => `<aside class="related-links"><h2>Related links</h2>${renderChildren(_node, ctx)}</aside>`,
855
+ 'topic/b': (_node, ctx, renderChildren) => `<strong class="ph b">${renderChildren(_node, ctx)}</strong>`,
856
+ 'topic/i': (_node, ctx, renderChildren) => `<em class="ph i">${renderChildren(_node, ctx)}</em>`,
857
+ 'topic/u': (_node, ctx, renderChildren) => `<u class="ph u">${renderChildren(_node, ctx)}</u>`,
858
+ 'topic/tt': (_node, ctx, renderChildren) => `<code class="ph tt">${renderChildren(_node, ctx)}</code>`,
859
+ 'topic/sup': (_node, ctx, renderChildren) => `<sup class="ph sup">${renderChildren(_node, ctx)}</sup>`,
860
+ 'topic/sub': (_node, ctx, renderChildren) => `<sub class="ph sub">${renderChildren(_node, ctx)}</sub>`,
861
+ // Highlight domain additions (specialize topic/ph; given element-specific
862
+ // baseTypes + renderers so the visual styling survives even when the class
863
+ // attribute is omitted from the XML — same approach as b/i/u above).
864
+ // line-through maps to the semantic <s> element (zero CSS, like b→<strong>);
865
+ // overline has no semantic HTML element, so it uses a .overline CSS class
866
+ // (defined in styles.css) instead of an inline style so themes can override it.
867
+ // Both are hi-d specialisations of ph, so (like b/i/u/tt/sup/sub) they carry the
868
+ // html5 `ph` token. overline is the one hi-d member rendered as a <span>, so
869
+ // styles.css excludes it from the span.ph dimming rule with :not(.overline).
870
+ 'topic/line-through': (_node, ctx, renderChildren) => `<s class="ph line-through">${renderChildren(_node, ctx)}</s>`,
871
+ 'topic/overline': (_node, ctx, renderChildren) => `<span class="ph overline">${renderChildren(_node, ctx)}</span>`,
872
+ 'topic/q': (_node, ctx, renderChildren) => `<q class="q">${renderChildren(_node, ctx)}</q>`,
873
+ 'topic/lq': (_node, ctx, renderChildren) => `<blockquote class="lq">${renderChildren(_node, ctx)}</blockquote>`,
874
+ 'topic/keyword': (_node, ctx, renderChildren) => `<span class="keyword">${renderChildren(_node, ctx)}</span>`,
875
+ 'topic/term': (_node, ctx, renderChildren) => `<span class="term">${renderChildren(_node, ctx)}</span>`,
876
+ 'topic/ph': (node, ctx, renderChildren) => {
877
+ const keyref = getAttr(node, 'keyref');
878
+ const hasContent = (node.children || []).some((c) => c.type === 'element' || (c.text || '').trim() !== '');
879
+ // Content wins over keyref (DITA spec). An empty ph with a resolvable
880
+ // keyref is substituted upstream; reaching here empty means unresolved.
881
+ if (keyref && !hasContent && ctx.resolveKey) {
882
+ const resolved = ctx.resolveKey(keyref);
883
+ if (resolved)
884
+ return `<span class="ph">${escapeAttr(resolved)}</span>`;
885
+ return `<span class="ph unresolved-keyref" title="Unresolved key: ${escapeAttr(keyref)}">[${escapeAttr(keyref)}]</span>`;
886
+ }
887
+ return `<span class="ph">${renderChildren(node, ctx)}</span>`;
888
+ },
889
+ // UI elements
890
+ 'topic/uicontrol': (_node, ctx, renderChildren) => `<span class="uicontrol">${renderChildren(_node, ctx)}</span>`,
891
+ 'topic/wintitle': (_node, ctx, renderChildren) => `<span class="wintitle">${renderChildren(_node, ctx)}</span>`,
892
+ 'topic/menucascade': (_node, ctx, renderChildren) => `<span class="menucascade">${renderChildren(_node, ctx)}</span>`,
893
+ // Computer interaction
894
+ 'topic/filepath': (_node, ctx, renderChildren) => `<span class="filepath">${renderChildren(_node, ctx)}</span>`,
895
+ 'topic/userinput': (_node, ctx, renderChildren) => `<span class="userinput">${renderChildren(_node, ctx)}</span>`,
896
+ 'topic/systemoutput': (_node, ctx, renderChildren) => `<span class="systemoutput">${renderChildren(_node, ctx)}</span>`,
897
+ // API & code references
898
+ 'topic/apiname': (_node, ctx, renderChildren) => `<span class="apiname">${renderChildren(_node, ctx)}</span>`,
899
+ 'topic/option': (_node, ctx, renderChildren) => `<span class="option">${renderChildren(_node, ctx)}</span>`,
900
+ 'topic/parmname': (_node, ctx, renderChildren) => `<span class="parmname">${renderChildren(_node, ctx)}</span>`,
901
+ 'topic/cmdname': (_node, ctx, renderChildren) => `<span class="cmdname">${renderChildren(_node, ctx)}</span>`,
902
+ 'topic/varname': (_node, ctx, renderChildren) => `<span class="varname">${renderChildren(_node, ctx)}</span>`,
903
+ 'topic/msgnum': (_node, ctx, renderChildren) => `<span class="msgnum">${renderChildren(_node, ctx)}</span>`,
904
+ // Programming domain additions
905
+ 'topic/codeph': (_node, ctx, renderChildren) => `<code class="codeph">${renderChildren(_node, ctx)}</code>`,
906
+ 'topic/coderef': (_node, ctx, renderChildren) => `<span class="coderef">${renderChildren(_node, ctx)}</span>`,
907
+ 'topic/synph': (_node, ctx, renderChildren) => `<span class="synph">${renderChildren(_node, ctx)}</span>`,
908
+ 'topic/kwd': (_node, ctx, renderChildren) => `<span class="kwd">${renderChildren(_node, ctx)}</span>`,
909
+ 'topic/var': (_node, ctx, renderChildren) => `<span class="var">${renderChildren(_node, ctx)}</span>`,
910
+ 'topic/oper': (_node, ctx, renderChildren) => `<span class="oper">${renderChildren(_node, ctx)}</span>`,
911
+ 'topic/sep': (_node, ctx, renderChildren) => `<span class="sep">${renderChildren(_node, ctx)}</span>`,
912
+ 'topic/delim': (_node, ctx, renderChildren) => `<span class="delim">${renderChildren(_node, ctx)}</span>`,
913
+ 'topic/fragment': (_node, ctx, renderChildren) => `<span class="fragment">${renderChildren(_node, ctx)}</span>`,
914
+ 'topic/fragref': (_node, ctx, renderChildren) => `<span class="fragref">${renderChildren(_node, ctx)}</span>`,
915
+ // synblk specialises figgroup (not pre): class is `figgroup synblk`. The <pre>
916
+ // element stays so the syntax text keeps its whitespace.
917
+ 'topic/synblk': (_node, ctx, renderChildren) => `<pre class="figgroup synblk">${renderChildren(_node, ctx)}</pre>`,
918
+ 'topic/synnote': (_node, ctx, renderChildren) => `<div class="synnote">${renderChildren(_node, ctx)}</div>`,
919
+ 'topic/synnoteref': (_node, ctx, renderChildren) => `<span class="synnoteref">${renderChildren(_node, ctx)}</span>`,
920
+ 'topic/syntaxdiagram': (_node, ctx, renderChildren) => `<div class="syntaxdiagram">${renderChildren(_node, ctx)}</div>`,
921
+ // Software domain
922
+ 'topic/screen': (_node, ctx, renderChildren) => `<pre class="pre screen">${renderChildren(_node, ctx)}</pre>`,
923
+ 'topic/msgph': (_node, ctx, renderChildren) => `<span class="msgph">${renderChildren(_node, ctx)}</span>`,
924
+ 'topic/msgblock': (_node, ctx, renderChildren) => `<pre class="pre msgblock">${renderChildren(_node, ctx)}</pre>`,
925
+ // Common body elements
926
+ 'topic/lines': (_node, ctx, renderChildren) => `<pre class="pre lines">${renderChildren(_node, ctx)}</pre>`,
927
+ 'topic/fn': (node, ctx, renderChildren) => {
928
+ const id = getAttr(node, 'id');
929
+ const cls = id ? ` fn-call-${escapeAttr(id)}` : '';
930
+ return `<sup class="fn${cls}">${renderChildren(node, ctx)}</sup>`;
931
+ },
932
+ 'topic/cite': (_node, ctx, renderChildren) => `<cite class="cite">${renderChildren(_node, ctx)}</cite>`,
933
+ 'topic/boolean': (node, ctx, renderChildren) => {
934
+ const val = getAttr(node, 'value') || '';
935
+ return `<span class="boolean" data-value="${escapeAttr(val)}">${escapeAttr(val) || renderChildren(node, ctx)}</span>`;
936
+ },
937
+ 'topic/tm': (_node, ctx, renderChildren) => `<span class="tm">${renderChildren(_node, ctx)}</span>`,
938
+ // Index terms carried no visual representation at all before this --
939
+ // <indexterm> rendered to '', so authored index entries were invisible
940
+ // in preview even though they're routinely used to check placement and
941
+ // wording while writing. This renders each indexterm as a small inline
942
+ // chip showing its full term path (indexterm nesting encodes
943
+ // primary/secondary/tertiary levels: <indexterm>A<indexterm>B</indexterm>
944
+ // </indexterm> means "A, B" as a two-level entry), plus any index-see/
945
+ // index-see-also cross-reference. Deliberately NOT a compiled, sorted
946
+ // index page the way a printed book's back-of-book index works --
947
+ // sorting only makes sense for scripts with a stable alphabetic/stroke
948
+ // order, and silently doing nothing useful (or something arbitrary) for
949
+ // e.g. Chinese content would be worse than not having a generated index
950
+ // at all. Showing the term(s) inline, right where they're authored, is
951
+ // useful in every language and needs no sort-order decision.
952
+ 'topic/indexterm': (node, ctx) => ctx.suppressIndexterm ? '' : collectIndextermChips(node).map((chip) => renderIndextermChip(chip, ctx)).join(''),
953
+ 'topic/indextermref': (node) => {
954
+ const key = getAttr(node, 'keyref');
955
+ return key ? `<span class="indexterm-chip indexterm-chip--ref" title="indextermref">\u{1F4D1} ${escapeAttr(key)}</span>` : '';
956
+ },
957
+ // index-see / index-see-also / index-sort-as are only ever meaningful as
958
+ // children consumed directly by their parent topic/indexterm's own
959
+ // renderer above (collectIndextermChips walks node.children itself
960
+ // rather than going through the generic renderChildren dispatch for
961
+ // these) -- if one of these somehow gets visited on its own (malformed
962
+ // markup with the referencing indexterm parent missing, or ctx.uiLanguage
963
+ // paths hitting some node.children traversal outside indexterm's own
964
+ // renderer), rendering empty is right: there is no sensible standalone
965
+ // presentation for "the target of a see-reference" with no surrounding
966
+ // indexterm chip to attach it to.
967
+ 'topic/index-see': () => '',
968
+ 'topic/index-see-also': () => '',
969
+ 'topic/index-sort-as': () => '',
970
+ 'topic/index-base': () => '',
971
+ 'topic/div': (_node, ctx, renderChildren) => `<div class="body-div div">${renderChildren(_node, ctx)}</div>`,
972
+ 'topic/sectiondiv': (_node, ctx, renderChildren) => `<div class="section-div sectiondiv">${renderChildren(_node, ctx)}</div>`,
973
+ 'topic/bodydiv': (_node, ctx, renderChildren) => `<div class="body-div bodydiv">${renderChildren(_node, ctx)}</div>`,
974
+ // Generic grouping container (programming domain
975
+ // groupchoice/groupcomp/groupseq alternatives). Same block treatment as
976
+ // bodydiv/sectiondiv — no distinct visual semantics of its own.
977
+ // (Image-map <area> groups no longer land here — see topic/imagemap
978
+ // above, which builds the real <map>/<area> structure.)
979
+ 'topic/figgroup': (_node, ctx, renderChildren) => `<div class="figgroup">${renderChildren(_node, ctx)}</div>`,
980
+ 'topic/desc': (_node, ctx, renderChildren) => `<span class="desc">${renderChildren(_node, ctx)}</span>`,
981
+ 'topic/alt': (_node, ctx, renderChildren) => `<span class="alt">${renderChildren(_node, ctx)}</span>`,
982
+ // Parameter lists
983
+ 'topic/parml': (_node, ctx, renderChildren) => `<dl class="parml">${renderChildren(_node, ctx)}</dl>`,
984
+ 'topic/plentry': (_node, ctx, renderChildren) => `<div class="plentry">${renderChildren(_node, ctx)}</div>`,
985
+ 'topic/pt': (_node, ctx, renderChildren) => `<dt class="pt">${renderChildren(_node, ctx)}</dt>`,
986
+ 'topic/pd': (_node, ctx, renderChildren) => `<dd class="pd">${renderChildren(_node, ctx)}</dd>`,
987
+ // Abbreviation & glossary
988
+ 'topic/abbreviated-form': (node, ctx, renderChildren) => {
989
+ const keyref = getAttr(node, 'keyref');
990
+ if (keyref && ctx.resolveKey)
991
+ return `<abbr class="abbreviated-form" title="${escapeAttr(keyref)}">${escapeAttr(ctx.resolveKey(keyref) || keyref)}</abbr>`;
992
+ return `<abbr class="abbreviated-form">${renderChildren(node, ctx)}</abbr>`;
993
+ },
994
+ 'topic/glossterm': (_node, ctx, renderChildren) => `<dfn class="glossterm">${renderChildren(_node, ctx)}</dfn>`,
995
+ 'topic/glossdef': (_node, ctx, renderChildren) => `<dd class="glossdef">${renderChildren(_node, ctx)}</dd>`,
996
+ 'topic/glossentry': (_node, ctx, renderChildren) => `<dl class="glossentry">${renderChildren(_node, ctx)}</dl>`,
997
+ 'topic/glossref': (_node, ctx, renderChildren) => `<span class="glossref">${renderChildren(_node, ctx)}</span>`,
998
+ 'topic/glossgroup': (_node, ctx, renderChildren) => `<div class="glossgroup">${renderChildren(_node, ctx)}</div>`,
999
+ // Hazard
1000
+ 'topic/hazardstatement': (node, ctx, renderChildren) => `<div class="hazardstatement">${renderChildren(node, ctx)}</div>`,
1001
+ 'topic/typeofhazard': (_node, ctx, renderChildren) => `<span class="typeofhazard">${renderChildren(_node, ctx)}</span>`,
1002
+ 'topic/hazardsymbol': () => '',
1003
+ 'topic/howtoavoid': (_node, ctx, renderChildren) => `<p class="howtoavoid">${renderChildren(_node, ctx)}</p>`,
1004
+ 'topic/consequence': (_node, ctx, renderChildren) => `<p class="consequence">${renderChildren(_node, ctx)}</p>`,
1005
+ // Multimedia
1006
+ 'topic/object': (_node, ctx, renderChildren) => `<object class="dita-object object">${renderChildren(_node, ctx)}</object>`,
1007
+ 'topic/param': () => '',
1008
+ // Anchors
1009
+ 'topic/anchor': (node) => {
1010
+ const id = getAttr(node, 'id');
1011
+ return id ? `<a${safeAttr('id', id)}></a>` : '';
1012
+ },
1013
+ 'topic/anchorid': (node) => {
1014
+ const id = getAttr(node, 'id');
1015
+ return id ? `<span${safeAttr('id', id)}></span>` : '';
1016
+ },
1017
+ 'topic/anchorkey': () => '',
1018
+ 'topic/anchorref': () => '',
1019
+ // Prolog — metadata container (author, critdates, permissions, metadata,
1020
+ // keywords, etc.). Entirely non-display; swallow the whole subtree so
1021
+ // nothing leaks into the body preview. Mirrors the anchorkey/anchorref
1022
+ // pattern. Evidence: base/dtd/commonElementMod.ent — class
1023
+ // "- topic/prolog " — appears between title and body in topic/concept/
1024
+ // task/reference. Without this entry the fallback renderer recurses into
1025
+ // children, causing author/keyword content to appear in the body.
1026
+ //
1027
+ // EXCEPT <indexterm>: declaring topic-level index entries inside
1028
+ // <prolog><metadata><keywords> (rather than as an inline marker inside
1029
+ // <body>) is a very common, arguably more common, real-world authoring
1030
+ // pattern -- and blanket-suppressing all of prolog meant those index
1031
+ // entries were silently invisible in preview for exactly that pattern,
1032
+ // even though the whole point of adding indexterm rendering (see
1033
+ // topic/indexterm below) was to make them visible. Every OTHER prolog
1034
+ // descendant (author, critdates, plain keyword text meant only for
1035
+ // search metadata, etc.) is still fully suppressed -- only indexterm
1036
+ // chips get pulled out.
1037
+ 'topic/prolog': (node, ctx) => {
1038
+ if (ctx.suppressIndexterm)
1039
+ return '';
1040
+ const topLevelTerms = findTopLevelIndextermsInSubtree(node);
1041
+ if (topLevelTerms.length === 0)
1042
+ return '';
1043
+ const chips = topLevelTerms
1044
+ .flatMap((termNode) => collectIndextermChips(termNode))
1045
+ .map((chip) => renderIndextermChip(chip, ctx))
1046
+ .join('');
1047
+ return chips ? `<div class="indexterm-chip-group" title="${escapeAttr(ctx.indexLabel || 'Index')}">${chips}</div>` : '';
1048
+ },
1049
+ // These three (topic/keywords, topic/metadata, topic/publisher) are always
1050
+ // nested inside <prolog> in valid DITA — topic/prolog already suppresses
1051
+ // the whole subtree above, so these never actually get reached. Mapped
1052
+ // explicitly anyway, matching the anchorid/anchorkey/anchorref/prolog
1053
+ // precedent of not relying solely on an ancestor's suppression.
1054
+ 'topic/keywords': () => '',
1055
+ 'topic/metadata': () => '',
1056
+ 'topic/publisher': () => '',
1057
+ };