@dita-viewer/core 0.2.1 → 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 (41) hide show
  1. package/README.md +20 -7
  2. package/dist/editor/renderContext.d.ts +7 -0
  3. package/dist/editor/renderContext.js +24 -0
  4. package/dist/editor/topicRender.d.ts +9 -0
  5. package/dist/editor/topicRender.js +4 -2
  6. package/dist/language/ditaLanguageUtils.js +2 -0
  7. package/dist/profiling.d.ts +7 -1
  8. package/dist/profiling.js +9 -3
  9. package/dist/render/baseTypeMap.js +28 -2
  10. package/dist/render/renderer.d.ts +24 -0
  11. package/dist/render/renderer.js +36 -9
  12. package/dist-esm/bookRender.js +145 -0
  13. package/dist-esm/completion.js +142 -0
  14. package/dist-esm/completionData.js +155 -0
  15. package/dist-esm/diagnostics.js +378 -0
  16. package/dist-esm/editor/conkeyref.js +104 -0
  17. package/dist-esm/editor/keySpace.js +201 -0
  18. package/dist-esm/editor/refResolvers.js +633 -0
  19. package/dist-esm/editor/renderContext.js +138 -0
  20. package/dist-esm/editor/sourceText.js +142 -0
  21. package/dist-esm/editor/topicRender.js +328 -0
  22. package/dist-esm/index.js +66 -0
  23. package/dist-esm/keyMapForDocument.js +23 -0
  24. package/dist-esm/language/ditaLanguageUtils.js +659 -0
  25. package/dist-esm/language/referenceableFiles.js +108 -0
  26. package/dist-esm/mapRender.js +24 -0
  27. package/dist-esm/package.json +1 -0
  28. package/dist-esm/parser/ditaParser.js +409 -0
  29. package/dist-esm/parser/domTypes.js +1 -0
  30. package/dist-esm/parser/mapTagMap.js +77 -0
  31. package/dist-esm/parser/namedEntities.js +321 -0
  32. package/dist-esm/parser/standardTagMap.js +393 -0
  33. package/dist-esm/profiling.js +224 -0
  34. package/dist-esm/render/baseTypeMap.js +1057 -0
  35. package/dist-esm/render/cjkSpacing.js +94 -0
  36. package/dist-esm/render/mapTypeMap.js +568 -0
  37. package/dist-esm/render/renderer.js +519 -0
  38. package/dist-esm/siteRender.js +261 -0
  39. package/package.json +4 -2
  40. package/styles/TOKENS.md +21 -0
  41. package/styles/dita-content.css +31 -17
@@ -0,0 +1,94 @@
1
+ /**
2
+ * CJK / Latin spacing around resolved keyref text.
3
+ *
4
+ * Pure functions with no vscode dependency, so preview and HTML export share
5
+ * one rule. The rule looks at the two characters that touch across a key
6
+ * boundary: a CJK ideograph on one side and a Latin letter/digit on the other,
7
+ * with nothing between them, needs one space. Anything else (punctuation,
8
+ * existing whitespace, same-script neighbours) is left exactly as authored.
9
+ */
10
+ /** Ancestors whose content is literal (code, paths, names) -- never touched. */
11
+ const NO_SPACING_BASE_TYPES = new Set([
12
+ 'topic/codeblock',
13
+ 'topic/codeph',
14
+ 'topic/filepath',
15
+ 'topic/varname',
16
+ 'topic/cmdname',
17
+ 'topic/msgph',
18
+ 'topic/systemoutput',
19
+ 'topic/userinput',
20
+ 'topic/apiname',
21
+ 'topic/parmname',
22
+ 'topic/option',
23
+ ]);
24
+ /** Per-element escape hatch: <ph keyref="x" outputclass="no-cjk-spacing"/> */
25
+ export const NO_SPACING_CLASS = 'no-cjk-spacing';
26
+ export function isCjk(ch) {
27
+ return !!ch && /[\u4E00-\u9FFF]/.test(ch);
28
+ }
29
+ export function isLatinAlnum(ch) {
30
+ return !!ch && /[A-Za-z0-9]/.test(ch);
31
+ }
32
+ /** True when a space must be inserted between two touching characters. */
33
+ export function needsSpace(prev, next) {
34
+ return (isCjk(prev) && isLatinAlnum(next)) || (isLatinAlnum(prev) && isCjk(next));
35
+ }
36
+ export function isSpacingSuppressed(parentBaseType, node) {
37
+ if (parentBaseType && NO_SPACING_BASE_TYPES.has(parentBaseType))
38
+ return true;
39
+ if (node.baseType && NO_SPACING_BASE_TYPES.has(node.baseType))
40
+ return true;
41
+ return (node.attributes?.outputclass || '').split(/\s+/).includes(NO_SPACING_CLASS);
42
+ }
43
+ /** Text a node contributes, substituting key values for empty keyref elements. */
44
+ export function nodeText(node, resolveKey) {
45
+ if (node.type === 'text')
46
+ return node.text || '';
47
+ const own = (node.children || []).map((c) => nodeText(c, resolveKey)).join('');
48
+ if (own === '' && resolveKey && node.attributes?.keyref) {
49
+ return resolveKey(node.attributes.keyref) || '';
50
+ }
51
+ return own;
52
+ }
53
+ export function isEmptyKeyref(node) {
54
+ if (node.type !== 'element' || !node.attributes?.keyref)
55
+ return false;
56
+ return !(node.children || []).some((c) => c.type === 'element' || (c.text || '') !== '');
57
+ }
58
+ /**
59
+ * For each child, decide whether a space is needed before and/or after it.
60
+ * Only empty keyref elements that actually resolve are candidates. Neighbour
61
+ * characters are found by scanning outward past siblings that contribute no
62
+ * text (images, index terms), so `汉字<indexterm/><ph keyref/>` still works.
63
+ */
64
+ export function computeKeyrefSpacing(children, parentBaseType, resolveKey) {
65
+ const texts = children.map((c) => nodeText(c, resolveKey));
66
+ const result = children.map(() => ({ before: false, after: false }));
67
+ if (!resolveKey)
68
+ return result;
69
+ children.forEach((child, i) => {
70
+ if (!isEmptyKeyref(child) || isSpacingSuppressed(parentBaseType, child))
71
+ return;
72
+ const own = texts[i];
73
+ if (!own)
74
+ return;
75
+ let prev;
76
+ for (let j = i - 1; j >= 0 && prev === undefined; j--) {
77
+ if (texts[j])
78
+ prev = texts[j][texts[j].length - 1];
79
+ }
80
+ let next;
81
+ for (let j = i + 1; j < children.length && next === undefined; j++) {
82
+ if (texts[j])
83
+ next = texts[j][0];
84
+ }
85
+ result[i].before = needsSpace(prev, own[0]);
86
+ result[i].after = needsSpace(own[own.length - 1], next);
87
+ });
88
+ // Two adjacent keys can both claim the same gap; keep only the left one's "after".
89
+ for (let i = 1; i < result.length; i++) {
90
+ if (result[i].before && result[i - 1].after)
91
+ result[i].before = false;
92
+ }
93
+ return result;
94
+ }
@@ -0,0 +1,568 @@
1
+ import { isAbsolute } from 'path';
2
+ import { mergeProfilingAttrs, profilingKeysAttr, profilingChipsHtml } from './renderer';
3
+ function escapeAttr(s) {
4
+ return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
5
+ }
6
+ function safeAttr(name, value) {
7
+ if (value == null)
8
+ return '';
9
+ return ` ${name}="${escapeAttr(value)}"`;
10
+ }
11
+ function getAttr(node, name) {
12
+ return node.attributes?.[name];
13
+ }
14
+ // BookMap topicref specializations carry structural semantics beyond a plain
15
+ // reference — surface them as role badges in tree view / sidebar / entries
16
+ export const BOOKMAP_REF_ROLES = {
17
+ chapter: 'Chapter',
18
+ part: 'Part',
19
+ appendix: 'Appendix',
20
+ preface: 'Preface',
21
+ notices: 'Notices',
22
+ draftintro: 'Draft Intro',
23
+ dedication: 'Dedication',
24
+ colophon: 'Colophon',
25
+ bookabstract: 'Abstract',
26
+ amendments: 'Amendments',
27
+ glossaryref: 'Glossary',
28
+ };
29
+ const ROMAN_NUMERALS = [
30
+ [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
31
+ [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'],
32
+ [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'],
33
+ ];
34
+ function toRoman(n) {
35
+ let out = '';
36
+ for (const [value, sym] of ROMAN_NUMERALS) {
37
+ while (n >= value) {
38
+ out += sym;
39
+ n -= value;
40
+ }
41
+ }
42
+ return out;
43
+ }
44
+ const defaultRoleFormat = ({ role, ordinal }) => ordinal ? `${role} ${ordinal}` : role;
45
+ /**
46
+ * Returns a stateful labeler that numbers book divisions per nesting depth:
47
+ * chapters "Chapter 1, 2, …", parts "Part I, II, …", appendixes
48
+ * "Appendix A, B, …". When a division is encountered at depth D, all
49
+ * counters at depths > D are reset, so nested chapters under a new
50
+ * sibling restart from 1:
51
+ *
52
+ * Chapter 1
53
+ * Chapter 1
54
+ * Chapter 2
55
+ * Chapter 2
56
+ * Chapter 1
57
+ *
58
+ * Other bookmap roles keep their plain names (Preface, Notices, …).
59
+ * Pass a formatter to control the display text (e.g. localized "第 1 章").
60
+ */
61
+ export function createBookRoleLabeler(format = defaultRoleFormat) {
62
+ let chapterCounters = [];
63
+ let partCounters = [];
64
+ let appendixCounters = [];
65
+ /** Increments the counter at `depth`, truncating deeper entries. */
66
+ const bump = (counters, depth) => {
67
+ while (counters.length <= depth)
68
+ counters.push(0);
69
+ counters[depth]++;
70
+ counters.length = depth + 1; // reset deeper counters for this type
71
+ return counters[depth];
72
+ };
73
+ /** Resets all counter types at depths > `depth` (new sibling = fresh children). */
74
+ const resetDeeperThan = (depth) => {
75
+ chapterCounters.length = Math.min(chapterCounters.length, depth + 1);
76
+ partCounters.length = Math.min(partCounters.length, depth + 1);
77
+ appendixCounters.length = Math.min(appendixCounters.length, depth + 1);
78
+ };
79
+ return (tagName, depth) => {
80
+ if (!tagName)
81
+ return undefined;
82
+ const base = BOOKMAP_REF_ROLES[tagName];
83
+ if (!base)
84
+ return undefined;
85
+ // Any recognized division resets deeper counters so nested divisions
86
+ // under a new sibling restart from 1
87
+ resetDeeperThan(depth);
88
+ if (tagName === 'chapter')
89
+ return format({ tagName, role: base, ordinal: String(bump(chapterCounters, depth)) });
90
+ if (tagName === 'part')
91
+ return format({ tagName, role: base, ordinal: toRoman(bump(partCounters, depth)) });
92
+ if (tagName === 'appendix') {
93
+ const n = bump(appendixCounters, depth);
94
+ let letters = '';
95
+ let m = n;
96
+ while (m > 0) {
97
+ m--;
98
+ letters = String.fromCharCode(65 + (m % 26)) + letters;
99
+ m = Math.floor(m / 26);
100
+ }
101
+ return format({ tagName, role: base, ordinal: letters });
102
+ }
103
+ return format({ tagName, role: base });
104
+ };
105
+ }
106
+ /**
107
+ * Plain-text map title. For bookmaps, <booktitle> groups <mainbooktitle>
108
+ * with optional <booktitlealt>/<subtitle> — prefer the main title instead
109
+ * of concatenating all inner text. A bookmap may also carry a plain
110
+ * <title> (the short form) alongside <booktitle>; the main book title is
111
+ * the one a tree row or a site header should answer to.
112
+ */
113
+ export function getMapTitleText(root, resolveKey) {
114
+ const titleEls = (root.children || []).filter((c) => c.type === 'element' && c.baseType === 'map/map-title');
115
+ if (titleEls.length === 0)
116
+ return undefined;
117
+ const titleEl = titleEls.find((c) => c.tagName === 'booktitle') ||
118
+ titleEls.find((c) => c.tagName === 'mainbooktitle') ||
119
+ titleEls[0];
120
+ const inner = (titleEl.children || []).filter((c) => c.type === 'element' && c.baseType === 'map/map-title');
121
+ const source = inner.find((c) => c.tagName === 'mainbooktitle') || inner[0] || titleEl;
122
+ const text = extractText(source, resolveKey).trim();
123
+ return text || undefined;
124
+ }
125
+ /**
126
+ * Text content of an element, substituting a keyref whose element carries
127
+ * no content of its own (an empty <ph keyref="version"/>): the pattern a
128
+ * manual's own title uses for product names and version numbers, so every
129
+ * title-extraction path (map titles, navtitles, topic titles read off
130
+ * disk) goes through here to render it. Element content wins over the
131
+ * keyref when both exist, per DITA keyref fallback semantics.
132
+ */
133
+ export function extractText(node, resolveKey) {
134
+ if (node.type === 'text')
135
+ return node.text || '';
136
+ const own = (node.children || []).map((c) => extractText(c, resolveKey)).join('');
137
+ // Empty element carrying a keyref (e.g. <ph keyref="product"/>): substitute
138
+ // the key value; element content wins over the keyref when both exist
139
+ if (!own.trim() && resolveKey) {
140
+ const keyref = node.attributes?.keyref;
141
+ if (keyref) {
142
+ const resolved = resolveKey(keyref);
143
+ if (resolved)
144
+ return resolved;
145
+ }
146
+ }
147
+ return own;
148
+ }
149
+ function getNodeText(node, childBaseTypes, resolveKey) {
150
+ for (const bt of childBaseTypes) {
151
+ const child = (node.children || []).find((c) => c.type === 'element' && c.baseType === bt);
152
+ if (child) {
153
+ const text = extractText(child, resolveKey).trim();
154
+ if (text)
155
+ return text;
156
+ }
157
+ }
158
+ return undefined;
159
+ }
160
+ export function getDisplayName(node, resolveKey) {
161
+ return getDisplayNameInfo(node, resolveKey).text;
162
+ }
163
+ /**
164
+ * Same resolution as getDisplayName, but also reports whether the map
165
+ * itself actually named this entry (an explicit navtitle/linktext/keyword)
166
+ * versus a fallback that isn't really a title at all (the href's own filename, or the raw `keys` value) -- docsite mode's
167
+ * sidebar (buildBookNavManifest/MapViewerProvider.ts) uses `explicit` to
168
+ * decide when it's worth reading the target topic's own <title> off disk
169
+ * instead of showing something that was never meant to be read as a title.
170
+ */
171
+ export function getDisplayNameInfo(node, resolveKey, opts = {}) {
172
+ const keys = getAttr(node, 'keys');
173
+ const href = getAttr(node, 'href');
174
+ // Priority 1: topicmeta > navtitle
175
+ // Priority 2: topicmeta > linktext
176
+ const topicmeta = (node.children || []).find((c) => c.type === 'element' && (c.baseType === 'map/topicmeta'));
177
+ if (topicmeta) {
178
+ // A <shortdesc> next to the navtitle is a description, never a name:
179
+ // using it as a fallback made chapters show a paragraph instead of a title.
180
+ const metaText = getNodeText(topicmeta, ['map/navtitle', 'map/linktext'], resolveKey);
181
+ if (metaText)
182
+ return { text: metaText, explicit: true };
183
+ // keyword within topicmeta > keywords > keyword
184
+ const keywords = opts.keywords === false ? undefined : topicmeta.children.find((c) => c.type === 'element' && c.baseType === 'map/keywords');
185
+ if (keywords) {
186
+ const kwText = getNodeText(keywords, ['map/keyword'], resolveKey);
187
+ if (kwText)
188
+ return { text: kwText, explicit: true };
189
+ }
190
+ }
191
+ // Priority 3: @navtitle attribute -- a valid DITA shortcut form for
192
+ // naming a topicref/topichead without a full <topicmeta>, and the *only*
193
+ // way to name a topichead at all when it carries neither. Authored
194
+ // content, same as Priority 1/2, so `explicit: true`. This mirrors
195
+ // ditaLanguageUtils.ts's getMapRefName (the outline/tree-view path),
196
+ // which already checked this attribute -- book/site mode and HTML
197
+ // export (both built on this function) did not, so a topichead named
198
+ // only this way rendered as a literal "(unnamed)" heading in those
199
+ // views while showing correctly in the outline.
200
+ const navtitleAttr = getAttr(node, 'navtitle');
201
+ if (navtitleAttr)
202
+ return { text: navtitleAttr, explicit: true };
203
+ // Priority 4: href filename without extension -- not really a title, just
204
+ // the only thing left to call this entry.
205
+ if (href) {
206
+ const parts = href.replace(/\\/g, '/').split('/');
207
+ const file = parts[parts.length - 1] || '';
208
+ const dotIdx = file.lastIndexOf('.');
209
+ return { text: dotIdx > 0 ? file.substring(0, dotIdx) : file, explicit: false };
210
+ }
211
+ // Priority 5: keys attribute -- a machine-readable identifier, not a title either.
212
+ if (keys)
213
+ return { text: keys, explicit: false };
214
+ // Fallback
215
+ return { text: '(unnamed)', explicit: false };
216
+ }
217
+ function isNavigable(node) {
218
+ const href = getAttr(node, 'href');
219
+ return !!href;
220
+ }
221
+ /**
222
+ * Own-attribute-only box+label for a map tree row, matching Oxygen: a box
223
+ * is only drawn (once) around a topicref that itself declares a profiling
224
+ * attribute, enclosing that topicref's whole subtree (nested <ul> included,
225
+ * since .profiled wraps the whole <li>), with the label appearing once at
226
+ * the bottom of that box -- not repeated on every descendant that merely
227
+ * inherited the same attribute. data-profile-keys still needs the full
228
+ * cascaded set for the Filter panel to hide inherited-only rows too; only
229
+ * the visible chrome is scoped to what a node declares for itself.
230
+ */
231
+ function ownProfilingMarkup(node) {
232
+ const own = mergeProfilingAttrs(node.attributes, {});
233
+ const ownKeys = profilingKeysAttr(own);
234
+ return {
235
+ boxClass: ownKeys ? ' profiled' : '',
236
+ label: ownKeys ? `<span class="profiling-label">${profilingChipsHtml(own)}</span>` : '',
237
+ };
238
+ }
239
+ function renderChildrenForNode(node, ctx, rendererFn) {
240
+ return (node.children || [])
241
+ .filter((c) => c.type === 'element')
242
+ .map((c) => rendererFn(c, ctx))
243
+ .join('');
244
+ }
245
+ function renderRef(node, ctx, renderChildren) {
246
+ const href = getAttr(node, 'href') || '';
247
+ const keys = getAttr(node, 'keys') || '';
248
+ const displayName = getDisplayName(node, ctx.resolveKey);
249
+ const nav = isNavigable(node);
250
+ const depth = ctx.depth ?? 0;
251
+ const role = ctx.roleLabel
252
+ ? ctx.roleLabel(node.tagName, depth)
253
+ : node.tagName
254
+ ? BOOKMAP_REF_ROLES[node.tagName]
255
+ : undefined;
256
+ // This topicref's own profiling attributes, merged on top of whatever
257
+ // cascaded down from its ancestors -- own values win over inherited ones
258
+ // for the same attribute name. Children inherit this merged result, not
259
+ // just this node's own attributes, so a.dita's rule reaches grandchildren
260
+ // through b.dita even if b.dita sets nothing of its own.
261
+ const effectiveProfiling = mergeProfilingAttrs(node.attributes, ctx.inheritedProfiling || {});
262
+ // Children of a topicref are one level deeper
263
+ const childCtx = { ...ctx, depth: depth + 1, inheritedProfiling: effectiveProfiling };
264
+ const childrenHtml = renderChildrenForNode(node, childCtx, renderChildren);
265
+ const badge = role ? `<span class="map-tree-badge">${escapeAttr(role)}</span>` : '';
266
+ // data-profile-keys (for the Filter panel to actually hide this row) uses
267
+ // the full cascaded set, same as always -- excluding an inherited
268
+ // attribute's value still has to hide this row even if the row itself
269
+ // never declared it. The visible box+label is scoped to what this node
270
+ // declares for itself (see ownProfilingMarkup): Oxygen draws one box
271
+ // around a topicref's own attribute, enclosing its whole subtree with
272
+ // the label appearing once at the bottom, rather than re-labeling every
273
+ // descendant with the same inherited chip.
274
+ const profileKeys = profilingKeysAttr(effectiveProfiling);
275
+ const profileAttr = profileKeys ? safeAttr('data-profile-keys', profileKeys) : '';
276
+ const { boxClass, label: profileLabel } = ownProfilingMarkup(node);
277
+ const icon = nav
278
+ ? '<span class="map-tree-icon map-tree-icon--file" aria-hidden="true">\u{1F4C4}</span>'
279
+ : '<span class="map-tree-icon map-tree-icon--key" aria-hidden="true">\u{1F511}</span>';
280
+ const nameAttr = escapeAttr(displayName);
281
+ const keyAttr = safeAttr('data-keys', keys);
282
+ const hrefAttr = href ? safeAttr('data-href', href) : '';
283
+ if (nav) {
284
+ return `<li class="map-tree-item map-tree-item--nav${boxClass}" role="treeitem"${keyAttr}${hrefAttr}${profileAttr}>
285
+ <a href="#" class="map-tree-link" data-href="${escapeAttr(href)}">${icon}${badge}<span class="map-tree-label">${nameAttr}</span></a>
286
+ ${childrenHtml ? `<ul class="map-tree" role="group">${childrenHtml}</ul>` : ''}
287
+ ${profileLabel}
288
+ </li>`;
289
+ }
290
+ return `<li class="map-tree-item map-tree-item--keydef${boxClass}" role="treeitem"${keyAttr}${hrefAttr}${profileAttr}>
291
+ ${icon}${badge}<span class="map-tree-label map-tree-label--keydef">${nameAttr}</span>
292
+ ${childrenHtml ? `<ul class="map-tree" role="group">${childrenHtml}</ul>` : ''}
293
+ ${profileLabel}
294
+ </li>`;
295
+ }
296
+ /**
297
+ * Renders the map title block. A bookmap <booktitle> wraps <mainbooktitle>
298
+ * plus optional <booktitlealt>/<subtitle>: elevate the main title to the
299
+ * headline and show alternates as subtitle lines instead of concatenating
300
+ * everything into a single string.
301
+ */
302
+ function renderMapTitle(titleEl, ctx) {
303
+ const inner = (titleEl.children || []).filter((c) => c.type === 'element' && c.baseType === 'map/map-title');
304
+ if (inner.length === 0) {
305
+ return `<h1 class="map-title">${escapeAttr(extractText(titleEl, ctx.resolveKey).trim())}</h1>`;
306
+ }
307
+ const main = inner.find((c) => c.tagName === 'mainbooktitle') || inner[0];
308
+ const subtitles = inner
309
+ .filter((c) => c !== main)
310
+ .map((c) => extractText(c, ctx.resolveKey).trim())
311
+ .filter((t) => t)
312
+ .map((t) => `<p class="book-subtitle">${escapeAttr(t)}</p>`)
313
+ .join('');
314
+ return `<div class="book-titlepage"><h1 class="map-title">${escapeAttr(extractText(main, ctx.resolveKey).trim())}</h1>${subtitles}</div>`;
315
+ }
316
+ const MAP_BASE_TYPE_RENDERERS = {
317
+ 'map/map': (node, ctx, renderChildren) => {
318
+ const titleEl = node.children.find((c) => c.type === 'element' && c.baseType === 'map/map-title');
319
+ const titleHtml = titleEl ? renderMapTitle(titleEl, ctx) : '';
320
+ const bodyChildren = node.children.filter((c) => c.type !== 'element' || c.baseType !== 'map/map-title');
321
+ // A select-att set directly on <map> (rare, but valid DITA) applies as
322
+ // the baseline every top-level topicref inherits from.
323
+ const effectiveProfiling = mergeProfilingAttrs(node.attributes, ctx.inheritedProfiling || {});
324
+ const bodyCtx = { ...ctx, inheritedProfiling: effectiveProfiling };
325
+ const bodyHtml = bodyChildren
326
+ .filter((c) => c.type === 'element')
327
+ .map((c) => renderChildren(c, bodyCtx))
328
+ .join('');
329
+ return `<div class="ditamap-container">
330
+ ${titleHtml}
331
+ <ul class="map-tree" role="tree" aria-label="${escapeAttr(ctx.treeLabel || 'Document outline')}">${bodyHtml}</ul>
332
+ </div>`;
333
+ },
334
+ 'map/map-title': (node, ctx, _renderChildren) => `<h1 class="map-title">${escapeAttr(extractText(node, ctx.resolveKey))}</h1>`,
335
+ 'map/topicref': renderRef,
336
+ 'map/topichead': (node, ctx, renderChildren) => {
337
+ const displayName = getDisplayName(node, ctx.resolveKey);
338
+ const effectiveProfiling = mergeProfilingAttrs(node.attributes, ctx.inheritedProfiling || {});
339
+ const childCtx = { ...ctx, depth: (ctx.depth ?? 0) + 1, inheritedProfiling: effectiveProfiling };
340
+ const childrenHtml = renderChildrenForNode(node, childCtx, renderChildren);
341
+ const profileKeys = profilingKeysAttr(effectiveProfiling);
342
+ const profileAttr = profileKeys ? safeAttr('data-profile-keys', profileKeys) : '';
343
+ const { boxClass, label: profileLabel } = ownProfilingMarkup(node);
344
+ return `<li class="map-tree-item map-tree-item--head${boxClass}" role="treeitem"${profileAttr}>
345
+ <span class="map-tree-label map-tree-label--head">${escapeAttr(displayName)}</span>
346
+ ${childrenHtml ? `<ul class="map-tree" role="group">${childrenHtml}</ul>` : ''}
347
+ ${profileLabel}
348
+ </li>`;
349
+ },
350
+ 'map/topicgroup': (node, ctx, renderChildren) => {
351
+ // topicgroup has no navtitle/entry of its own, but it can still carry
352
+ // select-atts that its topicref children should inherit.
353
+ const effectiveProfiling = mergeProfilingAttrs(node.attributes, ctx.inheritedProfiling || {});
354
+ const childCtx = { ...ctx, inheritedProfiling: effectiveProfiling };
355
+ const childrenHtml = renderChildrenForNode(node, childCtx, renderChildren);
356
+ // No visible label of its own (topicgroup is purely a profiling
357
+ // grouping), so it isn't a distinct treeitem -- role="group" alone,
358
+ // wrapping its children as if they were direct siblings of whatever
359
+ // contains this topicgroup.
360
+ return `<li class="map-tree-item map-tree-item--group" role="none">
361
+ <ul class="map-tree" role="group">${childrenHtml}</ul>
362
+ </li>`;
363
+ },
364
+ 'map/bookmap-structural': (node, ctx, renderChildren) => {
365
+ // BookMap structural containers (frontmatter, booklists, toc, etc.)
366
+ // render as visible non-navigable labels with nested children
367
+ const displayName = node.tagName
368
+ ? node.tagName.charAt(0).toUpperCase() + node.tagName.slice(1)
369
+ : '(unnamed)';
370
+ const effectiveProfiling = mergeProfilingAttrs(node.attributes, ctx.inheritedProfiling || {});
371
+ const childCtx = { ...ctx, inheritedProfiling: effectiveProfiling };
372
+ const childrenHtml = renderChildrenForNode(node, childCtx, renderChildren);
373
+ const profileKeys = profilingKeysAttr(effectiveProfiling);
374
+ const profileAttr = profileKeys ? safeAttr('data-profile-keys', profileKeys) : '';
375
+ const { boxClass, label: profileLabel } = ownProfilingMarkup(node);
376
+ return `<li class="map-tree-item map-tree-item--structural${boxClass}" role="treeitem"${profileAttr}>
377
+ <span class="map-tree-label map-tree-label--structural">${escapeAttr(displayName)}</span>
378
+ ${childrenHtml ? `<ul class="map-tree" role="group">${childrenHtml}</ul>` : ''}
379
+ ${profileLabel}
380
+ </li>`;
381
+ },
382
+ 'map/keydef': renderRef,
383
+ 'map/reltable': (node, ctx, renderChildren) => {
384
+ const relbody = node.children.filter((c) => c.type === 'element' && (c.baseType === 'map/relheader' || c.baseType === 'map/relrow'));
385
+ const bodyHtml = relbody.map((c) => renderChildren(c, ctx)).join('');
386
+ return `<div class="map-reltable"><h2 class="map-reltable-title">Related Information</h2>
387
+ <table class="map-reltable-table"><tbody>${bodyHtml}</tbody></table>
388
+ </div>`;
389
+ },
390
+ 'map/relheader': (node, ctx) => {
391
+ // Per the DITA spec relheader contains relcolspec (not relcell); show
392
+ // each column's title text as the header cell.
393
+ const cells = node.children
394
+ .filter((c) => c.type === 'element' && c.baseType === 'map/relcolspec')
395
+ .map((c) => {
396
+ const text = getAttr(c, 'navtitle') || extractText(c, ctx.resolveKey).trim();
397
+ return escapeAttr(text);
398
+ });
399
+ return `<tr class="relheader">${cells.map((c) => `<th>${c}</th>`).join('')}</tr>`;
400
+ },
401
+ 'map/relrow': (node, ctx, renderChildren) => {
402
+ const cells = node.children
403
+ .filter((c) => c.type === 'element' && c.baseType === 'map/relcell')
404
+ .map((c) => renderChildren(c, ctx));
405
+ return `<tr class="relrow">${cells.map((c) => `<td>${c}</td>`).join('')}</tr>`;
406
+ },
407
+ 'map/relcell': (node, ctx, renderChildren) => {
408
+ // relcell contains topicrefs, render them as an inline subtree
409
+ const childrenHtml = renderChildrenForNode(node, ctx, renderChildren);
410
+ return `<span class="relcell-content"><ul class="map-tree map-tree--inline">${childrenHtml}</ul></span>`;
411
+ },
412
+ 'map/relcolspec': () => '',
413
+ 'map/topicmeta': () => '',
414
+ 'map/linktext': () => '',
415
+ 'map/navtitle': () => '',
416
+ 'map/shortdesc': () => '',
417
+ 'map/keywords': () => '',
418
+ 'map/keyword': () => '',
419
+ 'map/anchor': () => '',
420
+ 'map/navref': () => '',
421
+ 'map/mapref': renderRef,
422
+ };
423
+ /** True when a bare href isn't a scoped/absolute/scheme'd reference to
424
+ * somewhere outside the local doc tree -- copy of ditaRenderUtils.ts's
425
+ * own private isLocalHref (kept private and duplicated here, not
426
+ * exported/shared, since it's a 4-line pure classification helper and
427
+ * this file otherwise has no runtime dependency on ditaRenderUtils.ts;
428
+ * see isDitamapRef below for why this file needs its own copy at all). */
429
+ function isLocalHref(href, scope) {
430
+ if (!href || href.startsWith('#'))
431
+ return false;
432
+ if (scope === 'external' || scope === 'peer')
433
+ return false;
434
+ if (/^[a-z][a-z0-9+.-]*:/i.test(href))
435
+ return false;
436
+ if (isAbsolute(href))
437
+ return false;
438
+ return true;
439
+ }
440
+ /** True when the node is a topicref/keydef/mapref pointing at another
441
+ * local .ditamap -- i.e. a node expandDitamapRefs (ditaRenderUtils.ts)
442
+ * inlines the referenced map's own top-level children into, in place of
443
+ * this node ever representing a page of its own. ditaRenderUtils.ts
444
+ * imports this rather than the other way around (this file has no
445
+ * runtime dependency on ditaRenderUtils.ts) since collectEntriesRecursive
446
+ * below needs the exact same definition expandDitamapRefs itself uses --
447
+ * a node this function says isn't a ditamap ref never gets its children
448
+ * spliced in by expandDitamapRefs in the first place, so the two must
449
+ * agree on every case. */
450
+ export function isDitamapRef(node) {
451
+ if (node.type !== 'element')
452
+ return false;
453
+ const baseType = node.baseType;
454
+ if (baseType !== 'map/topicref' && baseType !== 'map/keydef' && baseType !== 'map/mapref')
455
+ return false;
456
+ const href = node.attributes?.href;
457
+ if (!href || !isLocalHref(href, node.attributes?.scope))
458
+ return false;
459
+ const pathPart = href.split('#')[0].toLowerCase();
460
+ return pathPart.endsWith('.ditamap') || node.attributes?.format === 'ditamap';
461
+ }
462
+ function collectEntriesRecursive(node, depth, result, resolveKey, roleLabel, inheritedProcessingRole = 'normal') {
463
+ if (node.type !== 'element')
464
+ return;
465
+ const baseType = node.baseType;
466
+ // Skip reltable and its children
467
+ if (baseType === 'map/reltable')
468
+ return;
469
+ if (isDitamapRef(node)) {
470
+ // A transparent transclusion wrapper: expandDitamapRefs (called before
471
+ // collectMapEntries always runs) has already spliced the referenced
472
+ // map's own top-level children in as this node's own children, in
473
+ // place of this node ever being a page of its own -- a .ditamap href
474
+ // never resolves to a real topic file (resolveBookTopicPath in
475
+ // ditaRenderUtils.ts returns undefined for one), so this node was
476
+ // never going to survive downstream filtering as an entry anyway.
477
+ // More importantly: recursing at the SAME depth (not depth + 1) means
478
+ // the referenced map's own chapters/sections become peers of whatever
479
+ // this node itself would have been a peer of, continuing the same
480
+ // role-numbering sequence (createBookRoleLabeler's depth-keyed
481
+ // counters, below) rather than restarting from "Chapter 1" one nesting
482
+ // level deeper just because expandDitamapRefs happened to splice them
483
+ // in as DOM children of this wrapper node.
484
+ for (const child of node.children || []) {
485
+ collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, inheritedProcessingRole);
486
+ }
487
+ return;
488
+ }
489
+ // DITA processing-role inheritance: an explicit attribute on this node
490
+ // wins outright; failing that, a bare <keydef> defaults to resource-only
491
+ // (the one place a tag itself carries a different default than its
492
+ // ancestors, per spec) same as it would if it explicitly wrote
493
+ // processing-role="resource-only" itself; failing that, this node
494
+ // inherits whatever its own parent resolved to (passed in as
495
+ // inheritedProcessingRole), which is 'normal' unless some ancestor
496
+ // upstream already opted the branch into resource-only.
497
+ const ownProcessingRole = getAttr(node, 'processing-role');
498
+ const effectiveProcessingRole = ownProcessingRole === 'resource-only'
499
+ ? 'resource-only'
500
+ : ownProcessingRole === 'normal'
501
+ ? 'normal'
502
+ : baseType === 'map/keydef'
503
+ ? 'resource-only'
504
+ : inheritedProcessingRole;
505
+ if (baseType === 'map/topicref' || baseType === 'map/keydef' || baseType === 'map/mapref' || baseType === 'map/topichead') {
506
+ const href = getAttr(node, 'href');
507
+ const keys = getAttr(node, 'keys');
508
+ const nameInfo = getDisplayNameInfo(node, resolveKey);
509
+ result.push({
510
+ href,
511
+ displayName: nameInfo.text,
512
+ displayNameExplicit: nameInfo.explicit,
513
+ depth,
514
+ keys,
515
+ // A resource-only branch never burns/bumps a chapter-style counter
516
+ // slot -- it's never going to appear in a reading nav that shows
517
+ // role numbers, so numbering a chapter that will never be seen
518
+ // (and, worse, leaving a visible gap where its number would have
519
+ // been) serves no one.
520
+ role: effectiveProcessingRole === 'resource-only' ? undefined : roleLabel(node.tagName, depth),
521
+ resourceOnly: effectiveProcessingRole === 'resource-only',
522
+ });
523
+ // Recurse children at depth+1
524
+ for (const child of node.children || []) {
525
+ collectEntriesRecursive(child, depth + 1, result, resolveKey, roleLabel, effectiveProcessingRole);
526
+ }
527
+ }
528
+ else if (baseType === 'map/topicgroup' || baseType === 'map/bookmap-structural') {
529
+ // topicgroup / bookmap-structural: no entry itself, but recurse at same depth
530
+ for (const child of node.children || []) {
531
+ collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole);
532
+ }
533
+ }
534
+ else {
535
+ for (const child of node.children || []) {
536
+ collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole);
537
+ }
538
+ }
539
+ }
540
+ export function collectMapEntries(root, resolveKey, roleFormat) {
541
+ const result = [];
542
+ const roleLabel = createBookRoleLabeler(roleFormat);
543
+ // Start from map's children at depth 0
544
+ for (const child of root.children || []) {
545
+ collectEntriesRecursive(child, 0, result, resolveKey, roleLabel);
546
+ }
547
+ return result;
548
+ }
549
+ export function renderMapDocument(root, options) {
550
+ function renderElement(node, ctx) {
551
+ if (node.type === 'text')
552
+ return '';
553
+ const baseType = node.baseType;
554
+ const renderer = baseType ? MAP_BASE_TYPE_RENDERERS[baseType] : undefined;
555
+ if (renderer) {
556
+ return renderer(node, ctx, renderElement);
557
+ }
558
+ return renderChildrenForNode(node, ctx, renderElement);
559
+ }
560
+ const ctx = {
561
+ docDir: options.docDir,
562
+ resolveKey: options.resolveKey,
563
+ roleLabel: createBookRoleLabeler(options.roleFormat),
564
+ depth: 0,
565
+ treeLabel: options.treeLabel,
566
+ };
567
+ return renderElement(root, ctx);
568
+ }