@dita-viewer/core 0.2.4 → 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.
@@ -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
@@ -576,6 +633,9 @@ function renderElement(node, context, conrefMark) {
576
633
  }
577
634
  }
578
635
  const resolved = resolveConrefForNode(node, context);
636
+ if (resolved.refErrorReason !== undefined) {
637
+ return renderRefErrorPlaceholder(node, context, resolved.refErrorRef ?? conref, resolved.refErrorReason);
638
+ }
579
639
  const effectiveNode = resolveKeyrefForNode(resolved.node, context);
580
640
  // The element's own conref wins over a mark handed down by a range.
581
641
  return renderEffectiveNode(effectiveNode, context, resolved.chainKey, resolved.mark ?? conrefMark);
@@ -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
+ }
@@ -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 { makeFileCache, makeConrefResolver, makeConrefRangeResolver, makeFileTitleResolver, makeIsInCurrentBook, makeRefErrorResolver, detectNoteLabels, detectIndexLabel, readImageDimensions, decodeHrefPart, URL_SCHEME_RE, } from './refResolvers';
26
+ import { DEFAULT_REF_ERROR_TEXTS } from '../render/refErrorTexts';
25
27
  import { defaultTopicScopeChains, getKeyDefs, getKeyScopes, resolveKeyInScope } from './keySpace';
26
- import { resolveConkeyref } from './conkeyref';
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
@@ -80,6 +82,14 @@ export function buildRenderContext(input) {
80
82
  ctx.isInCurrentBook = makeIsInCurrentBook(docDir, input.bookMembers);
81
83
  if (input.clickableExternalXrefs)
82
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
+ }
83
93
  // conkeyref rides on the same file cache: a key's href resolves against the
84
94
  // map that defined it (baseDir), not the topic being rendered, so it needs
85
95
  // the absolute-path loader rather than the docDir-relative conref resolver.
@@ -134,6 +144,16 @@ export function buildRenderContext(input) {
134
144
  fileCache.noteOrigin(el, lastLoaded);
135
145
  return el;
136
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
+ }
137
157
  }
138
158
  // One hop further along a reference chain, resolved relative to the file
139
159
  // that holds `from`. conkeyref wins over conref when it resolves, the same
@@ -34,7 +34,7 @@ export function buildTitleMap(root) {
34
34
  return map;
35
35
  }
36
36
  export function renderTopicXml(input) {
37
- const { xml, docDir, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, docFile, markConrefs, keyScope } = input;
37
+ const { xml, docDir, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, docFile, markConrefs, refErrors, refErrorTexts, keyScope } = input;
38
38
  try {
39
39
  const preprocessedXml = preprocessEntities(xml);
40
40
  const ditaDoc = parseDita(preprocessedXml);
@@ -58,6 +58,8 @@ export function renderTopicXml(input) {
58
58
  collectDependencies,
59
59
  docFile,
60
60
  markConrefs,
61
+ refErrors,
62
+ refErrorTexts,
61
63
  keyScope,
62
64
  });
63
65
  const html = renderDocument(ditaDoc.root, ctx);
@@ -75,7 +77,7 @@ export function renderTopicXml(input) {
75
77
  }
76
78
  }
77
79
  export function renderTopicToHtml(input) {
78
- const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs, keyScope } = input;
80
+ const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs, refErrors, refErrorTexts, keyScope } = input;
79
81
  try {
80
82
  if (!existsSync(filePath)) {
81
83
  return { html: '', error: `File not found: ${filePath}` };
@@ -97,6 +99,8 @@ export function renderTopicToHtml(input) {
97
99
  clickableExternalXrefs,
98
100
  docFile: filePath,
99
101
  markConrefs,
102
+ refErrors,
103
+ refErrorTexts,
100
104
  keyScope,
101
105
  });
102
106
  return { html: result.html, title: result.title, error: result.error };
@@ -267,7 +271,12 @@ function dropOldestTopicEntry() {
267
271
  * different key text in each, so a hit from the other scope would be wrong.
268
272
  */
269
273
  export function renderTopicCached(input) {
270
- const key = `${input.filePath}\u0000${input.headingLevel}\u0000${input.keyScope ? JSON.stringify(input.keyScope) : ''}`;
274
+ // The hint wording is part of the key: two locales render different chip
275
+ // text for the same topic, so a hit from the other locale would be wrong.
276
+ // JSON of the (small, fixed-shape) overrides object is a cheap fingerprint;
277
+ // undefined and {} normalize to the same string.
278
+ const textsKey = JSON.stringify(input.refErrorTexts ?? {});
279
+ const key = `${input.filePath}\u0000${input.headingLevel}\u0000${input.keyScope ? JSON.stringify(input.keyScope) : ''}\u0000${textsKey}`;
271
280
  const cached = topicRenderCache.get(key);
272
281
  if (cached &&
273
282
  cached.keyMap === input.keyMap &&
@@ -287,8 +296,9 @@ export function renderTopicCached(input) {
287
296
  // Honour a caller-supplied sink as well, so anyone who passed one still
288
297
  // sees the dependency set instead of having it silently replaced.
289
298
  const dependencies = input.collectDependencies ?? new Set();
290
- // Previews only (see above), so conref'd content is always marked here.
291
- const result = renderTopicToHtml({ ...input, markConrefs: true, collectDependencies: dependencies });
299
+ // Previews only (see above), so conref'd content is always marked here and
300
+ // broken references always surface as hints rather than silent empties.
301
+ const result = renderTopicToHtml({ ...input, markConrefs: true, refErrors: true, collectDependencies: dependencies });
292
302
  if (result.error) {
293
303
  // Never cache a failure. A malformed mid-edit save is exactly the
294
304
  // transient case this path sees, and pinning it would keep serving the
package/dist-esm/index.js CHANGED
@@ -40,7 +40,8 @@ export { computeKeyrefSpacing, needsSpace } from './render/cjkSpacing';
40
40
  export { mergeProfilingAttrs, profilingChipsHtml, profilingKeysAttr } from './render/renderer';
41
41
  export { resolveConkeyref } from './editor/conkeyref';
42
42
  export { collectMapKeys, isKeyContextAvailable, keySourceMaps, qualifiedNames, qualifiedNamesMulti, resolveKeyInScope, scopeKeyIndexKey } from './editor/keySpace';
43
- export { DEFAULT_NOTE_LABELS, IMAGE_DIMENSIONS_CACHE_MAX, URL_SCHEME_RE, ZH_NOTE_LABELS, clearImageDimensionsCache, detectIndexLabel, detectNoteLabels, expandDitamapRefs, makeConrefRangeResolver, makeConrefResolver, makeFileCache, makeFileTitleResolver, makeIsInCurrentBook, readImageDimensions } from './editor/refResolvers';
43
+ export { DEFAULT_NOTE_LABELS, IMAGE_DIMENSIONS_CACHE_MAX, URL_SCHEME_RE, ZH_NOTE_LABELS, clearImageDimensionsCache, detectIndexLabel, detectNoteLabels, expandDitamapRefs, makeConrefRangeResolver, makeConrefResolver, makeFileCache, makeFileTitleResolver, makeIsInCurrentBook, makeRefErrorResolver, readImageDimensions } from './editor/refResolvers';
44
+ export { DEFAULT_REF_ERROR_TEXTS, fillRefErrorTemplate } from './render/refErrorTexts';
44
45
  export { buildRenderContext } from './editor/renderContext';
45
46
  export { clearAllSourceOverlays, dependsOn, noteSourceDependencies, sourceOverlaySize, sourceStamp, trackSourceReads } from './editor/sourceText';
46
47
  export { TOPIC_RENDER_CACHE_MAX_BYTES, clearTopicRenderCache, collectText, renderTopicCached, renderTopicToHtml, setTopicRenderCacheBudgetForTesting, stampFiles, topicRenderCacheBytesHeld, topicRenderCacheSize } from './editor/topicRender';
@@ -1,3 +1,5 @@
1
+ import { DEFAULT_REF_ERROR_TEXTS, fillRefErrorTemplate } from './refErrorTexts';
2
+ import { isDitaFormat } from './refTargets';
1
3
  // parentBaseType only reflects the immediate ancestor (entry sits under row,
2
4
  // not thead), so header status is carried by an explicit ctx flag set when
3
5
  // entering thead/sthead and cleared when entering tbody.
@@ -808,6 +810,28 @@ export const BASE_TYPE_RENDERERS = {
808
810
  return '';
809
811
  return `<span class="xref unresolved-keyref" title="Unresolved key: ${escapeAttr(keyref)}">[${escapeAttr(keyref)}]</span>`;
810
812
  }
813
+ // An EMPTY xref whose local target is broken (host-diagnosed, see
814
+ // RenderContext.refError): the title/href fallback below would render
815
+ // the raw href in a link-shaped hint that reads as if the reference
816
+ // worked -- the silent failure this marker exists to surface. Keep the
817
+ // arrow convention of the xref-external hint, but in the error colour
818
+ // with a dashed underline and the reason appended. An xref WITH author
819
+ // text keeps it (content wins, same rule as keyref); scope=external/peer
820
+ // references are not local documents and are never diagnosed.
821
+ if (!hasContentChildren(node) && ctx.refError) {
822
+ const scope = getAttr(node, 'scope');
823
+ // An xref whose @format names a non-DITA target (html, pdf, ...) does
824
+ // not point at a DITA id: its fragment is the target format's own
825
+ // (#page=3, #section), so it is never diagnosed.
826
+ if (scope !== 'external' && scope !== 'peer' && isDitaFormat(getAttr(node, 'format'))) {
827
+ const reason = ctx.refError(href);
828
+ if (reason !== undefined) {
829
+ const texts = { ...DEFAULT_REF_ERROR_TEXTS, ...ctx.refErrorTexts };
830
+ const text = fillRefErrorTemplate(texts.xref, href, reason);
831
+ return `<span class="xref-broken" title="${escapeAttr(href)}">${escapeAttr(text)}</span>`;
832
+ }
833
+ }
834
+ }
811
835
  let content;
812
836
  if (hasContentChildren(node)) {
813
837
  content = renderChildren(node, ctx);
@@ -0,0 +1,38 @@
1
+ // Wording for the broken-reference hints (RenderContext.refError).
2
+ //
3
+ // A LEAF module: no imports, so both the renderer (render/renderer.ts,
4
+ // render/baseTypeMap.ts) and the editor-layer resolver factory
5
+ // (editor/refResolvers.ts) can read it without a cycle -- the same reason
6
+ // FALLBACK_NOTE_LABELS is duplicated in baseTypeMap rather than imported
7
+ // from the editor layer, solved here by putting the shared strings below
8
+ // both instead.
9
+ //
10
+ // The renderer only PRESENTS: it asks RenderContext.refError whether a
11
+ // reference is broken and composes the answer with the templates below.
12
+ // The diagnosis itself is the host's (the callback), and so is the
13
+ // localization -- a host fills these from its own string catalog (the VS
14
+ // Code extension does, via vscode.l10n.t); the defaults here are English.
15
+ //
16
+ // Templates use {0}/{1} placeholders rather than concatenation so a
17
+ // locale controls the whole shape, punctuation included: zh-cn wraps the
18
+ // reason in full-width parentheses(…)where English uses (…) .
19
+ export const DEFAULT_REF_ERROR_TEXTS = {
20
+ content: 'Referenced content could not be resolved ({0})',
21
+ xref: '→ {0} ({1})',
22
+ missingKey: 'key is not defined or has no target',
23
+ missingFile: 'target file does not exist',
24
+ parseError: 'target file cannot be parsed as XML',
25
+ missingId: 'target ID does not exist',
26
+ };
27
+ /**
28
+ * Fills {0}, {1}, ... in a template. split/join rather than
29
+ * String.replace: the substituted values are arbitrary reference text
30
+ * (an href, a reason) and must not be read for $-patterns.
31
+ */
32
+ export function fillRefErrorTemplate(template, ...values) {
33
+ let out = template;
34
+ for (let i = 0; i < values.length; i++) {
35
+ out = out.split(`{${i}}`).join(values[i]);
36
+ }
37
+ return out;
38
+ }
@@ -0,0 +1,25 @@
1
+ // What a reference can point at, as far as the broken-reference hints are
2
+ // concerned: is this a target the hints may probe at all?
3
+ //
4
+ // A LEAF module (no imports, not even 'path'), like refErrorTexts.ts, so the
5
+ // renderer (baseTypeMap), the resolver factory (editor/refResolvers) and the
6
+ // conkeyref diagnosis (editor/conkeyref) can share ONE rule without a cycle
7
+ // or a dependency on the filesystem layer. Three call sites used to spell the
8
+ // rule out separately; a fourth extension (or a new scheme) now changes one
9
+ // place.
10
+ /** A URL scheme (https:, mailto:, ...) -- and, by the same shape, a Windows
11
+ * drive letter (C:\...), which is no DITA-relative path either. */
12
+ export const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
13
+ /**
14
+ * True for a file part that is not a local DITA document, so a hint must
15
+ * never probe it: a URL, an absolute path, or a web document (.html, .htm,
16
+ * .pdf), whose #fragment is the format's own (#page=3, #section) rather than
17
+ * a DITA id. Pass the part BEFORE any '#'.
18
+ */
19
+ export function isNonDitaTarget(filePart) {
20
+ return URL_SCHEME_RE.test(filePart) || /^[\\/]/.test(filePart) || /\.(html?|pdf)$/i.test(filePart);
21
+ }
22
+ /** True when an @format value names a DITA target (absent means DITA). */
23
+ export function isDitaFormat(format) {
24
+ return !format || format === 'dita' || format === 'ditamap';
25
+ }
@@ -1,5 +1,6 @@
1
1
  import { BASE_TYPE_RENDERERS } from './baseTypeMap';
2
2
  import { computeKeyrefSpacing } from './cjkSpacing';
3
+ import { DEFAULT_REF_ERROR_TEXTS, fillRefErrorTemplate } from './refErrorTexts';
3
4
  const CONTAINER_BASETYPES = new Set([
4
5
  'topic/section',
5
6
  'topic/example',
@@ -369,18 +370,74 @@ function resolveConrefForNode(node, context) {
369
370
  }
370
371
  }
371
372
  const conref = node.attributes?.conref;
372
- if (!conref || !context.resolveConref)
373
+ if (!conref || !context.resolveConref) {
374
+ // An unresolved conkeyref with no @conref to fall back on: the element
375
+ // would render its own (usually empty) content. Not on a cycle -- the
376
+ // chain check above already excluded that case.
377
+ if (conkeyref && !conref && context.resolveConkeyref && !context.conrefChain?.has(conkeyref)) {
378
+ const reason = context.conkeyrefError?.(conkeyref);
379
+ if (reason !== undefined)
380
+ return { node, refErrorReason: reason, refErrorRef: conkeyref };
381
+ }
373
382
  return { node };
383
+ }
374
384
  // A conref already resolved on this branch points back here — stop the
375
385
  // cycle and render the element's literal content instead of recursing.
376
386
  if (context.conrefChain?.has(conref))
377
387
  return { node };
378
388
  const target = context.resolveConref(conref);
379
- if (!target)
380
- return { node };
389
+ if (!target) {
390
+ // Resolution was attempted and pulled nothing. When the host wired a
391
+ // diagnosis, a broken reference reads as a placeholder chip instead of
392
+ // the element's (usually empty) literal content -- the silent-empty
393
+ // render is the dangerous shape in a review. A cycle above deliberately
394
+ // never reaches this branch.
395
+ const reason = context.refError?.(conref);
396
+ return reason !== undefined ? { node, refErrorReason: reason, refErrorRef: conref } : { node };
397
+ }
381
398
  const end = followConrefChain(target, context);
382
399
  return { node: mergeConrefTarget(node, end), chainKey: conref, mark: conrefMarkFor(end, context) };
383
400
  }
401
+ /**
402
+ * The placeholder chip for a conref that pulled nothing (see
403
+ * RenderContext.refError). title carries the raw reference value so it can
404
+ * be copied straight out of the tooltip to fix the source; the data-line*
405
+ * range is the referencing element's own, so the chip keeps participating
406
+ * in click-to-source, scroll-sync and diff highlighting exactly like the
407
+ * element it stands in for.
408
+ */
409
+ function renderRefErrorPlaceholder(node, context, ref, reason) {
410
+ const texts = { ...DEFAULT_REF_ERROR_TEXTS, ...context.refErrorTexts };
411
+ const range = node.sourceRange;
412
+ const label = escapeHtml(fillRefErrorTemplate(texts.content, reason));
413
+ const attrs = ` title="${escapeHtml(ref)}"` +
414
+ ` data-line="${range.startLine}" data-end-line="${range.endLine}"` +
415
+ ` data-start-col="${range.startCol}" data-end-col="${range.endCol}"`;
416
+ // The chip must be a legal child of whatever the stand-in element would
417
+ // have been: a bare <span> directly in <tbody> is foster-parented by the
418
+ // browser to just before the whole table (the same trap the comment
419
+ // renderer avoids), and a <span> directly in <ul> is invalid. So rows and
420
+ // cells stay rows and cells, items stay items, and a block-level slot
421
+ // gets a <div>; only a slot that holds running text keeps the inline span.
422
+ const baseType = node.baseType;
423
+ if (baseType === 'topic/row' || baseType === 'topic/strow') {
424
+ // colspan 1000 is the HTML maximum: the chip spans the whole row.
425
+ return `<tr class="ref-error-row"><td class="ref-error"${attrs} colspan="1000">${label}</td></tr>`;
426
+ }
427
+ if (baseType === 'topic/tbody' || baseType === 'topic/thead' || baseType === 'topic/tgroup' || baseType === 'topic/sthead') {
428
+ // A whole row group (or the tgroup around it) failed: one full-width
429
+ // row inside a <tbody> stands in for it, so it stays in the table.
430
+ return `<tbody class="ref-error-rows"><tr class="ref-error-row"><td class="ref-error"${attrs} colspan="1000">${label}</td></tr></tbody>`;
431
+ }
432
+ if (baseType === 'topic/entry' || baseType === 'topic/stentry') {
433
+ return `<td class="ref-error"${attrs}>${label}</td>`;
434
+ }
435
+ if (baseType === 'topic/li' || baseType === 'topic/sli') {
436
+ return `<li class="ref-error"${attrs}>${label}</li>`;
437
+ }
438
+ const tag = BLOCK_COMMENT_PARENTS.has(context.parentBaseType || '') ? 'div' : 'span';
439
+ return `<${tag} class="ref-error"${attrs}>${label}</${tag}>`;
440
+ }
384
441
  /**
385
442
  * Per DITA keyref semantics, the key's resource target becomes the
386
443
  * referencing element's effective href when the element carries no href of
@@ -568,6 +625,9 @@ export function renderElement(node, context, conrefMark) {
568
625
  }
569
626
  }
570
627
  const resolved = resolveConrefForNode(node, context);
628
+ if (resolved.refErrorReason !== undefined) {
629
+ return renderRefErrorPlaceholder(node, context, resolved.refErrorRef ?? conref, resolved.refErrorReason);
630
+ }
571
631
  const effectiveNode = resolveKeyrefForNode(resolved.node, context);
572
632
  // The element's own conref wins over a mark handed down by a range.
573
633
  return renderEffectiveNode(effectiveNode, context, resolved.chainKey, resolved.mark ?? conrefMark);
@@ -237,6 +237,8 @@ export function renderSiteXml(input) {
237
237
  bookMembers: new Set(members),
238
238
  docFile: current,
239
239
  markConrefs: true,
240
+ refErrors: true,
241
+ refErrorTexts: input.refErrorTexts,
240
242
  });
241
243
  if (result.error !== undefined) {
242
244
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dita-viewer/core",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Host-neutral DITA parsing and HTML rendering core, shared by the VS Code DITA Viewer and obsidian-dita.",
5
5
  "keywords": [
6
6
  "dita",