@dita-viewer/core 0.2.1 → 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/README.md +20 -7
- 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/language/ditaLanguageUtils.js +2 -0
- package/dist/profiling.d.ts +7 -1
- package/dist/profiling.js +9 -3
- package/dist/render/baseTypeMap.js +28 -2
- 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 +4 -2
- package/styles/TOKENS.md +21 -0
- package/styles/dita-content.css +31 -17
package/README.md
CHANGED
|
@@ -36,13 +36,26 @@ extension reads its `dist/`. `npm run verify` also runs this package's own
|
|
|
36
36
|
tests. `npm run watch` compiles it once, at the start; after editing it while
|
|
37
37
|
watching, run `npm run build:core`.
|
|
38
38
|
|
|
39
|
-
|
|
40
|
-
reads
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
39
|
+
The stylesheet is the same in both places apart from the host. The
|
|
40
|
+
extension's `media/styles.css` reads the same `--dita-*` tokens as
|
|
41
|
+
`styles/dita-content.css` in its content and outline rules, answered from VS
|
|
42
|
+
Code's theme in one `:root` block, and `src/test/media/hostTokens.test.ts`
|
|
43
|
+
fails when the set of tokens the two read drifts apart. What remains is that
|
|
44
|
+
the extension keeps its own copy of the rules; `dita-content.css` also holds the
|
|
45
|
+
Obsidian-only book and site rules the extension does not need.
|
|
46
|
+
|
|
47
|
+
## Two builds
|
|
48
|
+
|
|
49
|
+
`npm run build` writes `dist/` (CommonJS, with the type declarations) and
|
|
50
|
+
`dist-esm/` (the same modules as ES modules). `package.json` offers `dist-esm`
|
|
51
|
+
under the `module` condition of `exports`, which bundlers such as esbuild take
|
|
52
|
+
and Node ignores; Node, `require` and TypeScript get `dist/`. The point is size:
|
|
53
|
+
a bundler can leave out what the host does not import, which took about 43 KB
|
|
54
|
+
out of the extension's bundle (the site and book renderers, diagnostics and
|
|
55
|
+
completion, none of which it uses). `npm run check:core-pack` checks all three
|
|
56
|
+
paths: a Node `require`, a Node ES module `import`, and a bundler dropping the
|
|
57
|
+
modules it does not use. `dist-esm` is not meant for Node to load directly: its
|
|
58
|
+
relative imports have no file extensions.
|
|
46
59
|
|
|
47
60
|
## Publishing to npm
|
|
48
61
|
|
|
@@ -39,6 +39,13 @@ export interface BuildRenderContextInput {
|
|
|
39
39
|
suppressIndexterm?: boolean;
|
|
40
40
|
/** Book / docsite only: the set of files that make up the current book. */
|
|
41
41
|
bookMembers?: ReadonlySet<string>;
|
|
42
|
+
/**
|
|
43
|
+
* Standalone preview only: render non-book cross-file xrefs as real links
|
|
44
|
+
* carrying data-dita-href for the webview to hand to the host (see
|
|
45
|
+
* RenderContext.clickableExternalXrefs). Every other render path leaves it
|
|
46
|
+
* unset and keeps the historical non-clickable hint span.
|
|
47
|
+
*/
|
|
48
|
+
clickableExternalXrefs?: boolean;
|
|
42
49
|
/** Book / site only: sink that records every file the render read. */
|
|
43
50
|
collectDependencies?: Set<string>;
|
|
44
51
|
}
|
|
@@ -72,6 +72,8 @@ function buildRenderContext(input) {
|
|
|
72
72
|
ctx.indexLabel = (0, refResolvers_1.detectIndexLabel)(ownRoot, uiLanguage);
|
|
73
73
|
if (input.bookMembers)
|
|
74
74
|
ctx.isInCurrentBook = (0, refResolvers_1.makeIsInCurrentBook)(docDir, input.bookMembers);
|
|
75
|
+
if (input.clickableExternalXrefs)
|
|
76
|
+
ctx.clickableExternalXrefs = true;
|
|
75
77
|
// conkeyref rides on the same file cache: a key's href resolves against the
|
|
76
78
|
// map that defined it (baseDir), not the topic being rendered, so it needs
|
|
77
79
|
// the absolute-path loader rather than the docDir-relative conref resolver.
|
|
@@ -79,6 +81,28 @@ function buildRenderContext(input) {
|
|
|
79
81
|
let lastLoaded;
|
|
80
82
|
const keyDefs = input.keyDefs ?? (0, keySpace_1.getKeyDefs)(keyMap);
|
|
81
83
|
if (keyDefs && keyDefs.size > 0) {
|
|
84
|
+
// A keyref on a link-shaped element (topic/xref) resolves to the key's
|
|
85
|
+
// resource target as its effective href. The keydef's href is relative
|
|
86
|
+
// to the map that defined it, but every href the renderer consumes
|
|
87
|
+
// (isInCurrentBook, resolveTitle, the preview's own open-by-href) is
|
|
88
|
+
// relative to the DOCUMENT's folder -- so rebase here, preserving any
|
|
89
|
+
// element-id fragment, and hand through the shapes that are not
|
|
90
|
+
// filesystem paths (URL schemes, absolute paths) untouched.
|
|
91
|
+
ctx.resolveKeyHref = (key) => {
|
|
92
|
+
const def = keyDefs.get(key);
|
|
93
|
+
if (!def?.href)
|
|
94
|
+
return undefined;
|
|
95
|
+
const raw = def.href;
|
|
96
|
+
if (refResolvers_1.URL_SCHEME_RE.test(raw) || (0, path_1.isAbsolute)(raw))
|
|
97
|
+
return raw;
|
|
98
|
+
const hashIdx = raw.indexOf('#');
|
|
99
|
+
const pathPart = hashIdx >= 0 ? raw.slice(0, hashIdx) : raw;
|
|
100
|
+
const fragment = hashIdx >= 0 ? raw.slice(hashIdx) : '';
|
|
101
|
+
if (!pathPart)
|
|
102
|
+
return fragment || undefined;
|
|
103
|
+
const abs = (0, path_1.resolve)(def.baseDir, (0, refResolvers_1.decodeHrefPart)(pathPart));
|
|
104
|
+
return (0, path_1.relative)(docDir, abs).replace(/\\/g, '/') + fragment;
|
|
105
|
+
};
|
|
82
106
|
const loadTopic = (baseDir, href) => {
|
|
83
107
|
const absPath = (0, path_1.resolve)(baseDir, (0, refResolvers_1.decodeHrefPart)(href.split('#')[0]));
|
|
84
108
|
// A conkeyref target is a real dependency of the rendered HTML, exactly
|
|
@@ -31,6 +31,8 @@ export interface TopicRenderInput {
|
|
|
31
31
|
collectDependencies?: Set<string>;
|
|
32
32
|
/** See TopicXmlRenderInput.bookMembers below; passed through untouched. */
|
|
33
33
|
bookMembers?: ReadonlySet<string>;
|
|
34
|
+
/** See TopicXmlRenderInput.clickableExternalXrefs below; passed through untouched. */
|
|
35
|
+
clickableExternalXrefs?: boolean;
|
|
34
36
|
/**
|
|
35
37
|
* Mark conref'd content for the preview's tint and jump button (see
|
|
36
38
|
* RenderContext.conrefSource). Off for "Export as HTML"; renderTopicCached,
|
|
@@ -70,6 +72,13 @@ export interface TopicXmlRenderInput {
|
|
|
70
72
|
* whole point here.
|
|
71
73
|
*/
|
|
72
74
|
bookMembers?: ReadonlySet<string>;
|
|
75
|
+
/**
|
|
76
|
+
* Standalone preview only: render non-book cross-file xrefs as real links
|
|
77
|
+
* carrying data-dita-href for the webview to hand to the host (see
|
|
78
|
+
* RenderContext.clickableExternalXrefs). Undefined for book/site rendering
|
|
79
|
+
* and "Export as HTML", which keep the non-clickable xref-external hint.
|
|
80
|
+
*/
|
|
81
|
+
clickableExternalXrefs?: boolean;
|
|
73
82
|
/**
|
|
74
83
|
* Absolute path of the topic being rendered, and the opt-in that uses it:
|
|
75
84
|
* together they let the renderer mark conref'd content (same-file targets
|
|
@@ -48,7 +48,7 @@ function buildTitleMap(root) {
|
|
|
48
48
|
return map;
|
|
49
49
|
}
|
|
50
50
|
function renderTopicXml(input) {
|
|
51
|
-
const { xml, docDir, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, docFile, markConrefs } = input;
|
|
51
|
+
const { xml, docDir, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, docFile, markConrefs } = input;
|
|
52
52
|
try {
|
|
53
53
|
const preprocessedXml = (0, ditaParser_1.preprocessEntities)(xml);
|
|
54
54
|
const ditaDoc = (0, ditaParser_1.parseDita)(preprocessedXml);
|
|
@@ -68,6 +68,7 @@ function renderTopicXml(input) {
|
|
|
68
68
|
includeIndexLabel: true,
|
|
69
69
|
suppressIndexterm,
|
|
70
70
|
bookMembers,
|
|
71
|
+
clickableExternalXrefs,
|
|
71
72
|
collectDependencies,
|
|
72
73
|
docFile,
|
|
73
74
|
markConrefs,
|
|
@@ -87,7 +88,7 @@ function renderTopicXml(input) {
|
|
|
87
88
|
}
|
|
88
89
|
}
|
|
89
90
|
function renderTopicToHtml(input) {
|
|
90
|
-
const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, markConrefs } = input;
|
|
91
|
+
const { filePath, keyMap, asWebviewUri, headingLevel, uiLanguage, suppressIndexterm, collectDependencies, bookMembers, clickableExternalXrefs, markConrefs } = input;
|
|
91
92
|
try {
|
|
92
93
|
if (!(0, fs_1.existsSync)(filePath)) {
|
|
93
94
|
return { html: '', error: `File not found: ${filePath}` };
|
|
@@ -106,6 +107,7 @@ function renderTopicToHtml(input) {
|
|
|
106
107
|
suppressIndexterm,
|
|
107
108
|
collectDependencies,
|
|
108
109
|
bookMembers,
|
|
110
|
+
clickableExternalXrefs,
|
|
109
111
|
docFile: filePath,
|
|
110
112
|
markConrefs,
|
|
111
113
|
});
|
package/dist/profiling.d.ts
CHANGED
|
@@ -22,8 +22,14 @@ export interface ProfileFilter {
|
|
|
22
22
|
* The attributes the renderer records in data-profile-keys, in its order.
|
|
23
23
|
* Kept in step with PROFILING_ATTRS in render/renderer.ts (not exported from
|
|
24
24
|
* there); a test renders each one to catch drift.
|
|
25
|
+
*
|
|
26
|
+
* deliveryTarget joins the filter-atts group: DITA 1.3 added it to the
|
|
27
|
+
* select-atts (it replaces the deprecated DITA 1.2 @print), and DITA-OT
|
|
28
|
+
* filters on it exactly like the rest of the group, so an element carrying
|
|
29
|
+
* it must show up highlighted, in the filter panel, and in .ditaval
|
|
30
|
+
* filtering like any other profiling attribute.
|
|
25
31
|
*/
|
|
26
|
-
export declare const PROFILE_ATTRS: readonly ["props", "platform", "product", "audience", "otherprops", "base", "importance", "rev", "status"];
|
|
32
|
+
export declare const PROFILE_ATTRS: readonly ["props", "platform", "product", "audience", "otherprops", "deliveryTarget", "base", "importance", "rev", "status"];
|
|
27
33
|
/** The key a hand-picked value is stored under. */
|
|
28
34
|
export declare function profileKey(att: string, value: string): string;
|
|
29
35
|
/** The profiling values an element's attributes carry. */
|
package/dist/profiling.js
CHANGED
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
// The rules follow DITA-OT's filtering, which is what a .ditaval is written
|
|
13
13
|
// for:
|
|
14
14
|
// - an element is judged attribute by attribute (audience, platform,
|
|
15
|
-
// product, otherprops, props, and any attribute
|
|
16
|
-
// `props="name(value ...)"`);
|
|
15
|
+
// product, otherprops, deliveryTarget, props, and any attribute
|
|
16
|
+
// generalised through `props="name(value ...)"`);
|
|
17
17
|
// - for one attribute it is left out only when EVERY one of its values is
|
|
18
18
|
// excluded -- `audience="internal admin"` stays if admin is not excluded;
|
|
19
19
|
// - it is left out when ANY attribute leaves it out;
|
|
@@ -41,8 +41,14 @@ const sax_1 = __importDefault(require("sax"));
|
|
|
41
41
|
* The attributes the renderer records in data-profile-keys, in its order.
|
|
42
42
|
* Kept in step with PROFILING_ATTRS in render/renderer.ts (not exported from
|
|
43
43
|
* there); a test renders each one to catch drift.
|
|
44
|
+
*
|
|
45
|
+
* deliveryTarget joins the filter-atts group: DITA 1.3 added it to the
|
|
46
|
+
* select-atts (it replaces the deprecated DITA 1.2 @print), and DITA-OT
|
|
47
|
+
* filters on it exactly like the rest of the group, so an element carrying
|
|
48
|
+
* it must show up highlighted, in the filter panel, and in .ditaval
|
|
49
|
+
* filtering like any other profiling attribute.
|
|
44
50
|
*/
|
|
45
|
-
exports.PROFILE_ATTRS = ['props', 'platform', 'product', 'audience', 'otherprops', 'base', 'importance', 'rev', 'status'];
|
|
51
|
+
exports.PROFILE_ATTRS = ['props', 'platform', 'product', 'audience', 'otherprops', 'deliveryTarget', 'base', 'importance', 'rev', 'status'];
|
|
46
52
|
/**
|
|
47
53
|
* Attributes a .ditaval never acts on: DITA-OT filters on audience, platform,
|
|
48
54
|
* product, otherprops, props and their specialisations only. The rest are
|
|
@@ -782,8 +782,25 @@ exports.BASE_TYPE_RENDERERS = {
|
|
|
782
782
|
'topic/pre': (_node, ctx, renderChildren) => `<pre class="pre preformatted">${renderChildren(_node, ctx)}</pre>`,
|
|
783
783
|
'topic/xref': (node, ctx, renderChildren) => {
|
|
784
784
|
const href = getAttr(node, 'href') || '';
|
|
785
|
-
|
|
786
|
-
|
|
785
|
+
// No target at all: an xref with neither @href nor a keyref that
|
|
786
|
+
// resolves to one. Dropping the element silently (the old behaviour)
|
|
787
|
+
// hid both the author's text and the broken reference; keeping it
|
|
788
|
+
// visible -- its own content when it has any, an unresolved-key hint
|
|
789
|
+
// when it does not (the same treatment topic/ph gives an unresolved
|
|
790
|
+
// keyref) -- means a broken xref reads as one instead of vanishing.
|
|
791
|
+
if (!href) {
|
|
792
|
+
if (node.children.length > 0) {
|
|
793
|
+
const content = renderChildren(node, ctx);
|
|
794
|
+
const keyref = getAttr(node, 'keyref');
|
|
795
|
+
return keyref
|
|
796
|
+
? `<span class="xref unresolved-keyref" title="Unresolved key: ${escapeAttr(keyref)}">${content}</span>`
|
|
797
|
+
: `<span class="xref">${content}</span>`;
|
|
798
|
+
}
|
|
799
|
+
const keyref = getAttr(node, 'keyref');
|
|
800
|
+
if (!keyref)
|
|
801
|
+
return '';
|
|
802
|
+
return `<span class="xref unresolved-keyref" title="Unresolved key: ${escapeAttr(keyref)}">[${escapeAttr(keyref)}]</span>`;
|
|
803
|
+
}
|
|
787
804
|
let content;
|
|
788
805
|
if (node.children.length > 0) {
|
|
789
806
|
content = renderChildren(node, ctx);
|
|
@@ -819,6 +836,15 @@ exports.BASE_TYPE_RENDERERS = {
|
|
|
819
836
|
const target = bookTarget + (anchorId ? '#' + anchorId : '');
|
|
820
837
|
return `<a href="#" class="xref" data-dita-book-xref="${escapeAttr(target)}">${content}</a>`;
|
|
821
838
|
}
|
|
839
|
+
// Standalone preview opt-in (clickableExternalXrefs, no book context):
|
|
840
|
+
// keep the target's own href and let the webview hand it to the host,
|
|
841
|
+
// which opens DITA targets in their preview and everything else in the
|
|
842
|
+
// right place (see openHrefTarget) -- instead of the dead hint span.
|
|
843
|
+
// Without the opt-in (export, diff, book/site, the second host) the
|
|
844
|
+
// historical non-clickable hint below is kept exactly as it was.
|
|
845
|
+
if (ctx.clickableExternalXrefs) {
|
|
846
|
+
return `<a href="#" class="xref" data-dita-href="${escapeAttr(href)}">${content}</a>`;
|
|
847
|
+
}
|
|
822
848
|
return `<span class="xref-external">→ ${content}</span>`;
|
|
823
849
|
},
|
|
824
850
|
'topic/link': (node, ctx, renderChildren) => {
|
|
@@ -86,6 +86,30 @@ export interface RenderContext {
|
|
|
86
86
|
* MapViewerProvider) keeps showing chips exactly as before.
|
|
87
87
|
*/
|
|
88
88
|
suppressIndexterm?: boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Resolves a @keyref to the key's resource href ("other.dita#topic"),
|
|
91
|
+
* relative to the document being rendered, or undefined when the key
|
|
92
|
+
* defines no resource (a text-only key) or is not defined at all. Only
|
|
93
|
+
* link-shaped elements consume it (topic/xref): resolveKeyrefForNode
|
|
94
|
+
* copies the key's target onto the element's effective @href so
|
|
95
|
+
* `<xref keyref="k"/>` renders as a real link, exactly as DITA-OT
|
|
96
|
+
* resolves the same markup. The href is the caller's responsibility to
|
|
97
|
+
* make document-relative -- a keydef's href is relative to the map that
|
|
98
|
+
* defined it, and only the caller building this closure knows that
|
|
99
|
+
* directory (see buildRenderContext).
|
|
100
|
+
*/
|
|
101
|
+
resolveKeyHref?: (key: string) => string | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* Opt-in for the standalone single-topic preview: cross-file xrefs whose
|
|
104
|
+
* target is NOT part of a book (no isInCurrentBook context) render as a
|
|
105
|
+
* real <a> carrying the raw href in data-dita-href, which the preview's
|
|
106
|
+
* webview script hands to the extension host to open (another topic's
|
|
107
|
+
* preview, a ditamap, a web page). Without this flag the renderer keeps
|
|
108
|
+
* the historical non-clickable <span class="xref-external"> hint --
|
|
109
|
+
* "Export as HTML", the diff view, book/site rendering and the second
|
|
110
|
+
* host all stay byte-identical (a test locks each of those shapes).
|
|
111
|
+
*/
|
|
112
|
+
clickableExternalXrefs?: boolean;
|
|
89
113
|
/**
|
|
90
114
|
* Resolves a cross-file xref's raw href to an absolute path IF the
|
|
91
115
|
* referenced topic is part of the book/docsite this topic is itself
|
package/dist/render/renderer.js
CHANGED
|
@@ -27,12 +27,14 @@ function isContainerBaseType(baseType) {
|
|
|
27
27
|
// Per the OASIS DITA 1.3 select-atts entity (commonElements.mod): the full
|
|
28
28
|
// set of attributes conditional-processing tools (Oxygen's "Conditional
|
|
29
29
|
// Text" / DITA-OT's .ditaval) act on is props, platform, product, audience,
|
|
30
|
-
// otherprops (the filter-atts subgroup
|
|
31
|
-
//
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
|
|
30
|
+
// otherprops, deliveryTarget (the filter-atts subgroup -- DITA 1.3 added
|
|
31
|
+
// deliveryTarget, deprecating the DITA 1.2 @print), plus base, importance,
|
|
32
|
+
// rev, and status. This only *highlights* profiled content (matches it
|
|
33
|
+
// visually, the way Oxygen shows profiling by default) — it does not hide
|
|
34
|
+
// anything; that would be a real conditional-processing engine (a
|
|
35
|
+
// .ditaval-driven filter), which is a separate, larger feature this doesn't
|
|
36
|
+
// attempt.
|
|
37
|
+
const PROFILING_ATTRS = ['props', 'platform', 'product', 'audience', 'otherprops', 'deliveryTarget', 'base', 'importance', 'rev', 'status'];
|
|
36
38
|
const PROFILING_ATTR_LABELS = {
|
|
37
39
|
otherprops: 'Other',
|
|
38
40
|
};
|
|
@@ -377,6 +379,32 @@ function resolveConrefForNode(node, context) {
|
|
|
377
379
|
const end = followConrefChain(target, context);
|
|
378
380
|
return { node: mergeConrefTarget(node, end), chainKey: conref, mark: conrefMarkFor(end, context) };
|
|
379
381
|
}
|
|
382
|
+
/**
|
|
383
|
+
* Per DITA keyref semantics, the key's resource target becomes the
|
|
384
|
+
* referencing element's effective href when the element carries no href of
|
|
385
|
+
* its own -- this is what turns `<xref keyref="k"/>` into a link to the
|
|
386
|
+
* key's target. Applies to link-shaped elements only (topic/xref): other
|
|
387
|
+
* keyref consumers (ph, keyword, term) never link, and handing topic/link
|
|
388
|
+
* a href would change its rendered shape without the webview-side handling
|
|
389
|
+
* to click it safely, so the gate stays on the element's base type.
|
|
390
|
+
* Resolved for local content too: `<xref keyref="k">text</xref>` keeps its
|
|
391
|
+
* text and still links to the key's target.
|
|
392
|
+
*/
|
|
393
|
+
function withResolvedKeyHref(node, keyref, context) {
|
|
394
|
+
if (node.baseType !== 'topic/xref')
|
|
395
|
+
return node;
|
|
396
|
+
if (!context.resolveKeyHref || node.attributes?.href)
|
|
397
|
+
return node;
|
|
398
|
+
const keyHref = context.resolveKeyHref(keyref);
|
|
399
|
+
if (!keyHref) {
|
|
400
|
+
// The key resolves to text but names no resource (or the caller wired no
|
|
401
|
+
// defs): keep the keyref so the xref renderer can mark the element as an
|
|
402
|
+
// unlinkable keyref (unresolved-keyref) instead of a bare span that
|
|
403
|
+
// gives no hint anything is missing.
|
|
404
|
+
return { ...node, attributes: { ...node.attributes, keyref } };
|
|
405
|
+
}
|
|
406
|
+
return { ...node, attributes: { ...node.attributes, href: keyHref } };
|
|
407
|
+
}
|
|
380
408
|
function resolveKeyrefForNode(node, context) {
|
|
381
409
|
const keyref = node.attributes?.keyref;
|
|
382
410
|
if (!keyref || !context.resolveKey)
|
|
@@ -385,16 +413,15 @@ function resolveKeyrefForNode(node, context) {
|
|
|
385
413
|
// text — only substitute when the element is effectively empty.
|
|
386
414
|
const hasLocalContent = (node.children || []).some((c) => c.type === 'element' || (c.text || '').trim() !== '');
|
|
387
415
|
if (hasLocalContent)
|
|
388
|
-
return node;
|
|
416
|
+
return withResolvedKeyHref(node, keyref, context);
|
|
389
417
|
const resolved = context.resolveKey(keyref);
|
|
390
418
|
if (!resolved)
|
|
391
419
|
return node;
|
|
392
420
|
// Strip keyref after resolving, replace children with resolved text
|
|
393
421
|
const restAttrs = Object.fromEntries(Object.entries(node.attributes || {}).filter(([k]) => k !== 'keyref'));
|
|
394
422
|
return {
|
|
395
|
-
...node,
|
|
423
|
+
...withResolvedKeyHref({ ...node, attributes: restAttrs }, keyref, context),
|
|
396
424
|
children: [{ type: 'text', text: resolved, children: [], sourceRange: node.sourceRange }],
|
|
397
|
-
attributes: restAttrs,
|
|
398
425
|
};
|
|
399
426
|
}
|
|
400
427
|
// The "given a fully-resolved node, actually render it" half of
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Render a .ditamap as a book: every topic it references, in map order, on
|
|
2
|
+
// one page.
|
|
3
|
+
//
|
|
4
|
+
// Like mapRender.ts this is only glue around the copied parser and renderer:
|
|
5
|
+
// parse the map, splice in referenced submaps, collect the entries, then
|
|
6
|
+
// render each topic with renderTopicXml and wrap it in a section. The topic
|
|
7
|
+
// files are read from disk through readSourceText (the same cache and
|
|
8
|
+
// overlay rules the rest of the core uses).
|
|
9
|
+
//
|
|
10
|
+
// The wrapper carries the topic's absolute path in data-dita-book-file. A
|
|
11
|
+
// cross-file xref inside the book renders as data-dita-book-xref="path#id"
|
|
12
|
+
// (see baseTypeMap.ts); the host uses the wrapper to find the target section
|
|
13
|
+
// and scroll to it instead of opening another file.
|
|
14
|
+
import { dirname, isAbsolute, resolve } from 'path';
|
|
15
|
+
import { parseDitamap, preprocessEntities } from './parser/ditaParser';
|
|
16
|
+
import { decodeHrefPart, expandDitamapRefs } from './editor/refResolvers';
|
|
17
|
+
import { readSourceText } from './editor/sourceText';
|
|
18
|
+
import { renderTopicXml } from './editor/topicRender';
|
|
19
|
+
import { collectMapEntries, getMapTitleText } from './render/mapTypeMap';
|
|
20
|
+
import { pruneExcluded } from './profiling';
|
|
21
|
+
const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
|
|
22
|
+
function escapeHtml(s) {
|
|
23
|
+
return s
|
|
24
|
+
.replace(/&/g, '&')
|
|
25
|
+
.replace(/</g, '<')
|
|
26
|
+
.replace(/>/g, '>')
|
|
27
|
+
.replace(/"/g, '"')
|
|
28
|
+
.replace(/'/g, ''');
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The absolute path of the topic an entry points at, or undefined when it is
|
|
32
|
+
* not a local topic file (a URL, an absolute path, a fragment, a .ditamap,
|
|
33
|
+
* a PDF, ...). Map hrefs were rebased onto the root map's folder by
|
|
34
|
+
* expandDitamapRefs, so docDir is the only base needed here.
|
|
35
|
+
*/
|
|
36
|
+
export function topicPathOf(entry, docDir) {
|
|
37
|
+
const href = entry.href;
|
|
38
|
+
if (!href || href.startsWith('#'))
|
|
39
|
+
return undefined;
|
|
40
|
+
if (URL_SCHEME_RE.test(href) || isAbsolute(href))
|
|
41
|
+
return undefined;
|
|
42
|
+
const pathPart = decodeHrefPart(href.split('#')[0]);
|
|
43
|
+
const lower = pathPart.toLowerCase();
|
|
44
|
+
if (!lower.endsWith('.dita') && !lower.endsWith('.xml'))
|
|
45
|
+
return undefined;
|
|
46
|
+
return resolve(docDir, pathPart);
|
|
47
|
+
}
|
|
48
|
+
function roleHtml(entry) {
|
|
49
|
+
return entry.role ? `<p class="dita-book-role">${escapeHtml(entry.role)}</p>` : '';
|
|
50
|
+
}
|
|
51
|
+
function headingLevelFor(entry, base) {
|
|
52
|
+
return Math.min(6, Math.max(1, base + entry.depth));
|
|
53
|
+
}
|
|
54
|
+
export function renderBookXml(input) {
|
|
55
|
+
const doc = parseDitamap(preprocessEntities(input.xml));
|
|
56
|
+
const dependencies = input.collectDependencies ?? new Set();
|
|
57
|
+
const readFile = input.readFile ?? ((path) => readSourceText(path, 'utf-8'));
|
|
58
|
+
const read = (path, _enc) => {
|
|
59
|
+
dependencies.add(resolve(path));
|
|
60
|
+
return readFile(path);
|
|
61
|
+
};
|
|
62
|
+
expandDitamapRefs(doc.root, input.docDir, read);
|
|
63
|
+
pruneExcluded(doc.root, input.filter);
|
|
64
|
+
const keyMap = input.keyMap ?? new Map();
|
|
65
|
+
const resolveKey = (key) => keyMap.get(key);
|
|
66
|
+
const entries = collectMapEntries(doc.root, resolveKey, input.roleFormat);
|
|
67
|
+
const title = getMapTitleText(doc.root, resolveKey);
|
|
68
|
+
// Members are settled before any topic renders: every topic's cross-file
|
|
69
|
+
// xrefs need the complete set to decide whether they point inside the book.
|
|
70
|
+
const members = new Set();
|
|
71
|
+
const items = [];
|
|
72
|
+
for (const entry of entries) {
|
|
73
|
+
if (entry.resourceOnly)
|
|
74
|
+
continue;
|
|
75
|
+
const absPath = topicPathOf(entry, input.docDir);
|
|
76
|
+
if (absPath)
|
|
77
|
+
members.add(absPath);
|
|
78
|
+
items.push({ entry, absPath });
|
|
79
|
+
}
|
|
80
|
+
const baseLevel = input.headingLevel ?? 1;
|
|
81
|
+
const sections = [];
|
|
82
|
+
const renderedTopics = new Set();
|
|
83
|
+
for (const item of items) {
|
|
84
|
+
const { entry, absPath } = item;
|
|
85
|
+
if (!absPath) {
|
|
86
|
+
// A topichead (or a structural entry) has a title but no file: show it
|
|
87
|
+
// as a divider so "Part I" still appears between its chapters.
|
|
88
|
+
if (entry.href || !entry.displayName)
|
|
89
|
+
continue;
|
|
90
|
+
const level = headingLevelFor(entry, baseLevel);
|
|
91
|
+
sections.push(`<section class="dita-book-division" data-depth="${entry.depth}">${roleHtml(entry)}` +
|
|
92
|
+
`<h${level} class="dita-book-division-title">${escapeHtml(entry.displayName)}</h${level}></section>`);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
// A nested topicref with a fragment ("chapter.dita#section") points into
|
|
96
|
+
// a topic that may already be on the page in full; rendering the whole
|
|
97
|
+
// file again would duplicate it. The section itself is already there.
|
|
98
|
+
if ((entry.href ?? '').includes('#') && renderedTopics.has(absPath))
|
|
99
|
+
continue;
|
|
100
|
+
renderedTopics.add(absPath);
|
|
101
|
+
// The file is a dependency whether it exists or not: creating a missing
|
|
102
|
+
// topic should make the book re-render, just like editing an existing one.
|
|
103
|
+
dependencies.add(absPath);
|
|
104
|
+
let xml;
|
|
105
|
+
try {
|
|
106
|
+
xml = readFile(absPath);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
sections.push(`<p class="dita-book-missing">${escapeHtml(input.labels?.missingTopic ?? 'Missing topic')}: <code>${escapeHtml(entry.href ?? absPath)}</code></p>`);
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const docDir = dirname(absPath);
|
|
113
|
+
const asWebviewUri = (relPath) => {
|
|
114
|
+
if (!input.toResourceUrl)
|
|
115
|
+
return '';
|
|
116
|
+
return input.toResourceUrl(resolve(docDir, decodeHrefPart(relPath)));
|
|
117
|
+
};
|
|
118
|
+
const result = renderTopicXml({
|
|
119
|
+
xml,
|
|
120
|
+
docDir,
|
|
121
|
+
keyMap,
|
|
122
|
+
asWebviewUri,
|
|
123
|
+
headingLevel: headingLevelFor(entry, baseLevel),
|
|
124
|
+
uiLanguage: input.uiLanguage,
|
|
125
|
+
collectDependencies: dependencies,
|
|
126
|
+
bookMembers: members,
|
|
127
|
+
docFile: absPath,
|
|
128
|
+
markConrefs: true,
|
|
129
|
+
});
|
|
130
|
+
if (result.error !== undefined) {
|
|
131
|
+
sections.push(`<p class="dita-book-error">${escapeHtml(result.error)}</p>`);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
sections.push(`<section class="dita-book-topic" data-dita-book-file="${escapeHtml(absPath)}" data-depth="${entry.depth}">` +
|
|
135
|
+
`${roleHtml(entry)}${result.html}</section>`);
|
|
136
|
+
}
|
|
137
|
+
const header = title
|
|
138
|
+
? `<header class="dita-book-titlepage"><h1 class="dita-book-title">${escapeHtml(title)}</h1></header>`
|
|
139
|
+
: '';
|
|
140
|
+
return {
|
|
141
|
+
html: `<article class="dita-book">${header}${sections.join('\n')}</article>`,
|
|
142
|
+
title,
|
|
143
|
+
members: [...members],
|
|
144
|
+
};
|
|
145
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Completion for DITA source text: elements, attributes, attribute values, key
|
|
2
|
+
// references, file paths and ids.
|
|
3
|
+
//
|
|
4
|
+
// Host-neutral. It works on the document text and a cursor offset and returns
|
|
5
|
+
// plain suggestions; the host turns them into its own completion items (the
|
|
6
|
+
// Obsidian plugin maps them onto CodeMirror's). Everything it needs from
|
|
7
|
+
// outside -- the key space, the files on disk -- comes through CompletionEnv,
|
|
8
|
+
// so it runs unchanged in plain mocha.
|
|
9
|
+
//
|
|
10
|
+
// Context detection (where in a tag the cursor is) and tag-stack scanning are
|
|
11
|
+
// the VS Code DITA Viewer's own (language/ditaLanguageUtils.ts, copied
|
|
12
|
+
// verbatim); what is new here is ranking elements by their parent, image paths
|
|
13
|
+
// for <image href>, attribute de-duplication, and enumerated values.
|
|
14
|
+
import { STANDARD_TAG_TO_BASETYPE } from './parser/standardTagMap';
|
|
15
|
+
import { MAP_STANDARD_TAG_TO_BASETYPE } from './parser/mapTagMap';
|
|
16
|
+
import { collectIds, findUnclosedTag, getAttributesForTag, getCompletionContext } from './language/ditaLanguageUtils';
|
|
17
|
+
import { CHILD_HINTS, ENUM_VALUES, FILE_ATTRS, IMAGE_HREF_TAGS, ROOT_HINTS } from './completionData';
|
|
18
|
+
const BOOST_MAX = 90;
|
|
19
|
+
/** Rank by position in a hint list: earlier is higher. */
|
|
20
|
+
function rankBoost(index) {
|
|
21
|
+
return Math.max(1, BOOST_MAX - index);
|
|
22
|
+
}
|
|
23
|
+
export async function complete(text, offset, env) {
|
|
24
|
+
const ctx = getCompletionContext(text, offset);
|
|
25
|
+
switch (ctx.kind) {
|
|
26
|
+
case 'tag':
|
|
27
|
+
return ctx.closing ? completeCloseTag(text, offset, ctx.prefix ?? '') : completeTag(text, offset, ctx.prefix ?? '', env);
|
|
28
|
+
case 'attrName':
|
|
29
|
+
return completeAttrName(text, offset, ctx.tagName, ctx.prefix ?? '');
|
|
30
|
+
case 'attrValue':
|
|
31
|
+
return completeAttrValue(text, offset, ctx.tagName, ctx.attrName ?? '', ctx.prefix ?? '', env);
|
|
32
|
+
default:
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// ── elements ──
|
|
37
|
+
function completeCloseTag(text, offset, prefix) {
|
|
38
|
+
const lt = offset - prefix.length - 2;
|
|
39
|
+
const open = findUnclosedTag(text.slice(0, Math.max(lt, 0)));
|
|
40
|
+
if (!open)
|
|
41
|
+
return undefined;
|
|
42
|
+
return {
|
|
43
|
+
from: offset - prefix.length,
|
|
44
|
+
suggestions: [{ label: open, kind: 'closeTag', detail: 'close tag', insert: `${open}>`, boost: BOOST_MAX }],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function completeTag(text, offset, prefix, env) {
|
|
48
|
+
const lt = offset - prefix.length - 1;
|
|
49
|
+
const parent = findUnclosedTag(text.slice(0, Math.max(lt, 0)));
|
|
50
|
+
const vocabulary = env.isMap ? MAP_STANDARD_TAG_TO_BASETYPE : STANDARD_TAG_TO_BASETYPE;
|
|
51
|
+
const hints = parent
|
|
52
|
+
? CHILD_HINTS[parent] ?? []
|
|
53
|
+
: env.isMap
|
|
54
|
+
? ROOT_HINTS.map
|
|
55
|
+
: ROOT_HINTS.topic;
|
|
56
|
+
const rank = new Map(hints.map((name, i) => [name, rankBoost(i)]));
|
|
57
|
+
const suggestions = Object.keys(vocabulary).map((name) => ({
|
|
58
|
+
label: name,
|
|
59
|
+
kind: 'tag',
|
|
60
|
+
detail: vocabulary[name],
|
|
61
|
+
insert: name,
|
|
62
|
+
boost: rank.get(name) ?? 0,
|
|
63
|
+
}));
|
|
64
|
+
// A hinted name the vocabulary does not list (a specialization the hint table
|
|
65
|
+
// knows) is still worth offering where it is expected.
|
|
66
|
+
for (const [name, boost] of rank) {
|
|
67
|
+
if (!(name in vocabulary))
|
|
68
|
+
suggestions.push({ label: name, kind: 'tag', insert: name, boost });
|
|
69
|
+
}
|
|
70
|
+
return { from: offset - prefix.length, suggestions };
|
|
71
|
+
}
|
|
72
|
+
// ── attributes ──
|
|
73
|
+
/** Names of the attributes already written on the tag that ends at `offset`. */
|
|
74
|
+
function attributesPresent(text, offset, prefix) {
|
|
75
|
+
const lt = text.lastIndexOf('<', offset - 1);
|
|
76
|
+
const written = text.slice(lt, offset - prefix.length);
|
|
77
|
+
const names = new Set();
|
|
78
|
+
for (const m of written.matchAll(/([\w:.-]+)\s*=\s*(?:"[^"]*"|'[^']*')/g))
|
|
79
|
+
names.add(m[1]);
|
|
80
|
+
return names;
|
|
81
|
+
}
|
|
82
|
+
function completeAttrName(text, offset, tag, prefix) {
|
|
83
|
+
const present = attributesPresent(text, offset, prefix);
|
|
84
|
+
const names = getAttributesForTag(tag).filter((a) => !present.has(a));
|
|
85
|
+
if (names.length === 0)
|
|
86
|
+
return undefined;
|
|
87
|
+
return {
|
|
88
|
+
from: offset - prefix.length,
|
|
89
|
+
suggestions: names.map((attr, i) => ({
|
|
90
|
+
label: attr,
|
|
91
|
+
kind: 'attribute',
|
|
92
|
+
insert: `${attr}=""`,
|
|
93
|
+
cursor: attr.length + 2,
|
|
94
|
+
continueAfter: hasValueCompletion(tag, attr),
|
|
95
|
+
boost: rankBoost(i),
|
|
96
|
+
})),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function hasValueCompletion(tag, attr) {
|
|
100
|
+
return (attr === 'keyref' || attr === 'conkeyref' || attr in FILE_ATTRS ||
|
|
101
|
+
(tag !== undefined && `${tag}:${attr}` in ENUM_VALUES) || attr in ENUM_VALUES);
|
|
102
|
+
}
|
|
103
|
+
// ── attribute values ──
|
|
104
|
+
async function completeAttrValue(text, offset, tag, attr, prefix, env) {
|
|
105
|
+
const from = offset - prefix.length;
|
|
106
|
+
if (attr === 'keyref' || attr === 'conkeyref') {
|
|
107
|
+
// conkeyref="key/elementid": only the key is completed here.
|
|
108
|
+
if (prefix.includes('/'))
|
|
109
|
+
return undefined;
|
|
110
|
+
const suggestions = [];
|
|
111
|
+
for (const [key, value] of env.keys()) {
|
|
112
|
+
suggestions.push({ label: key, kind: 'key', detail: value !== key ? value : undefined, insert: key, boost: 0 });
|
|
113
|
+
}
|
|
114
|
+
return suggestions.length > 0 ? { from, suggestions } : undefined;
|
|
115
|
+
}
|
|
116
|
+
if (attr in FILE_ATTRS)
|
|
117
|
+
return completeReference(text, offset, tag, prefix, env);
|
|
118
|
+
const values = (tag !== undefined ? ENUM_VALUES[`${tag}:${attr}`] : undefined) ?? ENUM_VALUES[attr];
|
|
119
|
+
if (values) {
|
|
120
|
+
return { from, suggestions: values.map((v, i) => ({ label: v, kind: 'value', insert: v, boost: rankBoost(i) })) };
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
async function completeReference(text, offset, tag, prefix, env) {
|
|
125
|
+
const valueStart = offset - prefix.length;
|
|
126
|
+
const hash = prefix.indexOf('#');
|
|
127
|
+
// After '#': ids in the target file ("#topicid/elementid" replaces from the last '/').
|
|
128
|
+
if (hash >= 0) {
|
|
129
|
+
const filePart = prefix.slice(0, hash);
|
|
130
|
+
const ids = filePart ? env.idsIn(filePart) : collectIds(text);
|
|
131
|
+
if (!ids || ids.length === 0)
|
|
132
|
+
return undefined;
|
|
133
|
+
const fragment = prefix.slice(hash + 1);
|
|
134
|
+
const from = valueStart + hash + 1 + fragment.lastIndexOf('/') + 1;
|
|
135
|
+
return { from, suggestions: ids.map((id) => ({ label: id, kind: 'id', insert: id, boost: 0 })) };
|
|
136
|
+
}
|
|
137
|
+
const kind = tag !== undefined && IMAGE_HREF_TAGS.has(tag) ? 'image' : 'topic';
|
|
138
|
+
const files = await env.files(kind);
|
|
139
|
+
if (files.length === 0)
|
|
140
|
+
return undefined;
|
|
141
|
+
return { from: valueStart, suggestions: files.map((f) => ({ label: f, kind: 'file', insert: f, boost: 0 })) };
|
|
142
|
+
}
|