@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 type { RefErrorTexts } from '../render/refErrorTexts';
2
3
  export declare function collectText(node: DitaNode): string;
3
4
  export declare function buildTitleMap(root: DitaNode): Map<string, string>;
4
5
  export interface TopicRenderInput {
@@ -6,6 +7,13 @@ export interface TopicRenderInput {
6
7
  keyMap: Map<string, string>;
7
8
  asWebviewUri: (relPath: string) => string;
8
9
  headingLevel: number;
10
+ /**
11
+ * The key scope chains the topic is read in, when the caller knows where the
12
+ * topic sits (book / site: the scope of the topicref that placed it). Left
13
+ * undefined, the first topicref that publishes the file decides. See
14
+ * BuildRenderContextInput.keyScope.
15
+ */
16
+ keyScope?: string[][];
9
17
  /**
10
18
  * Fallback language (e.g. from vscode.env.language) used to pick note
11
19
  * labels (Warning/Attention/...) when the topic itself has no xml:lang
@@ -39,6 +47,13 @@ export interface TopicRenderInput {
39
47
  * which only ever serves previews, turns it on.
40
48
  */
41
49
  markConrefs?: boolean;
50
+ /** See BuildRenderContextInput.refErrors -- passed through untouched.
51
+ * renderTopicCached (previews only) forces it on, like markConrefs. */
52
+ refErrors?: boolean;
53
+ /** See BuildRenderContextInput.refErrorTexts -- the host's localized
54
+ * wording for the broken-reference hints. Part of renderTopicCached's
55
+ * cache key: the same topic renders different hint text per locale. */
56
+ refErrorTexts?: Partial<RefErrorTexts>;
42
57
  }
43
58
  export interface TopicRenderResult {
44
59
  html: string;
@@ -86,6 +101,12 @@ export interface TopicXmlRenderInput {
86
101
  */
87
102
  docFile?: string;
88
103
  markConrefs?: boolean;
104
+ /** See TopicRenderInput.refErrors. */
105
+ refErrors?: boolean;
106
+ /** See TopicRenderInput.refErrorTexts. */
107
+ refErrorTexts?: Partial<RefErrorTexts>;
108
+ /** See BuildRenderContextInput.keyScope. */
109
+ keyScope?: string[][];
89
110
  }
90
111
  export interface ParsedTopicResult {
91
112
  doc?: import('../parser/domTypes').DitaDocument;
@@ -184,6 +205,8 @@ export declare function setTopicRenderCacheBudgetForTesting(bytes?: number): voi
184
205
  * headingLevel is part of the key rather than a merely validated field
185
206
  * because the same topic legitimately sits at different depths across two
186
207
  * open books -- validating it instead would make those two entries evict each
187
- * other on every pass.
208
+ * other on every pass. The key scope is part of it for the same reason, and
209
+ * for a stronger one: a topic published under two keyscopes renders with
210
+ * different key text in each, so a hit from the other scope would be wrong.
188
211
  */
189
212
  export declare function renderTopicCached(input: TopicRenderInput): TopicRenderResult;
@@ -48,7 +48,7 @@ function buildTitleMap(root) {
48
48
  return map;
49
49
  }
50
50
  function renderTopicXml(input) {
51
- const { xml, docDir, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, docFile, markConrefs } = input;
51
+ const { xml, docDir, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, docFile, markConrefs, refErrors, refErrorTexts, keyScope } = input;
52
52
  try {
53
53
  const preprocessedXml = (0, ditaParser_1.preprocessEntities)(xml);
54
54
  const ditaDoc = (0, ditaParser_1.parseDita)(preprocessedXml);
@@ -72,6 +72,9 @@ function renderTopicXml(input) {
72
72
  collectDependencies,
73
73
  docFile,
74
74
  markConrefs,
75
+ refErrors,
76
+ refErrorTexts,
77
+ keyScope,
75
78
  });
76
79
  const html = (0, renderer_1.renderDocument)(ditaDoc.root, ctx);
77
80
  if (collectDependencies) {
@@ -88,7 +91,7 @@ function renderTopicXml(input) {
88
91
  }
89
92
  }
90
93
  function renderTopicToHtml(input) {
91
- const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs } = input;
94
+ const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs, refErrors, refErrorTexts, keyScope } = input;
92
95
  try {
93
96
  if (!(0, fs_1.existsSync)(filePath)) {
94
97
  return { html: '', error: `File not found: ${filePath}` };
@@ -110,6 +113,9 @@ function renderTopicToHtml(input) {
110
113
  clickableExternalXrefs,
111
114
  docFile: filePath,
112
115
  markConrefs,
116
+ refErrors,
117
+ refErrorTexts,
118
+ keyScope,
113
119
  });
114
120
  return { html: result.html, title: result.title, error: result.error };
115
121
  }
@@ -274,10 +280,17 @@ function dropOldestTopicEntry() {
274
280
  * headingLevel is part of the key rather than a merely validated field
275
281
  * because the same topic legitimately sits at different depths across two
276
282
  * open books -- validating it instead would make those two entries evict each
277
- * other on every pass.
283
+ * other on every pass. The key scope is part of it for the same reason, and
284
+ * for a stronger one: a topic published under two keyscopes renders with
285
+ * different key text in each, so a hit from the other scope would be wrong.
278
286
  */
279
287
  function renderTopicCached(input) {
280
- const key = `${input.filePath}\u0000${input.headingLevel}`;
288
+ // The hint wording is part of the key: two locales render different chip
289
+ // text for the same topic, so a hit from the other locale would be wrong.
290
+ // JSON of the (small, fixed-shape) overrides object is a cheap fingerprint;
291
+ // undefined and {} normalize to the same string.
292
+ const textsKey = JSON.stringify(input.refErrorTexts ?? {});
293
+ const key = `${input.filePath}\u0000${input.headingLevel}\u0000${input.keyScope ? JSON.stringify(input.keyScope) : ''}\u0000${textsKey}`;
281
294
  const cached = topicRenderCache.get(key);
282
295
  if (cached &&
283
296
  cached.keyMap === input.keyMap &&
@@ -297,8 +310,9 @@ function renderTopicCached(input) {
297
310
  // Honour a caller-supplied sink as well, so anyone who passed one still
298
311
  // sees the dependency set instead of having it silently replaced.
299
312
  const dependencies = input.collectDependencies ?? new Set();
300
- // Previews only (see above), so conref'd content is always marked here.
301
- const result = renderTopicToHtml({ ...input, markConrefs: true, collectDependencies: dependencies });
313
+ // Previews only (see above), so conref'd content is always marked here and
314
+ // broken references always surface as hints rather than silent empties.
315
+ const result = renderTopicToHtml({ ...input, markConrefs: true, refErrors: true, collectDependencies: dependencies });
302
316
  if (result.error) {
303
317
  // Never cache a failure. A malformed mid-edit save is exactly the
304
318
  // transient case this path sees, and pinning it would keep serving the
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { renderTopicXml, buildTitleMap, collectDitamapFilesUpward } from './editor/topicRender';
2
2
  export type { TopicXmlRenderInput, TopicRenderInput, TopicRenderResult, ParsedTopicResult } from './editor/topicRender';
3
- export { buildKeySpace, getKeyDefs } from './editor/keySpace';
4
- export type { KeyHrefDef, KeySpace } from './editor/keySpace';
3
+ export { buildKeySpace, getKeyDefs, getKeyScopes, getTopicScopeChains, createKeyScopeIndex } from './editor/keySpace';
4
+ export type { KeyHrefDef, KeyScopeIndex, KeySpace } from './editor/keySpace';
5
5
  export { readSourceText, setSourceOverlay, clearSourceOverlay } from './editor/sourceText';
6
6
  export { decodeHrefPart } from './editor/refResolvers';
7
7
  export { buildKeyMapForDocument, buildKeySpaceForDocument } from './keyMapForDocument';
@@ -41,9 +41,11 @@ export { BASE_TYPE_RENDERERS } from './render/baseTypeMap';
41
41
  export { computeKeyrefSpacing, needsSpace } from './render/cjkSpacing';
42
42
  export { mergeProfilingAttrs, profilingChipsHtml, profilingKeysAttr } from './render/renderer';
43
43
  export { resolveConkeyref } from './editor/conkeyref';
44
- export { collectMapKeys, isKeyContextAvailable, keySourceMaps, qualifiedNames, qualifiedNamesMulti } from './editor/keySpace';
45
- 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';
44
+ export { collectMapKeys, isKeyContextAvailable, keySourceMaps, qualifiedNames, qualifiedNamesMulti, resolveKeyInScope, scopeKeyIndexKey } from './editor/keySpace';
45
+ 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';
46
46
  export type { FileReader } from './editor/refResolvers';
47
+ export { DEFAULT_REF_ERROR_TEXTS, fillRefErrorTemplate } from './render/refErrorTexts';
48
+ export type { RefErrorTexts } from './render/refErrorTexts';
47
49
  export { buildRenderContext } from './editor/renderContext';
48
50
  export { clearAllSourceOverlays, dependsOn, noteSourceDependencies, sourceOverlaySize, sourceStamp, trackSourceReads } from './editor/sourceText';
49
51
  export { TOPIC_RENDER_CACHE_MAX_BYTES, clearTopicRenderCache, collectText, renderTopicCached, renderTopicToHtml, setTopicRenderCacheBudgetForTesting, stampFiles, topicRenderCacheBytesHeld, topicRenderCacheSize } from './editor/topicRender';
package/dist/index.js CHANGED
@@ -6,9 +6,9 @@
6
6
  // and holds no copies of ./parser, ./render and ./editor (see README), so they
7
7
  // are edited here and released as a new version.
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.renderMapDocument = exports.isDitamapRef = exports.getDisplayNameInfo = exports.extractText = exports.createBookRoleLabeler = exports.findTopLevelIndextermsInSubtree = exports.collectIndextermChips = exports.renderElement = exports.renderDocument = exports.MAP_STANDARD_TAG_TO_BASETYPE = exports.STANDARD_TAG_TO_BASETYPE = exports.preprocessEntities = exports.parseDitamap = exports.parseDita = exports.getMapTitleText = exports.collectMapEntries = exports.pruneExcluded = exports.profileValuesOfKeys = exports.profileValuesOf = exports.profileKey = exports.profileGroups = exports.parseDitaval = exports.isValueExcluded = exports.isExcluded = exports.isEmptyFilter = exports.ditavalAction = exports.PROFILE_ATTRS = exports.renderSiteXml = exports.renderBookXml = exports.renderMapXml = exports.offsetToLineCol = exports.collectRefEntries = exports.splitRefFragment = exports.collectIds = exports.IMAGE_EXT = exports.toRelativeHref = exports.collectReferenceableFiles = exports.collectDiagnostics = exports.complete = exports.buildKeySpaceForDocument = exports.buildKeyMapForDocument = exports.decodeHrefPart = exports.clearSourceOverlay = exports.setSourceOverlay = exports.readSourceText = exports.getKeyDefs = exports.buildKeySpace = exports.collectDitamapFilesUpward = exports.buildTitleMap = exports.renderTopicXml = void 0;
10
- exports.findIdAttrAt = exports.findEnclosingKeydefKeys = exports.findConrefTargetOffset = exports.collectUnknownElements = exports.collectTopicSymbols = exports.collectMapSymbols = exports.topicRenderCacheSize = exports.topicRenderCacheBytesHeld = exports.stampFiles = exports.setTopicRenderCacheBudgetForTesting = exports.renderTopicToHtml = exports.renderTopicCached = exports.collectText = exports.clearTopicRenderCache = exports.TOPIC_RENDER_CACHE_MAX_BYTES = exports.trackSourceReads = exports.sourceStamp = exports.sourceOverlaySize = exports.noteSourceDependencies = exports.dependsOn = exports.clearAllSourceOverlays = exports.buildRenderContext = exports.readImageDimensions = exports.makeIsInCurrentBook = exports.makeFileTitleResolver = exports.makeFileCache = exports.makeConrefResolver = exports.makeConrefRangeResolver = exports.expandDitamapRefs = exports.detectNoteLabels = exports.detectIndexLabel = exports.clearImageDimensionsCache = exports.ZH_NOTE_LABELS = exports.URL_SCHEME_RE = exports.IMAGE_DIMENSIONS_CACHE_MAX = exports.DEFAULT_NOTE_LABELS = exports.qualifiedNamesMulti = exports.qualifiedNames = exports.keySourceMaps = exports.isKeyContextAvailable = exports.collectMapKeys = exports.resolveConkeyref = exports.profilingKeysAttr = exports.profilingChipsHtml = exports.mergeProfilingAttrs = exports.needsSpace = exports.computeKeyrefSpacing = exports.BASE_TYPE_RENDERERS = exports.lookupNamedEntity = exports.isExternalRef = void 0;
11
- exports.HOST_TOKENS = exports.stripSameDocumentFragmentPrefix = exports.getMapRefName = exports.getCompletionContext = exports.getCloseTagCompletion = exports.getAutoCloseTag = exports.getAttributesForTag = exports.findUnclosedTag = exports.findRefAttrAt = exports.findKeysAttrAt = exports.findKeyDefinitionOffset = void 0;
9
+ exports.extractText = exports.createBookRoleLabeler = exports.findTopLevelIndextermsInSubtree = exports.collectIndextermChips = exports.renderElement = exports.renderDocument = exports.MAP_STANDARD_TAG_TO_BASETYPE = exports.STANDARD_TAG_TO_BASETYPE = exports.preprocessEntities = exports.parseDitamap = exports.parseDita = exports.getMapTitleText = exports.collectMapEntries = exports.pruneExcluded = exports.profileValuesOfKeys = exports.profileValuesOf = exports.profileKey = exports.profileGroups = exports.parseDitaval = exports.isValueExcluded = exports.isExcluded = exports.isEmptyFilter = exports.ditavalAction = exports.PROFILE_ATTRS = exports.renderSiteXml = exports.renderBookXml = exports.renderMapXml = exports.offsetToLineCol = exports.collectRefEntries = exports.splitRefFragment = exports.collectIds = exports.IMAGE_EXT = exports.toRelativeHref = exports.collectReferenceableFiles = exports.collectDiagnostics = exports.complete = exports.buildKeySpaceForDocument = exports.buildKeyMapForDocument = exports.decodeHrefPart = exports.clearSourceOverlay = exports.setSourceOverlay = exports.readSourceText = exports.createKeyScopeIndex = exports.getTopicScopeChains = exports.getKeyScopes = exports.getKeyDefs = exports.buildKeySpace = exports.collectDitamapFilesUpward = exports.buildTitleMap = exports.renderTopicXml = void 0;
10
+ exports.stampFiles = exports.setTopicRenderCacheBudgetForTesting = exports.renderTopicToHtml = exports.renderTopicCached = exports.collectText = exports.clearTopicRenderCache = exports.TOPIC_RENDER_CACHE_MAX_BYTES = exports.trackSourceReads = exports.sourceStamp = exports.sourceOverlaySize = exports.noteSourceDependencies = exports.dependsOn = exports.clearAllSourceOverlays = exports.buildRenderContext = exports.fillRefErrorTemplate = exports.DEFAULT_REF_ERROR_TEXTS = exports.readImageDimensions = exports.makeRefErrorResolver = exports.makeIsInCurrentBook = exports.makeFileTitleResolver = exports.makeFileCache = exports.makeConrefResolver = exports.makeConrefRangeResolver = exports.expandDitamapRefs = exports.detectNoteLabels = exports.detectIndexLabel = exports.clearImageDimensionsCache = exports.ZH_NOTE_LABELS = exports.URL_SCHEME_RE = exports.IMAGE_DIMENSIONS_CACHE_MAX = exports.DEFAULT_NOTE_LABELS = exports.scopeKeyIndexKey = exports.resolveKeyInScope = exports.qualifiedNamesMulti = exports.qualifiedNames = exports.keySourceMaps = exports.isKeyContextAvailable = exports.collectMapKeys = exports.resolveConkeyref = exports.profilingKeysAttr = exports.profilingChipsHtml = exports.mergeProfilingAttrs = exports.needsSpace = exports.computeKeyrefSpacing = exports.BASE_TYPE_RENDERERS = exports.lookupNamedEntity = exports.isExternalRef = exports.renderMapDocument = exports.isDitamapRef = exports.getDisplayNameInfo = void 0;
11
+ exports.HOST_TOKENS = exports.stripSameDocumentFragmentPrefix = exports.getMapRefName = exports.getCompletionContext = exports.getCloseTagCompletion = exports.getAutoCloseTag = exports.getAttributesForTag = exports.findUnclosedTag = exports.findRefAttrAt = exports.findKeysAttrAt = exports.findKeyDefinitionOffset = exports.findIdAttrAt = exports.findEnclosingKeydefKeys = exports.findConrefTargetOffset = exports.collectUnknownElements = exports.collectTopicSymbols = exports.collectMapSymbols = exports.topicRenderCacheSize = exports.topicRenderCacheBytesHeld = void 0;
12
12
  var topicRender_1 = require("./editor/topicRender");
13
13
  Object.defineProperty(exports, "renderTopicXml", { enumerable: true, get: function () { return topicRender_1.renderTopicXml; } });
14
14
  Object.defineProperty(exports, "buildTitleMap", { enumerable: true, get: function () { return topicRender_1.buildTitleMap; } });
@@ -16,6 +16,9 @@ Object.defineProperty(exports, "collectDitamapFilesUpward", { enumerable: true,
16
16
  var keySpace_1 = require("./editor/keySpace");
17
17
  Object.defineProperty(exports, "buildKeySpace", { enumerable: true, get: function () { return keySpace_1.buildKeySpace; } });
18
18
  Object.defineProperty(exports, "getKeyDefs", { enumerable: true, get: function () { return keySpace_1.getKeyDefs; } });
19
+ Object.defineProperty(exports, "getKeyScopes", { enumerable: true, get: function () { return keySpace_1.getKeyScopes; } });
20
+ Object.defineProperty(exports, "getTopicScopeChains", { enumerable: true, get: function () { return keySpace_1.getTopicScopeChains; } });
21
+ Object.defineProperty(exports, "createKeyScopeIndex", { enumerable: true, get: function () { return keySpace_1.createKeyScopeIndex; } });
19
22
  var sourceText_1 = require("./editor/sourceText");
20
23
  Object.defineProperty(exports, "readSourceText", { enumerable: true, get: function () { return sourceText_1.readSourceText; } });
21
24
  Object.defineProperty(exports, "setSourceOverlay", { enumerable: true, get: function () { return sourceText_1.setSourceOverlay; } });
@@ -109,6 +112,8 @@ Object.defineProperty(exports, "isKeyContextAvailable", { enumerable: true, get:
109
112
  Object.defineProperty(exports, "keySourceMaps", { enumerable: true, get: function () { return keySpace_2.keySourceMaps; } });
110
113
  Object.defineProperty(exports, "qualifiedNames", { enumerable: true, get: function () { return keySpace_2.qualifiedNames; } });
111
114
  Object.defineProperty(exports, "qualifiedNamesMulti", { enumerable: true, get: function () { return keySpace_2.qualifiedNamesMulti; } });
115
+ Object.defineProperty(exports, "resolveKeyInScope", { enumerable: true, get: function () { return keySpace_2.resolveKeyInScope; } });
116
+ Object.defineProperty(exports, "scopeKeyIndexKey", { enumerable: true, get: function () { return keySpace_2.scopeKeyIndexKey; } });
112
117
  var refResolvers_2 = require("./editor/refResolvers");
113
118
  Object.defineProperty(exports, "DEFAULT_NOTE_LABELS", { enumerable: true, get: function () { return refResolvers_2.DEFAULT_NOTE_LABELS; } });
114
119
  Object.defineProperty(exports, "IMAGE_DIMENSIONS_CACHE_MAX", { enumerable: true, get: function () { return refResolvers_2.IMAGE_DIMENSIONS_CACHE_MAX; } });
@@ -123,7 +128,11 @@ Object.defineProperty(exports, "makeConrefResolver", { enumerable: true, get: fu
123
128
  Object.defineProperty(exports, "makeFileCache", { enumerable: true, get: function () { return refResolvers_2.makeFileCache; } });
124
129
  Object.defineProperty(exports, "makeFileTitleResolver", { enumerable: true, get: function () { return refResolvers_2.makeFileTitleResolver; } });
125
130
  Object.defineProperty(exports, "makeIsInCurrentBook", { enumerable: true, get: function () { return refResolvers_2.makeIsInCurrentBook; } });
131
+ Object.defineProperty(exports, "makeRefErrorResolver", { enumerable: true, get: function () { return refResolvers_2.makeRefErrorResolver; } });
126
132
  Object.defineProperty(exports, "readImageDimensions", { enumerable: true, get: function () { return refResolvers_2.readImageDimensions; } });
133
+ var refErrorTexts_1 = require("./render/refErrorTexts");
134
+ Object.defineProperty(exports, "DEFAULT_REF_ERROR_TEXTS", { enumerable: true, get: function () { return refErrorTexts_1.DEFAULT_REF_ERROR_TEXTS; } });
135
+ Object.defineProperty(exports, "fillRefErrorTemplate", { enumerable: true, get: function () { return refErrorTexts_1.fillRefErrorTemplate; } });
127
136
  var renderContext_1 = require("./editor/renderContext");
128
137
  Object.defineProperty(exports, "buildRenderContext", { enumerable: true, get: function () { return renderContext_1.buildRenderContext; } });
129
138
  var sourceText_2 = require("./editor/sourceText");
@@ -71,6 +71,7 @@ function makeRange() {
71
71
  */
72
72
  function scanTagEvents(xml) {
73
73
  const events = [];
74
+ const comments = [];
74
75
  let i = 0;
75
76
  while (i < xml.length) {
76
77
  const lt = xml.indexOf('<', i);
@@ -78,7 +79,13 @@ function scanTagEvents(xml) {
78
79
  break;
79
80
  if (xml.startsWith('<!--', lt)) {
80
81
  const end = xml.indexOf('-->', lt + 4);
81
- i = end < 0 ? xml.length : end + 3;
82
+ if (end < 0) {
83
+ // Unterminated: sax rejects it in strict mode, so nothing will ask
84
+ // for a position -- record nothing rather than invent one.
85
+ break;
86
+ }
87
+ comments.push({ start: lt, end: end + 3, contentStart: lt + 4, contentEnd: end });
88
+ i = end + 3;
82
89
  continue;
83
90
  }
84
91
  if (xml.startsWith('<![CDATA[', lt)) {
@@ -136,7 +143,7 @@ function scanTagEvents(xml) {
136
143
  events.push({ name, selfClosing, isClose, start: lt, end: gt + 1 });
137
144
  i = gt + 1;
138
145
  }
139
- return events;
146
+ return { tags: events, comments };
140
147
  }
141
148
  function makeParser(tagMap) {
142
149
  const parseBaseType = makeParseBaseType(tagMap);
@@ -155,25 +162,33 @@ function makeParser(tagMap) {
155
162
  // onclosetag sax fires immediately after for it.
156
163
  let selfClosingEnd;
157
164
  // The source scan feeding exact tag offsets to the handlers below.
158
- const tagEvents = scanTagEvents(xml);
165
+ const { tags: tagEvents, comments: commentEvents } = scanTagEvents(xml);
159
166
  let q = 0;
167
+ let cq = 0;
160
168
  // (line, col) of a raw offset, via an ever-forward line-start cursor.
161
- // Tag offsets are consumed in document order, so it never rewinds.
162
- let lastLineStart = 0;
163
- let currentLine = 0;
164
- function locAt(pos) {
165
- let i = lastLineStart;
166
- let line = currentLine;
167
- let nl = xml.indexOf('\n', i);
168
- while (nl !== -1 && nl < pos) {
169
- i = nl + 1;
170
- line++;
171
- nl = xml.indexOf('\n', i);
172
- }
173
- lastLineStart = i;
174
- currentLine = line;
175
- return { line, col: pos - i };
169
+ // Offsets are consumed in document order (tags and comments each in their
170
+ // own stream), so a cursor never rewinds -- which is why each stream gets
171
+ // its own: a comment can sit between two tags that the tag queue has
172
+ // already looked past.
173
+ function makeLocator() {
174
+ let lastLineStart = 0;
175
+ let currentLine = 0;
176
+ return function locAt(pos) {
177
+ let i = lastLineStart;
178
+ let line = currentLine;
179
+ let nl = xml.indexOf('\n', i);
180
+ while (nl !== -1 && nl < pos) {
181
+ i = nl + 1;
182
+ line++;
183
+ nl = xml.indexOf('\n', i);
184
+ }
185
+ lastLineStart = i;
186
+ currentLine = line;
187
+ return { line, col: pos - i };
188
+ };
176
189
  }
190
+ const locAt = makeLocator();
191
+ const commentLocAt = makeLocator();
177
192
  /**
178
193
  * Pops the queue's next tag of the given kind, trusting sax as the
179
194
  * authority on order but the scan as the authority on position. sax
@@ -199,6 +214,23 @@ function makeParser(tagMap) {
199
214
  function saxFallbackEnd() {
200
215
  return { line: parser.line, col: parser.column };
201
216
  }
217
+ /**
218
+ * Pops the scan's next comment whose inner text matches what sax reported.
219
+ * Matched by content, not by position in the stream alone: `<!--` inside a
220
+ * CDATA section or an attribute value is not a comment, so the two scans
221
+ * may legitimately disagree, and content is the one thing both agree on.
222
+ * A window keeps a single disagreement from desynchronising the rest.
223
+ */
224
+ function nextComment(text) {
225
+ for (let k = cq; k < Math.min(cq + 8, commentEvents.length); k++) {
226
+ const e = commentEvents[k];
227
+ if (xml.slice(e.contentStart, e.contentEnd) !== text)
228
+ continue;
229
+ cq = k + 1;
230
+ return e;
231
+ }
232
+ return undefined;
233
+ }
202
234
  function flushText() {
203
235
  if (currentText.length > 0) {
204
236
  const parent = stack[stack.length - 1];
@@ -298,6 +330,32 @@ function makeParser(tagMap) {
298
330
  }
299
331
  currentText += text;
300
332
  };
333
+ // An XML comment becomes a node of its own, kept where it was written:
334
+ // the preview shows a comment's text in place (the way Oxygen's Author
335
+ // mode does), so dropping comments here made them invisible. Its range
336
+ // spans `<!--` through `-->` so a click in the preview lands on the
337
+ // comment's own source line. The pending text is flushed first, so the
338
+ // text either side of it stays on the right side of the comment.
339
+ parser.oncomment = (comment) => {
340
+ flushText();
341
+ const parent = stack[stack.length - 1];
342
+ const event = nextComment(comment);
343
+ const start = event ? commentLocAt(event.start) : saxFallbackEnd();
344
+ const end = event ? commentLocAt(event.end) : saxFallbackEnd();
345
+ if (!parent)
346
+ return;
347
+ parent.children.push({
348
+ type: 'comment',
349
+ comment,
350
+ children: [],
351
+ sourceRange: {
352
+ startLine: start.line,
353
+ startCol: start.col,
354
+ endLine: end.line,
355
+ endCol: end.col,
356
+ },
357
+ });
358
+ };
301
359
  parser.onerror = (err) => {
302
360
  throw new Error(`SAX parse error at line ${parser.line}:${parser.column}: ${err.message}`);
303
361
  };
@@ -5,13 +5,21 @@ export interface SourceRange {
5
5
  endCol: number;
6
6
  }
7
7
  export interface DitaNode {
8
- type: 'element' | 'text';
8
+ type: 'element' | 'text' | 'comment';
9
9
  tagName?: string;
10
10
  classTokens?: string[];
11
11
  baseType?: string;
12
12
  attributes?: Record<string, string>;
13
13
  children: DitaNode[];
14
14
  text?: string;
15
+ /**
16
+ * Inner text of an XML comment (`<!--` … `-->` content, delimiters stripped),
17
+ * set only when type === 'comment'. Deliberately NOT stored in `text`: every
18
+ * text extraction in the codebase reads a text node's `text` as visible
19
+ * content (titles, key values, xref fallbacks, search body), and a comment
20
+ * is not content. Only the renderer shows it, and only where it was written.
21
+ */
22
+ comment?: string;
15
23
  sourceRange: SourceRange;
16
24
  }
17
25
  export interface DitaDocument {
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BASE_TYPE_RENDERERS = void 0;
4
4
  exports.collectIndextermChips = collectIndextermChips;
5
5
  exports.findTopLevelIndextermsInSubtree = findTopLevelIndextermsInSubtree;
6
+ const refErrorTexts_1 = require("./refErrorTexts");
7
+ const refTargets_1 = require("./refTargets");
6
8
  // parentBaseType only reflects the immediate ancestor (entry sits under row,
7
9
  // not thead), so header status is carried by an explicit ctx flag set when
8
10
  // entering thead/sthead and cleared when entering tbody.
@@ -229,7 +231,7 @@ function expandMfenced(node) {
229
231
  // spurious extra separator characters for the whitespace "children"
230
232
  // surrounding the real one.
231
233
  const items = (node.children || [])
232
- .filter((c) => c.type !== 'text' || (c.text || '').trim() !== '')
234
+ .filter((c) => c.type !== 'comment' && (c.type !== 'text' || (c.text || '').trim() !== ''))
233
235
  .map(serializeForeignContent);
234
236
  let inner = '';
235
237
  if (open !== '')
@@ -247,6 +249,14 @@ function expandMfenced(node) {
247
249
  inner += `<mo>${escapeHtml(close)}</mo>`;
248
250
  return `<mrow>${inner}</mrow>`;
249
251
  }
252
+ /**
253
+ * True when the element has any child that is author content. An XML comment
254
+ * is a node of its own in the parse tree (shown in place by the renderer) but
255
+ * is never content: `<xref href="a.dita"><!-- note --></xref>` has no label.
256
+ */
257
+ function hasContentChildren(node) {
258
+ return (node.children || []).some((c) => c.type !== 'comment');
259
+ }
250
260
  function serializeForeignContent(node) {
251
261
  if (node.type === 'text')
252
262
  return escapeHtml(node.text || '');
@@ -781,6 +791,10 @@ exports.BASE_TYPE_RENDERERS = {
781
791
  },
782
792
  'topic/pre': (_node, ctx, renderChildren) => `<pre class="pre preformatted">${renderChildren(_node, ctx)}</pre>`,
783
793
  'topic/xref': (node, ctx, renderChildren) => {
794
+ // An xref whose only child is an XML comment (<!-- Pull title from ... -->)
795
+ // has no author-written label: it falls back to the resolved title / href
796
+ // exactly as an empty one does, rather than showing the comment as its
797
+ // link text. hasContentChildren() is the single place that says so.
784
798
  const href = getAttr(node, 'href') || '';
785
799
  // No target at all: an xref with neither @href nor a keyref that
786
800
  // resolves to one. Dropping the element silently (the old behaviour)
@@ -789,7 +803,7 @@ exports.BASE_TYPE_RENDERERS = {
789
803
  // when it does not (the same treatment topic/ph gives an unresolved
790
804
  // keyref) -- means a broken xref reads as one instead of vanishing.
791
805
  if (!href) {
792
- if (node.children.length > 0) {
806
+ if (hasContentChildren(node)) {
793
807
  const content = renderChildren(node, ctx);
794
808
  const keyref = getAttr(node, 'keyref');
795
809
  return keyref
@@ -801,8 +815,30 @@ exports.BASE_TYPE_RENDERERS = {
801
815
  return '';
802
816
  return `<span class="xref unresolved-keyref" title="Unresolved key: ${escapeAttr(keyref)}">[${escapeAttr(keyref)}]</span>`;
803
817
  }
818
+ // An EMPTY xref whose local target is broken (host-diagnosed, see
819
+ // RenderContext.refError): the title/href fallback below would render
820
+ // the raw href in a link-shaped hint that reads as if the reference
821
+ // worked -- the silent failure this marker exists to surface. Keep the
822
+ // arrow convention of the xref-external hint, but in the error colour
823
+ // with a dashed underline and the reason appended. An xref WITH author
824
+ // text keeps it (content wins, same rule as keyref); scope=external/peer
825
+ // references are not local documents and are never diagnosed.
826
+ if (!hasContentChildren(node) && ctx.refError) {
827
+ const scope = getAttr(node, 'scope');
828
+ // An xref whose @format names a non-DITA target (html, pdf, ...) does
829
+ // not point at a DITA id: its fragment is the target format's own
830
+ // (#page=3, #section), so it is never diagnosed.
831
+ if (scope !== 'external' && scope !== 'peer' && (0, refTargets_1.isDitaFormat)(getAttr(node, 'format'))) {
832
+ const reason = ctx.refError(href);
833
+ if (reason !== undefined) {
834
+ const texts = { ...refErrorTexts_1.DEFAULT_REF_ERROR_TEXTS, ...ctx.refErrorTexts };
835
+ const text = (0, refErrorTexts_1.fillRefErrorTemplate)(texts.xref, href, reason);
836
+ return `<span class="xref-broken" title="${escapeAttr(href)}">${escapeAttr(text)}</span>`;
837
+ }
838
+ }
839
+ }
804
840
  let content;
805
- if (node.children.length > 0) {
841
+ if (hasContentChildren(node)) {
806
842
  content = renderChildren(node, ctx);
807
843
  }
808
844
  else if (href.startsWith('#')) {
@@ -134,6 +134,12 @@ export interface MapEntry {
134
134
  * reading-oriented consumers (buildBookNavManifest, renderBookParts,
135
135
  * exportHtml.ts) that skip an entry once they see resourceOnly true. */
136
136
  resourceOnly?: boolean;
137
+ /** The key scope chains this entry sits in (`[[]]` at the root; a keyscope listing
138
+ * several names gives several chains), the entry's own `keyscope` included, as
139
+ * collectMapKeys files the keys it defines. A topic the entry publishes is read
140
+ * in these scopes. Always set by collectMapEntries; optional so an entry built by
141
+ * hand (a test, another host) need not carry one. */
142
+ scopeChains?: string[][];
137
143
  }
138
144
  export declare function collectMapEntries(root: DitaNode, resolveKey?: ResolveKey, roleFormat?: RoleLabelFormatter): MapEntry[];
139
145
  export declare function renderMapDocument(root: DitaNode, options: {
@@ -470,10 +470,15 @@ function isDitamapRef(node) {
470
470
  const pathPart = href.split('#')[0].toLowerCase();
471
471
  return pathPart.endsWith('.ditamap') || node.attributes?.format === 'ditamap';
472
472
  }
473
- function collectEntriesRecursive(node, depth, result, resolveKey, roleLabel, inheritedProcessingRole = 'normal') {
473
+ function collectEntriesRecursive(node, depth, result, resolveKey, roleLabel, inheritedProcessingRole = 'normal', outerScopes = [[]]) {
474
474
  if (node.type !== 'element')
475
475
  return;
476
476
  const baseType = node.baseType;
477
+ // A keyscope names a scope for the element carrying it and everything below.
478
+ const keyscope = getAttr(node, 'keyscope');
479
+ const scopeChains = keyscope
480
+ ? outerScopes.flatMap((chain) => keyscope.trim().split(/\s+/).filter(Boolean).map((name) => chain.concat(name)))
481
+ : outerScopes;
477
482
  // Skip reltable and its children
478
483
  if (baseType === 'map/reltable')
479
484
  return;
@@ -493,7 +498,7 @@ function collectEntriesRecursive(node, depth, result, resolveKey, roleLabel, inh
493
498
  // level deeper just because expandDitamapRefs happened to splice them
494
499
  // in as DOM children of this wrapper node.
495
500
  for (const child of node.children || []) {
496
- collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, inheritedProcessingRole);
501
+ collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, inheritedProcessingRole, scopeChains);
497
502
  }
498
503
  return;
499
504
  }
@@ -530,21 +535,22 @@ function collectEntriesRecursive(node, depth, result, resolveKey, roleLabel, inh
530
535
  // been) serves no one.
531
536
  role: effectiveProcessingRole === 'resource-only' ? undefined : roleLabel(node.tagName, depth),
532
537
  resourceOnly: effectiveProcessingRole === 'resource-only',
538
+ scopeChains,
533
539
  });
534
540
  // Recurse children at depth+1
535
541
  for (const child of node.children || []) {
536
- collectEntriesRecursive(child, depth + 1, result, resolveKey, roleLabel, effectiveProcessingRole);
542
+ collectEntriesRecursive(child, depth + 1, result, resolveKey, roleLabel, effectiveProcessingRole, scopeChains);
537
543
  }
538
544
  }
539
545
  else if (baseType === 'map/topicgroup' || baseType === 'map/bookmap-structural') {
540
546
  // topicgroup / bookmap-structural: no entry itself, but recurse at same depth
541
547
  for (const child of node.children || []) {
542
- collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole);
548
+ collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole, scopeChains);
543
549
  }
544
550
  }
545
551
  else {
546
552
  for (const child of node.children || []) {
547
- collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole);
553
+ collectEntriesRecursive(child, depth, result, resolveKey, roleLabel, effectiveProcessingRole, scopeChains);
548
554
  }
549
555
  }
550
556
  }
@@ -0,0 +1,27 @@
1
+ export interface RefErrorTexts {
2
+ /**
3
+ * Placeholder chip replacing a conref that pulled nothing.
4
+ * {0} = the reason refError returned.
5
+ */
6
+ content: string;
7
+ /**
8
+ * Marker replacing an EMPTY xref whose target is broken.
9
+ * {0} = the raw href, {1} = the reason refError returned.
10
+ */
11
+ xref: string;
12
+ /** Reason (conkeyref only): the key is not defined, or has no resource target. */
13
+ missingKey: string;
14
+ /** Reason: the referenced file is not in the repository closure. */
15
+ missingFile: string;
16
+ /** Reason: the file exists but is not well-formed XML. */
17
+ parseError: string;
18
+ /** Reason: the file parses but #topicId/elementId names no id in it. */
19
+ missingId: string;
20
+ }
21
+ export declare const DEFAULT_REF_ERROR_TEXTS: RefErrorTexts;
22
+ /**
23
+ * Fills {0}, {1}, ... in a template. split/join rather than
24
+ * String.replace: the substituted values are arbitrary reference text
25
+ * (an href, a reason) and must not be read for $-patterns.
26
+ */
27
+ export declare function fillRefErrorTemplate(template: string, ...values: string[]): string;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ // Wording for the broken-reference hints (RenderContext.refError).
3
+ //
4
+ // A LEAF module: no imports, so both the renderer (render/renderer.ts,
5
+ // render/baseTypeMap.ts) and the editor-layer resolver factory
6
+ // (editor/refResolvers.ts) can read it without a cycle -- the same reason
7
+ // FALLBACK_NOTE_LABELS is duplicated in baseTypeMap rather than imported
8
+ // from the editor layer, solved here by putting the shared strings below
9
+ // both instead.
10
+ //
11
+ // The renderer only PRESENTS: it asks RenderContext.refError whether a
12
+ // reference is broken and composes the answer with the templates below.
13
+ // The diagnosis itself is the host's (the callback), and so is the
14
+ // localization -- a host fills these from its own string catalog (the VS
15
+ // Code extension does, via vscode.l10n.t); the defaults here are English.
16
+ //
17
+ // Templates use {0}/{1} placeholders rather than concatenation so a
18
+ // locale controls the whole shape, punctuation included: zh-cn wraps the
19
+ // reason in full-width parentheses(…)where English uses (…) .
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.DEFAULT_REF_ERROR_TEXTS = void 0;
22
+ exports.fillRefErrorTemplate = fillRefErrorTemplate;
23
+ exports.DEFAULT_REF_ERROR_TEXTS = {
24
+ content: 'Referenced content could not be resolved ({0})',
25
+ xref: '→ {0} ({1})',
26
+ missingKey: 'key is not defined or has no target',
27
+ missingFile: 'target file does not exist',
28
+ parseError: 'target file cannot be parsed as XML',
29
+ missingId: 'target ID does not exist',
30
+ };
31
+ /**
32
+ * Fills {0}, {1}, ... in a template. split/join rather than
33
+ * String.replace: the substituted values are arbitrary reference text
34
+ * (an href, a reason) and must not be read for $-patterns.
35
+ */
36
+ function fillRefErrorTemplate(template, ...values) {
37
+ let out = template;
38
+ for (let i = 0; i < values.length; i++) {
39
+ out = out.split(`{${i}}`).join(values[i]);
40
+ }
41
+ return out;
42
+ }
43
+ //# sourceMappingURL=refErrorTexts.js.map
@@ -0,0 +1,12 @@
1
+ /** A URL scheme (https:, mailto:, ...) -- and, by the same shape, a Windows
2
+ * drive letter (C:\...), which is no DITA-relative path either. */
3
+ export declare const URL_SCHEME_RE: RegExp;
4
+ /**
5
+ * True for a file part that is not a local DITA document, so a hint must
6
+ * never probe it: a URL, an absolute path, or a web document (.html, .htm,
7
+ * .pdf), whose #fragment is the format's own (#page=3, #section) rather than
8
+ * a DITA id. Pass the part BEFORE any '#'.
9
+ */
10
+ export declare function isNonDitaTarget(filePart: string): boolean;
11
+ /** True when an @format value names a DITA target (absent means DITA). */
12
+ export declare function isDitaFormat(format: string | undefined): boolean;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ // What a reference can point at, as far as the broken-reference hints are
3
+ // concerned: is this a target the hints may probe at all?
4
+ //
5
+ // A LEAF module (no imports, not even 'path'), like refErrorTexts.ts, so the
6
+ // renderer (baseTypeMap), the resolver factory (editor/refResolvers) and the
7
+ // conkeyref diagnosis (editor/conkeyref) can share ONE rule without a cycle
8
+ // or a dependency on the filesystem layer. Three call sites used to spell the
9
+ // rule out separately; a fourth extension (or a new scheme) now changes one
10
+ // place.
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.URL_SCHEME_RE = void 0;
13
+ exports.isNonDitaTarget = isNonDitaTarget;
14
+ exports.isDitaFormat = isDitaFormat;
15
+ /** A URL scheme (https:, mailto:, ...) -- and, by the same shape, a Windows
16
+ * drive letter (C:\...), which is no DITA-relative path either. */
17
+ exports.URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
18
+ /**
19
+ * True for a file part that is not a local DITA document, so a hint must
20
+ * never probe it: a URL, an absolute path, or a web document (.html, .htm,
21
+ * .pdf), whose #fragment is the format's own (#page=3, #section) rather than
22
+ * a DITA id. Pass the part BEFORE any '#'.
23
+ */
24
+ function isNonDitaTarget(filePart) {
25
+ return exports.URL_SCHEME_RE.test(filePart) || /^[\\/]/.test(filePart) || /\.(html?|pdf)$/i.test(filePart);
26
+ }
27
+ /** True when an @format value names a DITA target (absent means DITA). */
28
+ function isDitaFormat(format) {
29
+ return !format || format === 'dita' || format === 'ditamap';
30
+ }
31
+ //# sourceMappingURL=refTargets.js.map