@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
@@ -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 } = 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,9 @@ export function renderTopicXml(input) {
58
58
  collectDependencies,
59
59
  docFile,
60
60
  markConrefs,
61
+ refErrors,
62
+ refErrorTexts,
63
+ keyScope,
61
64
  });
62
65
  const html = renderDocument(ditaDoc.root, ctx);
63
66
  if (collectDependencies) {
@@ -74,7 +77,7 @@ export function renderTopicXml(input) {
74
77
  }
75
78
  }
76
79
  export function renderTopicToHtml(input) {
77
- const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs } = input;
80
+ const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs, refErrors, refErrorTexts, keyScope } = input;
78
81
  try {
79
82
  if (!existsSync(filePath)) {
80
83
  return { html: '', error: `File not found: ${filePath}` };
@@ -96,6 +99,9 @@ export function renderTopicToHtml(input) {
96
99
  clickableExternalXrefs,
97
100
  docFile: filePath,
98
101
  markConrefs,
102
+ refErrors,
103
+ refErrorTexts,
104
+ keyScope,
99
105
  });
100
106
  return { html: result.html, title: result.title, error: result.error };
101
107
  }
@@ -260,10 +266,17 @@ function dropOldestTopicEntry() {
260
266
  * headingLevel is part of the key rather than a merely validated field
261
267
  * because the same topic legitimately sits at different depths across two
262
268
  * open books -- validating it instead would make those two entries evict each
263
- * other on every pass.
269
+ * other on every pass. The key scope is part of it for the same reason, and
270
+ * for a stronger one: a topic published under two keyscopes renders with
271
+ * different key text in each, so a hit from the other scope would be wrong.
264
272
  */
265
273
  export function renderTopicCached(input) {
266
- const key = `${input.filePath}\u0000${input.headingLevel}`;
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}`;
267
280
  const cached = topicRenderCache.get(key);
268
281
  if (cached &&
269
282
  cached.keyMap === input.keyMap &&
@@ -283,8 +296,9 @@ export function renderTopicCached(input) {
283
296
  // Honour a caller-supplied sink as well, so anyone who passed one still
284
297
  // sees the dependency set instead of having it silently replaced.
285
298
  const dependencies = input.collectDependencies ?? new Set();
286
- // Previews only (see above), so conref'd content is always marked here.
287
- 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 });
288
302
  if (result.error) {
289
303
  // Never cache a failure. A malformed mid-edit save is exactly the
290
304
  // transient case this path sees, and pinning it would keep serving the
package/dist-esm/index.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // and holds no copies of ./parser, ./render and ./editor (see README), so they
6
6
  // are edited here and released as a new version.
7
7
  export { renderTopicXml, buildTitleMap, collectDitamapFilesUpward } from './editor/topicRender';
8
- export { buildKeySpace, getKeyDefs } from './editor/keySpace';
8
+ export { buildKeySpace, getKeyDefs, getKeyScopes, getTopicScopeChains, createKeyScopeIndex } from './editor/keySpace';
9
9
  export { readSourceText, setSourceOverlay, clearSourceOverlay } from './editor/sourceText';
10
10
  export { decodeHrefPart } from './editor/refResolvers';
11
11
  export { buildKeyMapForDocument, buildKeySpaceForDocument } from './keyMapForDocument';
@@ -39,8 +39,9 @@ export { BASE_TYPE_RENDERERS } from './render/baseTypeMap';
39
39
  export { computeKeyrefSpacing, needsSpace } from './render/cjkSpacing';
40
40
  export { mergeProfilingAttrs, profilingChipsHtml, profilingKeysAttr } from './render/renderer';
41
41
  export { resolveConkeyref } from './editor/conkeyref';
42
- export { collectMapKeys, isKeyContextAvailable, keySourceMaps, qualifiedNames, qualifiedNamesMulti } 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';
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, 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';
@@ -63,6 +63,7 @@ function makeRange() {
63
63
  */
64
64
  function scanTagEvents(xml) {
65
65
  const events = [];
66
+ const comments = [];
66
67
  let i = 0;
67
68
  while (i < xml.length) {
68
69
  const lt = xml.indexOf('<', i);
@@ -70,7 +71,13 @@ function scanTagEvents(xml) {
70
71
  break;
71
72
  if (xml.startsWith('<!--', lt)) {
72
73
  const end = xml.indexOf('-->', lt + 4);
73
- i = end < 0 ? xml.length : end + 3;
74
+ if (end < 0) {
75
+ // Unterminated: sax rejects it in strict mode, so nothing will ask
76
+ // for a position -- record nothing rather than invent one.
77
+ break;
78
+ }
79
+ comments.push({ start: lt, end: end + 3, contentStart: lt + 4, contentEnd: end });
80
+ i = end + 3;
74
81
  continue;
75
82
  }
76
83
  if (xml.startsWith('<![CDATA[', lt)) {
@@ -128,7 +135,7 @@ function scanTagEvents(xml) {
128
135
  events.push({ name, selfClosing, isClose, start: lt, end: gt + 1 });
129
136
  i = gt + 1;
130
137
  }
131
- return events;
138
+ return { tags: events, comments };
132
139
  }
133
140
  function makeParser(tagMap) {
134
141
  const parseBaseType = makeParseBaseType(tagMap);
@@ -147,25 +154,33 @@ function makeParser(tagMap) {
147
154
  // onclosetag sax fires immediately after for it.
148
155
  let selfClosingEnd;
149
156
  // The source scan feeding exact tag offsets to the handlers below.
150
- const tagEvents = scanTagEvents(xml);
157
+ const { tags: tagEvents, comments: commentEvents } = scanTagEvents(xml);
151
158
  let q = 0;
159
+ let cq = 0;
152
160
  // (line, col) of a raw offset, via an ever-forward line-start cursor.
153
- // Tag offsets are consumed in document order, so it never rewinds.
154
- let lastLineStart = 0;
155
- let currentLine = 0;
156
- function locAt(pos) {
157
- let i = lastLineStart;
158
- let line = currentLine;
159
- let nl = xml.indexOf('\n', i);
160
- while (nl !== -1 && nl < pos) {
161
- i = nl + 1;
162
- line++;
163
- nl = xml.indexOf('\n', i);
164
- }
165
- lastLineStart = i;
166
- currentLine = line;
167
- return { line, col: pos - i };
161
+ // Offsets are consumed in document order (tags and comments each in their
162
+ // own stream), so a cursor never rewinds -- which is why each stream gets
163
+ // its own: a comment can sit between two tags that the tag queue has
164
+ // already looked past.
165
+ function makeLocator() {
166
+ let lastLineStart = 0;
167
+ let currentLine = 0;
168
+ return function locAt(pos) {
169
+ let i = lastLineStart;
170
+ let line = currentLine;
171
+ let nl = xml.indexOf('\n', i);
172
+ while (nl !== -1 && nl < pos) {
173
+ i = nl + 1;
174
+ line++;
175
+ nl = xml.indexOf('\n', i);
176
+ }
177
+ lastLineStart = i;
178
+ currentLine = line;
179
+ return { line, col: pos - i };
180
+ };
168
181
  }
182
+ const locAt = makeLocator();
183
+ const commentLocAt = makeLocator();
169
184
  /**
170
185
  * Pops the queue's next tag of the given kind, trusting sax as the
171
186
  * authority on order but the scan as the authority on position. sax
@@ -191,6 +206,23 @@ function makeParser(tagMap) {
191
206
  function saxFallbackEnd() {
192
207
  return { line: parser.line, col: parser.column };
193
208
  }
209
+ /**
210
+ * Pops the scan's next comment whose inner text matches what sax reported.
211
+ * Matched by content, not by position in the stream alone: `<!--` inside a
212
+ * CDATA section or an attribute value is not a comment, so the two scans
213
+ * may legitimately disagree, and content is the one thing both agree on.
214
+ * A window keeps a single disagreement from desynchronising the rest.
215
+ */
216
+ function nextComment(text) {
217
+ for (let k = cq; k < Math.min(cq + 8, commentEvents.length); k++) {
218
+ const e = commentEvents[k];
219
+ if (xml.slice(e.contentStart, e.contentEnd) !== text)
220
+ continue;
221
+ cq = k + 1;
222
+ return e;
223
+ }
224
+ return undefined;
225
+ }
194
226
  function flushText() {
195
227
  if (currentText.length > 0) {
196
228
  const parent = stack[stack.length - 1];
@@ -290,6 +322,32 @@ function makeParser(tagMap) {
290
322
  }
291
323
  currentText += text;
292
324
  };
325
+ // An XML comment becomes a node of its own, kept where it was written:
326
+ // the preview shows a comment's text in place (the way Oxygen's Author
327
+ // mode does), so dropping comments here made them invisible. Its range
328
+ // spans `<!--` through `-->` so a click in the preview lands on the
329
+ // comment's own source line. The pending text is flushed first, so the
330
+ // text either side of it stays on the right side of the comment.
331
+ parser.oncomment = (comment) => {
332
+ flushText();
333
+ const parent = stack[stack.length - 1];
334
+ const event = nextComment(comment);
335
+ const start = event ? commentLocAt(event.start) : saxFallbackEnd();
336
+ const end = event ? commentLocAt(event.end) : saxFallbackEnd();
337
+ if (!parent)
338
+ return;
339
+ parent.children.push({
340
+ type: 'comment',
341
+ comment,
342
+ children: [],
343
+ sourceRange: {
344
+ startLine: start.line,
345
+ startCol: start.col,
346
+ endLine: end.line,
347
+ endCol: end.col,
348
+ },
349
+ });
350
+ };
293
351
  parser.onerror = (err) => {
294
352
  throw new Error(`SAX parse error at line ${parser.line}:${parser.column}: ${err.message}`);
295
353
  };
@@ -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.
@@ -224,7 +226,7 @@ function expandMfenced(node) {
224
226
  // spurious extra separator characters for the whitespace "children"
225
227
  // surrounding the real one.
226
228
  const items = (node.children || [])
227
- .filter((c) => c.type !== 'text' || (c.text || '').trim() !== '')
229
+ .filter((c) => c.type !== 'comment' && (c.type !== 'text' || (c.text || '').trim() !== ''))
228
230
  .map(serializeForeignContent);
229
231
  let inner = '';
230
232
  if (open !== '')
@@ -242,6 +244,14 @@ function expandMfenced(node) {
242
244
  inner += `<mo>${escapeHtml(close)}</mo>`;
243
245
  return `<mrow>${inner}</mrow>`;
244
246
  }
247
+ /**
248
+ * True when the element has any child that is author content. An XML comment
249
+ * is a node of its own in the parse tree (shown in place by the renderer) but
250
+ * is never content: `<xref href="a.dita"><!-- note --></xref>` has no label.
251
+ */
252
+ function hasContentChildren(node) {
253
+ return (node.children || []).some((c) => c.type !== 'comment');
254
+ }
245
255
  function serializeForeignContent(node) {
246
256
  if (node.type === 'text')
247
257
  return escapeHtml(node.text || '');
@@ -776,6 +786,10 @@ export const BASE_TYPE_RENDERERS = {
776
786
  },
777
787
  'topic/pre': (_node, ctx, renderChildren) => `<pre class="pre preformatted">${renderChildren(_node, ctx)}</pre>`,
778
788
  'topic/xref': (node, ctx, renderChildren) => {
789
+ // An xref whose only child is an XML comment (<!-- Pull title from ... -->)
790
+ // has no author-written label: it falls back to the resolved title / href
791
+ // exactly as an empty one does, rather than showing the comment as its
792
+ // link text. hasContentChildren() is the single place that says so.
779
793
  const href = getAttr(node, 'href') || '';
780
794
  // No target at all: an xref with neither @href nor a keyref that
781
795
  // resolves to one. Dropping the element silently (the old behaviour)
@@ -784,7 +798,7 @@ export const BASE_TYPE_RENDERERS = {
784
798
  // when it does not (the same treatment topic/ph gives an unresolved
785
799
  // keyref) -- means a broken xref reads as one instead of vanishing.
786
800
  if (!href) {
787
- if (node.children.length > 0) {
801
+ if (hasContentChildren(node)) {
788
802
  const content = renderChildren(node, ctx);
789
803
  const keyref = getAttr(node, 'keyref');
790
804
  return keyref
@@ -796,8 +810,30 @@ export const BASE_TYPE_RENDERERS = {
796
810
  return '';
797
811
  return `<span class="xref unresolved-keyref" title="Unresolved key: ${escapeAttr(keyref)}">[${escapeAttr(keyref)}]</span>`;
798
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
+ }
799
835
  let content;
800
- if (node.children.length > 0) {
836
+ if (hasContentChildren(node)) {
801
837
  content = renderChildren(node, ctx);
802
838
  }
803
839
  else if (href.startsWith('#')) {
@@ -459,10 +459,15 @@ export function isDitamapRef(node) {
459
459
  const pathPart = href.split('#')[0].toLowerCase();
460
460
  return pathPart.endsWith('.ditamap') || node.attributes?.format === 'ditamap';
461
461
  }
462
- function collectEntriesRecursive(node, depth, result, resolveKey, roleLabel, inheritedProcessingRole = 'normal') {
462
+ function collectEntriesRecursive(node, depth, result, resolveKey, roleLabel, inheritedProcessingRole = 'normal', outerScopes = [[]]) {
463
463
  if (node.type !== 'element')
464
464
  return;
465
465
  const baseType = node.baseType;
466
+ // A keyscope names a scope for the element carrying it and everything below.
467
+ const keyscope = getAttr(node, 'keyscope');
468
+ const scopeChains = keyscope
469
+ ? outerScopes.flatMap((chain) => keyscope.trim().split(/\s+/).filter(Boolean).map((name) => chain.concat(name)))
470
+ : outerScopes;
466
471
  // Skip reltable and its children
467
472
  if (baseType === 'map/reltable')
468
473
  return;
@@ -482,7 +487,7 @@ function collectEntriesRecursive(node, depth, result, resolveKey, roleLabel, inh
482
487
  // level deeper just because expandDitamapRefs happened to splice them
483
488
  // in as DOM children of this wrapper node.
484
489
  for (const child of node.children || []) {
485
- collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, inheritedProcessingRole);
490
+ collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, inheritedProcessingRole, scopeChains);
486
491
  }
487
492
  return;
488
493
  }
@@ -519,21 +524,22 @@ function collectEntriesRecursive(node, depth, result, resolveKey, roleLabel, inh
519
524
  // been) serves no one.
520
525
  role: effectiveProcessingRole === 'resource-only' ? undefined : roleLabel(node.tagName, depth),
521
526
  resourceOnly: effectiveProcessingRole === 'resource-only',
527
+ scopeChains,
522
528
  });
523
529
  // Recurse children at depth+1
524
530
  for (const child of node.children || []) {
525
- collectEntriesRecursive(child, depth + 1, result, resolveKey, roleLabel, effectiveProcessingRole);
531
+ collectEntriesRecursive(child, depth + 1, result, resolveKey, roleLabel, effectiveProcessingRole, scopeChains);
526
532
  }
527
533
  }
528
534
  else if (baseType === 'map/topicgroup' || baseType === 'map/bookmap-structural') {
529
535
  // topicgroup / bookmap-structural: no entry itself, but recurse at same depth
530
536
  for (const child of node.children || []) {
531
- collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole);
537
+ collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole, scopeChains);
532
538
  }
533
539
  }
534
540
  else {
535
541
  for (const child of node.children || []) {
536
- collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole);
542
+ collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole, scopeChains);
537
543
  }
538
544
  }
539
545
  }
@@ -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
@@ -491,10 +548,70 @@ function renderConrefRange(node, range, context, conref) {
491
548
  })
492
549
  .join('');
493
550
  }
551
+ // Parents whose content model is element-only, so a comment written inside
552
+ // them sits between blocks rather than inside a sentence and should get a
553
+ // block of its own. Everything else -- p, ph, li, entry, title, note text --
554
+ // holds mixed content, where an inline <span> is both valid and what the
555
+ // author saw. This is the same inline/block distinction profiling markers
556
+ // make (INLINE_PROFILING_BASETYPES), stated the other way round: there,
557
+ // inline was the short list; here the inline cases are the majority, and
558
+ // getting it wrong on the block side is the harmless direction (a comment on
559
+ // its own line inside a phrase) while a <div> inside a <p> would make the
560
+ // browser close the paragraph and split the sentence around it.
561
+ const BLOCK_COMMENT_PARENTS = new Set([
562
+ 'topic/body',
563
+ 'topic/section',
564
+ 'topic/example',
565
+ 'topic/fig',
566
+ 'topic/div',
567
+ 'topic/bodydiv',
568
+ 'topic/sectiondiv',
569
+ 'topic/topic',
570
+ 'topic/abstract',
571
+ 'topic/related-links',
572
+ 'topic/imagemap',
573
+ // List containers: a comment written between two <li>s is not part of
574
+ // either item's sentence, and an inline span there would be a stray
575
+ // fragment of the previous item.
576
+ 'topic/ul',
577
+ 'topic/ol',
578
+ 'topic/sl',
579
+ 'topic/dl',
580
+ ]);
581
+ /**
582
+ * An XML comment, shown in the flow at the position it was authored in --
583
+ * Oxygen's Author mode shows the comment text the same way, instead of the
584
+ * reader having to open the source. The text is the comment's inner content
585
+ * with the `<!-- -->` delimiters stripped: the delimiters are markup, and a
586
+ * comment's *text* is what the author wanted read. data-dita-tagname makes the
587
+ * story explicit through the Tags toggle (its tooltip reads "comment"), and
588
+ * data-line* keeps preview clicks and scroll-sync landing on the comment's own
589
+ * source lines -- its range spans `<!--` through `-->`.
590
+ *
591
+ * An empty or whitespace-only comment renders nothing: it is a spelling of
592
+ * "nothing here", and an empty box in the page would only be noise.
593
+ */
594
+ function renderComment(node, context) {
595
+ const text = (node.comment || '').replace(/\r\n?/g, '\n').trim();
596
+ if (!text)
597
+ return '';
598
+ const block = BLOCK_COMMENT_PARENTS.has(context.parentBaseType || '');
599
+ const tag = block ? 'div' : 'span';
600
+ const cls = block ? 'dv-comment dv-comment--block' : 'dv-comment';
601
+ const range = node.sourceRange;
602
+ return (`<${tag} class="${cls}" data-dita-tagname="comment"` +
603
+ ` data-line="${range.startLine}" data-end-line="${range.endLine}"` +
604
+ ` data-start-col="${range.startCol}" data-end-col="${range.endCol}">` +
605
+ escapeHtml(text) +
606
+ `</${tag}>`);
607
+ }
494
608
  export function renderElement(node, context, conrefMark) {
495
609
  if (node.type === 'text') {
496
610
  return escapeHtml(node.text || '');
497
611
  }
612
+ if (node.type === 'comment') {
613
+ return renderComment(node, context);
614
+ }
498
615
  const conref = node.attributes?.conref;
499
616
  const conrefend = node.attributes?.conrefend;
500
617
  if (conref && conrefend && context.resolveConrefRange && !context.conrefChain?.has(conref)) {
@@ -508,12 +625,30 @@ export function renderElement(node, context, conrefMark) {
508
625
  }
509
626
  }
510
627
  const resolved = resolveConrefForNode(node, context);
628
+ if (resolved.refErrorReason !== undefined) {
629
+ return renderRefErrorPlaceholder(node, context, resolved.refErrorRef ?? conref, resolved.refErrorReason);
630
+ }
511
631
  const effectiveNode = resolveKeyrefForNode(resolved.node, context);
512
632
  // The element's own conref wins over a mark handed down by a range.
513
633
  return renderEffectiveNode(effectiveNode, context, resolved.chainKey, resolved.mark ?? conrefMark);
514
634
  }
635
+ // Parents whose children must not include a comment span or block:
636
+ // - table machinery: a <span>/<div> directly inside <table>, <tbody> or <tr>
637
+ // is foster-parented by the browser to just before the whole table, so the
638
+ // comment would show up away from where it was written;
639
+ // - preformatted blocks: the comment's text would read, and copy, as code;
640
+ // - titles: the heading's text feeds the outline / table of contents.
641
+ // Keyed by the baseType of the element being rendered (the real parent), not
642
+ // by the overloaded context.parentBaseType.
643
+ const NO_COMMENT_CHILDREN = new Set([
644
+ 'topic/table', 'topic/tgroup', 'topic/thead', 'topic/tbody', 'topic/row',
645
+ 'topic/simpletable', 'topic/sthead', 'topic/strow',
646
+ 'topic/pre', 'topic/codeblock', 'topic/lines',
647
+ 'topic/title',
648
+ ]);
515
649
  function renderChildren(node, context) {
516
- const children = node.children || [];
650
+ const skipComments = !!node.baseType && NO_COMMENT_CHILDREN.has(node.baseType);
651
+ const children = (node.children || []).filter((c) => !(skipComments && c.type === 'comment'));
517
652
  // Resolved key text can leave CJK and Latin glued together (`打开` + `ABC`).
518
653
  // Insert a display-only space outside the key element; the source is untouched.
519
654
  const spacing = computeKeyrefSpacing(children, node.baseType, context.resolveKey);
@@ -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.3",
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",