@dita-viewer/core 0.2.0 → 0.2.2
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.
- package/LICENSE +21 -21
- package/README.md +90 -58
- package/dist/editor/renderContext.d.ts +7 -0
- package/dist/editor/renderContext.js +24 -0
- package/dist/editor/topicRender.d.ts +9 -0
- package/dist/editor/topicRender.js +4 -2
- package/dist/index.js +3 -3
- package/dist/language/ditaLanguageUtils.js +2 -0
- package/dist/profiling.d.ts +9 -3
- package/dist/profiling.js +12 -6
- package/dist/render/baseTypeMap.js +28 -2
- package/dist/render/mapTypeMap.js +23 -23
- package/dist/render/renderer.d.ts +24 -0
- package/dist/render/renderer.js +36 -9
- package/dist-esm/bookRender.js +145 -0
- package/dist-esm/completion.js +142 -0
- package/dist-esm/completionData.js +155 -0
- package/dist-esm/diagnostics.js +378 -0
- package/dist-esm/editor/conkeyref.js +104 -0
- package/dist-esm/editor/keySpace.js +201 -0
- package/dist-esm/editor/refResolvers.js +633 -0
- package/dist-esm/editor/renderContext.js +138 -0
- package/dist-esm/editor/sourceText.js +142 -0
- package/dist-esm/editor/topicRender.js +328 -0
- package/dist-esm/index.js +66 -0
- package/dist-esm/keyMapForDocument.js +23 -0
- package/dist-esm/language/ditaLanguageUtils.js +659 -0
- package/dist-esm/language/referenceableFiles.js +108 -0
- package/dist-esm/mapRender.js +24 -0
- package/dist-esm/package.json +1 -0
- package/dist-esm/parser/ditaParser.js +409 -0
- package/dist-esm/parser/domTypes.js +1 -0
- package/dist-esm/parser/mapTagMap.js +77 -0
- package/dist-esm/parser/namedEntities.js +321 -0
- package/dist-esm/parser/standardTagMap.js +393 -0
- package/dist-esm/profiling.js +224 -0
- package/dist-esm/render/baseTypeMap.js +1057 -0
- package/dist-esm/render/cjkSpacing.js +94 -0
- package/dist-esm/render/mapTypeMap.js +568 -0
- package/dist-esm/render/renderer.js +519 -0
- package/dist-esm/siteRender.js +261 -0
- package/package.json +55 -53
- package/styles/TOKENS.md +59 -38
- package/styles/dita-content.css +1171 -1157
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
// Authoring problems in one DITA source file, for a host's editor.
|
|
2
|
+
//
|
|
3
|
+
// Project-owned, not one of the verbatim VS Code files: the viewer's own
|
|
4
|
+
// diagnostics are built on `vscode.Diagnostic`, and this is the part a host
|
|
5
|
+
// without that type needs. Positions are 0-based line/column pairs with an
|
|
6
|
+
// exclusive end, the same convention as the parser's SourceRange.
|
|
7
|
+
//
|
|
8
|
+
// Two passes. The source must first be well-formed XML; a broken document gets
|
|
9
|
+
// that one error and nothing else, because every element position after the
|
|
10
|
+
// error would be a guess. Only then is the tree walked for the mistakes that
|
|
11
|
+
// read fine as XML: references to nothing and ids used twice.
|
|
12
|
+
import { existsSync } from 'fs';
|
|
13
|
+
import { dirname, isAbsolute, resolve } from 'path';
|
|
14
|
+
import sax from 'sax';
|
|
15
|
+
import { parseDita, parseDitamap } from './parser/ditaParser';
|
|
16
|
+
import { decodeHrefPart } from './editor/refResolvers';
|
|
17
|
+
import { splitRefFragment } from './language/ditaLanguageUtils';
|
|
18
|
+
/** A file whose #id anchors can be checked with idsIn. */
|
|
19
|
+
const DITA_FILE = /\.(dita|ditamap|xml)$/i;
|
|
20
|
+
/** `http:`, `mailto:`, `C:` — a reference the vault cannot resolve by path. */
|
|
21
|
+
const URL_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
|
22
|
+
/** Attributes that point at a file or an element. */
|
|
23
|
+
const FILE_ATTRIBUTES = ['href', 'conref', 'conrefend'];
|
|
24
|
+
/** Attributes that point at a key. conkeyref adds an element id after a '/'. */
|
|
25
|
+
const KEY_ATTRIBUTES = ['keyref', 'conkeyref'];
|
|
26
|
+
// ── line/column helpers ──
|
|
27
|
+
/** Offsets of every line start, so a source position and an offset convert both ways. */
|
|
28
|
+
function lineStarts(text) {
|
|
29
|
+
const starts = [0];
|
|
30
|
+
for (let i = 0; i < text.length; i++)
|
|
31
|
+
if (text.charCodeAt(i) === 10)
|
|
32
|
+
starts.push(i + 1);
|
|
33
|
+
return starts;
|
|
34
|
+
}
|
|
35
|
+
function offsetOf(starts, text, line, col) {
|
|
36
|
+
const start = starts[Math.min(Math.max(0, line), starts.length - 1)];
|
|
37
|
+
return Math.min(text.length, start + Math.max(0, col));
|
|
38
|
+
}
|
|
39
|
+
function positionOf(starts, offset) {
|
|
40
|
+
let lo = 0;
|
|
41
|
+
let hi = starts.length - 1;
|
|
42
|
+
while (lo < hi) {
|
|
43
|
+
const mid = (lo + hi + 1) >> 1;
|
|
44
|
+
if (starts[mid] <= offset)
|
|
45
|
+
lo = mid;
|
|
46
|
+
else
|
|
47
|
+
hi = mid - 1;
|
|
48
|
+
}
|
|
49
|
+
return { line: lo, col: offset - starts[lo] };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Index just past the '>' that closes the tag opening at `start`, skipping
|
|
53
|
+
* quoted attribute values (a conref can contain '>'), or `start + 1` when the
|
|
54
|
+
* tag is unterminated.
|
|
55
|
+
*/
|
|
56
|
+
function openingTagEnd(text, start) {
|
|
57
|
+
let quote;
|
|
58
|
+
for (let i = start + 1; i < text.length; i++) {
|
|
59
|
+
const ch = text[i];
|
|
60
|
+
if (quote) {
|
|
61
|
+
if (ch === quote)
|
|
62
|
+
quote = undefined;
|
|
63
|
+
}
|
|
64
|
+
else if (ch === '"' || ch === "'") {
|
|
65
|
+
quote = ch;
|
|
66
|
+
}
|
|
67
|
+
else if (ch === '>') {
|
|
68
|
+
return i + 1;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return start + 1;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The range to underline for an element: its opening tag. The parser records
|
|
75
|
+
* the whole element (open through close), which for a container would paint
|
|
76
|
+
* half the screen for one bad attribute.
|
|
77
|
+
*/
|
|
78
|
+
function openingTagRange(text, starts, node) {
|
|
79
|
+
const start = offsetOf(starts, text, node.sourceRange.startLine, node.sourceRange.startCol);
|
|
80
|
+
const end = openingTagEnd(text, start);
|
|
81
|
+
const endPos = positionOf(starts, end);
|
|
82
|
+
return {
|
|
83
|
+
startLine: node.sourceRange.startLine,
|
|
84
|
+
startCol: node.sourceRange.startCol,
|
|
85
|
+
endLine: endPos.line,
|
|
86
|
+
endCol: endPos.col,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
// ── well-formedness ──
|
|
90
|
+
/**
|
|
91
|
+
* Replaces the DOCTYPE declaration with spaces instead of deleting it, so the
|
|
92
|
+
* line and column SAX reports still match the editor. A DITA DOCTYPE is often
|
|
93
|
+
* two lines long; deleting it (as preprocessEntities does) would shift every
|
|
94
|
+
* position after it up by one.
|
|
95
|
+
*/
|
|
96
|
+
function blankDoctype(xml) {
|
|
97
|
+
const start = xml.indexOf('<!DOCTYPE');
|
|
98
|
+
if (start < 0)
|
|
99
|
+
return xml;
|
|
100
|
+
let i = start + '<!DOCTYPE'.length;
|
|
101
|
+
let quote;
|
|
102
|
+
let subset = false;
|
|
103
|
+
for (; i < xml.length; i++) {
|
|
104
|
+
const ch = xml[i];
|
|
105
|
+
if (quote) {
|
|
106
|
+
if (ch === quote)
|
|
107
|
+
quote = undefined;
|
|
108
|
+
}
|
|
109
|
+
else if (ch === '"' || ch === "'") {
|
|
110
|
+
quote = ch;
|
|
111
|
+
}
|
|
112
|
+
else if (ch === '[') {
|
|
113
|
+
subset = true;
|
|
114
|
+
}
|
|
115
|
+
else if (ch === ']') {
|
|
116
|
+
subset = false;
|
|
117
|
+
}
|
|
118
|
+
else if (ch === '>' && !subset) {
|
|
119
|
+
i++;
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const blanked = xml.slice(start, i).replace(/[^\n]/g, ' ');
|
|
124
|
+
return xml.slice(0, start) + blanked + xml.slice(i);
|
|
125
|
+
}
|
|
126
|
+
/** CDATA and comments are skipped; what is left is a named entity reference. */
|
|
127
|
+
const CDATA_COMMENT_OR_ENTITY = /(<!\[CDATA\[[\s\S]*?\]\]>|<!--[\s\S]*?-->)|&([A-Za-z_][\w.-]*);/g;
|
|
128
|
+
const XML_BUILTIN = new Set(['amp', 'lt', 'gt', 'quot', 'apos']);
|
|
129
|
+
/**
|
|
130
|
+
* Makes a DITA source parseable without changing where anything is.
|
|
131
|
+
*
|
|
132
|
+
* DITA sources use ` ` and friends with no DTD loaded to declare them, so
|
|
133
|
+
* a strict XML parser would stop at the first one. preprocessEntities (the
|
|
134
|
+
* renderer's answer) swaps each for its character, which is right for
|
|
135
|
+
* rendering but moves every later column on that line: an underline placed by
|
|
136
|
+
* the parser's position would land on the wrong tag. Here each named
|
|
137
|
+
* reference becomes the same number of spaces instead, so line and column
|
|
138
|
+
* still match the editor. The result is only ever parsed, never shown.
|
|
139
|
+
*/
|
|
140
|
+
function parseableSource(xml) {
|
|
141
|
+
return blankDoctype(xml).replace(CDATA_COMMENT_OR_ENTITY, (full, verbatim, name) => verbatim !== undefined || XML_BUILTIN.has(name) ? full : ' '.repeat(full.length));
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The first XML error, with the tag it belongs to underlined where one can be
|
|
145
|
+
* found.
|
|
146
|
+
*/
|
|
147
|
+
function checkWellFormed(xml) {
|
|
148
|
+
const source = parseableSource(xml);
|
|
149
|
+
const parser = sax.parser(true, { trim: false, normalize: false });
|
|
150
|
+
let failure;
|
|
151
|
+
parser.onerror = (err) => {
|
|
152
|
+
failure = { line: parser.line, column: parser.column, message: err.message };
|
|
153
|
+
// Abort: SAX would otherwise keep parsing whatever follows the error.
|
|
154
|
+
throw err;
|
|
155
|
+
};
|
|
156
|
+
try {
|
|
157
|
+
parser.write(source).close();
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
// onerror recorded it; the throw above is only the abort mechanism.
|
|
161
|
+
}
|
|
162
|
+
if (!failure)
|
|
163
|
+
return undefined;
|
|
164
|
+
const message = failure.message.split('\n')[0].trim() || failure.message;
|
|
165
|
+
const starts = lineStarts(xml);
|
|
166
|
+
const at = offsetOf(starts, xml, failure.line, Math.max(0, failure.column - 1));
|
|
167
|
+
// The error points just past the offending character (often a tag's '>').
|
|
168
|
+
// Widening to the enclosing tag underlines `</para>` rather than one char
|
|
169
|
+
// after it; at end of file there is no tag, so the position stays as is.
|
|
170
|
+
const tagStart = Math.max(xml.lastIndexOf('<', at), xml.lastIndexOf('<', at - 1));
|
|
171
|
+
const tagEnd = tagStart >= 0 ? openingTagEnd(xml, tagStart) : -1;
|
|
172
|
+
const insideTag = tagStart >= 0 && at < tagEnd;
|
|
173
|
+
// A tag whose '>' is missing swallows the next one, and the parser only
|
|
174
|
+
// notices at that next tag. Blame the tag that was left open.
|
|
175
|
+
const previous = insideTag ? xml.lastIndexOf('<', tagStart - 1) : -1;
|
|
176
|
+
if (previous >= 0 && /[A-Za-z_:]/.test(xml[previous + 1] ?? '') && openingTagEnd(xml, previous) > tagStart) {
|
|
177
|
+
const name = /^<([^\s/>]+)/.exec(xml.slice(previous))?.[1] ?? '';
|
|
178
|
+
const end = previous + xml.slice(previous, tagStart).trimEnd().length;
|
|
179
|
+
const a = positionOf(starts, previous);
|
|
180
|
+
const b = positionOf(starts, end);
|
|
181
|
+
return {
|
|
182
|
+
severity: 'error',
|
|
183
|
+
message: `The <${name}> tag is missing its closing ">"`,
|
|
184
|
+
startLine: a.line,
|
|
185
|
+
startCol: a.col,
|
|
186
|
+
endLine: b.line,
|
|
187
|
+
endCol: b.col,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
const from = insideTag ? positionOf(starts, tagStart) : positionOf(starts, at);
|
|
191
|
+
const to = insideTag ? positionOf(starts, tagEnd) : positionOf(starts, Math.min(xml.length, at + 1));
|
|
192
|
+
return {
|
|
193
|
+
severity: 'error',
|
|
194
|
+
message,
|
|
195
|
+
startLine: from.line,
|
|
196
|
+
startCol: from.col,
|
|
197
|
+
endLine: to.line,
|
|
198
|
+
endCol: to.col,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
// ── document walk ──
|
|
202
|
+
function elementChildren(node) {
|
|
203
|
+
return (node.children ?? []).filter((c) => c.type === 'element');
|
|
204
|
+
}
|
|
205
|
+
function walk(root, visit) {
|
|
206
|
+
visit(root);
|
|
207
|
+
for (const child of elementChildren(root))
|
|
208
|
+
walk(child, visit);
|
|
209
|
+
}
|
|
210
|
+
/** Every id in the document, mapped to the 0-based line it is first used on. */
|
|
211
|
+
function idsWithLines(root) {
|
|
212
|
+
const ids = new Map();
|
|
213
|
+
walk(root, (node) => {
|
|
214
|
+
const id = node.attributes?.id;
|
|
215
|
+
if (id && !ids.has(id))
|
|
216
|
+
ids.set(id, node.sourceRange.startLine);
|
|
217
|
+
});
|
|
218
|
+
return ids;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* The first id a `#fragment` names that `has` does not know. A fragment is
|
|
222
|
+
* `topicid` or `topicid/elementid` (DITA's two-part form), so both halves must
|
|
223
|
+
* exist; a single id may be a topic's or an element's.
|
|
224
|
+
*/
|
|
225
|
+
export function missingFragmentId(fragment, has) {
|
|
226
|
+
const { topicId, elementId } = splitRefFragment(fragment);
|
|
227
|
+
const wanted = topicId ? [topicId, elementId] : [elementId];
|
|
228
|
+
return wanted.filter((id) => id !== '').find((id) => !has(id));
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* The key a keyref/conkeyref names: everything before the first '/' (the rest,
|
|
232
|
+
* if any, is an element id inside the target topic).
|
|
233
|
+
*/
|
|
234
|
+
function keyNameOf(value) {
|
|
235
|
+
const slash = value.indexOf('/');
|
|
236
|
+
return (slash < 0 ? value : value.slice(0, slash)).trim();
|
|
237
|
+
}
|
|
238
|
+
function report(state, node, message) {
|
|
239
|
+
state.out.push({ severity: 'warning', message, ...openingTagRange(state.text, state.starts, node) });
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* True when the href names a file this vault can open: no scheme, no absolute
|
|
243
|
+
* path, and not marked external or peer (a peer is in another deliverable, so
|
|
244
|
+
* it need not exist next to this file).
|
|
245
|
+
*/
|
|
246
|
+
function isLocalRef(node, value) {
|
|
247
|
+
const scope = node.attributes?.scope;
|
|
248
|
+
if (scope === 'external' || scope === 'peer')
|
|
249
|
+
return false;
|
|
250
|
+
if (URL_SCHEME.test(value) || isAbsolute(value))
|
|
251
|
+
return false;
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
function checkFileRef(state, node, attribute) {
|
|
255
|
+
const raw = (node.attributes?.[attribute] ?? '').trim();
|
|
256
|
+
if (!raw || raw === '#')
|
|
257
|
+
return;
|
|
258
|
+
const hash = raw.indexOf('#');
|
|
259
|
+
const pathPart = (hash < 0 ? raw : raw.slice(0, hash)).split('?')[0];
|
|
260
|
+
const fragment = hash < 0 ? '' : raw.slice(hash + 1);
|
|
261
|
+
if (!pathPart) {
|
|
262
|
+
// "#id": a target in this file. An id the document does not define is a
|
|
263
|
+
// broken link even though the file it "points at" trivially exists.
|
|
264
|
+
const missing = fragment ? missingFragmentId(decodeHrefPart(fragment), (id) => state.ownIds.has(id)) : undefined;
|
|
265
|
+
if (missing !== undefined)
|
|
266
|
+
report(state, node, `No element with id "${missing}" in this file`);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (!isLocalRef(node, raw))
|
|
270
|
+
return;
|
|
271
|
+
const target = resolve(state.docDir, decodeHrefPart(pathPart));
|
|
272
|
+
// Watched even when it does not exist: creating the file is exactly the
|
|
273
|
+
// fix for "File not found", and must clear the warning without reopening.
|
|
274
|
+
state.deps?.add(target);
|
|
275
|
+
if (!state.fileExists(target)) {
|
|
276
|
+
report(state, node, `File not found: ${pathPart}`);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (!fragment || !state.idsIn || !DITA_FILE.test(target))
|
|
280
|
+
return;
|
|
281
|
+
const ids = state.idsIn(target);
|
|
282
|
+
const missing = ids ? missingFragmentId(decodeHrefPart(fragment), (id) => ids.includes(id)) : undefined;
|
|
283
|
+
if (missing !== undefined)
|
|
284
|
+
report(state, node, `No element with id "${missing}" in ${pathPart}`);
|
|
285
|
+
}
|
|
286
|
+
function checkKeyRef(state, node, attribute) {
|
|
287
|
+
const raw = (node.attributes?.[attribute] ?? '').trim();
|
|
288
|
+
if (!raw)
|
|
289
|
+
return;
|
|
290
|
+
const name = keyNameOf(raw);
|
|
291
|
+
// No key space at all means no map was found near the document, not that
|
|
292
|
+
// every key is missing: a topic opened on its own would otherwise warn on
|
|
293
|
+
// each keyref it has.
|
|
294
|
+
if (state.keys.size === 0)
|
|
295
|
+
return;
|
|
296
|
+
if (name && !state.keys.has(name)) {
|
|
297
|
+
report(state, node, `Key "${name}" is not defined by the maps near this document`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Duplicate ids, within each topic. DITA only requires an id to be unique in
|
|
302
|
+
* its own topic, so the same id in a nested topic is legal; a topic's own id
|
|
303
|
+
* belongs to the scope it sits in. A map has no topics and is one scope.
|
|
304
|
+
*/
|
|
305
|
+
function checkDuplicateIds(state, root) {
|
|
306
|
+
const visit = (node, scope) => {
|
|
307
|
+
const id = node.attributes?.id;
|
|
308
|
+
if (id) {
|
|
309
|
+
const first = scope.get(id);
|
|
310
|
+
// The first use is the definition; every later one is the mistake.
|
|
311
|
+
// Tracked per id rather than by position so two tags on one line clash.
|
|
312
|
+
if (first === undefined)
|
|
313
|
+
scope.set(id, node.sourceRange.startLine);
|
|
314
|
+
else
|
|
315
|
+
report(state, node, `Duplicate id "${id}"; first used on line ${first + 1}`);
|
|
316
|
+
}
|
|
317
|
+
const inner = node.baseType === 'topic/topic' ? new Map() : scope;
|
|
318
|
+
for (const child of elementChildren(node))
|
|
319
|
+
visit(child, inner);
|
|
320
|
+
};
|
|
321
|
+
visit(root, new Map());
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* What is wrong with this source, sorted by position. An empty array means the
|
|
325
|
+
* document is well formed and every reference it makes can be resolved.
|
|
326
|
+
*/
|
|
327
|
+
export function collectDiagnostics(input) {
|
|
328
|
+
const { xml, absPath, keys, keyFiles, fileExists = existsSync, idsIn, collectDependencies } = input;
|
|
329
|
+
// Key maps are dependencies whatever the document turns out to contain: a
|
|
330
|
+
// keyref that resolves today can stop resolving when the map changes, and
|
|
331
|
+
// no other file is read to find that out.
|
|
332
|
+
if (collectDependencies)
|
|
333
|
+
for (const map of keyFiles ?? [])
|
|
334
|
+
collectDependencies.add(map);
|
|
335
|
+
const wellFormed = checkWellFormed(xml);
|
|
336
|
+
if (wellFormed)
|
|
337
|
+
return [wellFormed];
|
|
338
|
+
const isMap = input.isMap ?? /\.ditamap$/i.test(absPath);
|
|
339
|
+
let root;
|
|
340
|
+
try {
|
|
341
|
+
root = (isMap ? parseDitamap : parseDita)(parseableSource(xml)).root;
|
|
342
|
+
}
|
|
343
|
+
catch (e) {
|
|
344
|
+
// Well-formed, but not something the renderer can walk (an empty root,
|
|
345
|
+
// say). Report it at the top rather than pretending the file is clean.
|
|
346
|
+
return [{
|
|
347
|
+
severity: 'error',
|
|
348
|
+
message: e instanceof Error ? e.message : String(e),
|
|
349
|
+
startLine: 0,
|
|
350
|
+
startCol: 0,
|
|
351
|
+
endLine: 0,
|
|
352
|
+
endCol: 0,
|
|
353
|
+
}];
|
|
354
|
+
}
|
|
355
|
+
const state = {
|
|
356
|
+
text: xml,
|
|
357
|
+
starts: lineStarts(xml),
|
|
358
|
+
docDir: dirname(absPath),
|
|
359
|
+
keys: keys ?? new Map(),
|
|
360
|
+
fileExists,
|
|
361
|
+
idsIn,
|
|
362
|
+
deps: collectDependencies,
|
|
363
|
+
ownIds: idsWithLines(root),
|
|
364
|
+
out: [],
|
|
365
|
+
};
|
|
366
|
+
checkDuplicateIds(state, root);
|
|
367
|
+
walk(root, (node) => {
|
|
368
|
+
for (const attribute of KEY_ATTRIBUTES)
|
|
369
|
+
checkKeyRef(state, node, attribute);
|
|
370
|
+
// keyref wins over href when both are present (DITA's indirect-first
|
|
371
|
+
// rule), so a co-located href is a fallback and not worth a warning.
|
|
372
|
+
if (node.attributes?.keyref)
|
|
373
|
+
return;
|
|
374
|
+
for (const attribute of FILE_ATTRIBUTES)
|
|
375
|
+
checkFileRef(state, node, attribute);
|
|
376
|
+
});
|
|
377
|
+
return state.out.sort((a, b) => a.startLine - b.startLine || a.startCol - b.startCol);
|
|
378
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// conkeyref resolution (P3) -- the DITA "content reference by key".
|
|
2
|
+
//
|
|
3
|
+
// A conkeyref value ("keyname", "keyname/elementid" or
|
|
4
|
+
// "keyname/topicid/elementid") is an indirect content reference: the leading
|
|
5
|
+
// segment is a key, resolved through the map key space to the target topic's
|
|
6
|
+
// href, and the remaining segments address an element inside that topic. It is
|
|
7
|
+
// the key-based analogue of a direct conref -- once the target element is
|
|
8
|
+
// found, the renderer substitutes it exactly as it would a conref target
|
|
9
|
+
// (same-type merge, cross-type replacement, cycle guard).
|
|
10
|
+
//
|
|
11
|
+
// This module is pure: no vscode, no filesystem, no parser. It takes the key
|
|
12
|
+
// space's href definitions plus an injected `loadTopic` (the caller owns file
|
|
13
|
+
// IO, caching and parsing) and returns the resolved target element or
|
|
14
|
+
// undefined. Returning undefined is how the caller learns to fall back: per the
|
|
15
|
+
// DITA 1.3 spec (and DITA-OT's DOTJ046E behaviour), when a conkeyref cannot be
|
|
16
|
+
// resolved -- key not defined, key with no href, target file missing, addressed
|
|
17
|
+
// id not present -- an element that also carries a direct @conref uses that
|
|
18
|
+
// instead, and when there is no conref the element renders its own literal
|
|
19
|
+
// content.
|
|
20
|
+
//
|
|
21
|
+
// Key-space precedence is inherited unchanged from the definitions it is given
|
|
22
|
+
// (first definition wins; a context map fully replaces the ancestor scan) --
|
|
23
|
+
// this function only reads the map it is handed, so switching the key context
|
|
24
|
+
// switches conkeyref targets for free.
|
|
25
|
+
/**
|
|
26
|
+
* Addressing inside the key's target topic: the whole topic when the value has
|
|
27
|
+
* only the key name, otherwise the last path segment (the element id, for both
|
|
28
|
+
* the "key/elemid" and the "key/topicid/elemid" forms -- the intermediate topic
|
|
29
|
+
* id is redundant for a by-id lookup).
|
|
30
|
+
*/
|
|
31
|
+
function parseConkeyref(conkeyref) {
|
|
32
|
+
const segments = conkeyref.split('/').filter((s) => s !== '');
|
|
33
|
+
const keyName = segments[0];
|
|
34
|
+
const elementId = segments.length > 1 ? segments[segments.length - 1] : undefined;
|
|
35
|
+
return { keyName, elementId };
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The element id a key's own href addresses: the last path segment of its
|
|
39
|
+
* fragment ("file.dita#topicid/elemid" -> "elemid"; "file.dita#topicid" ->
|
|
40
|
+
* "topicid"), or undefined when the href has no fragment. This is what a bare
|
|
41
|
+
* conkeyref="keyname" points at when the key was defined against an element.
|
|
42
|
+
*/
|
|
43
|
+
function hrefFragmentTarget(href) {
|
|
44
|
+
const hash = href.indexOf('#');
|
|
45
|
+
if (hash < 0)
|
|
46
|
+
return undefined;
|
|
47
|
+
const segments = href.slice(hash + 1).split('/').filter((s) => s !== '');
|
|
48
|
+
if (segments.length === 0)
|
|
49
|
+
return undefined;
|
|
50
|
+
const last = segments[segments.length - 1];
|
|
51
|
+
try {
|
|
52
|
+
return decodeURIComponent(last);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return last;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function findElementById(root, targetId) {
|
|
59
|
+
if (root.attributes?.id === targetId)
|
|
60
|
+
return root;
|
|
61
|
+
for (const child of root.children || []) {
|
|
62
|
+
const found = findElementById(child, targetId);
|
|
63
|
+
if (found)
|
|
64
|
+
return found;
|
|
65
|
+
}
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Resolve a conkeyref to its target element.
|
|
70
|
+
*
|
|
71
|
+
* Cycle protection is deliberately NOT done here. A conkeyref that resolves
|
|
72
|
+
* back into an already-rendered chain (A -> B -> A) is caught one level up, by
|
|
73
|
+
* the renderer: resolveConrefForNode only calls this when the value is not
|
|
74
|
+
* already on its conrefChain, mirroring direct-conref cycle protection. Keeping
|
|
75
|
+
* the guard out of this pure function means one owner for the rule and no dead
|
|
76
|
+
* parameter at the call sites (buildRenderContext never threads a chain in).
|
|
77
|
+
*
|
|
78
|
+
* @param conkeyref the raw @conkeyref value.
|
|
79
|
+
* @param defs the key space's href definitions (from KeySpace.defs).
|
|
80
|
+
* @param loadTopic loads and parses the topic at `href` (relative to
|
|
81
|
+
* `baseDir`), returning its root, or undefined when the file
|
|
82
|
+
* is missing or unparseable.
|
|
83
|
+
*/
|
|
84
|
+
export function resolveConkeyref(conkeyref, defs, loadTopic) {
|
|
85
|
+
if (!conkeyref)
|
|
86
|
+
return undefined;
|
|
87
|
+
const { keyName, elementId } = parseConkeyref(conkeyref);
|
|
88
|
+
if (!keyName)
|
|
89
|
+
return undefined;
|
|
90
|
+
const def = defs.get(keyName);
|
|
91
|
+
// Key not defined, or defined without a resource target: nothing to pull.
|
|
92
|
+
if (!def || !def.href)
|
|
93
|
+
return undefined;
|
|
94
|
+
const root = loadTopic(def.baseDir, def.href);
|
|
95
|
+
if (!root)
|
|
96
|
+
return undefined;
|
|
97
|
+
// An id in the conkeyref itself wins; otherwise the key's own href may name
|
|
98
|
+
// the element ("file.dita#topicid/elemid"); with neither, the reference
|
|
99
|
+
// targets the key's whole topic.
|
|
100
|
+
const targetId = elementId ?? hrefFragmentTarget(def.href);
|
|
101
|
+
if (!targetId)
|
|
102
|
+
return root;
|
|
103
|
+
return findElementById(root, targetId);
|
|
104
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// ── key definitions of one ditamap (vscode-free, unit-testable) ──
|
|
2
|
+
//
|
|
3
|
+
// Split out of keyMap.ts, which imports vscode and so cannot be loaded by
|
|
4
|
+
// the mocha suite. buildKeyMap (keyMap.ts) and any other consumer of "the
|
|
5
|
+
// keys a map defines" go through collectMapKeys so there is one rule for
|
|
6
|
+
// what a keydef contributes.
|
|
7
|
+
import { dirname } from 'path';
|
|
8
|
+
import { parseDitamap, preprocessEntities } from '../parser/ditaParser';
|
|
9
|
+
import { expandDitamapRefs } from './refResolvers';
|
|
10
|
+
import { sourceStamp } from './sourceText';
|
|
11
|
+
function extractTextFromNode(node) {
|
|
12
|
+
if (node.type === 'text')
|
|
13
|
+
return node.text || '';
|
|
14
|
+
return (node.children || []).map(extractTextFromNode).join('');
|
|
15
|
+
}
|
|
16
|
+
function getNodeValue(node, childBaseTypes) {
|
|
17
|
+
for (const bt of childBaseTypes) {
|
|
18
|
+
const child = (node.children || []).find((c) => c.type === 'element' && c.baseType === bt);
|
|
19
|
+
if (child) {
|
|
20
|
+
const text = extractTextFromNode(child).trim();
|
|
21
|
+
if (text)
|
|
22
|
+
return text;
|
|
23
|
+
}
|
|
24
|
+
// DITA wraps <keyword> inside <keywords>; also search inside known wrappers
|
|
25
|
+
const wrapper = (node.children || []).find((c) => c.type === 'element' && (c.baseType === 'map/keywords'));
|
|
26
|
+
if (wrapper) {
|
|
27
|
+
const inner = (wrapper.children || []).find((c) => c.type === 'element' && c.baseType === bt);
|
|
28
|
+
if (inner) {
|
|
29
|
+
const text = extractTextFromNode(inner).trim();
|
|
30
|
+
if (text)
|
|
31
|
+
return text;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
function getKeyValueFromRef(node) {
|
|
38
|
+
// Priority: keyword > linktext > navtitle > shortdesc > indexterm
|
|
39
|
+
const topicmeta = (node.children || []).find((c) => c.type === 'element' && (c.baseType === 'map/topicmeta'));
|
|
40
|
+
if (!topicmeta)
|
|
41
|
+
return undefined; // No topicmeta, no value
|
|
42
|
+
return getNodeValue(topicmeta, [
|
|
43
|
+
'map/keyword',
|
|
44
|
+
'map/linktext',
|
|
45
|
+
'map/navtitle',
|
|
46
|
+
'map/shortdesc',
|
|
47
|
+
]);
|
|
48
|
+
}
|
|
49
|
+
/** The individual key names in a `keys` attribute (whitespace-separated). */
|
|
50
|
+
export function splitKeyNames(keys) {
|
|
51
|
+
return keys.split(/\s+/).filter(Boolean);
|
|
52
|
+
}
|
|
53
|
+
/** All names a key defined under the given scope chain answers to: bare plus each qualified form. */
|
|
54
|
+
export function qualifiedNames(name, scopeChain) {
|
|
55
|
+
const out = [name];
|
|
56
|
+
for (let i = 0; i < scopeChain.length; i++) {
|
|
57
|
+
out.push(scopeChain.slice(i).join('.') + '.' + name);
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
/** Like qualifiedNames, for a definition that lives in several scope chains at once. */
|
|
62
|
+
export function qualifiedNamesMulti(name, scopeChains) {
|
|
63
|
+
const out = new Set([name]);
|
|
64
|
+
for (const chain of scopeChains)
|
|
65
|
+
for (const q of qualifiedNames(name, chain))
|
|
66
|
+
out.add(q);
|
|
67
|
+
return [...out];
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Parses one ditamap, expands the ditamaps it references, and adds every
|
|
71
|
+
* key it defines to `into` (first definition wins, in document order).
|
|
72
|
+
* When `hrefs` is supplied, each newly defined key also records its resource
|
|
73
|
+
* 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.
|
|
76
|
+
*/
|
|
77
|
+
export function collectMapKeys(mapPath, into, read, hrefs) {
|
|
78
|
+
const content = read(mapPath, 'utf-8');
|
|
79
|
+
const doc = parseDitamap(preprocessEntities(content));
|
|
80
|
+
const mapRoot = doc.root;
|
|
81
|
+
const mapDir = dirname(mapPath);
|
|
82
|
+
// Expand referenced ditamaps so keydefs from included maps are visible
|
|
83
|
+
expandDitamapRefs(mapRoot, mapDir, read);
|
|
84
|
+
// scopeChains: the keyscope names enclosing `node`, outermost first; several
|
|
85
|
+
// chains when a keyscope lists several names. A key answers to its bare name
|
|
86
|
+
// and to every qualified form (`a.k`, `x.a.k`), so a keyref written either
|
|
87
|
+
// way finds it. The bare name is still defined unscoped -- the lookup does
|
|
88
|
+
// not know where the referencing element sits, so it cannot tell which
|
|
89
|
+
// scope's `k` is meant; the qualified names are what tell scopes apart.
|
|
90
|
+
function walk(node, scopeChains) {
|
|
91
|
+
if (node.type !== 'element')
|
|
92
|
+
return;
|
|
93
|
+
const baseType = node.baseType;
|
|
94
|
+
let chains = scopeChains;
|
|
95
|
+
const keyscope = node.attributes?.keyscope;
|
|
96
|
+
if (keyscope) {
|
|
97
|
+
const scopes = splitKeyNames(keyscope);
|
|
98
|
+
if (scopes.length)
|
|
99
|
+
chains = chains.flatMap((chain) => scopes.map((s) => chain.concat(s)));
|
|
100
|
+
}
|
|
101
|
+
if ((baseType === 'map/topicref' || baseType === 'map/keydef') && node.attributes?.keys) {
|
|
102
|
+
const value = getKeyValueFromRef(node);
|
|
103
|
+
// keys is a space-separated list: one keydef defines every name in it
|
|
104
|
+
// with the same resource. First definition of each name wins (DITA
|
|
105
|
+
// precedence; nearest map scanned first).
|
|
106
|
+
for (const keyName of splitKeyNames(node.attributes.keys)) {
|
|
107
|
+
for (const name of qualifiedNamesMulti(keyName, chains)) {
|
|
108
|
+
if (!into.has(name)) {
|
|
109
|
+
into.set(name, value || keyName);
|
|
110
|
+
hrefs?.set(name, { href: node.attributes?.href, baseDir: mapDir });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
for (const child of node.children || [])
|
|
116
|
+
walk(child, chains);
|
|
117
|
+
}
|
|
118
|
+
for (const child of mapRoot.children || [])
|
|
119
|
+
walk(child, [[]]);
|
|
120
|
+
}
|
|
121
|
+
/** A context counts only while its file (or an unsaved copy of it) exists. */
|
|
122
|
+
export function isKeyContextAvailable(contextMap) {
|
|
123
|
+
return contextMap !== undefined && sourceStamp(contextMap) !== '?';
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The ditamaps the key definitions come from: the context map alone when one
|
|
127
|
+
* is set and available, otherwise the ancestor maps. The single answer to
|
|
128
|
+
* "where do keys come from" -- the key map behind previews and diagnostics
|
|
129
|
+
* (buildKeySpace) and go-to-definition on a keyref must both ask this, or a
|
|
130
|
+
* preview can show one brand's value while F12 jumps to another's.
|
|
131
|
+
* `ancestorMaps` is a function so the directory walk is skipped when the
|
|
132
|
+
* context answers.
|
|
133
|
+
*/
|
|
134
|
+
export function keySourceMaps(contextMap, ancestorMaps) {
|
|
135
|
+
return isKeyContextAvailable(contextMap) ? [contextMap] : ancestorMaps();
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* The key space every keyref in the workspace resolves against.
|
|
139
|
+
*
|
|
140
|
+
* With a context map (Oxygen's DITA Maps Manager "context"), the keys are
|
|
141
|
+
* those of that one map, expanded through its map references, and nothing
|
|
142
|
+
* else: the ancestor maps are NOT consulted, so choosing one brand's keydef
|
|
143
|
+
* map cannot pick up another brand's definition of the same key. Without a
|
|
144
|
+
* context it is the ancestor scan buildKeyMap always did.
|
|
145
|
+
*
|
|
146
|
+
* A context whose file no longer exists falls back to the ancestor scan and
|
|
147
|
+
* says so ('missing') -- the caller decides how to tell the user. A context
|
|
148
|
+
* that exists but cannot be parsed is reported through onError and yields an
|
|
149
|
+
* empty key space rather than quietly resolving against other maps.
|
|
150
|
+
*/
|
|
151
|
+
export function buildKeySpace(contextMap, ancestorMaps, read, onError = () => undefined) {
|
|
152
|
+
const files = [];
|
|
153
|
+
const recordingRead = (path, encoding) => {
|
|
154
|
+
files.push(path);
|
|
155
|
+
return read(path, encoding);
|
|
156
|
+
};
|
|
157
|
+
const sources = keySourceMaps(contextMap, () => ancestorMaps);
|
|
158
|
+
let status = 'none';
|
|
159
|
+
if (contextMap !== undefined) {
|
|
160
|
+
// Listed even when missing, so the file reappearing changes the stamp.
|
|
161
|
+
files.push(contextMap);
|
|
162
|
+
status = isKeyContextAvailable(contextMap) ? 'active' : 'missing';
|
|
163
|
+
}
|
|
164
|
+
const keys = new Map();
|
|
165
|
+
const defs = new Map();
|
|
166
|
+
for (const mf of sources) {
|
|
167
|
+
try {
|
|
168
|
+
collectMapKeys(mf, keys, recordingRead, defs);
|
|
169
|
+
}
|
|
170
|
+
catch (e) {
|
|
171
|
+
onError(mf, e);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// Pair the href definitions with the values map they were built from, so a
|
|
175
|
+
// consumer handed only the values map (the render paths thread `keyMap`
|
|
176
|
+
// everywhere but not `defs`) can still find the conkeyref targets for that
|
|
177
|
+
// exact instance. Registered here rather than in keyMap.ts so every producer
|
|
178
|
+
// of a KeySpace -- including the direct buildKeySpace callers the conkeyref
|
|
179
|
+
// tests drive -- gets it, and so renderContext.ts can read it without
|
|
180
|
+
// importing the vscode-dependent keyMap.ts.
|
|
181
|
+
registerKeyDefs(keys, defs);
|
|
182
|
+
return { keys, defs, files: [...new Set(files)], status };
|
|
183
|
+
}
|
|
184
|
+
// ── values map -> href defs, by instance identity ──
|
|
185
|
+
//
|
|
186
|
+
// The keys a map defines (values) and their resource targets (defs) are always
|
|
187
|
+
// produced together by one buildKeySpace call, and buildKeyMap hands back the
|
|
188
|
+
// SAME values-map instance for as long as its cache entry is valid -- the exact
|
|
189
|
+
// identity property renderTopicCached already leans on for cache keying. So a
|
|
190
|
+
// WeakMap from the values map to its defs travels with it: any render path that
|
|
191
|
+
// has the keyMap has its conkeyref defs, with no new field to thread through the
|
|
192
|
+
// many interfaces keyMap already passes through (and no path able to forget to).
|
|
193
|
+
const defsByKeyMap = new WeakMap();
|
|
194
|
+
export function registerKeyDefs(keys, defs) {
|
|
195
|
+
defsByKeyMap.set(keys, defs);
|
|
196
|
+
}
|
|
197
|
+
/** The href defs paired with a given values map, or undefined if it was not
|
|
198
|
+
* produced by buildKeySpace (e.g. a hand-built map in a test). */
|
|
199
|
+
export function getKeyDefs(keys) {
|
|
200
|
+
return defsByKeyMap.get(keys);
|
|
201
|
+
}
|