@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,519 @@
1
+ import { BASE_TYPE_RENDERERS } from './baseTypeMap';
2
+ import { computeKeyrefSpacing } from './cjkSpacing';
3
+ const CONTAINER_BASETYPES = new Set([
4
+ 'topic/section',
5
+ 'topic/example',
6
+ 'topic/fig',
7
+ 'topic/imagemap',
8
+ 'topic/related-links',
9
+ ]);
10
+ const PASS_THROUGH_BASETYPES = new Set([
11
+ 'topic/tgroup',
12
+ 'topic/link',
13
+ 'topic/linktext',
14
+ ]);
15
+ function isContainerBaseType(baseType) {
16
+ return CONTAINER_BASETYPES.has(baseType);
17
+ }
18
+ // ── Profiling / conditional-processing attribute highlighting ──
19
+ // Per the OASIS DITA 1.3 select-atts entity (commonElements.mod): the full
20
+ // set of attributes conditional-processing tools (Oxygen's "Conditional
21
+ // Text" / DITA-OT's .ditaval) act on is props, platform, product, audience,
22
+ // otherprops, deliveryTarget (the filter-atts subgroup -- DITA 1.3 added
23
+ // deliveryTarget, deprecating the DITA 1.2 @print), plus base, importance,
24
+ // rev, and status. This only *highlights* profiled content (matches it
25
+ // visually, the way Oxygen shows profiling by default) — it does not hide
26
+ // anything; that would be a real conditional-processing engine (a
27
+ // .ditaval-driven filter), which is a separate, larger feature this doesn't
28
+ // attempt.
29
+ const PROFILING_ATTRS = ['props', 'platform', 'product', 'audience', 'otherprops', 'deliveryTarget', 'base', 'importance', 'rev', 'status'];
30
+ const PROFILING_ATTR_LABELS = {
31
+ otherprops: 'Other',
32
+ };
33
+ function profilingAttrLabel(attr) {
34
+ return PROFILING_ATTR_LABELS[attr] || attr.charAt(0).toUpperCase() + attr.slice(1);
35
+ }
36
+ // ── Shared with the ditamap renderer (mapTypeMap.ts) ──
37
+ // A topicref's profiling attributes cascade to every descendant topicref
38
+ // that doesn't set its own value for the same attribute (own value replaces
39
+ // the inherited one wholesale, it doesn't merge token-by-token — this
40
+ // matches real .ditaval/Oxygen conditional-processing semantics, and is
41
+ // also how DITA-OT itself resolves the same attribute set at different
42
+ // levels of a map). mapTypeMap.ts calls this while walking the map tree so
43
+ // each topicref/topichead/topicgroup gets the correctly cascaded effective
44
+ // set, including through map-of-maps (expandDitamapRefs has already
45
+ // flattened those into the same tree by the time this runs).
46
+ export function mergeProfilingAttrs(own, inherited) {
47
+ const effective = { ...inherited };
48
+ const attrs = own || {};
49
+ for (const name of PROFILING_ATTRS) {
50
+ const v = attrs[name];
51
+ if (v && v.trim())
52
+ effective[name] = v;
53
+ }
54
+ return effective;
55
+ }
56
+ /** The data-profile-keys attribute value the webview's filter panel keys off of. */
57
+ export function profilingKeysAttr(effective) {
58
+ const chips = getProfilingChipsFromEffective(effective);
59
+ return chips.map((c) => `${encodeURIComponent(c.attr)}:${encodeURIComponent(c.value)}`).join(',');
60
+ }
61
+ /** Human-readable "Attr [value]" chip spans, for visual display next to a map entry. */
62
+ export function profilingChipsHtml(effective) {
63
+ return getProfilingChipsFromEffective(effective)
64
+ .map((c) => `<span class="profiling-chip">${escapeHtml(profilingAttrLabel(c.attr))} <span class="profiling-chip__value">[${escapeHtml(c.value)}]</span></span>`)
65
+ .join('');
66
+ }
67
+ function getProfilingChipsFromEffective(effective) {
68
+ const chips = [];
69
+ for (const name of PROFILING_ATTRS) {
70
+ const raw = effective[name];
71
+ if (!raw)
72
+ continue;
73
+ for (const token of raw.trim().split(/\s+/)) {
74
+ if (token)
75
+ chips.push({ attr: name, value: token });
76
+ }
77
+ }
78
+ return chips;
79
+ }
80
+ // Elements commonly authored inline, within a sentence — highlighting these
81
+ // as a full-width block would break the surrounding text flow, so they get
82
+ // an inline-flavored wrapper instead. Not an exhaustive classification (the
83
+ // renderer has no general block/inline taxonomy to draw on); anything not
84
+ // listed here defaults to the block treatment, which matches the more
85
+ // common case of profiling applied at paragraph/step/section granularity
86
+ // (as in the reported example) rather than to individual inline phrases.
87
+ const INLINE_PROFILING_BASETYPES = new Set([
88
+ 'topic/ph', 'topic/b', 'topic/i', 'topic/u', 'topic/sup', 'topic/sub',
89
+ 'topic/term', 'topic/keyword', 'topic/tm', 'topic/xref', 'topic/cite',
90
+ 'topic/q', 'topic/filepath', 'topic/userinput', 'topic/systemoutput',
91
+ 'topic/varname', 'topic/cmdname', 'topic/wintitle', 'topic/uicontrol',
92
+ 'topic/menucascade', 'topic/shortcut',
93
+ ]);
94
+ function getProfilingChips(node) {
95
+ return getProfilingChipsFromEffective(node.attributes || {});
96
+ }
97
+ // li (and other block content whose own layout/marker position depends on
98
+ // its *real* parent -- ul/ol for li, but block content generally shouldn't
99
+ // gain a synthetic intermediate parent either) can't just be wrapped in an
100
+ // extra <span>: the browser positions a list marker relative to the li's
101
+ // own containing block, and wrapping it in a block-level .profiled <span>
102
+ // makes that wrapper the containing block instead of the real <ul>/<ol> --
103
+ // the marker ends up offset by .profiled's own padding/border, both
104
+ // visually overlapping the marker and making a profiled <li>'s indent not
105
+ // match its plain siblings. injectBlockProfiling adds the class/data
106
+ // attribute onto the block element's own tag in place, and the label just
107
+ // before its own closing tag, instead of introducing a wrapper element at
108
+ // all -- the DOM shape for a profiled block element ends up identical to
109
+ // an unprofiled one, just with two extra attributes and one extra child.
110
+ function injectBlockProfiling(html, tagName, keysAttr, labelHtml) {
111
+ const openTagEnd = html.indexOf('>');
112
+ const openTag = openTagEnd >= 0 ? html.slice(0, openTagEnd) : html;
113
+ const hasClass = / class="/.test(openTag);
114
+ let out = hasClass
115
+ ? html.replace(/ class="([^"]*)"/, (_m, existing) => ` class="${existing ? `${existing} profiled` : 'profiled'}"`)
116
+ : html.replace(/^<([a-zA-Z][a-zA-Z0-9]*)/, '<$1 class="profiled"');
117
+ out = out.replace(/^<([a-zA-Z][a-zA-Z0-9]*)/, `<$1 data-profile-keys="${keysAttr}"`);
118
+ // `tagName` is the *DITA source* element name (e.g. "row", "entry",
119
+ // "stentry"), passed through from effectiveNode.tagName purely so
120
+ // injectAttributes can stamp the original authoring tag onto
121
+ // data-dita-tagname for tooltips. It is NOT reliable for finding this
122
+ // element's own closing tag in `html`: several base types render under a
123
+ // different HTML tag than their DITA element name -- a <row> renders as
124
+ // <tr>, and <entry>/<stentry> render as <td> or <th> depending on
125
+ // header context. Building the close-tag search from `tagName` in that
126
+ // case (`</row>`, `</entry>`) never matches anything in `html` (which
127
+ // actually contains `</tr>`/`</td>`/`</th>`), so the lookup below fell
128
+ // through its "not found" branch and silently dropped the label for
129
+ // every profiled table row or cell. Reading the real tag straight out of
130
+ // the opening tag we just edited keeps this correct regardless of what
131
+ // the DITA source called the element.
132
+ const actualTagMatch = /^<([a-zA-Z][a-zA-Z0-9]*)/.exec(out);
133
+ const actualTag = actualTagMatch ? actualTagMatch[1] : tagName;
134
+ // html is always exactly one complete element at this point in the
135
+ // pipeline (possibly with same-named descendants nested inside, e.g. a
136
+ // <li> containing a nested <ul><li>...) -- proper nesting guarantees any
137
+ // child's closing tag appears before its parent's, so the *last*
138
+ // occurrence of this tag's own closing tag in the string is always the
139
+ // outermost (real) one, letting the label be inserted as the true last
140
+ // child without needing a full tag-depth parser.
141
+ const closeTag = `</${actualTag}>`;
142
+ const closeIdx = out.lastIndexOf(closeTag);
143
+ if (closeIdx === -1)
144
+ return out;
145
+ if (actualTag === 'tr') {
146
+ // A <tr>'s only legal direct children are <td>/<th> (plus
147
+ // script/template) -- inserting the label <span> as the row's own
148
+ // last child, the way every other block element is handled below, is
149
+ // invalid content. The HTML parser "fixes" that by foster-parenting
150
+ // the span out of the table entirely (per the "in row"/"in table"
151
+ // insertion modes: anything that isn't a cell gets relocated to just
152
+ // before the <table>, not left where it was written). That relocation
153
+ // is exactly what produced both reported symptoms: the label render­
154
+ // ing detached from its own row -- so it shows up vertically offset,
155
+ // stacked wherever the parser moved it rather than next to its row --
156
+ // and the <tr>'s child list no longer matching what was authored,
157
+ // which breaks the shared collapsed-border edge with the row below
158
+ // it. The fix is to anchor the label inside the row's own last cell
159
+ // instead, which is valid content there.
160
+ const lastTd = out.lastIndexOf('</td>', closeIdx);
161
+ const lastTh = out.lastIndexOf('</th>', closeIdx);
162
+ const lastCellClose = Math.max(lastTd, lastTh);
163
+ if (lastCellClose === -1)
164
+ return out; // no cells to anchor the label to
165
+ return `${out.slice(0, lastCellClose)}<span class="profiling-label">${labelHtml}</span>${out.slice(lastCellClose)}`;
166
+ }
167
+ return `${out.slice(0, closeIdx)}<span class="profiling-label">${labelHtml}</span>${out.slice(closeIdx)}`;
168
+ }
169
+ function wrapProfilingHighlight(html, node, tagName) {
170
+ const chips = getProfilingChips(node);
171
+ if (chips.length === 0)
172
+ return html;
173
+ const inline = node.baseType ? INLINE_PROFILING_BASETYPES.has(node.baseType) : false;
174
+ const labelHtml = chips
175
+ .map((c) => `<span class="profiling-chip">${escapeHtml(profilingAttrLabel(c.attr))} <span class="profiling-chip__value">[${escapeHtml(c.value)}]</span></span>`)
176
+ .join('');
177
+ // Machine-readable twin of the human-readable chips above, for the
178
+ // toolbar's filter panel (webview-side) to key visibility off of without
179
+ // re-parsing chip text. encodeURIComponent on each part keeps the ':'/','
180
+ // delimiters unambiguous regardless of what characters appear in a real
181
+ // attribute value (DITA doesn't restrict these to a safe token charset).
182
+ const keysAttr = escapeHtml(chips.map((c) => `${encodeURIComponent(c.attr)}:${encodeURIComponent(c.value)}`).join(','));
183
+ if (!inline && tagName) {
184
+ return injectBlockProfiling(html, tagName, keysAttr, labelHtml);
185
+ }
186
+ const cls = inline ? 'profiled profiled--inline' : 'profiled';
187
+ return `<span class="${cls}" data-profile-keys="${keysAttr}">${html}<span class="profiling-label">${labelHtml}</span></span>`;
188
+ }
189
+ function escapeHtml(text) {
190
+ return text
191
+ .replace(/&/g, '&amp;')
192
+ .replace(/</g, '&lt;')
193
+ .replace(/>/g, '&gt;')
194
+ .replace(/"/g, '&quot;');
195
+ }
196
+ function injectAttributes(html, tagName, range) {
197
+ // A renderer's own `title=` (checked only within its opening tag, not
198
+ // inside any nested children's markup) wins over the generic
199
+ // tag-name-as-tooltip fallback — otherwise the generic one lands first
200
+ // in the tag and, per HTML5's first-duplicate-wins parsing rule, silently
201
+ // shadows whatever the renderer intended (e.g. topic/image using the
202
+ // resolved alt text as its tooltip instead of the literal word "image").
203
+ //
204
+ // The generic fallback itself is a data attribute, not a second title=:
205
+ // baking "every element gets a native browser tooltip reading its raw
206
+ // tag name" straight into the HTML made it impossible to turn off without
207
+ // a full re-render, and reading the tag name on hover is useful while
208
+ // learning DITA but noisy otherwise. data-dita-tagname carries the same
209
+ // information; the "Tags" toolbar toggle promotes it to a real title
210
+ // attribute only when the reader has asked for it (see applyTagTooltips
211
+ // in DitaViewerProvider.ts/MapViewerProvider.ts's webview scripts).
212
+ const openTagEnd = html.indexOf('>');
213
+ const openTag = openTagEnd >= 0 ? html.slice(0, openTagEnd) : html;
214
+ const hasOwnTitle = / title="/.test(openTag);
215
+ const tagNamePart = hasOwnTitle ? '' : ` data-dita-tagname="${tagName}"`;
216
+ return html.replace(/^<([a-zA-Z][a-zA-Z0-9]*)/, `<$1${tagNamePart} data-line="${range.startLine}" data-end-line="${range.endLine}" data-start-col="${range.startCol}" data-end-col="${range.endCol}"`);
217
+ }
218
+ // Content pulled in by a conref/conkeyref/conrefend merge is authored in the
219
+ // *target* file, but data-line highlighting and scroll-sync resolve against
220
+ // the referencing document's editor. Left with the target's own line numbers,
221
+ // the merged subtree is a field of foreign ranges inside this document:
222
+ // findContaining matches the click position against them (highlighting an
223
+ // arbitrary entry of a block the cursor never touched, or the whole coarse
224
+ // ancestor when nothing matches), and findClosest falls back to whichever
225
+ // foreign start-line is numerically nearest. So every transplanted node is
226
+ // re-stamped with the referencing element's range — the only position in
227
+ // this file that content legitimately has. All elements of one merged run
228
+ // then share one range: clicking anywhere on the referencing tag picks that
229
+ // tag, which is exactly what "go to my source" means for content that has
230
+ // no per-entry source line here.
231
+ function stampSourceRange(node, range) {
232
+ return {
233
+ ...node,
234
+ sourceRange: range,
235
+ children: node.children?.map((child) => stampSourceRange(child, range)),
236
+ };
237
+ }
238
+ // Shared by both a normal single-target conref and the first member of a
239
+ // conrefend range: the referencing element's own attributes (minus
240
+ // conref/conrefend/conkeyref) take precedence, and its tag/baseType is kept when the
241
+ // target is the same baseType (DITA's "same-type" conref semantics) —
242
+ // otherwise the target's tag/baseType wins instead, since a same-shaped
243
+ // substitution isn't possible.
244
+ //
245
+ // Chains (A -> B -> C) are followed by followConrefChain before the merge, so
246
+ // `target` here is already the end of the chain. Conrefs nested *inside* the
247
+ // resolved content are followed as well, since renderNode resolves each child
248
+ // as it walks.
249
+ function mergeConrefTarget(node, target) {
250
+ const restAttrs = Object.fromEntries(Object.entries(node.attributes || {}).filter(([k]) => k !== 'conref' && k !== 'conrefend' && k !== 'conkeyref'));
251
+ if (target.baseType && target.baseType === node.baseType) {
252
+ return { ...node, children: (target.children || []).map((c) => stampSourceRange(c, node.sourceRange)), attributes: restAttrs };
253
+ }
254
+ // Cross-type merge: the target's element shape wins, but never its source
255
+ // position — the target and all of its descendants sit at the referencing
256
+ // element's range.
257
+ const stamped = stampSourceRange(target, node.sourceRange);
258
+ const targetAttrs = Object.fromEntries(Object.entries(stamped.attributes || {})
259
+ .filter(([k]) => k !== 'conref' && k !== 'conrefend' && k !== 'conkeyref' && k !== 'id'));
260
+ return { ...stamped, attributes: { ...targetAttrs, ...restAttrs } };
261
+ }
262
+ // The target's own sourceRange is read here, BEFORE mergeConrefTarget
263
+ // re-stamps it with the referencing element's range (see stampSourceRange):
264
+ // the stamped copy points into this document, which is exactly the position
265
+ // the jump must NOT land on.
266
+ function conrefMarkFor(target, context) {
267
+ const file = context.conrefSource?.(target);
268
+ if (!file)
269
+ return undefined;
270
+ return { file, line: target.sourceRange.startLine, col: target.sourceRange.startCol };
271
+ }
272
+ // How the jump icon is laid out, chosen from the tag that actually rendered
273
+ // (not the DITA name: <row> renders as <tr>, <entry> as <td>/<th>).
274
+ // inline -- a phrase inside running text: a small icon after it.
275
+ // cell -- table structure, which cannot take an in-flow block before its
276
+ // first child: the icon floats over the top-left corner instead.
277
+ // block -- everything else: the icon sits on its own line above the content.
278
+ const CONREF_CELL_TAGS = new Set(['table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'colgroup', 'caption']);
279
+ // Of the cell kind, only these are a sensible keyboard stop. table, thead,
280
+ // tbody, tfoot, tr, colgroup and caption keep the mouse icon but get no
281
+ // tabindex: colgroup has no box to draw a focus ring on, an outline on a tr
282
+ // is not reliable across browsers, and a Tab stop on every structural wrapper
283
+ // of a reused table is noise. Jumping from a reused table is a cell-level act.
284
+ const CONREF_FOCUSABLE_CELL_TAGS = new Set(['td', 'th']);
285
+ function openingTag(html) {
286
+ return (/^<([a-zA-Z][a-zA-Z0-9]*)/.exec(html)?.[1] ?? '').toLowerCase();
287
+ }
288
+ function conrefKind(html, baseType) {
289
+ const tag = openingTag(html);
290
+ if (CONREF_CELL_TAGS.has(tag))
291
+ return 'cell';
292
+ if (baseType && INLINE_PROFILING_BASETYPES.has(baseType))
293
+ return 'inline';
294
+ return 'block';
295
+ }
296
+ /**
297
+ * Stamps conref'd content onto its own opening tag, in place (no wrapper
298
+ * element: a wrapper would change the DOM shape under li/tr/table the same
299
+ * way profiling's wrapper did, see injectBlockProfiling).
300
+ * data-conref="block|inline|cell" -- the styling hook and icon layout
301
+ * data-conref-file / -line / -col -- the target, for the jump button
302
+ * tabindex + aria-describedby -- (tabindex 0 on the outermost mark, -1 on
303
+ * a mark nested inside another, so reuse-in-reuse is not a Tab stop each;
304
+ * omitted on table/thead/tbody/tfoot/tr/colgroup/caption, see
305
+ * CONREF_FOCUSABLE_CELL_TAGS) the badge is a background with no DOM,
306
+ * so the marked element itself is made focusable and points its accessible
307
+ * description at the one hidden hint node the webview script injects. The
308
+ * id literal must stay equal to CONREF_JUMP_HINT_ID in
309
+ * editor/webview/conrefJumpScript.ts (renderer cannot import from editor,
310
+ * so it is duplicated here; conrefJump.test asserts they match).
311
+ * The webview treats the file as untrusted input and the host re-validates
312
+ * it before opening anything.
313
+ */
314
+ function markConrefContent(html, mark, baseType, nested) {
315
+ const kind = conrefKind(html, baseType);
316
+ const focusable = kind !== 'cell' || CONREF_FOCUSABLE_CELL_TAGS.has(openingTag(html));
317
+ const a11y = focusable ? ` tabindex="${nested ? -1 : 0}" aria-describedby="dv-conref-jump-hint"` : '';
318
+ const attrs = `data-conref="${kind}" data-conref-file="${escapeHtml(mark.file)}" data-conref-line="${mark.line}" data-conref-col="${mark.col}"${a11y}`;
319
+ // A function replacement: the path is arbitrary text and must not be read
320
+ // for $-patterns.
321
+ return html.replace(/^<([a-zA-Z][a-zA-Z0-9]*)/, (_m, tag) => `<${tag} ${attrs}`);
322
+ }
323
+ /** Most hops a reference chain may take; a deeper chain degrades to one hop. */
324
+ export const MAX_CONREF_CHAIN_DEPTH = 10;
325
+ // Follow A -> B -> C transitively from the first resolved target. The first
326
+ // target counts as hop 1. An unresolvable later hop ends the chain at the last
327
+ // element that did resolve; a cycle or a chain deeper than the cap falls back
328
+ // to the first hop, which is what the renderer did before chains were followed.
329
+ function followConrefChain(first, context) {
330
+ const hop = context.resolveChainHop;
331
+ if (!hop)
332
+ return first;
333
+ const seen = new Set([first]);
334
+ let current = first;
335
+ for (let depth = 1;; depth++) {
336
+ if (!current.attributes?.conref && !current.attributes?.conkeyref)
337
+ return current;
338
+ const next = hop(current);
339
+ if (!next)
340
+ return current;
341
+ if (seen.has(next) || depth >= MAX_CONREF_CHAIN_DEPTH)
342
+ return first;
343
+ seen.add(next);
344
+ current = next;
345
+ }
346
+ }
347
+ // Resolve one content reference for a node. conkeyref (indirect, by key) takes
348
+ // precedence over conref (direct) when it resolves — matching the DITA 1.3
349
+ // rule and DITA-OT's behaviour, where an unresolvable conkeyref falls back to
350
+ // the element's @conref. The returned chainKey is whichever reference actually
351
+ // fired, so the caller adds it to conrefChain for cycle protection.
352
+ function resolveConrefForNode(node, context) {
353
+ const conkeyref = node.attributes?.conkeyref;
354
+ if (conkeyref && context.resolveConkeyref && !context.conrefChain?.has(conkeyref)) {
355
+ const keyTarget = context.resolveConkeyref(conkeyref);
356
+ if (keyTarget) {
357
+ const end = followConrefChain(keyTarget, context);
358
+ return { node: mergeConrefTarget(node, end), chainKey: conkeyref, mark: conrefMarkFor(end, context) };
359
+ }
360
+ }
361
+ const conref = node.attributes?.conref;
362
+ if (!conref || !context.resolveConref)
363
+ return { node };
364
+ // A conref already resolved on this branch points back here — stop the
365
+ // cycle and render the element's literal content instead of recursing.
366
+ if (context.conrefChain?.has(conref))
367
+ return { node };
368
+ const target = context.resolveConref(conref);
369
+ if (!target)
370
+ return { node };
371
+ const end = followConrefChain(target, context);
372
+ return { node: mergeConrefTarget(node, end), chainKey: conref, mark: conrefMarkFor(end, context) };
373
+ }
374
+ /**
375
+ * Per DITA keyref semantics, the key's resource target becomes the
376
+ * referencing element's effective href when the element carries no href of
377
+ * its own -- this is what turns `<xref keyref="k"/>` into a link to the
378
+ * key's target. Applies to link-shaped elements only (topic/xref): other
379
+ * keyref consumers (ph, keyword, term) never link, and handing topic/link
380
+ * a href would change its rendered shape without the webview-side handling
381
+ * to click it safely, so the gate stays on the element's base type.
382
+ * Resolved for local content too: `<xref keyref="k">text</xref>` keeps its
383
+ * text and still links to the key's target.
384
+ */
385
+ function withResolvedKeyHref(node, keyref, context) {
386
+ if (node.baseType !== 'topic/xref')
387
+ return node;
388
+ if (!context.resolveKeyHref || node.attributes?.href)
389
+ return node;
390
+ const keyHref = context.resolveKeyHref(keyref);
391
+ if (!keyHref) {
392
+ // The key resolves to text but names no resource (or the caller wired no
393
+ // defs): keep the keyref so the xref renderer can mark the element as an
394
+ // unlinkable keyref (unresolved-keyref) instead of a bare span that
395
+ // gives no hint anything is missing.
396
+ return { ...node, attributes: { ...node.attributes, keyref } };
397
+ }
398
+ return { ...node, attributes: { ...node.attributes, href: keyHref } };
399
+ }
400
+ function resolveKeyrefForNode(node, context) {
401
+ const keyref = node.attributes?.keyref;
402
+ if (!keyref || !context.resolveKey)
403
+ return node;
404
+ // Per the DITA spec, existing element content wins over the key-resolved
405
+ // text — only substitute when the element is effectively empty.
406
+ const hasLocalContent = (node.children || []).some((c) => c.type === 'element' || (c.text || '').trim() !== '');
407
+ if (hasLocalContent)
408
+ return withResolvedKeyHref(node, keyref, context);
409
+ const resolved = context.resolveKey(keyref);
410
+ if (!resolved)
411
+ return node;
412
+ // Strip keyref after resolving, replace children with resolved text
413
+ const restAttrs = Object.fromEntries(Object.entries(node.attributes || {}).filter(([k]) => k !== 'keyref'));
414
+ return {
415
+ ...withResolvedKeyHref({ ...node, attributes: restAttrs }, keyref, context),
416
+ children: [{ type: 'text', text: resolved, children: [], sourceRange: node.sourceRange }],
417
+ };
418
+ }
419
+ // The "given a fully-resolved node, actually render it" half of
420
+ // renderElement — factored out so the conrefend range path below can reuse
421
+ // it for the merged first range member without re-running conref/keyref
422
+ // resolution on something that's already resolved.
423
+ function renderEffectiveNode(effectiveNode, context, resolvedConref, mark) {
424
+ const baseType = effectiveNode.baseType;
425
+ const renderer = baseType ? BASE_TYPE_RENDERERS[baseType] : undefined;
426
+ const isContainer = baseType ? isContainerBaseType(baseType) : false;
427
+ const nextHeadingLevel = isContainer
428
+ ? context.headingLevel + 1
429
+ : context.headingLevel;
430
+ const childCtx = {
431
+ ...context,
432
+ headingLevel: nextHeadingLevel,
433
+ parentBaseType: baseType,
434
+ ownerBaseType: context.parentBaseType,
435
+ conrefChain: resolvedConref
436
+ ? new Set([...(context.conrefChain || []), resolvedConref])
437
+ : context.conrefChain,
438
+ insideConref: context.insideConref || !!mark,
439
+ };
440
+ if (renderer) {
441
+ let html = renderer(effectiveNode, childCtx, renderChildren);
442
+ if (baseType && !PASS_THROUGH_BASETYPES.has(baseType)) {
443
+ const tagName = effectiveNode.tagName || baseType.split('/').pop() || baseType;
444
+ html = injectAttributes(html, tagName, effectiveNode.sourceRange);
445
+ // Before the profiling wrapper: an inline element's wrapper span would
446
+ // otherwise become the "first tag" the mark lands on.
447
+ if (mark)
448
+ html = markConrefContent(html, mark, baseType, !!context.insideConref);
449
+ html = wrapProfilingHighlight(html, effectiveNode, tagName);
450
+ }
451
+ return html;
452
+ }
453
+ return wrapProfilingHighlight(renderChildren(effectiveNode, childCtx), effectiveNode);
454
+ }
455
+ // conrefend replaces a *single* referencing element with a *run* of
456
+ // elements pulled from the target document (the conref target through the
457
+ // conrefend target, inclusive) — a fundamentally different shape from
458
+ // normal conref's one-for-one substitution, so it's handled as its own
459
+ // path rather than folded into resolveConrefForNode. Only the first
460
+ // element in the range takes on the referencing element's own
461
+ // tag/attributes (mergeConrefTarget, same rule as normal conref) — the
462
+ // rest render as themselves, straight from the target document, since
463
+ // there's no second referencing element for them to inherit from.
464
+ //
465
+ // Every member is re-stamped with the referencing element's sourceRange
466
+ // (see stampSourceRange): the whole run highlights as the referencing tag,
467
+ // and no member leaks target-document line numbers into this file's
468
+ // data-line map — the bug that used to make range members after the first
469
+ // steal highlights and scroll-sync for unrelated lines.
470
+ function renderConrefRange(node, range, context, conref) {
471
+ return range
472
+ .map((rangeNode, i) => {
473
+ // Each member is its own target in the source file, so each carries its
474
+ // own jump position (the first one's merge keeps the referencing tag).
475
+ const mark = conrefMarkFor(rangeNode, context);
476
+ if (i === 0) {
477
+ const merged = mergeConrefTarget(node, rangeNode);
478
+ return renderEffectiveNode(merged, context, conref, mark);
479
+ }
480
+ return renderElement(stampSourceRange(rangeNode, node.sourceRange), context, mark);
481
+ })
482
+ .join('');
483
+ }
484
+ export function renderElement(node, context, conrefMark) {
485
+ if (node.type === 'text') {
486
+ return escapeHtml(node.text || '');
487
+ }
488
+ const conref = node.attributes?.conref;
489
+ const conrefend = node.attributes?.conrefend;
490
+ if (conref && conrefend && context.resolveConrefRange && !context.conrefChain?.has(conref)) {
491
+ const range = context.resolveConrefRange(conref, conrefend);
492
+ // A range that fails to resolve (e.g. the two ids aren't siblings, or
493
+ // one doesn't exist) falls through to normal single-target conref
494
+ // handling below instead — showing the conref target alone is a more
495
+ // useful degradation than showing nothing.
496
+ if (range && range.length > 0) {
497
+ return renderConrefRange(node, range, context, conref);
498
+ }
499
+ }
500
+ const resolved = resolveConrefForNode(node, context);
501
+ const effectiveNode = resolveKeyrefForNode(resolved.node, context);
502
+ // The element's own conref wins over a mark handed down by a range.
503
+ return renderEffectiveNode(effectiveNode, context, resolved.chainKey, resolved.mark ?? conrefMark);
504
+ }
505
+ function renderChildren(node, context) {
506
+ const children = node.children || [];
507
+ // Resolved key text can leave CJK and Latin glued together (`打开` + `ABC`).
508
+ // Insert a display-only space outside the key element; the source is untouched.
509
+ const spacing = computeKeyrefSpacing(children, node.baseType, context.resolveKey);
510
+ return children
511
+ .map((child, i) => {
512
+ const html = renderElement(child, context);
513
+ return (spacing[i].before ? ' ' : '') + html + (spacing[i].after ? ' ' : '');
514
+ })
515
+ .join('');
516
+ }
517
+ export function renderDocument(root, context) {
518
+ return renderElement(root, context);
519
+ }