@dita-viewer/core 0.2.3 → 0.2.5

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 (42) hide show
  1. package/dist/bookRender.d.ts +8 -0
  2. package/dist/bookRender.js +2 -0
  3. package/dist/editor/conkeyref.d.ts +12 -2
  4. package/dist/editor/conkeyref.js +32 -0
  5. package/dist/editor/keySpace.d.ts +57 -3
  6. package/dist/editor/keySpace.js +112 -5
  7. package/dist/editor/refResolvers.d.ts +28 -1
  8. package/dist/editor/refResolvers.js +68 -4
  9. package/dist/editor/renderContext.d.ts +28 -0
  10. package/dist/editor/renderContext.js +38 -3
  11. package/dist/editor/topicRender.d.ts +24 -1
  12. package/dist/editor/topicRender.js +20 -6
  13. package/dist/index.d.ts +6 -4
  14. package/dist/index.js +12 -3
  15. package/dist/parser/ditaParser.js +76 -18
  16. package/dist/parser/domTypes.d.ts +9 -1
  17. package/dist/render/baseTypeMap.js +39 -3
  18. package/dist/render/mapTypeMap.d.ts +6 -0
  19. package/dist/render/mapTypeMap.js +11 -5
  20. package/dist/render/refErrorTexts.d.ts +27 -0
  21. package/dist/render/refErrorTexts.js +43 -0
  22. package/dist/render/refTargets.d.ts +12 -0
  23. package/dist/render/refTargets.js +31 -0
  24. package/dist/render/renderer.d.ts +38 -0
  25. package/dist/render/renderer.js +139 -4
  26. package/dist/siteRender.js +2 -0
  27. package/dist-esm/bookRender.js +2 -0
  28. package/dist-esm/editor/conkeyref.js +31 -0
  29. package/dist-esm/editor/keySpace.js +107 -7
  30. package/dist-esm/editor/refResolvers.js +64 -1
  31. package/dist-esm/editor/renderContext.js +41 -6
  32. package/dist-esm/editor/topicRender.js +20 -6
  33. package/dist-esm/index.js +4 -3
  34. package/dist-esm/parser/ditaParser.js +76 -18
  35. package/dist-esm/render/baseTypeMap.js +39 -3
  36. package/dist-esm/render/mapTypeMap.js +11 -5
  37. package/dist-esm/render/refErrorTexts.js +38 -0
  38. package/dist-esm/render/refTargets.js +25 -0
  39. package/dist-esm/render/renderer.js +139 -4
  40. package/dist-esm/siteRender.js +2 -0
  41. package/package.json +1 -1
  42. package/styles/dita-content.css +69 -0
@@ -1,4 +1,5 @@
1
1
  import { DitaNode } from '../parser/domTypes';
2
+ import { RefErrorTexts } from './refErrorTexts';
2
3
  export interface RenderContext {
3
4
  headingLevel: number;
4
5
  asWebviewUri: (path: string) => string;
@@ -130,6 +131,43 @@ export interface RenderContext {
130
131
  * applied to xref titles.
131
132
  */
132
133
  isInCurrentBook?: (href: string) => string | undefined;
134
+ /**
135
+ * Opt-in broken-reference diagnosis: given a raw @conref or @href value,
136
+ * returns a human-readable reason when the reference is broken (the
137
+ * target file is missing, does not parse as XML, or names no such id),
138
+ * and undefined when it is fine -- or when the host chooses not to
139
+ * diagnose it (external URLs and absolute paths are the host's to
140
+ * exclude; see makeRefErrorResolver). The renderer only PRESENTS the
141
+ * answer: a conref that resolved to nothing becomes a .ref-error
142
+ * placeholder chip instead of a silently empty element, and an EMPTY
143
+ * xref with a broken target becomes a .xref-broken marker instead of a
144
+ * link-shaped hint that reads as if it worked. Same injection pattern
145
+ * as noteLabels/resolveTitle -- the host owns the diagnosis logic and
146
+ * the wording's locale, this module stays host-neutral. Absent: every
147
+ * render path keeps its historical shape byte-for-byte.
148
+ *
149
+ * Deliberately NOT consulted for a conref cycle (conrefChain already
150
+ * holds the reference): a loop renders its literal content, and a
151
+ * "could not be resolved" chip there would mislabel a different class
152
+ * of problem. A failed conrefend range falls through to the single
153
+ * conref path, so the chip covers it naturally.
154
+ */
155
+ refError?: (ref: string) => string | undefined;
156
+ /**
157
+ * Wording for the two refError presentations (see refErrorTexts.ts).
158
+ * The host localizes these; absent or partial fields fall back to the
159
+ * English defaults. Only read when refError is wired.
160
+ */
161
+ refErrorTexts?: RefErrorTexts;
162
+ /**
163
+ * The conkeyref counterpart of refError: given a raw @conkeyref value,
164
+ * the reason it pulls nothing (key not defined / no target, file missing
165
+ * or unparseable, id absent), or undefined when it resolves. Wired only
166
+ * when the host has a key space, so a topic previewed without a map is
167
+ * not flagged for keys it cannot have. Consulted only when the element
168
+ * has no @conref of its own that rescues it.
169
+ */
170
+ conkeyrefError?: (conkeyref: string) => string | undefined;
133
171
  }
134
172
  export declare function mergeProfilingAttrs(own: Record<string, string> | undefined, inherited: Record<string, string>): Record<string, string>;
135
173
  /** The data-profile-keys attribute value the webview's filter panel keys off of. */
@@ -8,6 +8,7 @@ exports.renderElement = renderElement;
8
8
  exports.renderDocument = renderDocument;
9
9
  const baseTypeMap_1 = require("./baseTypeMap");
10
10
  const cjkSpacing_1 = require("./cjkSpacing");
11
+ const refErrorTexts_1 = require("./refErrorTexts");
11
12
  const CONTAINER_BASETYPES = new Set([
12
13
  'topic/section',
13
14
  'topic/example',
@@ -377,18 +378,74 @@ function resolveConrefForNode(node, context) {
377
378
  }
378
379
  }
379
380
  const conref = node.attributes?.conref;
380
- if (!conref || !context.resolveConref)
381
+ if (!conref || !context.resolveConref) {
382
+ // An unresolved conkeyref with no @conref to fall back on: the element
383
+ // would render its own (usually empty) content. Not on a cycle -- the
384
+ // chain check above already excluded that case.
385
+ if (conkeyref && !conref && context.resolveConkeyref && !context.conrefChain?.has(conkeyref)) {
386
+ const reason = context.conkeyrefError?.(conkeyref);
387
+ if (reason !== undefined)
388
+ return { node, refErrorReason: reason, refErrorRef: conkeyref };
389
+ }
381
390
  return { node };
391
+ }
382
392
  // A conref already resolved on this branch points back here — stop the
383
393
  // cycle and render the element's literal content instead of recursing.
384
394
  if (context.conrefChain?.has(conref))
385
395
  return { node };
386
396
  const target = context.resolveConref(conref);
387
- if (!target)
388
- return { node };
397
+ if (!target) {
398
+ // Resolution was attempted and pulled nothing. When the host wired a
399
+ // diagnosis, a broken reference reads as a placeholder chip instead of
400
+ // the element's (usually empty) literal content -- the silent-empty
401
+ // render is the dangerous shape in a review. A cycle above deliberately
402
+ // never reaches this branch.
403
+ const reason = context.refError?.(conref);
404
+ return reason !== undefined ? { node, refErrorReason: reason, refErrorRef: conref } : { node };
405
+ }
389
406
  const end = followConrefChain(target, context);
390
407
  return { node: mergeConrefTarget(node, end), chainKey: conref, mark: conrefMarkFor(end, context) };
391
408
  }
409
+ /**
410
+ * The placeholder chip for a conref that pulled nothing (see
411
+ * RenderContext.refError). title carries the raw reference value so it can
412
+ * be copied straight out of the tooltip to fix the source; the data-line*
413
+ * range is the referencing element's own, so the chip keeps participating
414
+ * in click-to-source, scroll-sync and diff highlighting exactly like the
415
+ * element it stands in for.
416
+ */
417
+ function renderRefErrorPlaceholder(node, context, ref, reason) {
418
+ const texts = { ...refErrorTexts_1.DEFAULT_REF_ERROR_TEXTS, ...context.refErrorTexts };
419
+ const range = node.sourceRange;
420
+ const label = escapeHtml((0, refErrorTexts_1.fillRefErrorTemplate)(texts.content, reason));
421
+ const attrs = ` title="${escapeHtml(ref)}"` +
422
+ ` data-line="${range.startLine}" data-end-line="${range.endLine}"` +
423
+ ` data-start-col="${range.startCol}" data-end-col="${range.endCol}"`;
424
+ // The chip must be a legal child of whatever the stand-in element would
425
+ // have been: a bare <span> directly in <tbody> is foster-parented by the
426
+ // browser to just before the whole table (the same trap the comment
427
+ // renderer avoids), and a <span> directly in <ul> is invalid. So rows and
428
+ // cells stay rows and cells, items stay items, and a block-level slot
429
+ // gets a <div>; only a slot that holds running text keeps the inline span.
430
+ const baseType = node.baseType;
431
+ if (baseType === 'topic/row' || baseType === 'topic/strow') {
432
+ // colspan 1000 is the HTML maximum: the chip spans the whole row.
433
+ return `<tr class="ref-error-row"><td class="ref-error"${attrs} colspan="1000">${label}</td></tr>`;
434
+ }
435
+ if (baseType === 'topic/tbody' || baseType === 'topic/thead' || baseType === 'topic/tgroup' || baseType === 'topic/sthead') {
436
+ // A whole row group (or the tgroup around it) failed: one full-width
437
+ // row inside a <tbody> stands in for it, so it stays in the table.
438
+ return `<tbody class="ref-error-rows"><tr class="ref-error-row"><td class="ref-error"${attrs} colspan="1000">${label}</td></tr></tbody>`;
439
+ }
440
+ if (baseType === 'topic/entry' || baseType === 'topic/stentry') {
441
+ return `<td class="ref-error"${attrs}>${label}</td>`;
442
+ }
443
+ if (baseType === 'topic/li' || baseType === 'topic/sli') {
444
+ return `<li class="ref-error"${attrs}>${label}</li>`;
445
+ }
446
+ const tag = BLOCK_COMMENT_PARENTS.has(context.parentBaseType || '') ? 'div' : 'span';
447
+ return `<${tag} class="ref-error"${attrs}>${label}</${tag}>`;
448
+ }
392
449
  /**
393
450
  * Per DITA keyref semantics, the key's resource target becomes the
394
451
  * referencing element's effective href when the element carries no href of
@@ -499,10 +556,70 @@ function renderConrefRange(node, range, context, conref) {
499
556
  })
500
557
  .join('');
501
558
  }
559
+ // Parents whose content model is element-only, so a comment written inside
560
+ // them sits between blocks rather than inside a sentence and should get a
561
+ // block of its own. Everything else -- p, ph, li, entry, title, note text --
562
+ // holds mixed content, where an inline <span> is both valid and what the
563
+ // author saw. This is the same inline/block distinction profiling markers
564
+ // make (INLINE_PROFILING_BASETYPES), stated the other way round: there,
565
+ // inline was the short list; here the inline cases are the majority, and
566
+ // getting it wrong on the block side is the harmless direction (a comment on
567
+ // its own line inside a phrase) while a <div> inside a <p> would make the
568
+ // browser close the paragraph and split the sentence around it.
569
+ const BLOCK_COMMENT_PARENTS = new Set([
570
+ 'topic/body',
571
+ 'topic/section',
572
+ 'topic/example',
573
+ 'topic/fig',
574
+ 'topic/div',
575
+ 'topic/bodydiv',
576
+ 'topic/sectiondiv',
577
+ 'topic/topic',
578
+ 'topic/abstract',
579
+ 'topic/related-links',
580
+ 'topic/imagemap',
581
+ // List containers: a comment written between two <li>s is not part of
582
+ // either item's sentence, and an inline span there would be a stray
583
+ // fragment of the previous item.
584
+ 'topic/ul',
585
+ 'topic/ol',
586
+ 'topic/sl',
587
+ 'topic/dl',
588
+ ]);
589
+ /**
590
+ * An XML comment, shown in the flow at the position it was authored in --
591
+ * Oxygen's Author mode shows the comment text the same way, instead of the
592
+ * reader having to open the source. The text is the comment's inner content
593
+ * with the `<!-- -->` delimiters stripped: the delimiters are markup, and a
594
+ * comment's *text* is what the author wanted read. data-dita-tagname makes the
595
+ * story explicit through the Tags toggle (its tooltip reads "comment"), and
596
+ * data-line* keeps preview clicks and scroll-sync landing on the comment's own
597
+ * source lines -- its range spans `<!--` through `-->`.
598
+ *
599
+ * An empty or whitespace-only comment renders nothing: it is a spelling of
600
+ * "nothing here", and an empty box in the page would only be noise.
601
+ */
602
+ function renderComment(node, context) {
603
+ const text = (node.comment || '').replace(/\r\n?/g, '\n').trim();
604
+ if (!text)
605
+ return '';
606
+ const block = BLOCK_COMMENT_PARENTS.has(context.parentBaseType || '');
607
+ const tag = block ? 'div' : 'span';
608
+ const cls = block ? 'dv-comment dv-comment--block' : 'dv-comment';
609
+ const range = node.sourceRange;
610
+ return (`<${tag} class="${cls}" data-dita-tagname="comment"` +
611
+ ` data-line="${range.startLine}" data-end-line="${range.endLine}"` +
612
+ ` data-start-col="${range.startCol}" data-end-col="${range.endCol}">` +
613
+ escapeHtml(text) +
614
+ `</${tag}>`);
615
+ }
502
616
  function renderElement(node, context, conrefMark) {
503
617
  if (node.type === 'text') {
504
618
  return escapeHtml(node.text || '');
505
619
  }
620
+ if (node.type === 'comment') {
621
+ return renderComment(node, context);
622
+ }
506
623
  const conref = node.attributes?.conref;
507
624
  const conrefend = node.attributes?.conrefend;
508
625
  if (conref && conrefend && context.resolveConrefRange && !context.conrefChain?.has(conref)) {
@@ -516,12 +633,30 @@ function renderElement(node, context, conrefMark) {
516
633
  }
517
634
  }
518
635
  const resolved = resolveConrefForNode(node, context);
636
+ if (resolved.refErrorReason !== undefined) {
637
+ return renderRefErrorPlaceholder(node, context, resolved.refErrorRef ?? conref, resolved.refErrorReason);
638
+ }
519
639
  const effectiveNode = resolveKeyrefForNode(resolved.node, context);
520
640
  // The element's own conref wins over a mark handed down by a range.
521
641
  return renderEffectiveNode(effectiveNode, context, resolved.chainKey, resolved.mark ?? conrefMark);
522
642
  }
643
+ // Parents whose children must not include a comment span or block:
644
+ // - table machinery: a <span>/<div> directly inside <table>, <tbody> or <tr>
645
+ // is foster-parented by the browser to just before the whole table, so the
646
+ // comment would show up away from where it was written;
647
+ // - preformatted blocks: the comment's text would read, and copy, as code;
648
+ // - titles: the heading's text feeds the outline / table of contents.
649
+ // Keyed by the baseType of the element being rendered (the real parent), not
650
+ // by the overloaded context.parentBaseType.
651
+ const NO_COMMENT_CHILDREN = new Set([
652
+ 'topic/table', 'topic/tgroup', 'topic/thead', 'topic/tbody', 'topic/row',
653
+ 'topic/simpletable', 'topic/sthead', 'topic/strow',
654
+ 'topic/pre', 'topic/codeblock', 'topic/lines',
655
+ 'topic/title',
656
+ ]);
523
657
  function renderChildren(node, context) {
524
- const children = node.children || [];
658
+ const skipComments = !!node.baseType && NO_COMMENT_CHILDREN.has(node.baseType);
659
+ const children = (node.children || []).filter((c) => !(skipComments && c.type === 'comment'));
525
660
  // Resolved key text can leave CJK and Latin glued together (`打开` + `ABC`).
526
661
  // Insert a display-only space outside the key element; the source is untouched.
527
662
  const spacing = (0, cjkSpacing_1.computeKeyrefSpacing)(children, node.baseType, context.resolveKey);
@@ -240,6 +240,8 @@ function renderSiteXml(input) {
240
240
  bookMembers: new Set(members),
241
241
  docFile: current,
242
242
  markConrefs: true,
243
+ refErrors: true,
244
+ refErrorTexts: input.refErrorTexts,
243
245
  });
244
246
  if (result.error !== undefined) {
245
247
  return {
@@ -126,6 +126,8 @@ export function renderBookXml(input) {
126
126
  bookMembers: members,
127
127
  docFile: absPath,
128
128
  markConrefs: true,
129
+ refErrors: true,
130
+ refErrorTexts: input.refErrorTexts,
129
131
  });
130
132
  if (result.error !== undefined) {
131
133
  sections.push(`<p class="dita-book-error">${escapeHtml(result.error)}</p>`);
@@ -22,6 +22,7 @@
22
22
  // (first definition wins; a context map fully replaces the ancestor scan) --
23
23
  // this function only reads the map it is handed, so switching the key context
24
24
  // switches conkeyref targets for free.
25
+ import { isNonDitaTarget } from '../render/refTargets';
25
26
  /**
26
27
  * Addressing inside the key's target topic: the whole topic when the value has
27
28
  * only the key name, otherwise the last path segment (the element id, for both
@@ -102,3 +103,33 @@ export function resolveConkeyref(conkeyref, defs, loadTopic) {
102
103
  return root;
103
104
  return findElementById(root, targetId);
104
105
  }
106
+ /**
107
+ * Why a conkeyref pulls nothing, in the order resolveConkeyref checks:
108
+ * the key is undefined or has no href; its file is missing or not
109
+ * well-formed (`fileExists` tells the two apart, as loadTopic cannot); the
110
+ * addressed id is absent. Undefined when the reference resolves. Kept next
111
+ * to resolveConkeyref and built on the same steps so the two cannot
112
+ * disagree about what "resolves" means.
113
+ */
114
+ export function diagnoseConkeyref(conkeyref, defs, loadTopic, fileExists) {
115
+ const { keyName, elementId } = parseConkeyref(conkeyref);
116
+ if (!keyName)
117
+ return undefined;
118
+ const def = defs.get(keyName);
119
+ if (!def || !def.href)
120
+ return 'missingKey';
121
+ // A keydef may name a non-local or non-DITA resource (scope="external"
122
+ // href="https://...", format="pdf" href="manual.pdf"): keySpace records
123
+ // hrefs without filtering scope/format, so the exclusion lives here, from
124
+ // the same rule makeRefErrorResolver applies to a direct ref. The fragment
125
+ // is stripped first -- it is the target format's own, not a DITA id.
126
+ if (isNonDitaTarget(def.href.split('#')[0]))
127
+ return undefined;
128
+ const root = loadTopic(def.baseDir, def.href);
129
+ if (!root)
130
+ return fileExists(def.baseDir, def.href) ? 'parseError' : 'missingFile';
131
+ const targetId = elementId ?? hrefFragmentTarget(def.href);
132
+ if (!targetId)
133
+ return undefined;
134
+ return findElementById(root, targetId) ? undefined : 'missingId';
135
+ }
@@ -4,9 +4,10 @@
4
4
  // the mocha suite. buildKeyMap (keyMap.ts) and any other consumer of "the
5
5
  // keys a map defines" go through collectMapKeys so there is one rule for
6
6
  // what a keydef contributes.
7
- import { dirname } from 'path';
7
+ import { dirname, resolve } from 'path';
8
8
  import { parseDitamap, preprocessEntities } from '../parser/ditaParser';
9
- import { expandDitamapRefs } from './refResolvers';
9
+ import { isDitamapRef } from '../render/mapTypeMap';
10
+ import { decodeHrefPart, expandDitamapRefs } from './refResolvers';
10
11
  import { sourceStamp } from './sourceText';
11
12
  function extractTextFromNode(node) {
12
13
  if (node.type === 'text')
@@ -66,15 +67,83 @@ export function qualifiedNamesMulti(name, scopeChains) {
66
67
  out.add(q);
67
68
  return [...out];
68
69
  }
70
+ /** The key of one (scope, name) entry in a scope index; `scopeId` is the chain joined with "/" ("" is the root). */
71
+ export function scopeKeyIndexKey(scopeId, name) {
72
+ return `${scopeId}\u0000${name}`;
73
+ }
74
+ /**
75
+ * Resolves a key written at a place that sits in the given scope chains, against an
76
+ * index of `scopeKeyIndexKey(scope, name)` entries: its own scope first, then each
77
+ * enclosing one, the nearest definition winning (DITA's scope precedence). A name with
78
+ * scope qualifiers (`a.k`, or `x.a.k` for nested scopes) is looked up below the scope
79
+ * the search starts from, so a key defined inside a scope is bare only within it and
80
+ * reachable from outside only by its qualified name. A place in several chains (a
81
+ * `keyscope` listing several names) resolves in the first chain that finds the key.
82
+ *
83
+ * The one rule behind both the completeness checks and the preview, so the two cannot
84
+ * disagree about which definition a reference reaches.
85
+ */
86
+ export function resolveKeyInScope(key, chains, index) {
87
+ const parts = key.split('.');
88
+ for (const chain of chains) {
89
+ for (let depth = chain.length; depth >= 0; depth--) {
90
+ const prefix = chain.slice(0, depth);
91
+ for (let j = 0; j < parts.length; j++) {
92
+ const scope = prefix.concat(parts.slice(0, j)).join('/');
93
+ const def = index.get(scopeKeyIndexKey(scope, parts.slice(j).join('.')));
94
+ if (def !== undefined)
95
+ return def;
96
+ }
97
+ }
98
+ }
99
+ return undefined;
100
+ }
101
+ export function createKeyScopeIndex() {
102
+ return { values: new Map(), defs: new Map(), topicScopes: new Map() };
103
+ }
104
+ function topicScopeKey(absPath) {
105
+ const p = resolve(absPath);
106
+ return process.platform === 'win32' ? p.toLowerCase() : p;
107
+ }
108
+ /** The scope chains of the topicrefs that publish `absPath`, or undefined when no topicref does. */
109
+ export function getTopicScopeChains(scopes, absPath) {
110
+ return scopes.topicScopes.get(topicScopeKey(absPath));
111
+ }
112
+ function noteTopicScope(scopes, absPath, chains) {
113
+ const k = topicScopeKey(absPath);
114
+ const known = scopes.topicScopes.get(k);
115
+ const sig = JSON.stringify(chains);
116
+ if (!known)
117
+ scopes.topicScopes.set(k, [chains]);
118
+ else if (!known.some((c) => JSON.stringify(c) === sig))
119
+ known.push(chains);
120
+ }
121
+ /**
122
+ * The scope chains a topic is read in when nothing says where it sits: the first
123
+ * topicref in the map that publishes it, or the root scope when none does (a topic
124
+ * no map publishes belongs to no keyscope).
125
+ */
126
+ export function defaultTopicScopeChains(scopes, absPath) {
127
+ return getTopicScopeChains(scopes, absPath)?.[0] ?? [[]];
128
+ }
129
+ /** A topicref href that names a file of this project: no scheme, not marked external. */
130
+ function localTopicPath(href, scope) {
131
+ if (!href || scope === 'external' || /^[a-z][a-z0-9+.-]*:/i.test(href))
132
+ return undefined;
133
+ const path = href.split('#')[0];
134
+ return path || undefined;
135
+ }
69
136
  /**
70
137
  * Parses one ditamap, expands the ditamaps it references, and adds every
71
138
  * key it defines to `into` (first definition wins, in document order).
72
139
  * When `hrefs` is supplied, each newly defined key also records its resource
73
140
  * target there (same first-definition-wins gate as the value), keyed by the
74
- * individual name. Throws if the map itself cannot be read or parsed; the
75
- * caller decides whether that is fatal.
141
+ * individual name. When `scopes` is supplied, every definition is also recorded
142
+ * under the scope it sits in, and every topic a topicref publishes under the scope
143
+ * of that topicref (same first-definition-wins gate). Throws if the map itself
144
+ * cannot be read or parsed; the caller decides whether that is fatal.
76
145
  */
77
- export function collectMapKeys(mapPath, into, read, hrefs) {
146
+ export function collectMapKeys(mapPath, into, read, hrefs, scopes) {
78
147
  const content = read(mapPath, 'utf-8');
79
148
  const doc = parseDitamap(preprocessEntities(content));
80
149
  const mapRoot = doc.root;
@@ -110,8 +179,26 @@ export function collectMapKeys(mapPath, into, read, hrefs) {
110
179
  hrefs?.set(name, { href: node.attributes?.href, baseDir: mapDir });
111
180
  }
112
181
  }
182
+ if (scopes) {
183
+ // The same definition, filed by scope: a lookup that knows where it is
184
+ // asking from finds the nearest one instead of the first in the file.
185
+ for (const chain of chains) {
186
+ const at = scopeKeyIndexKey(chain.join('/'), keyName);
187
+ if (!scopes.values.has(at)) {
188
+ scopes.values.set(at, value || keyName);
189
+ scopes.defs.set(at, { href: node.attributes?.href, baseDir: mapDir });
190
+ }
191
+ }
192
+ }
113
193
  }
114
194
  }
195
+ // A topicref publishes its topic in the scopes it sits in. A keydef does not (it
196
+ // is resource-only), and a submap reference was expanded into its children above.
197
+ if (scopes && baseType === 'map/topicref' && !isDitamapRef(node)) {
198
+ const path = localTopicPath(node.attributes?.href, node.attributes?.scope);
199
+ if (path)
200
+ noteTopicScope(scopes, resolve(mapDir, decodeHrefPart(path)), chains);
201
+ }
115
202
  for (const child of node.children || [])
116
203
  walk(child, chains);
117
204
  }
@@ -163,9 +250,10 @@ export function buildKeySpace(contextMap, ancestorMaps, read, onError = () => un
163
250
  }
164
251
  const keys = new Map();
165
252
  const defs = new Map();
253
+ const scopes = createKeyScopeIndex();
166
254
  for (const mf of sources) {
167
255
  try {
168
- collectMapKeys(mf, keys, recordingRead, defs);
256
+ collectMapKeys(mf, keys, recordingRead, defs, scopes);
169
257
  }
170
258
  catch (e) {
171
259
  onError(mf, e);
@@ -179,7 +267,8 @@ export function buildKeySpace(contextMap, ancestorMaps, read, onError = () => un
179
267
  // tests drive -- gets it, and so renderContext.ts can read it without
180
268
  // importing the vscode-dependent keyMap.ts.
181
269
  registerKeyDefs(keys, defs);
182
- return { keys, defs, files: [...new Set(files)], status };
270
+ registerKeyScopes(keys, scopes);
271
+ return { keys, defs, scopes, files: [...new Set(files)], status };
183
272
  }
184
273
  // ── values map -> href defs, by instance identity ──
185
274
  //
@@ -199,3 +288,14 @@ export function registerKeyDefs(keys, defs) {
199
288
  export function getKeyDefs(keys) {
200
289
  return defsByKeyMap.get(keys);
201
290
  }
291
+ // The scope index travels with the values map the same way, for the same reason: the
292
+ // render paths hand around `keyMap` and nothing else.
293
+ const scopesByKeyMap = new WeakMap();
294
+ export function registerKeyScopes(keys, scopes) {
295
+ scopesByKeyMap.set(keys, scopes);
296
+ }
297
+ /** The scope index paired with a given values map, or undefined if it was not
298
+ * produced by buildKeySpace (e.g. a hand-built map in a test). */
299
+ export function getKeyScopes(keys) {
300
+ return scopesByKeyMap.get(keys);
301
+ }
@@ -13,6 +13,8 @@ import { existsSync, openSync, readSync, closeSync, statSync } from 'fs';
13
13
  import { resolve, isAbsolute, extname, dirname, relative, normalize } from 'path';
14
14
  import { parseDita, parseDitamap, preprocessEntities } from '../parser/ditaParser';
15
15
  import { extractText, getMapTitleText, isDitamapRef } from '../render/mapTypeMap';
16
+ import { DEFAULT_REF_ERROR_TEXTS } from '../render/refErrorTexts';
17
+ import { URL_SCHEME_RE, isNonDitaTarget } from '../render/refTargets';
16
18
  import { readSourceText } from './sourceText';
17
19
  // ── Image dimensions (for reserving layout space before the image loads) ──
18
20
  //
@@ -424,6 +426,67 @@ export function makeConrefRangeResolver(docDir, ownRoot, sharedCache) {
424
426
  return run;
425
427
  };
426
428
  }
429
+ /**
430
+ * Default broken-reference diagnosis for RenderContext.refError: the
431
+ * three-state reason a local reference can fail with, in the order the
432
+ * resolver chain itself checks --
433
+ * missing file -- nothing at the referenced path in the closure;
434
+ * parse error -- the file is there but is not well-formed XML (the
435
+ * common review case: an author broke a DIFFERENT file);
436
+ * missing id -- the file parses but #topicId/elementId names no id.
437
+ * Returns undefined for a reference that resolves, and for ones it will
438
+ * not diagnose at all: external URLs, absolute paths, and hrefs that are
439
+ * neither a fragment nor a DITA-shaped file path (a bare id is not a
440
+ * filename to probe). Same-document fragments (#id, #./topicId/id) are
441
+ * checked against ownRoot without touching the filesystem.
442
+ *
443
+ * Rides the shared file cache so a target already loaded for conref/title
444
+ * resolution is not parsed twice, and every probed path -- missing ones
445
+ * included -- lands in touchedFiles() for the caller's dependency set:
446
+ * creating the missing target is exactly the change that must invalidate
447
+ * a cached render. The cache memoizes missing and unparsable alike as
448
+ * undefined, so existsSync is what tells the two apart.
449
+ *
450
+ * The renderer only presents the returned reason (see refErrorTexts.ts);
451
+ * a host with its own diagnostic rules supplies its own callback instead.
452
+ */
453
+ export function makeRefErrorResolver(docDir, ownRoot, sharedCache, texts = DEFAULT_REF_ERROR_TEXTS) {
454
+ const cache = sharedCache ?? makeFileCache(docDir);
455
+ return (ref) => {
456
+ if (!ref)
457
+ return undefined;
458
+ const hashIdx = ref.indexOf('#');
459
+ const filePath = hashIdx >= 0 ? ref.substring(0, hashIdx) : ref;
460
+ // "#./topicId/elementId" shorthand: strip the same-document marker
461
+ // before splitting, the same rule makeConrefRangeResolver applies.
462
+ const idPart = hashIdx >= 0 ? ref.substring(hashIdx + 1).replace(/^\.\/+/, '') : '';
463
+ const parts = idPart.split('/');
464
+ const elementId = parts.length > 1 ? parts[1] : parts[0];
465
+ // URL, absolute path, or a web document (guide.html#sec): not a local
466
+ // DITA target, so never probed -- see isNonDitaTarget.
467
+ if (isNonDitaTarget(filePath))
468
+ return undefined;
469
+ if (!filePath) {
470
+ // Same-document fragment: the id must exist in the document itself.
471
+ if (!idPart || !elementId || !ownRoot)
472
+ return undefined;
473
+ return cache.findElementById(ownRoot, elementId) ? undefined : texts.missingId;
474
+ }
475
+ // No fragment: only a DITA-shaped file path is a file-level reference
476
+ // worth probing (a bare word is not a filename). With a fragment the
477
+ // file part is always checked, whatever its extension -- conref/xref
478
+ // targets are .dita/.xml in practice but the resolver loads any path.
479
+ if (hashIdx < 0 && !/\.(dita|xml|ditamap)$/i.test(filePath))
480
+ return undefined;
481
+ const abs = resolve(docDir, decodeHrefPart(filePath));
482
+ const root = cache.loadAbsPath(abs);
483
+ if (!root)
484
+ return existsSync(abs) ? texts.parseError : texts.missingFile;
485
+ if (!elementId)
486
+ return undefined;
487
+ return cache.findElementById(root, elementId) ? undefined : texts.missingId;
488
+ };
489
+ }
427
490
  export function makeFileTitleResolver(docDir, sharedCache, resolveKey) {
428
491
  const cache = sharedCache ?? makeFileCache(docDir);
429
492
  return (href) => {
@@ -510,7 +573,7 @@ export function detectIndexLabel(root, uiLanguage) {
510
573
  const lang = root.attributes?.['xml:lang'] || uiLanguage || '';
511
574
  return lang.startsWith('zh') ? '\u7d22\u5f15' : 'Index';
512
575
  }
513
- export const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
576
+ export { URL_SCHEME_RE };
514
577
  /**
515
578
  * Builds the render context's isInCurrentBook resolver: given a cross-file
516
579
  * xref's raw href, return the absolute path of the target IF it is one of
@@ -20,10 +20,12 @@
20
20
  // - collectDependencies / bookMembers: only the book/site path uses them.
21
21
  // collectDependencies also folds image reads into the dependency set.
22
22
  // - suppressIndexterm: only the export path sets it.
23
+ import { existsSync } from 'fs';
23
24
  import { resolve, relative, isAbsolute } from 'path';
24
- import { makeFileCache, makeConrefResolver, makeConrefRangeResolver, makeFileTitleResolver, makeIsInCurrentBook, detectNoteLabels, detectIndexLabel, readImageDimensions, decodeHrefPart, URL_SCHEME_RE, } from './refResolvers';
25
- import { getKeyDefs } from './keySpace';
26
- import { resolveConkeyref } from './conkeyref';
25
+ import { makeFileCache, makeConrefResolver, makeConrefRangeResolver, makeFileTitleResolver, makeIsInCurrentBook, makeRefErrorResolver, detectNoteLabels, detectIndexLabel, readImageDimensions, decodeHrefPart, URL_SCHEME_RE, } from './refResolvers';
26
+ import { DEFAULT_REF_ERROR_TEXTS } from '../render/refErrorTexts';
27
+ import { defaultTopicScopeChains, getKeyDefs, getKeyScopes, resolveKeyInScope } from './keySpace';
28
+ import { diagnoseConkeyref, resolveConkeyref } from './conkeyref';
27
29
  export function buildRenderContext(input) {
28
30
  const { docDir, ownRoot, titleMap, keyMap, asWebviewUri, headingLevel, uiLanguage } = input;
29
31
  // One cache shared by all three resolvers. They routinely load the same
@@ -33,13 +35,22 @@ export function buildRenderContext(input) {
33
35
  const conrefResolver = makeConrefResolver(docDir, ownRoot, fileCache);
34
36
  const conrefRangeResolver = makeConrefRangeResolver(docDir, ownRoot, fileCache);
35
37
  const fileTitleResolver = makeFileTitleResolver(docDir, fileCache);
38
+ // Which scope a reference is read in, and the lookups bound to it. The preview's key
39
+ // space also keeps a flat name map (first definition wins, bare names visible
40
+ // everywhere); a lookup that knows where it sits reads the scope index instead, so it
41
+ // finds the nearest definition the way the completeness checks do.
42
+ const scopeIndex = getKeyScopes(keyMap);
43
+ const keyChains = scopeIndex
44
+ ? (input.keyScope ?? (input.docFile ? defaultTopicScopeChains(scopeIndex, input.docFile) : undefined))
45
+ : undefined;
46
+ const lookupKey = (key) => scopeIndex && keyChains ? resolveKeyInScope(key, keyChains, scopeIndex.values) : keyMap.get(key);
36
47
  const ctx = {
37
48
  headingLevel,
38
49
  asWebviewUri,
39
50
  documentDir: docDir,
40
51
  // Local id match first, then cross-file ("file.dita#topicId" or "file.dita").
41
52
  resolveTitle: (id) => titleMap.get(id) || fileTitleResolver(id),
42
- resolveKey: (key) => keyMap.get(key),
53
+ resolveKey: lookupKey,
43
54
  resolveConref: (conref) => conrefResolver(conref),
44
55
  resolveConrefRange: (conref, conrefend) => conrefRangeResolver(conref, conrefend),
45
56
  noteLabels: detectNoteLabels(ownRoot, uiLanguage),
@@ -71,13 +82,27 @@ export function buildRenderContext(input) {
71
82
  ctx.isInCurrentBook = makeIsInCurrentBook(docDir, input.bookMembers);
72
83
  if (input.clickableExternalXrefs)
73
84
  ctx.clickableExternalXrefs = true;
85
+ if (input.refErrors) {
86
+ const texts = { ...DEFAULT_REF_ERROR_TEXTS, ...input.refErrorTexts };
87
+ ctx.refErrorTexts = texts;
88
+ // Same shared cache as the conref/title resolvers: a target probed here
89
+ // is usually one they already loaded, and every probe (missing files
90
+ // included) joins touchedFiles for the caller's dependency set.
91
+ ctx.refError = makeRefErrorResolver(docDir, ownRoot, fileCache, texts);
92
+ }
74
93
  // conkeyref rides on the same file cache: a key's href resolves against the
75
94
  // map that defined it (baseDir), not the topic being rendered, so it needs
76
95
  // the absolute-path loader rather than the docDir-relative conref resolver.
77
96
  // Discovered from keyMap by identity unless the caller passed defs directly.
78
97
  let lastLoaded;
79
- const keyDefs = input.keyDefs ?? getKeyDefs(keyMap);
80
- if (keyDefs && keyDefs.size > 0) {
98
+ const flatDefs = input.keyDefs ?? getKeyDefs(keyMap);
99
+ // Definitions come from the same scope as the text, so a conkeyref or an xref keyref
100
+ // cannot reach one scope's file while the text shows another's. Defs handed in
101
+ // explicitly (tests) are used as given.
102
+ const keyDefs = flatDefs && !input.keyDefs && scopeIndex && keyChains
103
+ ? { get: (name) => resolveKeyInScope(name, keyChains, scopeIndex.defs) }
104
+ : flatDefs;
105
+ if (keyDefs && flatDefs && flatDefs.size > 0) {
81
106
  // A keyref on a link-shaped element (topic/xref) resolves to the key's
82
107
  // resource target as its effective href. The keydef's href is relative
83
108
  // to the map that defined it, but every href the renderer consumes
@@ -119,6 +144,16 @@ export function buildRenderContext(input) {
119
144
  fileCache.noteOrigin(el, lastLoaded);
120
145
  return el;
121
146
  };
147
+ // Only with a key space (this block): a topic previewed with no map has
148
+ // no keys at all, and "key is not defined" there would flag every
149
+ // conkeyref for a reason the author cannot act on.
150
+ if (input.refErrors) {
151
+ const texts = { ...DEFAULT_REF_ERROR_TEXTS, ...input.refErrorTexts };
152
+ ctx.conkeyrefError = (conkeyref) => {
153
+ const failure = diagnoseConkeyref(conkeyref, keyDefs, loadTopic, (baseDir, href) => existsSync(resolve(baseDir, decodeHrefPart(href.split('#')[0]))));
154
+ return failure === undefined ? undefined : texts[failure];
155
+ };
156
+ }
122
157
  }
123
158
  // One hop further along a reference chain, resolved relative to the file
124
159
  // that holds `from`. conkeyref wins over conref when it resolves, the same