@dita-viewer/core 0.2.2 → 0.2.4

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,5 +1,5 @@
1
1
  import { DitaNode } from '../parser/domTypes';
2
- import { KeyHrefDef } from './keySpace';
2
+ import { KeyDefLookup } from './keySpace';
3
3
  /**
4
4
  * Resolve a conkeyref to its target element.
5
5
  *
@@ -16,4 +16,4 @@ import { KeyHrefDef } from './keySpace';
16
16
  * `baseDir`), returning its root, or undefined when the file
17
17
  * is missing or unparseable.
18
18
  */
19
- export declare function resolveConkeyref(conkeyref: string, defs: ReadonlyMap<string, KeyHrefDef>, loadTopic: (baseDir: string, href: string) => DitaNode | undefined): DitaNode | undefined;
19
+ export declare function resolveConkeyref(conkeyref: string, defs: KeyDefLookup, loadTopic: (baseDir: string, href: string) => DitaNode | undefined): DitaNode | undefined;
@@ -5,6 +5,21 @@ export declare function splitKeyNames(keys: string): string[];
5
5
  export declare function qualifiedNames(name: string, scopeChain: string[]): string[];
6
6
  /** Like qualifiedNames, for a definition that lives in several scope chains at once. */
7
7
  export declare function qualifiedNamesMulti(name: string, scopeChains: string[][]): string[];
8
+ /** The key of one (scope, name) entry in a scope index; `scopeId` is the chain joined with "/" ("" is the root). */
9
+ export declare function scopeKeyIndexKey(scopeId: string, name: string): string;
10
+ /**
11
+ * Resolves a key written at a place that sits in the given scope chains, against an
12
+ * index of `scopeKeyIndexKey(scope, name)` entries: its own scope first, then each
13
+ * enclosing one, the nearest definition winning (DITA's scope precedence). A name with
14
+ * scope qualifiers (`a.k`, or `x.a.k` for nested scopes) is looked up below the scope
15
+ * the search starts from, so a key defined inside a scope is bare only within it and
16
+ * reachable from outside only by its qualified name. A place in several chains (a
17
+ * `keyscope` listing several names) resolves in the first chain that finds the key.
18
+ *
19
+ * The one rule behind both the completeness checks and the preview, so the two cannot
20
+ * disagree about which definition a reference reaches.
21
+ */
22
+ export declare function resolveKeyInScope<T>(key: string, chains: string[][], index: ReadonlyMap<string, T>): T | undefined;
8
23
  /**
9
24
  * A key's resource target, captured alongside its text value so conkeyref can
10
25
  * resolve `keyname/elementid` to a file. `href` is relative to `baseDir` (the
@@ -18,20 +33,55 @@ export interface KeyHrefDef {
18
33
  href?: string;
19
34
  baseDir: string;
20
35
  }
36
+ /**
37
+ * The keys of a key space by scope, kept beside the flat name map (which answers to
38
+ * bare and qualified names alike and cannot tell scopes apart). Built by the same walk
39
+ * as the flat map, so the two never disagree about what is defined, only about where a
40
+ * lookup may find it.
41
+ */
42
+ export interface KeyScopeIndex {
43
+ /** `scopeKeyIndexKey(scope, name)` -> the key's text value. First definition wins. */
44
+ values: Map<string, string>;
45
+ /** `scopeKeyIndexKey(scope, name)` -> the key's resource target, from the same definition as the value. */
46
+ defs: Map<string, KeyHrefDef>;
47
+ /**
48
+ * A topic's absolute path (see getTopicScopeChains) -> the scope chains each topicref that
49
+ * publishes it sits in, one entry per publishing scope, in document order, no repeats.
50
+ * A topic nothing publishes has no entry.
51
+ */
52
+ topicScopes: Map<string, string[][][]>;
53
+ }
54
+ export declare function createKeyScopeIndex(): KeyScopeIndex;
55
+ /** The scope chains of the topicrefs that publish `absPath`, or undefined when no topicref does. */
56
+ export declare function getTopicScopeChains(scopes: KeyScopeIndex, absPath: string): string[][][] | undefined;
57
+ /**
58
+ * The scope chains a topic is read in when nothing says where it sits: the first
59
+ * topicref in the map that publishes it, or the root scope when none does (a topic
60
+ * no map publishes belongs to no keyscope).
61
+ */
62
+ export declare function defaultTopicScopeChains(scopes: KeyScopeIndex, absPath: string): string[][];
63
+ /** What a definition lookup needs; a Map satisfies it, and so does a scope-bound view of one. */
64
+ export interface KeyDefLookup {
65
+ get(name: string): KeyHrefDef | undefined;
66
+ }
21
67
  /**
22
68
  * Parses one ditamap, expands the ditamaps it references, and adds every
23
69
  * key it defines to `into` (first definition wins, in document order).
24
70
  * When `hrefs` is supplied, each newly defined key also records its resource
25
71
  * target there (same first-definition-wins gate as the value), keyed by the
26
- * individual name. Throws if the map itself cannot be read or parsed; the
27
- * caller decides whether that is fatal.
72
+ * individual name. When `scopes` is supplied, every definition is also recorded
73
+ * under the scope it sits in, and every topic a topicref publishes under the scope
74
+ * of that topicref (same first-definition-wins gate). Throws if the map itself
75
+ * cannot be read or parsed; the caller decides whether that is fatal.
28
76
  */
29
- export declare function collectMapKeys(mapPath: string, into: Map<string, string>, read: FileReader, hrefs?: Map<string, KeyHrefDef>): void;
77
+ export declare function collectMapKeys(mapPath: string, into: Map<string, string>, read: FileReader, hrefs?: Map<string, KeyHrefDef>, scopes?: KeyScopeIndex): void;
30
78
  export type KeyContextStatus = 'none' | 'active' | 'missing';
31
79
  export interface KeySpace {
32
80
  keys: Map<string, string>;
33
81
  /** Each key's resource target (href + defining map dir), for conkeyref. */
34
82
  defs: Map<string, KeyHrefDef>;
83
+ /** The same definitions filed by key scope, and the scopes that publish each topic. */
84
+ scopes: KeyScopeIndex;
35
85
  /** Every file the key values were derived from (for cache stamping). */
36
86
  files: string[];
37
87
  /** 'none': no context set. 'active': keys come from the context map alone.
@@ -70,3 +120,7 @@ export declare function registerKeyDefs(keys: Map<string, string>, defs: Readonl
70
120
  /** The href defs paired with a given values map, or undefined if it was not
71
121
  * produced by buildKeySpace (e.g. a hand-built map in a test). */
72
122
  export declare function getKeyDefs(keys: Map<string, string>): ReadonlyMap<string, KeyHrefDef> | undefined;
123
+ export declare function registerKeyScopes(keys: Map<string, string>, scopes: KeyScopeIndex): void;
124
+ /** The scope index paired with a given values map, or undefined if it was not
125
+ * produced by buildKeySpace (e.g. a hand-built map in a test). */
126
+ export declare function getKeyScopes(keys: Map<string, string>): KeyScopeIndex | undefined;
@@ -9,14 +9,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.splitKeyNames = splitKeyNames;
10
10
  exports.qualifiedNames = qualifiedNames;
11
11
  exports.qualifiedNamesMulti = qualifiedNamesMulti;
12
+ exports.scopeKeyIndexKey = scopeKeyIndexKey;
13
+ exports.resolveKeyInScope = resolveKeyInScope;
14
+ exports.createKeyScopeIndex = createKeyScopeIndex;
15
+ exports.getTopicScopeChains = getTopicScopeChains;
16
+ exports.defaultTopicScopeChains = defaultTopicScopeChains;
12
17
  exports.collectMapKeys = collectMapKeys;
13
18
  exports.isKeyContextAvailable = isKeyContextAvailable;
14
19
  exports.keySourceMaps = keySourceMaps;
15
20
  exports.buildKeySpace = buildKeySpace;
16
21
  exports.registerKeyDefs = registerKeyDefs;
17
22
  exports.getKeyDefs = getKeyDefs;
23
+ exports.registerKeyScopes = registerKeyScopes;
24
+ exports.getKeyScopes = getKeyScopes;
18
25
  const path_1 = require("path");
19
26
  const ditaParser_1 = require("../parser/ditaParser");
27
+ const mapTypeMap_1 = require("../render/mapTypeMap");
20
28
  const refResolvers_1 = require("./refResolvers");
21
29
  const sourceText_1 = require("./sourceText");
22
30
  function extractTextFromNode(node) {
@@ -77,15 +85,83 @@ function qualifiedNamesMulti(name, scopeChains) {
77
85
  out.add(q);
78
86
  return [...out];
79
87
  }
88
+ /** The key of one (scope, name) entry in a scope index; `scopeId` is the chain joined with "/" ("" is the root). */
89
+ function scopeKeyIndexKey(scopeId, name) {
90
+ return `${scopeId}\u0000${name}`;
91
+ }
92
+ /**
93
+ * Resolves a key written at a place that sits in the given scope chains, against an
94
+ * index of `scopeKeyIndexKey(scope, name)` entries: its own scope first, then each
95
+ * enclosing one, the nearest definition winning (DITA's scope precedence). A name with
96
+ * scope qualifiers (`a.k`, or `x.a.k` for nested scopes) is looked up below the scope
97
+ * the search starts from, so a key defined inside a scope is bare only within it and
98
+ * reachable from outside only by its qualified name. A place in several chains (a
99
+ * `keyscope` listing several names) resolves in the first chain that finds the key.
100
+ *
101
+ * The one rule behind both the completeness checks and the preview, so the two cannot
102
+ * disagree about which definition a reference reaches.
103
+ */
104
+ function resolveKeyInScope(key, chains, index) {
105
+ const parts = key.split('.');
106
+ for (const chain of chains) {
107
+ for (let depth = chain.length; depth >= 0; depth--) {
108
+ const prefix = chain.slice(0, depth);
109
+ for (let j = 0; j < parts.length; j++) {
110
+ const scope = prefix.concat(parts.slice(0, j)).join('/');
111
+ const def = index.get(scopeKeyIndexKey(scope, parts.slice(j).join('.')));
112
+ if (def !== undefined)
113
+ return def;
114
+ }
115
+ }
116
+ }
117
+ return undefined;
118
+ }
119
+ function createKeyScopeIndex() {
120
+ return { values: new Map(), defs: new Map(), topicScopes: new Map() };
121
+ }
122
+ function topicScopeKey(absPath) {
123
+ const p = (0, path_1.resolve)(absPath);
124
+ return process.platform === 'win32' ? p.toLowerCase() : p;
125
+ }
126
+ /** The scope chains of the topicrefs that publish `absPath`, or undefined when no topicref does. */
127
+ function getTopicScopeChains(scopes, absPath) {
128
+ return scopes.topicScopes.get(topicScopeKey(absPath));
129
+ }
130
+ function noteTopicScope(scopes, absPath, chains) {
131
+ const k = topicScopeKey(absPath);
132
+ const known = scopes.topicScopes.get(k);
133
+ const sig = JSON.stringify(chains);
134
+ if (!known)
135
+ scopes.topicScopes.set(k, [chains]);
136
+ else if (!known.some((c) => JSON.stringify(c) === sig))
137
+ known.push(chains);
138
+ }
139
+ /**
140
+ * The scope chains a topic is read in when nothing says where it sits: the first
141
+ * topicref in the map that publishes it, or the root scope when none does (a topic
142
+ * no map publishes belongs to no keyscope).
143
+ */
144
+ function defaultTopicScopeChains(scopes, absPath) {
145
+ return getTopicScopeChains(scopes, absPath)?.[0] ?? [[]];
146
+ }
147
+ /** A topicref href that names a file of this project: no scheme, not marked external. */
148
+ function localTopicPath(href, scope) {
149
+ if (!href || scope === 'external' || /^[a-z][a-z0-9+.-]*:/i.test(href))
150
+ return undefined;
151
+ const path = href.split('#')[0];
152
+ return path || undefined;
153
+ }
80
154
  /**
81
155
  * Parses one ditamap, expands the ditamaps it references, and adds every
82
156
  * key it defines to `into` (first definition wins, in document order).
83
157
  * When `hrefs` is supplied, each newly defined key also records its resource
84
158
  * target there (same first-definition-wins gate as the value), keyed by the
85
- * individual name. Throws if the map itself cannot be read or parsed; the
86
- * caller decides whether that is fatal.
159
+ * individual name. When `scopes` is supplied, every definition is also recorded
160
+ * under the scope it sits in, and every topic a topicref publishes under the scope
161
+ * of that topicref (same first-definition-wins gate). Throws if the map itself
162
+ * cannot be read or parsed; the caller decides whether that is fatal.
87
163
  */
88
- function collectMapKeys(mapPath, into, read, hrefs) {
164
+ function collectMapKeys(mapPath, into, read, hrefs, scopes) {
89
165
  const content = read(mapPath, 'utf-8');
90
166
  const doc = (0, ditaParser_1.parseDitamap)((0, ditaParser_1.preprocessEntities)(content));
91
167
  const mapRoot = doc.root;
@@ -121,8 +197,26 @@ function collectMapKeys(mapPath, into, read, hrefs) {
121
197
  hrefs?.set(name, { href: node.attributes?.href, baseDir: mapDir });
122
198
  }
123
199
  }
200
+ if (scopes) {
201
+ // The same definition, filed by scope: a lookup that knows where it is
202
+ // asking from finds the nearest one instead of the first in the file.
203
+ for (const chain of chains) {
204
+ const at = scopeKeyIndexKey(chain.join('/'), keyName);
205
+ if (!scopes.values.has(at)) {
206
+ scopes.values.set(at, value || keyName);
207
+ scopes.defs.set(at, { href: node.attributes?.href, baseDir: mapDir });
208
+ }
209
+ }
210
+ }
124
211
  }
125
212
  }
213
+ // A topicref publishes its topic in the scopes it sits in. A keydef does not (it
214
+ // is resource-only), and a submap reference was expanded into its children above.
215
+ if (scopes && baseType === 'map/topicref' && !(0, mapTypeMap_1.isDitamapRef)(node)) {
216
+ const path = localTopicPath(node.attributes?.href, node.attributes?.scope);
217
+ if (path)
218
+ noteTopicScope(scopes, (0, path_1.resolve)(mapDir, (0, refResolvers_1.decodeHrefPart)(path)), chains);
219
+ }
126
220
  for (const child of node.children || [])
127
221
  walk(child, chains);
128
222
  }
@@ -174,9 +268,10 @@ function buildKeySpace(contextMap, ancestorMaps, read, onError = () => undefined
174
268
  }
175
269
  const keys = new Map();
176
270
  const defs = new Map();
271
+ const scopes = createKeyScopeIndex();
177
272
  for (const mf of sources) {
178
273
  try {
179
- collectMapKeys(mf, keys, recordingRead, defs);
274
+ collectMapKeys(mf, keys, recordingRead, defs, scopes);
180
275
  }
181
276
  catch (e) {
182
277
  onError(mf, e);
@@ -190,7 +285,8 @@ function buildKeySpace(contextMap, ancestorMaps, read, onError = () => undefined
190
285
  // tests drive -- gets it, and so renderContext.ts can read it without
191
286
  // importing the vscode-dependent keyMap.ts.
192
287
  registerKeyDefs(keys, defs);
193
- return { keys, defs, files: [...new Set(files)], status };
288
+ registerKeyScopes(keys, scopes);
289
+ return { keys, defs, scopes, files: [...new Set(files)], status };
194
290
  }
195
291
  // ── values map -> href defs, by instance identity ──
196
292
  //
@@ -210,4 +306,15 @@ function registerKeyDefs(keys, defs) {
210
306
  function getKeyDefs(keys) {
211
307
  return defsByKeyMap.get(keys);
212
308
  }
309
+ // The scope index travels with the values map the same way, for the same reason: the
310
+ // render paths hand around `keyMap` and nothing else.
311
+ const scopesByKeyMap = new WeakMap();
312
+ function registerKeyScopes(keys, scopes) {
313
+ scopesByKeyMap.set(keys, scopes);
314
+ }
315
+ /** The scope index paired with a given values map, or undefined if it was not
316
+ * produced by buildKeySpace (e.g. a hand-built map in a test). */
317
+ function getKeyScopes(keys) {
318
+ return scopesByKeyMap.get(keys);
319
+ }
213
320
  //# sourceMappingURL=keySpace.js.map
@@ -18,6 +18,16 @@ export interface BuildRenderContextInput {
18
18
  * explicitly only to drive conkeyref with a hand-built keyMap (tests).
19
19
  */
20
20
  keyDefs?: ReadonlyMap<string, KeyHrefDef>;
21
+ /**
22
+ * The key scope chains the document is read in (a keyscope listing several names
23
+ * gives several chains; `[[]]` is the root scope). A keyref / conkeyref resolves
24
+ * in the nearest scope that defines the key, as DITA says, instead of by name alone.
25
+ * Book / site rendering passes the scope of the topicref that put the topic on the
26
+ * page. Left undefined, the scope comes from `docFile` (the first topicref that
27
+ * publishes it); with neither, or with a `keyMap` that carries no scope index (one
28
+ * built by hand), keys resolve by name only, as they always did.
29
+ */
30
+ keyScope?: string[][];
21
31
  /**
22
32
  * Absolute path of the document being rendered. Together with `markConrefs`
23
33
  * it lets same-file conrefs be marked too (their target file is this one).
@@ -36,13 +36,22 @@ function buildRenderContext(input) {
36
36
  const conrefResolver = (0, refResolvers_1.makeConrefResolver)(docDir, ownRoot, fileCache);
37
37
  const conrefRangeResolver = (0, refResolvers_1.makeConrefRangeResolver)(docDir, ownRoot, fileCache);
38
38
  const fileTitleResolver = (0, refResolvers_1.makeFileTitleResolver)(docDir, fileCache);
39
+ // Which scope a reference is read in, and the lookups bound to it. The preview's key
40
+ // space also keeps a flat name map (first definition wins, bare names visible
41
+ // everywhere); a lookup that knows where it sits reads the scope index instead, so it
42
+ // finds the nearest definition the way the completeness checks do.
43
+ const scopeIndex = (0, keySpace_1.getKeyScopes)(keyMap);
44
+ const keyChains = scopeIndex
45
+ ? (input.keyScope ?? (input.docFile ? (0, keySpace_1.defaultTopicScopeChains)(scopeIndex, input.docFile) : undefined))
46
+ : undefined;
47
+ const lookupKey = (key) => scopeIndex && keyChains ? (0, keySpace_1.resolveKeyInScope)(key, keyChains, scopeIndex.values) : keyMap.get(key);
39
48
  const ctx = {
40
49
  headingLevel,
41
50
  asWebviewUri,
42
51
  documentDir: docDir,
43
52
  // Local id match first, then cross-file ("file.dita#topicId" or "file.dita").
44
53
  resolveTitle: (id) => titleMap.get(id) || fileTitleResolver(id),
45
- resolveKey: (key) => keyMap.get(key),
54
+ resolveKey: lookupKey,
46
55
  resolveConref: (conref) => conrefResolver(conref),
47
56
  resolveConrefRange: (conref, conrefend) => conrefRangeResolver(conref, conrefend),
48
57
  noteLabels: (0, refResolvers_1.detectNoteLabels)(ownRoot, uiLanguage),
@@ -79,8 +88,14 @@ function buildRenderContext(input) {
79
88
  // the absolute-path loader rather than the docDir-relative conref resolver.
80
89
  // Discovered from keyMap by identity unless the caller passed defs directly.
81
90
  let lastLoaded;
82
- const keyDefs = input.keyDefs ?? (0, keySpace_1.getKeyDefs)(keyMap);
83
- if (keyDefs && keyDefs.size > 0) {
91
+ const flatDefs = input.keyDefs ?? (0, keySpace_1.getKeyDefs)(keyMap);
92
+ // Definitions come from the same scope as the text, so a conkeyref or an xref keyref
93
+ // cannot reach one scope's file while the text shows another's. Defs handed in
94
+ // explicitly (tests) are used as given.
95
+ const keyDefs = flatDefs && !input.keyDefs && scopeIndex && keyChains
96
+ ? { get: (name) => (0, keySpace_1.resolveKeyInScope)(name, keyChains, scopeIndex.defs) }
97
+ : flatDefs;
98
+ if (keyDefs && flatDefs && flatDefs.size > 0) {
84
99
  // A keyref on a link-shaped element (topic/xref) resolves to the key's
85
100
  // resource target as its effective href. The keydef's href is relative
86
101
  // to the map that defined it, but every href the renderer consumes
@@ -6,6 +6,13 @@ export interface TopicRenderInput {
6
6
  keyMap: Map<string, string>;
7
7
  asWebviewUri: (relPath: string) => string;
8
8
  headingLevel: number;
9
+ /**
10
+ * The key scope chains the topic is read in, when the caller knows where the
11
+ * topic sits (book / site: the scope of the topicref that placed it). Left
12
+ * undefined, the first topicref that publishes the file decides. See
13
+ * BuildRenderContextInput.keyScope.
14
+ */
15
+ keyScope?: string[][];
9
16
  /**
10
17
  * Fallback language (e.g. from vscode.env.language) used to pick note
11
18
  * labels (Warning/Attention/...) when the topic itself has no xml:lang
@@ -86,6 +93,8 @@ export interface TopicXmlRenderInput {
86
93
  */
87
94
  docFile?: string;
88
95
  markConrefs?: boolean;
96
+ /** See BuildRenderContextInput.keyScope. */
97
+ keyScope?: string[][];
89
98
  }
90
99
  export interface ParsedTopicResult {
91
100
  doc?: import('../parser/domTypes').DitaDocument;
@@ -184,6 +193,8 @@ export declare function setTopicRenderCacheBudgetForTesting(bytes?: number): voi
184
193
  * headingLevel is part of the key rather than a merely validated field
185
194
  * because the same topic legitimately sits at different depths across two
186
195
  * open books -- validating it instead would make those two entries evict each
187
- * other on every pass.
196
+ * other on every pass. The key scope is part of it for the same reason, and
197
+ * for a stronger one: a topic published under two keyscopes renders with
198
+ * different key text in each, so a hit from the other scope would be wrong.
188
199
  */
189
200
  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, 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,7 @@ function renderTopicXml(input) {
72
72
  collectDependencies,
73
73
  docFile,
74
74
  markConrefs,
75
+ keyScope,
75
76
  });
76
77
  const html = (0, renderer_1.renderDocument)(ditaDoc.root, ctx);
77
78
  if (collectDependencies) {
@@ -88,7 +89,7 @@ function renderTopicXml(input) {
88
89
  }
89
90
  }
90
91
  function renderTopicToHtml(input) {
91
- const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs } = input;
92
+ const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs, keyScope } = input;
92
93
  try {
93
94
  if (!(0, fs_1.existsSync)(filePath)) {
94
95
  return { html: '', error: `File not found: ${filePath}` };
@@ -110,6 +111,7 @@ function renderTopicToHtml(input) {
110
111
  clickableExternalXrefs,
111
112
  docFile: filePath,
112
113
  markConrefs,
114
+ keyScope,
113
115
  });
114
116
  return { html: result.html, title: result.title, error: result.error };
115
117
  }
@@ -274,10 +276,12 @@ function dropOldestTopicEntry() {
274
276
  * headingLevel is part of the key rather than a merely validated field
275
277
  * because the same topic legitimately sits at different depths across two
276
278
  * open books -- validating it instead would make those two entries evict each
277
- * other on every pass.
279
+ * other on every pass. The key scope is part of it for the same reason, and
280
+ * for a stronger one: a topic published under two keyscopes renders with
281
+ * different key text in each, so a hit from the other scope would be wrong.
278
282
  */
279
283
  function renderTopicCached(input) {
280
- const key = `${input.filePath}\u0000${input.headingLevel}`;
284
+ const key = `${input.filePath}\u0000${input.headingLevel}\u0000${input.keyScope ? JSON.stringify(input.keyScope) : ''}`;
281
285
  const cached = topicRenderCache.get(key);
282
286
  if (cached &&
283
287
  cached.keyMap === input.keyMap &&
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,7 +41,7 @@ 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';
44
+ export { collectMapKeys, isKeyContextAvailable, keySourceMaps, qualifiedNames, qualifiedNamesMulti, resolveKeyInScope, scopeKeyIndexKey } from './editor/keySpace';
45
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';
46
46
  export type { FileReader } from './editor/refResolvers';
47
47
  export { buildRenderContext } from './editor/renderContext';
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.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.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 = 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; } });
@@ -16,8 +16,21 @@ export interface RefEntry {
16
16
  /** format attribute on the same tag, if any */
17
17
  format?: string;
18
18
  }
19
- /** Collects every reference-bearing attribute in the document text. */
20
- export declare function collectRefEntries(text: string): RefEntry[];
19
+ /**
20
+ * Collects every reference-bearing attribute in the document text.
21
+ *
22
+ * `attrs` names the attributes to collect and defaults to the navigable set
23
+ * (href / conref / conkeyref / keyref). A caller that needs more -- the rename
24
+ * participant also has to follow conrefend, copy-to, data and longdescref --
25
+ * passes its own set, so go-to-definition and find-references keep seeing
26
+ * exactly what they saw before.
27
+ *
28
+ * Comments, CDATA sections and processing instructions are not scanned: an
29
+ * `href` inside them is example text or a commented-out reference, not a live
30
+ * one, so rename, go-to-definition, find-references and diagnostics all leave
31
+ * it alone. Offsets still index the original `text`.
32
+ */
33
+ export declare function collectRefEntries(text: string, attrs?: ReadonlySet<string>): RefEntry[];
21
34
  /** Finds the reference attribute whose value contains the given offset. */
22
35
  export declare function findRefAttrAt(text: string, offset: number): RefEntry | undefined;
23
36
  /** True when the reference points outside the local project (not resolvable from disk). */
@@ -30,14 +30,44 @@ const mapTypeMap_1 = require("../render/mapTypeMap");
30
30
  // ── Reference attribute scanning ──
31
31
  /** Attributes whose values reference other files/keys/elements. */
32
32
  const REF_ATTRS = new Set(['href', 'conref', 'conkeyref', 'keyref']);
33
+ // One alternation, so whichever region opens first wins: a "<!--" inside a
34
+ // CDATA section is CDATA text, and a "<![CDATA[" inside a comment is comment
35
+ // text. An opener with no terminator matches nothing and is left alone, so a
36
+ // stray "<!--" cannot hide every reference after it.
37
+ const NON_MARKUP_RE = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>/g;
38
+ /**
39
+ * Blanks comments, CDATA sections and processing instructions with spaces of
40
+ * the same length (line breaks are kept), so every offset into the result is
41
+ * also an offset into `text`. What is left is only live markup and character
42
+ * data, which is what a reference scan should look at.
43
+ */
44
+ function blankNonMarkup(text) {
45
+ if (!text.includes('<!') && !text.includes('<?'))
46
+ return text;
47
+ return text.replace(NON_MARKUP_RE, (region) => region.replace(/[^\r\n]/g, ' '));
48
+ }
33
49
  const TAG_RE = /<([A-Za-z][\w.-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g;
34
50
  const ATTR_RE = /([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
35
- /** Collects every reference-bearing attribute in the document text. */
36
- function collectRefEntries(text) {
51
+ /**
52
+ * Collects every reference-bearing attribute in the document text.
53
+ *
54
+ * `attrs` names the attributes to collect and defaults to the navigable set
55
+ * (href / conref / conkeyref / keyref). A caller that needs more -- the rename
56
+ * participant also has to follow conrefend, copy-to, data and longdescref --
57
+ * passes its own set, so go-to-definition and find-references keep seeing
58
+ * exactly what they saw before.
59
+ *
60
+ * Comments, CDATA sections and processing instructions are not scanned: an
61
+ * `href` inside them is example text or a commented-out reference, not a live
62
+ * one, so rename, go-to-definition, find-references and diagnostics all leave
63
+ * it alone. Offsets still index the original `text`.
64
+ */
65
+ function collectRefEntries(text, attrs = REF_ATTRS) {
37
66
  const entries = [];
67
+ const scanText = blankNonMarkup(text);
38
68
  TAG_RE.lastIndex = 0;
39
69
  let tagMatch;
40
- while ((tagMatch = TAG_RE.exec(text)) !== null) {
70
+ while ((tagMatch = TAG_RE.exec(scanText)) !== null) {
41
71
  const tagName = tagMatch[1];
42
72
  const attrSegment = tagMatch[2];
43
73
  if (!attrSegment)
@@ -57,7 +87,7 @@ function collectRefEntries(text) {
57
87
  }
58
88
  ATTR_RE.lastIndex = 0;
59
89
  while ((am = ATTR_RE.exec(attrSegment)) !== null) {
60
- if (!REF_ATTRS.has(am[1]))
90
+ if (!attrs.has(am[1]))
61
91
  continue;
62
92
  const eqAndQuote = am[0].indexOf('=') + 1 + (am[0].slice(am[0].indexOf('=') + 1).match(/["']/)?.index ?? 0);
63
93
  const valueStart = segmentOffset + am.index + eqAndQuote + 1;