@dita-viewer/core 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +20 -7
  2. package/dist/editor/renderContext.d.ts +7 -0
  3. package/dist/editor/renderContext.js +24 -0
  4. package/dist/editor/topicRender.d.ts +9 -0
  5. package/dist/editor/topicRender.js +4 -2
  6. package/dist/language/ditaLanguageUtils.d.ts +15 -2
  7. package/dist/language/ditaLanguageUtils.js +36 -4
  8. package/dist/profiling.d.ts +7 -1
  9. package/dist/profiling.js +9 -3
  10. package/dist/render/baseTypeMap.js +28 -2
  11. package/dist/render/renderer.d.ts +24 -0
  12. package/dist/render/renderer.js +47 -10
  13. package/dist-esm/bookRender.js +145 -0
  14. package/dist-esm/completion.js +142 -0
  15. package/dist-esm/completionData.js +155 -0
  16. package/dist-esm/diagnostics.js +378 -0
  17. package/dist-esm/editor/conkeyref.js +104 -0
  18. package/dist-esm/editor/keySpace.js +201 -0
  19. package/dist-esm/editor/refResolvers.js +633 -0
  20. package/dist-esm/editor/renderContext.js +138 -0
  21. package/dist-esm/editor/sourceText.js +142 -0
  22. package/dist-esm/editor/topicRender.js +328 -0
  23. package/dist-esm/index.js +66 -0
  24. package/dist-esm/keyMapForDocument.js +23 -0
  25. package/dist-esm/language/ditaLanguageUtils.js +689 -0
  26. package/dist-esm/language/referenceableFiles.js +108 -0
  27. package/dist-esm/mapRender.js +24 -0
  28. package/dist-esm/package.json +1 -0
  29. package/dist-esm/parser/ditaParser.js +409 -0
  30. package/dist-esm/parser/domTypes.js +1 -0
  31. package/dist-esm/parser/mapTagMap.js +77 -0
  32. package/dist-esm/parser/namedEntities.js +321 -0
  33. package/dist-esm/parser/standardTagMap.js +393 -0
  34. package/dist-esm/profiling.js +224 -0
  35. package/dist-esm/render/baseTypeMap.js +1057 -0
  36. package/dist-esm/render/cjkSpacing.js +94 -0
  37. package/dist-esm/render/mapTypeMap.js +568 -0
  38. package/dist-esm/render/renderer.js +529 -0
  39. package/dist-esm/siteRender.js +261 -0
  40. package/package.json +4 -2
  41. package/styles/TOKENS.md +21 -0
  42. package/styles/dita-content.css +31 -17
@@ -0,0 +1,689 @@
1
+ // Pure, editor-agnostic logic behind the DITA language features
2
+ // (go-to-definition, completion, diagnostics, document symbols).
3
+ // Everything here works on raw text + offsets so it stays unit-testable;
4
+ // the VS Code glue lives in ditaLanguageFeatures.ts.
5
+ import { createBookRoleLabeler } from '../render/mapTypeMap';
6
+ // ── Reference attribute scanning ──
7
+ /** Attributes whose values reference other files/keys/elements. */
8
+ const REF_ATTRS = new Set(['href', 'conref', 'conkeyref', 'keyref']);
9
+ // One alternation, so whichever region opens first wins: a "<!--" inside a
10
+ // CDATA section is CDATA text, and a "<![CDATA[" inside a comment is comment
11
+ // text. An opener with no terminator matches nothing and is left alone, so a
12
+ // stray "<!--" cannot hide every reference after it.
13
+ const NON_MARKUP_RE = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>/g;
14
+ /**
15
+ * Blanks comments, CDATA sections and processing instructions with spaces of
16
+ * the same length (line breaks are kept), so every offset into the result is
17
+ * also an offset into `text`. What is left is only live markup and character
18
+ * data, which is what a reference scan should look at.
19
+ */
20
+ function blankNonMarkup(text) {
21
+ if (!text.includes('<!') && !text.includes('<?'))
22
+ return text;
23
+ return text.replace(NON_MARKUP_RE, (region) => region.replace(/[^\r\n]/g, ' '));
24
+ }
25
+ const TAG_RE = /<([A-Za-z][\w.-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g;
26
+ const ATTR_RE = /([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
27
+ /**
28
+ * Collects every reference-bearing attribute in the document text.
29
+ *
30
+ * `attrs` names the attributes to collect and defaults to the navigable set
31
+ * (href / conref / conkeyref / keyref). A caller that needs more -- the rename
32
+ * participant also has to follow conrefend, copy-to, data and longdescref --
33
+ * passes its own set, so go-to-definition and find-references keep seeing
34
+ * exactly what they saw before.
35
+ *
36
+ * Comments, CDATA sections and processing instructions are not scanned: an
37
+ * `href` inside them is example text or a commented-out reference, not a live
38
+ * one, so rename, go-to-definition, find-references and diagnostics all leave
39
+ * it alone. Offsets still index the original `text`.
40
+ */
41
+ export function collectRefEntries(text, attrs = REF_ATTRS) {
42
+ const entries = [];
43
+ const scanText = blankNonMarkup(text);
44
+ TAG_RE.lastIndex = 0;
45
+ let tagMatch;
46
+ while ((tagMatch = TAG_RE.exec(scanText)) !== null) {
47
+ const tagName = tagMatch[1];
48
+ const attrSegment = tagMatch[2];
49
+ if (!attrSegment)
50
+ continue;
51
+ const segmentOffset = tagMatch.index + 1 + tagName.length;
52
+ // First pass: pick up scope/format so hrefs can be classified
53
+ let scope;
54
+ let format;
55
+ ATTR_RE.lastIndex = 0;
56
+ let am;
57
+ while ((am = ATTR_RE.exec(attrSegment)) !== null) {
58
+ const val = am[2] ?? am[3];
59
+ if (am[1] === 'scope')
60
+ scope = val;
61
+ else if (am[1] === 'format')
62
+ format = val;
63
+ }
64
+ ATTR_RE.lastIndex = 0;
65
+ while ((am = ATTR_RE.exec(attrSegment)) !== null) {
66
+ if (!attrs.has(am[1]))
67
+ continue;
68
+ const eqAndQuote = am[0].indexOf('=') + 1 + (am[0].slice(am[0].indexOf('=') + 1).match(/["']/)?.index ?? 0);
69
+ const valueStart = segmentOffset + am.index + eqAndQuote + 1;
70
+ const val = am[2] ?? am[3];
71
+ entries.push({
72
+ attr: am[1],
73
+ value: val,
74
+ valueStart,
75
+ valueEnd: valueStart + val.length,
76
+ tagName,
77
+ scope,
78
+ format,
79
+ });
80
+ }
81
+ }
82
+ return entries;
83
+ }
84
+ /** Finds the reference attribute whose value contains the given offset. */
85
+ export function findRefAttrAt(text, offset) {
86
+ return collectRefEntries(text).find((e) => offset >= e.valueStart && offset <= e.valueEnd);
87
+ }
88
+ const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
89
+ const WIN_ABS_RE = /^([a-zA-Z]:[\\/]|\\\\|\/)/;
90
+ /** True when the reference points outside the local project (not resolvable from disk). */
91
+ export function isExternalRef(value, scope) {
92
+ if (!value)
93
+ return true;
94
+ if (scope === 'external' || scope === 'peer')
95
+ return true;
96
+ if (URL_SCHEME_RE.test(value))
97
+ return true;
98
+ if (WIN_ABS_RE.test(value))
99
+ return true;
100
+ return false;
101
+ }
102
+ // ── Key definition lookup ──
103
+ function escapeRegExp(s) {
104
+ return s.replace(/[.*+?^$\{\}()|[\]\\]/g, '\\$&');
105
+ }
106
+ /**
107
+ * Returns the offset of the keys="..." attribute that defines the given key
108
+ * inside a ditamap source text, or -1. A keys attribute may hold a
109
+ * space-separated list of key names.
110
+ */
111
+ export function findKeyDefinitionOffset(mapText, key) {
112
+ const re = /\bkeys\s*=\s*"([^"]*)"/g;
113
+ let m;
114
+ while ((m = re.exec(mapText)) !== null) {
115
+ const names = m[1].split(/\s+/).filter(Boolean);
116
+ if (names.includes(key))
117
+ return m.index;
118
+ }
119
+ return -1;
120
+ }
121
+ /**
122
+ * Strips the same-document marker some authors prefix onto a conref/href
123
+ * fragment -- the "./id" (or "./topicId/elementId") shorthand, carried over
124
+ * from relative-file-path conventions, that some tools accept as another
125
+ * way of writing a bare "#id". Once stripped, the rest of the fragment
126
+ * parses exactly like a plain "topicId/elementId" or bare "elementId"
127
+ * fragment. A fragment with no such prefix is returned unchanged.
128
+ *
129
+ * This is the single place that understands the "./" shorthand -- every
130
+ * caller that splits a fragment into a topic-scope part and an element-id
131
+ * part should normalize through here first, rather than special-casing
132
+ * "." locally, so the same-document marker is handled consistently
133
+ * wherever fragments are parsed (go-to-definition, find-references, and
134
+ * this file's own findConrefTargetOffset all split fragments this way).
135
+ */
136
+ export function stripSameDocumentFragmentPrefix(fragment) {
137
+ return fragment.replace(/^\.\/+/, '');
138
+ }
139
+ /**
140
+ * Splits a conref/href fragment into the two parts the DITA addressing
141
+ * grammar defines -- "topicId" or "topicId/elementId" -- after normalizing
142
+ * the "./" same-document shorthand. A one-part fragment addresses the topic
143
+ * itself, so topicId is undefined and the whole fragment is the id named.
144
+ *
145
+ * This is the single place that splits a fragment. Callers must not do their
146
+ * own split('/')[0]: that answers "which topic" when the question is nearly
147
+ * always "which element", and for the standard two-part form the two are
148
+ * different strings by definition. ditaRenderUtils resolves conref content
149
+ * this way already (parts.length > 1 ? parts[1] : parts[0]); find-references
150
+ * took parts[0] instead, which is why conrefs rendered fine but could not be
151
+ * found from their declaration.
152
+ */
153
+ export function splitRefFragment(fragment) {
154
+ const normalized = stripSameDocumentFragmentPrefix(fragment);
155
+ const slashIdx = normalized.indexOf('/');
156
+ return slashIdx >= 0
157
+ ? { topicId: normalized.substring(0, slashIdx), elementId: normalized.substring(slashIdx + 1) }
158
+ : { topicId: undefined, elementId: normalized };
159
+ }
160
+ /**
161
+ * Resolves a conref/href fragment ("topicId" or "topicId/elementId") to the
162
+ * offset of the target id="..." attribute in the target file's text, or -1.
163
+ */
164
+ export function findConrefTargetOffset(text, fragment) {
165
+ const { topicId, elementId } = splitRefFragment(fragment);
166
+ if (!elementId)
167
+ return -1;
168
+ const findId = (id, from) => {
169
+ const re = new RegExp(`\\bid\\s*=\\s*"${escapeRegExp(id)}"`, 'g');
170
+ re.lastIndex = from;
171
+ const m = re.exec(text);
172
+ return m ? m.index : -1;
173
+ };
174
+ // A bare elementId (no "/" at all) has no real topic to scope the search
175
+ // by. Before the stripSameDocumentFragmentPrefix normalization above, a
176
+ // same-document self-reference marker (e.g. conref="#./noteId") landed
177
+ // here as a literal "." topicId, which could never match a real
178
+ // id="..." and always reported the target as missing -- normalizing the
179
+ // fragment first means that case now falls into the same "no scope"
180
+ // bucket as a plain "#noteId" bare id.
181
+ if (topicId === undefined || topicId === '') {
182
+ return findId(elementId, 0);
183
+ }
184
+ const topicOff = findId(topicId, 0);
185
+ if (topicOff < 0)
186
+ return -1;
187
+ return findId(elementId, topicOff);
188
+ }
189
+ /** If the offset falls inside an id="..." attribute value, returns that id
190
+ * and the value's span; otherwise undefined. */
191
+ export function findIdAttrAt(text, offset) {
192
+ const re = /\bid\s*=\s*"([^"]*)"/g;
193
+ let m;
194
+ while ((m = re.exec(text)) !== null) {
195
+ const valueStart = m.index + m[0].indexOf('"') + 1;
196
+ const valueEnd = valueStart + m[1].length;
197
+ if (offset >= valueStart && offset <= valueEnd) {
198
+ return { id: m[1], valueStart, valueEnd };
199
+ }
200
+ }
201
+ return undefined;
202
+ }
203
+ /** If the offset falls inside one key of a keydef's keys="..." attribute
204
+ * value, returns that specific key token (not the whole space-separated
205
+ * list) and its span; otherwise undefined. Only matches on a <keydef> (or
206
+ * <topicref>/<mapref> carrying its own keys attribute) tag, not any other
207
+ * element that happens to have a "keys" attribute. */
208
+ export function findKeysAttrAt(text, offset) {
209
+ const re = /\bkeys\s*=\s*"([^"]*)"/g;
210
+ let m;
211
+ while ((m = re.exec(text)) !== null) {
212
+ const listStart = m.index + m[0].indexOf('"') + 1;
213
+ const listEnd = listStart + m[1].length;
214
+ if (offset < listStart || offset > listEnd)
215
+ continue;
216
+ const relOffset = offset - listStart;
217
+ let tokenStart = 0;
218
+ for (const token of m[1].split(/(\s+)/)) {
219
+ const tokenEnd = tokenStart + token.length;
220
+ if (!/^\s*$/.test(token) && relOffset >= tokenStart && relOffset <= tokenEnd) {
221
+ return { key: token, valueStart: listStart + tokenStart, valueEnd: listStart + tokenEnd };
222
+ }
223
+ tokenStart = tokenEnd;
224
+ }
225
+ return undefined;
226
+ }
227
+ return undefined;
228
+ }
229
+ /** If the offset falls ANYWHERE inside a <keydef> element -- not just
230
+ * literally inside its keys="..." attribute value the way findKeysAttrAt
231
+ * above requires -- returns every key that keydef declares.
232
+ *
233
+ * This exists specifically for Find All References: clicking on some
234
+ * OTHER part of a keydef (its <keyword> display text, its href, its
235
+ * topicmeta, whitespace inside a multi-line keydef) is an easy mistake
236
+ * for someone unfamiliar with the extension to make when trying to find
237
+ * where a key is used -- especially the keyword text, which is the
238
+ * human-readable label a reader would naturally click on. Silently
239
+ * falling through to the generic "who references this ditamap file"
240
+ * answer in that case is actively confusing: it still returns results,
241
+ * so it looks like it worked, but it answers a different question than
242
+ * the one being asked. findKeysAttrAt's narrower, attribute-value-only
243
+ * match still takes priority when it hits (see ditaLanguageFeatures.ts'
244
+ * resolveReferenceTarget) so clicking the exact key name still resolves
245
+ * to just that one key rather than every alias on the keydef. */
246
+ export function findEnclosingKeydefKeys(text, offset) {
247
+ const tagRe = /<keydef\b[^>]*>/g;
248
+ let m;
249
+ while ((m = tagRe.exec(text)) !== null) {
250
+ const tagStart = m.index;
251
+ const tagText = m[0];
252
+ const selfClosing = /\/\s*>$/.test(tagText);
253
+ let elementEnd;
254
+ if (selfClosing) {
255
+ elementEnd = tagStart + tagText.length;
256
+ }
257
+ else {
258
+ const closeTag = '</keydef>';
259
+ const closeIdx = text.indexOf(closeTag, tagStart + tagText.length);
260
+ elementEnd = closeIdx >= 0 ? closeIdx + closeTag.length : tagStart + tagText.length;
261
+ }
262
+ if (offset < tagStart || offset > elementEnd)
263
+ continue;
264
+ const keysMatch = /\bkeys\s*=\s*"([^"]*)"/.exec(tagText);
265
+ if (!keysMatch)
266
+ return undefined;
267
+ const keys = keysMatch[1].split(/\s+/).filter(Boolean);
268
+ return keys.length ? { keys } : undefined;
269
+ }
270
+ return undefined;
271
+ }
272
+ /** Collects all id="..." values declared in a document text. */
273
+ export function collectIds(text) {
274
+ const ids = [];
275
+ const re = /\bid\s*=\s*"([^"]+)"/g;
276
+ let m;
277
+ while ((m = re.exec(text)) !== null)
278
+ ids.push(m[1]);
279
+ return ids;
280
+ }
281
+ /** Converts a character offset into a 0-based line/column pair. */
282
+ export function offsetToLineCol(text, offset) {
283
+ let line = 0;
284
+ let lineStart = 0;
285
+ for (let i = 0; i < offset && i < text.length; i++) {
286
+ if (text.charCodeAt(i) === 10) {
287
+ line++;
288
+ lineStart = i + 1;
289
+ }
290
+ }
291
+ return { line, col: offset - lineStart };
292
+ }
293
+ /** Classifies what kind of completion applies at the given offset. */
294
+ export function getCompletionContext(text, offset) {
295
+ const lastLt = text.lastIndexOf('<', offset - 1);
296
+ if (lastLt < 0)
297
+ return { kind: 'none' };
298
+ const between = text.substring(lastLt, offset);
299
+ // Comments / processing instructions / closed tags → no structural completion
300
+ if (between.includes('>') || between.startsWith('<!') || between.startsWith('<?')) {
301
+ return { kind: 'none' };
302
+ }
303
+ // Still typing the tag name itself: "<", "<no", "</se"
304
+ const tagTyping = /^<(\/?)([\w.-]*)$/.exec(between);
305
+ if (tagTyping)
306
+ return { kind: 'tag', prefix: tagTyping[2], closing: tagTyping[1] === '/' };
307
+ const tagNameMatch = /^<\/?([\w.-]+)/.exec(between);
308
+ const tagName = tagNameMatch ? tagNameMatch[1] : undefined;
309
+ // Inside an attribute value: attr="partial
310
+ const valueMatch = /([\w:.-]+)\s*=\s*"([^"]*)$/.exec(between);
311
+ if (valueMatch) {
312
+ return {
313
+ kind: 'attrValue',
314
+ tagName,
315
+ attrName: valueMatch[1],
316
+ prefix: valueMatch[2],
317
+ valueStart: offset - valueMatch[2].length,
318
+ };
319
+ }
320
+ // After whitespace inside the tag → attribute name position
321
+ if (/[\s"']([\w:.-]*)$/.test(between)) {
322
+ const anm = /([\w:.-]*)$/.exec(between);
323
+ return { kind: 'attrName', tagName, prefix: anm ? anm[1] : '' };
324
+ }
325
+ return { kind: 'none' };
326
+ }
327
+ // ── Tag auto-closing ──
328
+ /**
329
+ * When the character just typed before `offset` is the '>' of an opening
330
+ * tag, returns the tag name to auto-close. Closing tags, self-closing tags,
331
+ * comments, PIs and '>' inside attribute values yield undefined.
332
+ */
333
+ export function getAutoCloseTag(text, offset) {
334
+ if (text[offset - 1] !== '>')
335
+ return undefined;
336
+ const lastLt = text.lastIndexOf('<', offset - 2);
337
+ if (lastLt < 0)
338
+ return undefined;
339
+ const tagText = text.substring(lastLt, offset);
340
+ if (tagText.startsWith('</') || tagText.startsWith('<!') || tagText.startsWith('<?')) {
341
+ return undefined;
342
+ }
343
+ if (/\/\s*>$/.test(tagText))
344
+ return undefined;
345
+ // An odd number of quotes means the '>' was typed inside an attribute value
346
+ if (((tagText.match(/"/g) || []).length) % 2 === 1)
347
+ return undefined;
348
+ const m = /^<([A-Za-z][\w.-]*)(?:[\s>]|$)/.exec(tagText);
349
+ return m ? m[1] : undefined;
350
+ }
351
+ /** Innermost tag left unclosed at the end of the given text. */
352
+ export function findUnclosedTag(text) {
353
+ // Strip constructs whose content must not feed the tag stack
354
+ const cleaned = text
355
+ .replace(/<!--[\s\S]*?-->/g, ' ')
356
+ .replace(/<!\[CDATA\[[\s\S]*?\]\]>/g, ' ')
357
+ .replace(/<\?[\s\S]*?\?>/g, ' ')
358
+ .replace(/<![^>]*>/g, ' ');
359
+ const stack = [];
360
+ const re = /<(\/?)([A-Za-z][\w.-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g;
361
+ let m;
362
+ while ((m = re.exec(cleaned)) !== null) {
363
+ if (m[1]) {
364
+ // Pop down to the matching open tag (tolerates malformed nesting)
365
+ const idx = stack.lastIndexOf(m[2]);
366
+ if (idx >= 0)
367
+ stack.length = idx;
368
+ }
369
+ else if (!/\/\s*$/.test(m[3])) {
370
+ stack.push(m[2]);
371
+ }
372
+ }
373
+ return stack[stack.length - 1];
374
+ }
375
+ /**
376
+ * When the two characters ending at `offset` are '</', returns the tag name
377
+ * that completes the closing tag, or undefined.
378
+ */
379
+ export function getCloseTagCompletion(text, offset) {
380
+ if (text.substring(offset - 2, offset) !== '</')
381
+ return undefined;
382
+ return findUnclosedTag(text.substring(0, offset - 2));
383
+ }
384
+ // ── Attribute knowledge for completion ──
385
+ const UNIVERSAL_ATTRS = [
386
+ 'id',
387
+ 'conref',
388
+ 'conkeyref',
389
+ 'keyref',
390
+ 'outputclass',
391
+ 'props',
392
+ 'audience',
393
+ 'platform',
394
+ 'product',
395
+ 'otherprops',
396
+ 'deliveryTarget',
397
+ 'rev',
398
+ 'importance',
399
+ 'translate',
400
+ 'xml:lang',
401
+ ];
402
+ const REF_TAG_ATTRS = ['href', 'keys', 'keyref', 'navtitle', 'format', 'scope', 'processing-role', 'toc', 'type', 'collection-type'];
403
+ export const TAG_SPECIFIC_ATTRS = {
404
+ xref: ['href', 'format', 'scope', 'type'],
405
+ link: ['href', 'format', 'scope', 'type'],
406
+ image: ['href', 'height', 'width', 'placement', 'align', 'scale'],
407
+ note: ['type', 'othertype'],
408
+ topicref: REF_TAG_ATTRS,
409
+ keydef: ['keys', 'href', 'format', 'scope', 'processing-role'],
410
+ mapref: ['href', 'format', 'processing-role'],
411
+ chapter: REF_TAG_ATTRS,
412
+ part: REF_TAG_ATTRS,
413
+ appendix: REF_TAG_ATTRS,
414
+ preface: REF_TAG_ATTRS,
415
+ glossaryref: REF_TAG_ATTRS,
416
+ topichead: ['navtitle', 'collection-type'],
417
+ table: ['frame', 'colsep', 'rowsep', 'pgwide'],
418
+ tgroup: ['cols'],
419
+ colspec: ['colname', 'colwidth', 'colnum'],
420
+ entry: ['colname', 'namest', 'nameend', 'morerows', 'valign', 'align'],
421
+ codeblock: ['outputclass', 'scale'],
422
+ ph: ['keyref'],
423
+ keyword: ['keyref'],
424
+ term: ['keyref'],
425
+ lq: ['href', 'reftitle'],
426
+ fig: ['frame', 'expanse'],
427
+ section: ['spectitle'],
428
+ };
429
+ /** Attribute names offered for a tag: tag-specific first, then universal. */
430
+ export function getAttributesForTag(tag) {
431
+ const specific = tag ? TAG_SPECIFIC_ATTRS[tag] || [] : [];
432
+ const merged = [...specific];
433
+ for (const a of UNIVERSAL_ATTRS)
434
+ if (!merged.includes(a))
435
+ merged.push(a);
436
+ return merged;
437
+ }
438
+ function plainText(node) {
439
+ if (node.type === 'text')
440
+ return node.text || '';
441
+ return (node.children || []).map(plainText).join('');
442
+ }
443
+ function findTitleText(node) {
444
+ const titleChild = (node.children || []).find((c) => c.type === 'element' && c.baseType === 'topic/title');
445
+ if (!titleChild)
446
+ return undefined;
447
+ const t = plainText(titleChild).trim();
448
+ return t || undefined;
449
+ }
450
+ /** Outline for a .dita topic file: topics, sections and examples. */
451
+ // Topic specializations are recognized by tag name too: authored source
452
+ // files carry no @class attribute, so their baseType stays undefined.
453
+ const TOPIC_ROOT_TAGS = new Set([
454
+ 'topic',
455
+ 'concept',
456
+ 'task',
457
+ 'reference',
458
+ 'glossentry',
459
+ 'glossgroup',
460
+ 'troubleshooting',
461
+ ]);
462
+ function isTopicNode(node) {
463
+ return node.baseType === 'topic/topic' || (!!node.tagName && TOPIC_ROOT_TAGS.has(node.tagName));
464
+ }
465
+ export function collectTopicSymbols(root) {
466
+ function walk(node) {
467
+ const result = [];
468
+ for (const child of node.children || []) {
469
+ if (child.type !== 'element')
470
+ continue;
471
+ const bt = child.baseType;
472
+ if (isTopicNode(child)) {
473
+ result.push({
474
+ name: findTitleText(child) || child.attributes?.id || '(topic)',
475
+ detail: child.tagName,
476
+ kind: 'topic',
477
+ range: child.sourceRange,
478
+ children: walk(child),
479
+ });
480
+ }
481
+ else if (bt === 'topic/section' || bt === 'topic/example') {
482
+ result.push({
483
+ name: findTitleText(child) || (bt === 'topic/example' ? '(example)' : '(section)'),
484
+ detail: child.tagName,
485
+ kind: 'section',
486
+ range: child.sourceRange,
487
+ children: walk(child),
488
+ });
489
+ }
490
+ else {
491
+ result.push(...walk(child));
492
+ }
493
+ }
494
+ return result;
495
+ }
496
+ // The root topic itself is represented too, so breadcrumbs show it
497
+ if (isTopicNode(root)) {
498
+ return [
499
+ {
500
+ name: findTitleText(root) || root.attributes?.id || '(topic)',
501
+ detail: root.tagName,
502
+ kind: 'topic',
503
+ range: root.sourceRange,
504
+ children: walk(root),
505
+ },
506
+ ];
507
+ }
508
+ return walk(root);
509
+ }
510
+ /** Display name for a map reference node (navtitle > linktext > href > keys). */
511
+ export function getMapRefName(node) {
512
+ const topicmeta = (node.children || []).find((c) => c.type === 'element' && c.baseType === 'map/topicmeta');
513
+ if (topicmeta) {
514
+ for (const bt of ['map/navtitle', 'map/linktext']) {
515
+ const child = (topicmeta.children || []).find((c) => c.type === 'element' && c.baseType === bt);
516
+ if (child) {
517
+ const t = plainText(child).trim();
518
+ if (t)
519
+ return t;
520
+ }
521
+ }
522
+ }
523
+ const navtitleAttr = node.attributes?.navtitle;
524
+ if (navtitleAttr)
525
+ return navtitleAttr;
526
+ const href = node.attributes?.href;
527
+ if (href)
528
+ return href;
529
+ const keys = node.attributes?.keys;
530
+ if (keys)
531
+ return keys;
532
+ return '(unnamed)';
533
+ }
534
+ /** Outline for a .ditamap file: topicref hierarchy with structural containers. */
535
+ export function collectMapSymbols(root, roleFormat) {
536
+ const roleLabel = createBookRoleLabeler(roleFormat);
537
+ function walk(node, depth) {
538
+ const result = [];
539
+ for (const child of node.children || []) {
540
+ if (child.type !== 'element')
541
+ continue;
542
+ const bt = child.baseType;
543
+ if (bt === 'map/topicref' || bt === 'map/mapref') {
544
+ // Book divisions surface their numbered role ("Chapter 1", …)
545
+ const label = roleLabel(child.tagName, depth);
546
+ result.push({
547
+ name: getMapRefName(child),
548
+ detail: label || child.tagName,
549
+ kind: 'ref',
550
+ range: child.sourceRange,
551
+ children: walk(child, depth + 1),
552
+ });
553
+ }
554
+ else if (bt === 'map/keydef') {
555
+ result.push({
556
+ name: child.attributes?.keys || '(keydef)',
557
+ detail: child.tagName,
558
+ kind: 'keydef',
559
+ range: child.sourceRange,
560
+ children: walk(child, depth + 1),
561
+ });
562
+ }
563
+ else if (bt === 'map/topichead') {
564
+ result.push({
565
+ name: getMapRefName(child),
566
+ detail: child.tagName,
567
+ kind: 'head',
568
+ range: child.sourceRange,
569
+ children: walk(child, depth + 1),
570
+ });
571
+ }
572
+ else if (bt === 'map/bookmap-structural') {
573
+ result.push({
574
+ name: child.tagName || '(container)',
575
+ kind: 'structural',
576
+ range: child.sourceRange,
577
+ children: walk(child, depth),
578
+ });
579
+ }
580
+ else if (bt === 'map/reltable') {
581
+ continue;
582
+ }
583
+ else {
584
+ result.push(...walk(child, depth));
585
+ }
586
+ }
587
+ return result;
588
+ }
589
+ return walk(root, 0);
590
+ }
591
+ // Base types whose own renderer takes full, exclusive ownership of its
592
+ // subtree instead of generically dispatching to each child by its own
593
+ // baseType. An unmapped tag name underneath one of these causes no silent
594
+ // content loss -- the reason this diagnostic exists at all -- because
595
+ // nothing under them is shown via the generic per-child path regardless of
596
+ // whether the parser could classify it:
597
+ //
598
+ // - topic/foreign (<foreign>, <mathml>, and this project's 'svg-container'
599
+ // convenience mapping in standardTagMap.ts): BASE_TYPE_RENDERERS in
600
+ // baseTypeMap.ts serializes its children as raw markup directly, without
601
+ // ever consulting each descendant's own baseType. Every MathML/SVG tag
602
+ // underneath is correctly unrecognized by parseBaseType() -- that is the
603
+ // point, it is not DITA -- so walking in and reporting its contents would
604
+ // just relabel valid MathML/SVG markup as "unknown DITA elements".
605
+ // - topic/prolog: its renderer (baseTypeMap.ts) extracts only top-level
606
+ // indexterm chips via a dedicated traversal and returns '' for
607
+ // everything else -- by its own comment, "every OTHER prolog descendant
608
+ // ... is still fully suppressed". author, critdate, metadata, audience,
609
+ // keywords and the rest of DITA's prolog vocabulary are real, valid,
610
+ // commonly-used elements; several (metadata, keywords, navtitle, author,
611
+ // critdate, ...) simply have no entry of their own in standardTagMap.ts,
612
+ // because nothing before this diagnostic ever needed one -- prolog's own
613
+ // renderer already hides the entire subtree, mapped or not.
614
+ // - map/topicmeta: the same shape one level up, for maps -- its renderer
615
+ // (mapTypeMap.ts) also returns '' unconditionally, with the topicref's
616
+ // navtitle/keyword text pulled out separately via getNodeText() rather
617
+ // than the generic per-child dispatch. indexterm is valid inside a map's
618
+ // <topicmeta><keywords> (DITA maps reuse several topic-level metadata
619
+ // elements verbatim) but was never given its own entry in mapTagMap.ts
620
+ // for the same reason: nothing needed it before.
621
+ // - map/map-title: the map's own <title> (and <booktitle>/<mainbooktitle>/
622
+ // <booktitlealt>/<subtitle>, which specialize the same base type) is
623
+ // rendered by extractText() -- a dedicated, baseType-agnostic recursive
624
+ // text walk with its own <ph keyref="..."> substitution built in, not
625
+ // the generic per-child dispatch either. Nothing under a map's <title>
626
+ // goes missing for being unmapped: extractText() walks every descendant
627
+ // by its .children/.text shape alone and does not consult baseType at
628
+ // all, which is exactly why a keyref-only <ph/> in a map title already
629
+ // resolves correctly -- and why flagging it here was never accurate.
630
+ //
631
+ // Skipping these four is about what the renderer actually does with a
632
+ // subtree, not about the elements in it being any less real or valid DITA
633
+ // than a <p> or a <note> -- unlike topic/foreign, which is correctly
634
+ // non-DITA content.
635
+ const SUBTREE_OWNED_BASETYPES = new Set([
636
+ 'topic/foreign',
637
+ 'topic/prolog',
638
+ 'map/topicmeta',
639
+ 'map/map-title',
640
+ // topic/indexterm's own renderer (collectIndextermChips() in
641
+ // baseTypeMap.ts) walks node.children itself -- direct text nodes plus
642
+ // nested topic/indexterm, topic/index-see and topic/index-see-also by
643
+ // baseType -- and never dispatches through the generic recursive
644
+ // renderer for anything else, so an unmapped tag anywhere inside an
645
+ // indexterm causes no additional silent content loss to report here.
646
+ // topic/index-see-also (and its siblings, all only ever valid inside an
647
+ // indexterm) are included defensively for the case where the enclosing
648
+ // indexterm itself failed to classify and so was not skipped.
649
+ 'topic/indexterm',
650
+ 'topic/index-see',
651
+ 'topic/index-see-also',
652
+ 'topic/index-sort-as',
653
+ 'topic/index-base',
654
+ // map/relheader falls back to a baseType-agnostic extractText() walk for
655
+ // a relcolspec's column title whenever @navtitle is absent (mapTypeMap.ts)
656
+ // -- same shape as map/map-title above, content is never actually lost.
657
+ 'map/relcolspec',
658
+ ]);
659
+ /**
660
+ * Walks a parsed document and collects every element the parser fell
661
+ * through on: neither its tag name nor an explicit @class attribute (DITA's
662
+ * own mechanism for a specialized element to say what it specializes)
663
+ * resolved to a known base type. renderEffectiveNode() in renderer.ts
664
+ * treats exactly this case as "render the children, drop the element" --
665
+ * silently, with no visual indication -- so from the reader's side a typo
666
+ * here looks identical to the content simply not being there. Reusing
667
+ * node.baseType, already computed by the same parseBaseType() the renderer
668
+ * itself relies on, means this can never disagree with what actually gets
669
+ * dropped: there is one source of truth for "does DITA Viewer recognize
670
+ * this element", not a second copy of the classification logic that could
671
+ * drift from it.
672
+ */
673
+ export function collectUnknownElements(root) {
674
+ const results = [];
675
+ function walk(node) {
676
+ if (node.type !== 'element')
677
+ return;
678
+ if (node.baseType && SUBTREE_OWNED_BASETYPES.has(node.baseType))
679
+ return;
680
+ if (!node.baseType && node.tagName) {
681
+ results.push({ tagName: node.tagName, sourceRange: node.sourceRange });
682
+ }
683
+ for (const child of node.children) {
684
+ walk(child);
685
+ }
686
+ }
687
+ walk(root);
688
+ return results;
689
+ }