@dita-viewer/core 0.2.3 → 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.
@@ -229,7 +229,7 @@ function expandMfenced(node) {
229
229
  // spurious extra separator characters for the whitespace "children"
230
230
  // surrounding the real one.
231
231
  const items = (node.children || [])
232
- .filter((c) => c.type !== 'text' || (c.text || '').trim() !== '')
232
+ .filter((c) => c.type !== 'comment' && (c.type !== 'text' || (c.text || '').trim() !== ''))
233
233
  .map(serializeForeignContent);
234
234
  let inner = '';
235
235
  if (open !== '')
@@ -247,6 +247,14 @@ function expandMfenced(node) {
247
247
  inner += `<mo>${escapeHtml(close)}</mo>`;
248
248
  return `<mrow>${inner}</mrow>`;
249
249
  }
250
+ /**
251
+ * True when the element has any child that is author content. An XML comment
252
+ * is a node of its own in the parse tree (shown in place by the renderer) but
253
+ * is never content: `<xref href="a.dita"><!-- note --></xref>` has no label.
254
+ */
255
+ function hasContentChildren(node) {
256
+ return (node.children || []).some((c) => c.type !== 'comment');
257
+ }
250
258
  function serializeForeignContent(node) {
251
259
  if (node.type === 'text')
252
260
  return escapeHtml(node.text || '');
@@ -781,6 +789,10 @@ exports.BASE_TYPE_RENDERERS = {
781
789
  },
782
790
  'topic/pre': (_node, ctx, renderChildren) => `<pre class="pre preformatted">${renderChildren(_node, ctx)}</pre>`,
783
791
  'topic/xref': (node, ctx, renderChildren) => {
792
+ // An xref whose only child is an XML comment (<!-- Pull title from ... -->)
793
+ // has no author-written label: it falls back to the resolved title / href
794
+ // exactly as an empty one does, rather than showing the comment as its
795
+ // link text. hasContentChildren() is the single place that says so.
784
796
  const href = getAttr(node, 'href') || '';
785
797
  // No target at all: an xref with neither @href nor a keyref that
786
798
  // resolves to one. Dropping the element silently (the old behaviour)
@@ -789,7 +801,7 @@ exports.BASE_TYPE_RENDERERS = {
789
801
  // when it does not (the same treatment topic/ph gives an unresolved
790
802
  // keyref) -- means a broken xref reads as one instead of vanishing.
791
803
  if (!href) {
792
- if (node.children.length > 0) {
804
+ if (hasContentChildren(node)) {
793
805
  const content = renderChildren(node, ctx);
794
806
  const keyref = getAttr(node, 'keyref');
795
807
  return keyref
@@ -802,7 +814,7 @@ exports.BASE_TYPE_RENDERERS = {
802
814
  return `<span class="xref unresolved-keyref" title="Unresolved key: ${escapeAttr(keyref)}">[${escapeAttr(keyref)}]</span>`;
803
815
  }
804
816
  let content;
805
- if (node.children.length > 0) {
817
+ if (hasContentChildren(node)) {
806
818
  content = renderChildren(node, ctx);
807
819
  }
808
820
  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
  }
@@ -499,10 +499,70 @@ function renderConrefRange(node, range, context, conref) {
499
499
  })
500
500
  .join('');
501
501
  }
502
+ // Parents whose content model is element-only, so a comment written inside
503
+ // them sits between blocks rather than inside a sentence and should get a
504
+ // block of its own. Everything else -- p, ph, li, entry, title, note text --
505
+ // holds mixed content, where an inline <span> is both valid and what the
506
+ // author saw. This is the same inline/block distinction profiling markers
507
+ // make (INLINE_PROFILING_BASETYPES), stated the other way round: there,
508
+ // inline was the short list; here the inline cases are the majority, and
509
+ // getting it wrong on the block side is the harmless direction (a comment on
510
+ // its own line inside a phrase) while a <div> inside a <p> would make the
511
+ // browser close the paragraph and split the sentence around it.
512
+ const BLOCK_COMMENT_PARENTS = new Set([
513
+ 'topic/body',
514
+ 'topic/section',
515
+ 'topic/example',
516
+ 'topic/fig',
517
+ 'topic/div',
518
+ 'topic/bodydiv',
519
+ 'topic/sectiondiv',
520
+ 'topic/topic',
521
+ 'topic/abstract',
522
+ 'topic/related-links',
523
+ 'topic/imagemap',
524
+ // List containers: a comment written between two <li>s is not part of
525
+ // either item's sentence, and an inline span there would be a stray
526
+ // fragment of the previous item.
527
+ 'topic/ul',
528
+ 'topic/ol',
529
+ 'topic/sl',
530
+ 'topic/dl',
531
+ ]);
532
+ /**
533
+ * An XML comment, shown in the flow at the position it was authored in --
534
+ * Oxygen's Author mode shows the comment text the same way, instead of the
535
+ * reader having to open the source. The text is the comment's inner content
536
+ * with the `<!-- -->` delimiters stripped: the delimiters are markup, and a
537
+ * comment's *text* is what the author wanted read. data-dita-tagname makes the
538
+ * story explicit through the Tags toggle (its tooltip reads "comment"), and
539
+ * data-line* keeps preview clicks and scroll-sync landing on the comment's own
540
+ * source lines -- its range spans `<!--` through `-->`.
541
+ *
542
+ * An empty or whitespace-only comment renders nothing: it is a spelling of
543
+ * "nothing here", and an empty box in the page would only be noise.
544
+ */
545
+ function renderComment(node, context) {
546
+ const text = (node.comment || '').replace(/\r\n?/g, '\n').trim();
547
+ if (!text)
548
+ return '';
549
+ const block = BLOCK_COMMENT_PARENTS.has(context.parentBaseType || '');
550
+ const tag = block ? 'div' : 'span';
551
+ const cls = block ? 'dv-comment dv-comment--block' : 'dv-comment';
552
+ const range = node.sourceRange;
553
+ return (`<${tag} class="${cls}" data-dita-tagname="comment"` +
554
+ ` data-line="${range.startLine}" data-end-line="${range.endLine}"` +
555
+ ` data-start-col="${range.startCol}" data-end-col="${range.endCol}">` +
556
+ escapeHtml(text) +
557
+ `</${tag}>`);
558
+ }
502
559
  function renderElement(node, context, conrefMark) {
503
560
  if (node.type === 'text') {
504
561
  return escapeHtml(node.text || '');
505
562
  }
563
+ if (node.type === 'comment') {
564
+ return renderComment(node, context);
565
+ }
506
566
  const conref = node.attributes?.conref;
507
567
  const conrefend = node.attributes?.conrefend;
508
568
  if (conref && conrefend && context.resolveConrefRange && !context.conrefChain?.has(conref)) {
@@ -520,8 +580,23 @@ function renderElement(node, context, conrefMark) {
520
580
  // The element's own conref wins over a mark handed down by a range.
521
581
  return renderEffectiveNode(effectiveNode, context, resolved.chainKey, resolved.mark ?? conrefMark);
522
582
  }
583
+ // Parents whose children must not include a comment span or block:
584
+ // - table machinery: a <span>/<div> directly inside <table>, <tbody> or <tr>
585
+ // is foster-parented by the browser to just before the whole table, so the
586
+ // comment would show up away from where it was written;
587
+ // - preformatted blocks: the comment's text would read, and copy, as code;
588
+ // - titles: the heading's text feeds the outline / table of contents.
589
+ // Keyed by the baseType of the element being rendered (the real parent), not
590
+ // by the overloaded context.parentBaseType.
591
+ const NO_COMMENT_CHILDREN = new Set([
592
+ 'topic/table', 'topic/tgroup', 'topic/thead', 'topic/tbody', 'topic/row',
593
+ 'topic/simpletable', 'topic/sthead', 'topic/strow',
594
+ 'topic/pre', 'topic/codeblock', 'topic/lines',
595
+ 'topic/title',
596
+ ]);
523
597
  function renderChildren(node, context) {
524
- const children = node.children || [];
598
+ const skipComments = !!node.baseType && NO_COMMENT_CHILDREN.has(node.baseType);
599
+ const children = (node.children || []).filter((c) => !(skipComments && c.type === 'comment'));
525
600
  // Resolved key text can leave CJK and Latin glued together (`打开` + `ABC`).
526
601
  // Insert a display-only space outside the key element; the source is untouched.
527
602
  const spacing = (0, cjkSpacing_1.computeKeyrefSpacing)(children, node.baseType, context.resolveKey);
@@ -4,9 +4,10 @@
4
4
  // the mocha suite. buildKeyMap (keyMap.ts) and any other consumer of "the
5
5
  // keys a map defines" go through collectMapKeys so there is one rule for
6
6
  // what a keydef contributes.
7
- import { dirname } from 'path';
7
+ import { dirname, resolve } from 'path';
8
8
  import { parseDitamap, preprocessEntities } from '../parser/ditaParser';
9
- import { expandDitamapRefs } from './refResolvers';
9
+ import { isDitamapRef } from '../render/mapTypeMap';
10
+ import { decodeHrefPart, expandDitamapRefs } from './refResolvers';
10
11
  import { sourceStamp } from './sourceText';
11
12
  function extractTextFromNode(node) {
12
13
  if (node.type === 'text')
@@ -66,15 +67,83 @@ export function qualifiedNamesMulti(name, scopeChains) {
66
67
  out.add(q);
67
68
  return [...out];
68
69
  }
70
+ /** The key of one (scope, name) entry in a scope index; `scopeId` is the chain joined with "/" ("" is the root). */
71
+ export function scopeKeyIndexKey(scopeId, name) {
72
+ return `${scopeId}\u0000${name}`;
73
+ }
74
+ /**
75
+ * Resolves a key written at a place that sits in the given scope chains, against an
76
+ * index of `scopeKeyIndexKey(scope, name)` entries: its own scope first, then each
77
+ * enclosing one, the nearest definition winning (DITA's scope precedence). A name with
78
+ * scope qualifiers (`a.k`, or `x.a.k` for nested scopes) is looked up below the scope
79
+ * the search starts from, so a key defined inside a scope is bare only within it and
80
+ * reachable from outside only by its qualified name. A place in several chains (a
81
+ * `keyscope` listing several names) resolves in the first chain that finds the key.
82
+ *
83
+ * The one rule behind both the completeness checks and the preview, so the two cannot
84
+ * disagree about which definition a reference reaches.
85
+ */
86
+ export function resolveKeyInScope(key, chains, index) {
87
+ const parts = key.split('.');
88
+ for (const chain of chains) {
89
+ for (let depth = chain.length; depth >= 0; depth--) {
90
+ const prefix = chain.slice(0, depth);
91
+ for (let j = 0; j < parts.length; j++) {
92
+ const scope = prefix.concat(parts.slice(0, j)).join('/');
93
+ const def = index.get(scopeKeyIndexKey(scope, parts.slice(j).join('.')));
94
+ if (def !== undefined)
95
+ return def;
96
+ }
97
+ }
98
+ }
99
+ return undefined;
100
+ }
101
+ export function createKeyScopeIndex() {
102
+ return { values: new Map(), defs: new Map(), topicScopes: new Map() };
103
+ }
104
+ function topicScopeKey(absPath) {
105
+ const p = resolve(absPath);
106
+ return process.platform === 'win32' ? p.toLowerCase() : p;
107
+ }
108
+ /** The scope chains of the topicrefs that publish `absPath`, or undefined when no topicref does. */
109
+ export function getTopicScopeChains(scopes, absPath) {
110
+ return scopes.topicScopes.get(topicScopeKey(absPath));
111
+ }
112
+ function noteTopicScope(scopes, absPath, chains) {
113
+ const k = topicScopeKey(absPath);
114
+ const known = scopes.topicScopes.get(k);
115
+ const sig = JSON.stringify(chains);
116
+ if (!known)
117
+ scopes.topicScopes.set(k, [chains]);
118
+ else if (!known.some((c) => JSON.stringify(c) === sig))
119
+ known.push(chains);
120
+ }
121
+ /**
122
+ * The scope chains a topic is read in when nothing says where it sits: the first
123
+ * topicref in the map that publishes it, or the root scope when none does (a topic
124
+ * no map publishes belongs to no keyscope).
125
+ */
126
+ export function defaultTopicScopeChains(scopes, absPath) {
127
+ return getTopicScopeChains(scopes, absPath)?.[0] ?? [[]];
128
+ }
129
+ /** A topicref href that names a file of this project: no scheme, not marked external. */
130
+ function localTopicPath(href, scope) {
131
+ if (!href || scope === 'external' || /^[a-z][a-z0-9+.-]*:/i.test(href))
132
+ return undefined;
133
+ const path = href.split('#')[0];
134
+ return path || undefined;
135
+ }
69
136
  /**
70
137
  * Parses one ditamap, expands the ditamaps it references, and adds every
71
138
  * key it defines to `into` (first definition wins, in document order).
72
139
  * When `hrefs` is supplied, each newly defined key also records its resource
73
140
  * target there (same first-definition-wins gate as the value), keyed by the
74
- * individual name. Throws if the map itself cannot be read or parsed; the
75
- * caller decides whether that is fatal.
141
+ * individual name. When `scopes` is supplied, every definition is also recorded
142
+ * under the scope it sits in, and every topic a topicref publishes under the scope
143
+ * of that topicref (same first-definition-wins gate). Throws if the map itself
144
+ * cannot be read or parsed; the caller decides whether that is fatal.
76
145
  */
77
- export function collectMapKeys(mapPath, into, read, hrefs) {
146
+ export function collectMapKeys(mapPath, into, read, hrefs, scopes) {
78
147
  const content = read(mapPath, 'utf-8');
79
148
  const doc = parseDitamap(preprocessEntities(content));
80
149
  const mapRoot = doc.root;
@@ -110,8 +179,26 @@ export function collectMapKeys(mapPath, into, read, hrefs) {
110
179
  hrefs?.set(name, { href: node.attributes?.href, baseDir: mapDir });
111
180
  }
112
181
  }
182
+ if (scopes) {
183
+ // The same definition, filed by scope: a lookup that knows where it is
184
+ // asking from finds the nearest one instead of the first in the file.
185
+ for (const chain of chains) {
186
+ const at = scopeKeyIndexKey(chain.join('/'), keyName);
187
+ if (!scopes.values.has(at)) {
188
+ scopes.values.set(at, value || keyName);
189
+ scopes.defs.set(at, { href: node.attributes?.href, baseDir: mapDir });
190
+ }
191
+ }
192
+ }
113
193
  }
114
194
  }
195
+ // A topicref publishes its topic in the scopes it sits in. A keydef does not (it
196
+ // is resource-only), and a submap reference was expanded into its children above.
197
+ if (scopes && baseType === 'map/topicref' && !isDitamapRef(node)) {
198
+ const path = localTopicPath(node.attributes?.href, node.attributes?.scope);
199
+ if (path)
200
+ noteTopicScope(scopes, resolve(mapDir, decodeHrefPart(path)), chains);
201
+ }
115
202
  for (const child of node.children || [])
116
203
  walk(child, chains);
117
204
  }
@@ -163,9 +250,10 @@ export function buildKeySpace(contextMap, ancestorMaps, read, onError = () => un
163
250
  }
164
251
  const keys = new Map();
165
252
  const defs = new Map();
253
+ const scopes = createKeyScopeIndex();
166
254
  for (const mf of sources) {
167
255
  try {
168
- collectMapKeys(mf, keys, recordingRead, defs);
256
+ collectMapKeys(mf, keys, recordingRead, defs, scopes);
169
257
  }
170
258
  catch (e) {
171
259
  onError(mf, e);
@@ -179,7 +267,8 @@ export function buildKeySpace(contextMap, ancestorMaps, read, onError = () => un
179
267
  // tests drive -- gets it, and so renderContext.ts can read it without
180
268
  // importing the vscode-dependent keyMap.ts.
181
269
  registerKeyDefs(keys, defs);
182
- return { keys, defs, files: [...new Set(files)], status };
270
+ registerKeyScopes(keys, scopes);
271
+ return { keys, defs, scopes, files: [...new Set(files)], status };
183
272
  }
184
273
  // ── values map -> href defs, by instance identity ──
185
274
  //
@@ -199,3 +288,14 @@ export function registerKeyDefs(keys, defs) {
199
288
  export function getKeyDefs(keys) {
200
289
  return defsByKeyMap.get(keys);
201
290
  }
291
+ // The scope index travels with the values map the same way, for the same reason: the
292
+ // render paths hand around `keyMap` and nothing else.
293
+ const scopesByKeyMap = new WeakMap();
294
+ export function registerKeyScopes(keys, scopes) {
295
+ scopesByKeyMap.set(keys, scopes);
296
+ }
297
+ /** The scope index paired with a given values map, or undefined if it was not
298
+ * produced by buildKeySpace (e.g. a hand-built map in a test). */
299
+ export function getKeyScopes(keys) {
300
+ return scopesByKeyMap.get(keys);
301
+ }
@@ -22,7 +22,7 @@
22
22
  // - suppressIndexterm: only the export path sets it.
23
23
  import { resolve, relative, isAbsolute } from 'path';
24
24
  import { makeFileCache, makeConrefResolver, makeConrefRangeResolver, makeFileTitleResolver, makeIsInCurrentBook, detectNoteLabels, detectIndexLabel, readImageDimensions, decodeHrefPart, URL_SCHEME_RE, } from './refResolvers';
25
- import { getKeyDefs } from './keySpace';
25
+ import { defaultTopicScopeChains, getKeyDefs, getKeyScopes, resolveKeyInScope } from './keySpace';
26
26
  import { resolveConkeyref } from './conkeyref';
27
27
  export function buildRenderContext(input) {
28
28
  const { docDir, ownRoot, titleMap, keyMap, asWebviewUri, headingLevel, uiLanguage } = input;
@@ -33,13 +33,22 @@ export function buildRenderContext(input) {
33
33
  const conrefResolver = makeConrefResolver(docDir, ownRoot, fileCache);
34
34
  const conrefRangeResolver = makeConrefRangeResolver(docDir, ownRoot, fileCache);
35
35
  const fileTitleResolver = makeFileTitleResolver(docDir, fileCache);
36
+ // Which scope a reference is read in, and the lookups bound to it. The preview's key
37
+ // space also keeps a flat name map (first definition wins, bare names visible
38
+ // everywhere); a lookup that knows where it sits reads the scope index instead, so it
39
+ // finds the nearest definition the way the completeness checks do.
40
+ const scopeIndex = getKeyScopes(keyMap);
41
+ const keyChains = scopeIndex
42
+ ? (input.keyScope ?? (input.docFile ? defaultTopicScopeChains(scopeIndex, input.docFile) : undefined))
43
+ : undefined;
44
+ const lookupKey = (key) => scopeIndex && keyChains ? resolveKeyInScope(key, keyChains, scopeIndex.values) : keyMap.get(key);
36
45
  const ctx = {
37
46
  headingLevel,
38
47
  asWebviewUri,
39
48
  documentDir: docDir,
40
49
  // Local id match first, then cross-file ("file.dita#topicId" or "file.dita").
41
50
  resolveTitle: (id) => titleMap.get(id) || fileTitleResolver(id),
42
- resolveKey: (key) => keyMap.get(key),
51
+ resolveKey: lookupKey,
43
52
  resolveConref: (conref) => conrefResolver(conref),
44
53
  resolveConrefRange: (conref, conrefend) => conrefRangeResolver(conref, conrefend),
45
54
  noteLabels: detectNoteLabels(ownRoot, uiLanguage),
@@ -76,8 +85,14 @@ export function buildRenderContext(input) {
76
85
  // the absolute-path loader rather than the docDir-relative conref resolver.
77
86
  // Discovered from keyMap by identity unless the caller passed defs directly.
78
87
  let lastLoaded;
79
- const keyDefs = input.keyDefs ?? getKeyDefs(keyMap);
80
- if (keyDefs && keyDefs.size > 0) {
88
+ const flatDefs = input.keyDefs ?? getKeyDefs(keyMap);
89
+ // Definitions come from the same scope as the text, so a conkeyref or an xref keyref
90
+ // cannot reach one scope's file while the text shows another's. Defs handed in
91
+ // explicitly (tests) are used as given.
92
+ const keyDefs = flatDefs && !input.keyDefs && scopeIndex && keyChains
93
+ ? { get: (name) => resolveKeyInScope(name, keyChains, scopeIndex.defs) }
94
+ : flatDefs;
95
+ if (keyDefs && flatDefs && flatDefs.size > 0) {
81
96
  // A keyref on a link-shaped element (topic/xref) resolves to the key's
82
97
  // resource target as its effective href. The keydef's href is relative
83
98
  // to the map that defined it, but every href the renderer consumes
@@ -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, keyScope } = input;
38
38
  try {
39
39
  const preprocessedXml = preprocessEntities(xml);
40
40
  const ditaDoc = parseDita(preprocessedXml);
@@ -58,6 +58,7 @@ export function renderTopicXml(input) {
58
58
  collectDependencies,
59
59
  docFile,
60
60
  markConrefs,
61
+ keyScope,
61
62
  });
62
63
  const html = renderDocument(ditaDoc.root, ctx);
63
64
  if (collectDependencies) {
@@ -74,7 +75,7 @@ export function renderTopicXml(input) {
74
75
  }
75
76
  }
76
77
  export function renderTopicToHtml(input) {
77
- const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs } = input;
78
+ const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs, keyScope } = input;
78
79
  try {
79
80
  if (!existsSync(filePath)) {
80
81
  return { html: '', error: `File not found: ${filePath}` };
@@ -96,6 +97,7 @@ export function renderTopicToHtml(input) {
96
97
  clickableExternalXrefs,
97
98
  docFile: filePath,
98
99
  markConrefs,
100
+ keyScope,
99
101
  });
100
102
  return { html: result.html, title: result.title, error: result.error };
101
103
  }
@@ -260,10 +262,12 @@ function dropOldestTopicEntry() {
260
262
  * headingLevel is part of the key rather than a merely validated field
261
263
  * because the same topic legitimately sits at different depths across two
262
264
  * open books -- validating it instead would make those two entries evict each
263
- * other on every pass.
265
+ * other on every pass. The key scope is part of it for the same reason, and
266
+ * for a stronger one: a topic published under two keyscopes renders with
267
+ * different key text in each, so a hit from the other scope would be wrong.
264
268
  */
265
269
  export function renderTopicCached(input) {
266
- const key = `${input.filePath}\u0000${input.headingLevel}`;
270
+ const key = `${input.filePath}\u0000${input.headingLevel}\u0000${input.keyScope ? JSON.stringify(input.keyScope) : ''}`;
267
271
  const cached = topicRenderCache.get(key);
268
272
  if (cached &&
269
273
  cached.keyMap === input.keyMap &&
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,7 +39,7 @@ 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';
42
+ export { collectMapKeys, isKeyContextAvailable, keySourceMaps, qualifiedNames, qualifiedNamesMulti, resolveKeyInScope, scopeKeyIndexKey } from './editor/keySpace';
43
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';
44
44
  export { buildRenderContext } from './editor/renderContext';
45
45
  export { clearAllSourceOverlays, dependsOn, noteSourceDependencies, sourceOverlaySize, sourceStamp, trackSourceReads } from './editor/sourceText';
@@ -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
  };