@dita-viewer/core 0.0.0-stage → 0.2.0

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +58 -3
  3. package/dist/bookRender.d.ts +63 -0
  4. package/dist/bookRender.js +150 -0
  5. package/dist/completion.d.ts +32 -0
  6. package/dist/completion.js +146 -0
  7. package/dist/completionData.d.ts +13 -0
  8. package/dist/completionData.js +159 -0
  9. package/dist/diagnostics.d.ts +57 -0
  10. package/dist/diagnostics.js +386 -0
  11. package/dist/editor/conkeyref.d.ts +19 -0
  12. package/dist/editor/conkeyref.js +108 -0
  13. package/dist/editor/keySpace.d.ts +72 -0
  14. package/dist/editor/keySpace.js +213 -0
  15. package/dist/editor/refResolvers.d.ts +54 -0
  16. package/dist/editor/refResolvers.js +648 -0
  17. package/dist/editor/renderContext.d.ts +51 -0
  18. package/dist/editor/renderContext.js +118 -0
  19. package/dist/editor/sourceText.d.ts +55 -0
  20. package/dist/editor/sourceText.js +154 -0
  21. package/dist/editor/topicRender.d.ts +180 -0
  22. package/dist/editor/topicRender.js +341 -0
  23. package/dist/index.d.ts +57 -0
  24. package/dist/index.js +182 -0
  25. package/dist/keyMapForDocument.d.ts +24 -0
  26. package/dist/keyMapForDocument.js +28 -0
  27. package/dist/language/ditaLanguageUtils.d.ts +185 -0
  28. package/dist/language/ditaLanguageUtils.js +682 -0
  29. package/dist/language/referenceableFiles.d.ts +53 -0
  30. package/dist/language/referenceableFiles.js +114 -0
  31. package/dist/mapRender.d.ts +14 -0
  32. package/dist/mapRender.js +28 -0
  33. package/dist/parser/ditaParser.d.ts +21 -0
  34. package/dist/parser/ditaParser.js +418 -0
  35. package/dist/parser/domTypes.d.ts +20 -0
  36. package/dist/parser/domTypes.js +3 -0
  37. package/dist/parser/mapTagMap.d.ts +1 -0
  38. package/dist/parser/mapTagMap.js +81 -0
  39. package/dist/parser/namedEntities.d.ts +2 -0
  40. package/dist/parser/namedEntities.js +325 -0
  41. package/dist/parser/standardTagMap.d.ts +1 -0
  42. package/dist/parser/standardTagMap.js +397 -0
  43. package/dist/profiling.d.ts +65 -0
  44. package/dist/profiling.js +235 -0
  45. package/dist/render/baseTypeMap.d.ts +26 -0
  46. package/dist/render/baseTypeMap.js +1037 -0
  47. package/dist/render/cjkSpacing.d.ts +30 -0
  48. package/dist/render/cjkSpacing.js +105 -0
  49. package/dist/render/mapTypeMap.d.ts +145 -0
  50. package/dist/render/mapTypeMap.js +580 -0
  51. package/dist/render/renderer.d.ts +125 -0
  52. package/dist/render/renderer.js +501 -0
  53. package/dist/siteRender.d.ts +52 -0
  54. package/dist/siteRender.js +265 -0
  55. package/package.json +53 -6
  56. package/styles/TOKENS.md +38 -0
  57. package/styles/dita-content.css +1157 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aREversez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @dita-viewer/core
2
+
3
+ Host-neutral DITA parsing and HTML rendering, shared by the
4
+ [VS Code DITA Viewer](https://github.com/aREversez/VS-Code-DITA-Viewer) and
5
+ [obsidian-dita](https://github.com/aREversez/obsidian-dita).
6
+
7
+ ## What is in it
8
+
9
+ | Path | Origin |
10
+ | --- | --- |
11
+ | `src/parser/`, `src/render/`, `src/editor/*.ts` | **Verbatim copies** of the same paths in the VS Code DITA Viewer, taken from `dev` at commit `596202d`, except `editor/topicRender.ts`, which is from the upstream change "move openHrefTarget out of topicRender" (it was identical before that, and the other files were checked identical to `dev` at `de5a237`). The 15 files in `parser/`, `render/` and `editor/` are exactly the transitive import closure of `renderTopicToHtml` and import nothing from `vscode`. |
12
+ | `src/language/ditaLanguageUtils.ts`, `src/language/referenceableFiles.ts` | **Verbatim copies** too (same commit): completion-context detection, tag-stack scanning, and the file walk behind `href` completion. Both are `vscode`-free. |
13
+ | `src/keyMapForDocument.ts`, `src/mapRender.ts`, `src/bookRender.ts`, `src/siteRender.ts`, `src/index.ts` | New here. The public API; the key-map lookup without the VS Code workspace features; `renderMapXml`, which sequences the copied map parser and renderer for a `.ditamap` outline; `renderBookXml` for the whole map on one page; and `renderSiteXml`, which renders one map topic at a time plus the sidebar manifest. |
14
+ | `src/profiling.ts` | New here. Conditional processing: read a `.ditaval`, read the profiling values of an element or of the renderer's `data-profile-keys`, decide whether an element stays (DITA-OT rules), list the values for a filter panel, and prune filtered entries from a parsed map. `renderBookXml` and `renderSiteXml` take it as `filter`. Informed by the VS Code viewer's `src/editor/ditaval.ts`, which only answers the exclusion question and is not a drop-in. |
15
+ | `src/index.ts` | New here. The public API. Besides the high-level `render*` functions it exports the parser and renderer entry points (`parseDita`, `parseDitamap`, `renderDocument`, ...) and the types they use, which is everything the VS Code viewer imports from the modules it copied; `test/publicApi.test.ts` pins that list. |
16
+ | `src/completion.ts`, `src/completionData.ts` | New here. Host-neutral completion engine (`complete(text, offset, env)`) and its tables: usual children per element (a ranking aid only, never a filter), enumerated attribute values, which attributes name files. |
17
+ | `styles/dita-content.css` | The topic-content, `.ditamap` outline-tree, and map page/site rules of the VS Code `media/styles.css`, with every `--vscode-*` replaced by a `--dita-*` host token. See the header comment for the complete list of differences. |
18
+ | `styles/TOKENS.md` | The contract between the stylesheet and a host. |
19
+ | `test/` | The upstream tests whose imports stay inside the 15 files (plus tests for completion, map rendering, book and site rendering), unchanged except for import paths. |
20
+
21
+ ## Keeping it in sync
22
+
23
+ Do not edit the verbatim files here. Change them upstream, then copy them over
24
+ and run `npm test`. Because they are byte-identical, `diff -r` against the
25
+ upstream tree shows exactly what is out of date.
26
+
27
+ The intended end state is that the VS Code extension depends on this package
28
+ instead of holding its own copies. Two small upstream changes make that
29
+ possible. The first is done: `openHrefTarget` now lives in the extension's own
30
+ `editor/openHrefTarget.ts`, so `topicRender.ts` mentions no host and the
31
+ `vscode` type stand-in is gone. The second is done in part: the extension's
32
+ `media/styles.css` reads these `--dita-*` tokens in its content and outline
33
+ rules, answered from VS Code's theme in one `:root` block, with rendering
34
+ unchanged. It is not yet interchangeable with `styles/dita-content.css`; the
35
+ open differences (selectors, three colour families this package folds into one
36
+ token, two tokens nothing upstream reads yet) are listed in `ROADMAP.md`.
37
+
38
+ ## Publishing to npm
39
+
40
+ The `@dita-viewer` scope must belong to the publisher: create an npm
41
+ organisation called `dita-viewer` (free for public packages), or rename the
42
+ package under a user scope in both repositories.
43
+
44
+ ```
45
+ npm login # two-factor authentication is required
46
+ npm run verify
47
+ npm run check:pack # packs, installs the tarball into an empty project, requires it, type-checks it
48
+ cd packages/dita-core
49
+ npm version patch # or minor; keep it in step with what changed
50
+ npm publish # publishConfig makes it public; prepublishOnly builds first
51
+ ```
52
+
53
+ A published version can never be reused, so run `check:pack` every time. The
54
+ plugin depends on the core as `*`: an exact version would stop matching the
55
+ workspace after the first bump, and npm would then install the published copy
56
+ next to it, so `verify` would test the plugin against old code. Until
57
+ the host-token and selector gaps in `ROADMAP.md` are closed, keep the version at
58
+ `0.x`: the exported surface is allowed to change.
@@ -0,0 +1,63 @@
1
+ import type { MapEntry, RoleLabelFormatter } from './render/mapTypeMap';
2
+ import type { ProfileFilter } from './profiling';
3
+ export interface BookXmlRenderInput {
4
+ /** The map's source text. */
5
+ xml: string;
6
+ /**
7
+ * Folder of the map. Hrefs in the map and in every spliced-in submap are
8
+ * relative to it by the time collectMapEntries sees them.
9
+ */
10
+ docDir: string;
11
+ /**
12
+ * Key name -> text, for keyref in titles and navtitles. Pass the Map a
13
+ * buildKeySpace / buildKeyMapForDocument call returned, not a copy: the
14
+ * renderer finds each key's file target through that very instance, so a
15
+ * copy silently turns conkeyref and keyref-with-href into empty output.
16
+ */
17
+ keyMap?: Map<string, string>;
18
+ /** Words the book itself adds, for a host that shows another language. */
19
+ labels?: {
20
+ missingTopic?: string;
21
+ };
22
+ /** Formats bookmap division labels ("Chapter 1", "第 1 章", ...). */
23
+ roleFormat?: RoleLabelFormatter;
24
+ /** Fallback language for note labels, as in renderTopicXml. */
25
+ uiLanguage?: string;
26
+ /** Heading level of a top-level topic (default 1); nested entries go deeper. */
27
+ headingLevel?: number;
28
+ /**
29
+ * Maps an absolute file path to a URL the preview can load. Called for
30
+ * every image in every topic, with the path already resolved against that
31
+ * topic's own folder.
32
+ */
33
+ toResourceUrl?: (absPath: string) => string;
34
+ /** Receives the absolute path of every map and topic file read. */
35
+ collectDependencies?: Set<string>;
36
+ /**
37
+ * Conditional processing: map entries the filter leaves out (a topicref with
38
+ * `audience="internal"`, say) are dropped, with their sub-entries, before
39
+ * anything is rendered. Profiled content inside a topic is not touched here;
40
+ * it carries data-profile-keys for the host to hide.
41
+ */
42
+ filter?: ProfileFilter;
43
+ /**
44
+ * Reads a topic file. Defaults to readSourceText; injectable so tests can
45
+ * render without touching the disk.
46
+ */
47
+ readFile?: (absPath: string) => string;
48
+ }
49
+ export interface BookXmlRenderResult {
50
+ html: string;
51
+ /** The map's own title, when it has one. */
52
+ title?: string;
53
+ /** Absolute paths of every topic shown, in reading order. */
54
+ members: string[];
55
+ }
56
+ /**
57
+ * The absolute path of the topic an entry points at, or undefined when it is
58
+ * not a local topic file (a URL, an absolute path, a fragment, a .ditamap,
59
+ * a PDF, ...). Map hrefs were rebased onto the root map's folder by
60
+ * expandDitamapRefs, so docDir is the only base needed here.
61
+ */
62
+ export declare function topicPathOf(entry: MapEntry, docDir: string): string | undefined;
63
+ export declare function renderBookXml(input: BookXmlRenderInput): BookXmlRenderResult;
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ // Render a .ditamap as a book: every topic it references, in map order, on
3
+ // one page.
4
+ //
5
+ // Like mapRender.ts this is only glue around the copied parser and renderer:
6
+ // parse the map, splice in referenced submaps, collect the entries, then
7
+ // render each topic with renderTopicXml and wrap it in a section. The topic
8
+ // files are read from disk through readSourceText (the same cache and
9
+ // overlay rules the rest of the core uses).
10
+ //
11
+ // The wrapper carries the topic's absolute path in data-dita-book-file. A
12
+ // cross-file xref inside the book renders as data-dita-book-xref="path#id"
13
+ // (see baseTypeMap.ts); the host uses the wrapper to find the target section
14
+ // and scroll to it instead of opening another file.
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.topicPathOf = topicPathOf;
17
+ exports.renderBookXml = renderBookXml;
18
+ const path_1 = require("path");
19
+ const ditaParser_1 = require("./parser/ditaParser");
20
+ const refResolvers_1 = require("./editor/refResolvers");
21
+ const sourceText_1 = require("./editor/sourceText");
22
+ const topicRender_1 = require("./editor/topicRender");
23
+ const mapTypeMap_1 = require("./render/mapTypeMap");
24
+ const profiling_1 = require("./profiling");
25
+ const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
26
+ function escapeHtml(s) {
27
+ return s
28
+ .replace(/&/g, '&amp;')
29
+ .replace(/</g, '&lt;')
30
+ .replace(/>/g, '&gt;')
31
+ .replace(/"/g, '&quot;')
32
+ .replace(/'/g, '&#39;');
33
+ }
34
+ /**
35
+ * The absolute path of the topic an entry points at, or undefined when it is
36
+ * not a local topic file (a URL, an absolute path, a fragment, a .ditamap,
37
+ * a PDF, ...). Map hrefs were rebased onto the root map's folder by
38
+ * expandDitamapRefs, so docDir is the only base needed here.
39
+ */
40
+ function topicPathOf(entry, docDir) {
41
+ const href = entry.href;
42
+ if (!href || href.startsWith('#'))
43
+ return undefined;
44
+ if (URL_SCHEME_RE.test(href) || (0, path_1.isAbsolute)(href))
45
+ return undefined;
46
+ const pathPart = (0, refResolvers_1.decodeHrefPart)(href.split('#')[0]);
47
+ const lower = pathPart.toLowerCase();
48
+ if (!lower.endsWith('.dita') && !lower.endsWith('.xml'))
49
+ return undefined;
50
+ return (0, path_1.resolve)(docDir, pathPart);
51
+ }
52
+ function roleHtml(entry) {
53
+ return entry.role ? `<p class="dita-book-role">${escapeHtml(entry.role)}</p>` : '';
54
+ }
55
+ function headingLevelFor(entry, base) {
56
+ return Math.min(6, Math.max(1, base + entry.depth));
57
+ }
58
+ function renderBookXml(input) {
59
+ const doc = (0, ditaParser_1.parseDitamap)((0, ditaParser_1.preprocessEntities)(input.xml));
60
+ const dependencies = input.collectDependencies ?? new Set();
61
+ const readFile = input.readFile ?? ((path) => (0, sourceText_1.readSourceText)(path, 'utf-8'));
62
+ const read = (path, _enc) => {
63
+ dependencies.add((0, path_1.resolve)(path));
64
+ return readFile(path);
65
+ };
66
+ (0, refResolvers_1.expandDitamapRefs)(doc.root, input.docDir, read);
67
+ (0, profiling_1.pruneExcluded)(doc.root, input.filter);
68
+ const keyMap = input.keyMap ?? new Map();
69
+ const resolveKey = (key) => keyMap.get(key);
70
+ const entries = (0, mapTypeMap_1.collectMapEntries)(doc.root, resolveKey, input.roleFormat);
71
+ const title = (0, mapTypeMap_1.getMapTitleText)(doc.root, resolveKey);
72
+ // Members are settled before any topic renders: every topic's cross-file
73
+ // xrefs need the complete set to decide whether they point inside the book.
74
+ const members = new Set();
75
+ const items = [];
76
+ for (const entry of entries) {
77
+ if (entry.resourceOnly)
78
+ continue;
79
+ const absPath = topicPathOf(entry, input.docDir);
80
+ if (absPath)
81
+ members.add(absPath);
82
+ items.push({ entry, absPath });
83
+ }
84
+ const baseLevel = input.headingLevel ?? 1;
85
+ const sections = [];
86
+ const renderedTopics = new Set();
87
+ for (const item of items) {
88
+ const { entry, absPath } = item;
89
+ if (!absPath) {
90
+ // A topichead (or a structural entry) has a title but no file: show it
91
+ // as a divider so "Part I" still appears between its chapters.
92
+ if (entry.href || !entry.displayName)
93
+ continue;
94
+ const level = headingLevelFor(entry, baseLevel);
95
+ sections.push(`<section class="dita-book-division" data-depth="${entry.depth}">${roleHtml(entry)}` +
96
+ `<h${level} class="dita-book-division-title">${escapeHtml(entry.displayName)}</h${level}></section>`);
97
+ continue;
98
+ }
99
+ // A nested topicref with a fragment ("chapter.dita#section") points into
100
+ // a topic that may already be on the page in full; rendering the whole
101
+ // file again would duplicate it. The section itself is already there.
102
+ if ((entry.href ?? '').includes('#') && renderedTopics.has(absPath))
103
+ continue;
104
+ renderedTopics.add(absPath);
105
+ // The file is a dependency whether it exists or not: creating a missing
106
+ // topic should make the book re-render, just like editing an existing one.
107
+ dependencies.add(absPath);
108
+ let xml;
109
+ try {
110
+ xml = readFile(absPath);
111
+ }
112
+ catch {
113
+ sections.push(`<p class="dita-book-missing">${escapeHtml(input.labels?.missingTopic ?? 'Missing topic')}: <code>${escapeHtml(entry.href ?? absPath)}</code></p>`);
114
+ continue;
115
+ }
116
+ const docDir = (0, path_1.dirname)(absPath);
117
+ const asWebviewUri = (relPath) => {
118
+ if (!input.toResourceUrl)
119
+ return '';
120
+ return input.toResourceUrl((0, path_1.resolve)(docDir, (0, refResolvers_1.decodeHrefPart)(relPath)));
121
+ };
122
+ const result = (0, topicRender_1.renderTopicXml)({
123
+ xml,
124
+ docDir,
125
+ keyMap,
126
+ asWebviewUri,
127
+ headingLevel: headingLevelFor(entry, baseLevel),
128
+ uiLanguage: input.uiLanguage,
129
+ collectDependencies: dependencies,
130
+ bookMembers: members,
131
+ docFile: absPath,
132
+ markConrefs: true,
133
+ });
134
+ if (result.error !== undefined) {
135
+ sections.push(`<p class="dita-book-error">${escapeHtml(result.error)}</p>`);
136
+ continue;
137
+ }
138
+ sections.push(`<section class="dita-book-topic" data-dita-book-file="${escapeHtml(absPath)}" data-depth="${entry.depth}">` +
139
+ `${roleHtml(entry)}${result.html}</section>`);
140
+ }
141
+ const header = title
142
+ ? `<header class="dita-book-titlepage"><h1 class="dita-book-title">${escapeHtml(title)}</h1></header>`
143
+ : '';
144
+ return {
145
+ html: `<article class="dita-book">${header}${sections.join('\n')}</article>`,
146
+ title,
147
+ members: [...members],
148
+ };
149
+ }
150
+ //# sourceMappingURL=bookRender.js.map
@@ -0,0 +1,32 @@
1
+ export type SuggestionKind = 'tag' | 'closeTag' | 'attribute' | 'value' | 'key' | 'file' | 'id';
2
+ export interface Suggestion {
3
+ /** What the user types to match this, and what is shown. */
4
+ label: string;
5
+ kind: SuggestionKind;
6
+ /** Short explanation shown beside the label. */
7
+ detail?: string;
8
+ /** Text that replaces the typed prefix (defaults to the label). */
9
+ insert: string;
10
+ /** Caret position within `insert` after applying (defaults to its end). */
11
+ cursor?: number;
12
+ /** Open a new completion straight after applying, e.g. for the value of an inserted attribute. */
13
+ continueAfter?: boolean;
14
+ /** Ranking, -99..99: higher is listed first among equal matches. */
15
+ boost: number;
16
+ }
17
+ export interface CompletionResult {
18
+ /** Start of the text the suggestions replace; it ends at the cursor. */
19
+ from: number;
20
+ suggestions: Suggestion[];
21
+ }
22
+ export interface CompletionEnv {
23
+ /** A .ditamap rather than a topic: picks the element vocabulary. */
24
+ isMap: boolean;
25
+ /** Key name -> its value, for keyref / conkeyref. */
26
+ keys(): ReadonlyMap<string, string>;
27
+ /** Files an href/conref may point at, relative to the document: topics and maps, or images. */
28
+ files(kind: 'topic' | 'image'): Promise<string[]> | string[];
29
+ /** Element ids in another file, or undefined if it cannot be read. `filePart` is as written in the href. */
30
+ idsIn(filePart: string): string[] | undefined;
31
+ }
32
+ export declare function complete(text: string, offset: number, env: CompletionEnv): Promise<CompletionResult | undefined>;
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ // Completion for DITA source text: elements, attributes, attribute values, key
3
+ // references, file paths and ids.
4
+ //
5
+ // Host-neutral. It works on the document text and a cursor offset and returns
6
+ // plain suggestions; the host turns them into its own completion items (the
7
+ // Obsidian plugin maps them onto CodeMirror's). Everything it needs from
8
+ // outside -- the key space, the files on disk -- comes through CompletionEnv,
9
+ // so it runs unchanged in plain mocha.
10
+ //
11
+ // Context detection (where in a tag the cursor is) and tag-stack scanning are
12
+ // the VS Code DITA Viewer's own (language/ditaLanguageUtils.ts, copied
13
+ // verbatim); what is new here is ranking elements by their parent, image paths
14
+ // for <image href>, attribute de-duplication, and enumerated values.
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.complete = complete;
17
+ const standardTagMap_1 = require("./parser/standardTagMap");
18
+ const mapTagMap_1 = require("./parser/mapTagMap");
19
+ const ditaLanguageUtils_1 = require("./language/ditaLanguageUtils");
20
+ const completionData_1 = require("./completionData");
21
+ const BOOST_MAX = 90;
22
+ /** Rank by position in a hint list: earlier is higher. */
23
+ function rankBoost(index) {
24
+ return Math.max(1, BOOST_MAX - index);
25
+ }
26
+ async function complete(text, offset, env) {
27
+ const ctx = (0, ditaLanguageUtils_1.getCompletionContext)(text, offset);
28
+ switch (ctx.kind) {
29
+ case 'tag':
30
+ return ctx.closing ? completeCloseTag(text, offset, ctx.prefix ?? '') : completeTag(text, offset, ctx.prefix ?? '', env);
31
+ case 'attrName':
32
+ return completeAttrName(text, offset, ctx.tagName, ctx.prefix ?? '');
33
+ case 'attrValue':
34
+ return completeAttrValue(text, offset, ctx.tagName, ctx.attrName ?? '', ctx.prefix ?? '', env);
35
+ default:
36
+ return undefined;
37
+ }
38
+ }
39
+ // ── elements ──
40
+ function completeCloseTag(text, offset, prefix) {
41
+ const lt = offset - prefix.length - 2;
42
+ const open = (0, ditaLanguageUtils_1.findUnclosedTag)(text.slice(0, Math.max(lt, 0)));
43
+ if (!open)
44
+ return undefined;
45
+ return {
46
+ from: offset - prefix.length,
47
+ suggestions: [{ label: open, kind: 'closeTag', detail: 'close tag', insert: `${open}>`, boost: BOOST_MAX }],
48
+ };
49
+ }
50
+ function completeTag(text, offset, prefix, env) {
51
+ const lt = offset - prefix.length - 1;
52
+ const parent = (0, ditaLanguageUtils_1.findUnclosedTag)(text.slice(0, Math.max(lt, 0)));
53
+ const vocabulary = env.isMap ? mapTagMap_1.MAP_STANDARD_TAG_TO_BASETYPE : standardTagMap_1.STANDARD_TAG_TO_BASETYPE;
54
+ const hints = parent
55
+ ? completionData_1.CHILD_HINTS[parent] ?? []
56
+ : env.isMap
57
+ ? completionData_1.ROOT_HINTS.map
58
+ : completionData_1.ROOT_HINTS.topic;
59
+ const rank = new Map(hints.map((name, i) => [name, rankBoost(i)]));
60
+ const suggestions = Object.keys(vocabulary).map((name) => ({
61
+ label: name,
62
+ kind: 'tag',
63
+ detail: vocabulary[name],
64
+ insert: name,
65
+ boost: rank.get(name) ?? 0,
66
+ }));
67
+ // A hinted name the vocabulary does not list (a specialization the hint table
68
+ // knows) is still worth offering where it is expected.
69
+ for (const [name, boost] of rank) {
70
+ if (!(name in vocabulary))
71
+ suggestions.push({ label: name, kind: 'tag', insert: name, boost });
72
+ }
73
+ return { from: offset - prefix.length, suggestions };
74
+ }
75
+ // ── attributes ──
76
+ /** Names of the attributes already written on the tag that ends at `offset`. */
77
+ function attributesPresent(text, offset, prefix) {
78
+ const lt = text.lastIndexOf('<', offset - 1);
79
+ const written = text.slice(lt, offset - prefix.length);
80
+ const names = new Set();
81
+ for (const m of written.matchAll(/([\w:.-]+)\s*=\s*(?:"[^"]*"|'[^']*')/g))
82
+ names.add(m[1]);
83
+ return names;
84
+ }
85
+ function completeAttrName(text, offset, tag, prefix) {
86
+ const present = attributesPresent(text, offset, prefix);
87
+ const names = (0, ditaLanguageUtils_1.getAttributesForTag)(tag).filter((a) => !present.has(a));
88
+ if (names.length === 0)
89
+ return undefined;
90
+ return {
91
+ from: offset - prefix.length,
92
+ suggestions: names.map((attr, i) => ({
93
+ label: attr,
94
+ kind: 'attribute',
95
+ insert: `${attr}=""`,
96
+ cursor: attr.length + 2,
97
+ continueAfter: hasValueCompletion(tag, attr),
98
+ boost: rankBoost(i),
99
+ })),
100
+ };
101
+ }
102
+ function hasValueCompletion(tag, attr) {
103
+ return (attr === 'keyref' || attr === 'conkeyref' || attr in completionData_1.FILE_ATTRS ||
104
+ (tag !== undefined && `${tag}:${attr}` in completionData_1.ENUM_VALUES) || attr in completionData_1.ENUM_VALUES);
105
+ }
106
+ // ── attribute values ──
107
+ async function completeAttrValue(text, offset, tag, attr, prefix, env) {
108
+ const from = offset - prefix.length;
109
+ if (attr === 'keyref' || attr === 'conkeyref') {
110
+ // conkeyref="key/elementid": only the key is completed here.
111
+ if (prefix.includes('/'))
112
+ return undefined;
113
+ const suggestions = [];
114
+ for (const [key, value] of env.keys()) {
115
+ suggestions.push({ label: key, kind: 'key', detail: value !== key ? value : undefined, insert: key, boost: 0 });
116
+ }
117
+ return suggestions.length > 0 ? { from, suggestions } : undefined;
118
+ }
119
+ if (attr in completionData_1.FILE_ATTRS)
120
+ return completeReference(text, offset, tag, prefix, env);
121
+ const values = (tag !== undefined ? completionData_1.ENUM_VALUES[`${tag}:${attr}`] : undefined) ?? completionData_1.ENUM_VALUES[attr];
122
+ if (values) {
123
+ return { from, suggestions: values.map((v, i) => ({ label: v, kind: 'value', insert: v, boost: rankBoost(i) })) };
124
+ }
125
+ return undefined;
126
+ }
127
+ async function completeReference(text, offset, tag, prefix, env) {
128
+ const valueStart = offset - prefix.length;
129
+ const hash = prefix.indexOf('#');
130
+ // After '#': ids in the target file ("#topicid/elementid" replaces from the last '/').
131
+ if (hash >= 0) {
132
+ const filePart = prefix.slice(0, hash);
133
+ const ids = filePart ? env.idsIn(filePart) : (0, ditaLanguageUtils_1.collectIds)(text);
134
+ if (!ids || ids.length === 0)
135
+ return undefined;
136
+ const fragment = prefix.slice(hash + 1);
137
+ const from = valueStart + hash + 1 + fragment.lastIndexOf('/') + 1;
138
+ return { from, suggestions: ids.map((id) => ({ label: id, kind: 'id', insert: id, boost: 0 })) };
139
+ }
140
+ const kind = tag !== undefined && completionData_1.IMAGE_HREF_TAGS.has(tag) ? 'image' : 'topic';
141
+ const files = await env.files(kind);
142
+ if (files.length === 0)
143
+ return undefined;
144
+ return { from: valueStart, suggestions: files.map((f) => ({ label: f, kind: 'file', insert: f, boost: 0 })) };
145
+ }
146
+ //# sourceMappingURL=completion.js.map
@@ -0,0 +1,13 @@
1
+ export declare const CHILD_HINTS: Readonly<Record<string, readonly string[]>>;
2
+ /** Roots offered where no element is open yet. */
3
+ export declare const ROOT_HINTS: {
4
+ readonly topic: readonly ["concept", "task", "reference", "topic", "glossentry", "troubleshooting"];
5
+ readonly map: readonly ["map", "bookmap"];
6
+ };
7
+ /** Values for enumerated attributes. A `tag:attr` key outranks a bare `attr`. */
8
+ export declare const ENUM_VALUES: Readonly<Record<string, readonly string[]>>;
9
+ /** Attributes whose value is a path, and which kind of file it names. */
10
+ export declare const FILE_ATTRS: Readonly<Record<string, 'topic' | 'image'>>;
11
+ /** Elements whose `href` points at an image or other binary rather than a topic. */
12
+ export declare const IMAGE_HREF_TAGS: ReadonlySet<string>;
13
+ export declare const IMAGE_EXT: RegExp;
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ // What the completion engine knows about DITA, as data.
3
+ //
4
+ // CHILD_HINTS says which elements are the usual children of a parent. It is a
5
+ // ranking aid, not a content model: every known element is still offered
6
+ // everywhere, and a hinted one is merely listed first. A wrong or missing
7
+ // entry therefore costs a suggestion's position, never its availability, which
8
+ // is why this can be a curated table rather than a copy of the DTDs.
9
+ //
10
+ // Entries follow the DITA 1.3 technical-content and map vocabularies. Order is
11
+ // the order the suggestions appear in.
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.IMAGE_EXT = exports.IMAGE_HREF_TAGS = exports.FILE_ATTRS = exports.ENUM_VALUES = exports.ROOT_HINTS = exports.CHILD_HINTS = void 0;
14
+ const INLINE = [
15
+ 'ph', 'codeph', 'keyword', 'term', 'xref', 'b', 'i', 'u', 'tt', 'sup', 'sub',
16
+ 'uicontrol', 'menucascade', 'userinput', 'systemoutput', 'varname', 'filepath',
17
+ 'cmdname', 'apiname', 'parmname', 'option', 'image', 'q', 'indexterm', 'fn',
18
+ 'data', 'tm', 'cite', 'abbreviated-form', 'xmlelement', 'xmlatt', 'msgph',
19
+ 'wintitle', 'shortcut', 'synph',
20
+ ];
21
+ const BLOCKS = [
22
+ 'p', 'ul', 'ol', 'dl', 'note', 'table', 'simpletable', 'fig', 'codeblock',
23
+ 'pre', 'lines', 'lq', 'sl', 'image', 'object', 'div', 'hazardstatement',
24
+ 'draft-comment', 'required-cleanup', 'foreign', 'data',
25
+ ];
26
+ const BODY = ['p', 'section', 'example', 'ul', 'ol', 'dl', 'note', 'table', 'simpletable', 'fig', 'codeblock', 'pre', 'lines', 'lq', 'sl', 'image', 'div', 'bodydiv', 'sectiondiv', 'hazardstatement', 'object', 'foreign', 'data', 'draft-comment', 'required-cleanup', 'fn', 'indexterm'];
27
+ const MIXED = [...new Set([...BLOCKS, ...INLINE])];
28
+ const TITLED_SECTION = ['title', ...BLOCKS];
29
+ const TOPIC_PARTS = ['title', 'titlealts', 'shortdesc', 'abstract', 'prolog'];
30
+ const MAP_REF_CHILDREN = ['topicmeta', 'topicref', 'keydef', 'mapref', 'topicgroup', 'topichead'];
31
+ exports.CHILD_HINTS = {
32
+ // Topic roots
33
+ concept: [...TOPIC_PARTS, 'conbody', 'related-links'],
34
+ task: [...TOPIC_PARTS, 'taskbody', 'related-links'],
35
+ reference: [...TOPIC_PARTS, 'refbody', 'related-links'],
36
+ topic: [...TOPIC_PARTS, 'body', 'related-links'],
37
+ glossentry: ['glossterm', 'glossdef', 'glossBody', 'prolog'],
38
+ troubleshooting: [...TOPIC_PARTS, 'troublebody', 'related-links'],
39
+ // Bodies
40
+ body: BODY,
41
+ conbody: BODY,
42
+ refbody: ['section', 'refsyn', 'properties', 'table', 'simpletable', 'example', 'dl', 'p', 'ul', 'ol', 'note', 'codeblock'],
43
+ taskbody: ['prereq', 'context', 'steps', 'steps-unordered', 'steps-informal', 'result', 'example', 'postreq', 'section'],
44
+ troublebody: ['condition', 'troubleSolution', 'section', 'example'],
45
+ section: TITLED_SECTION,
46
+ example: TITLED_SECTION,
47
+ sectiondiv: BLOCKS,
48
+ bodydiv: BODY,
49
+ div: MIXED,
50
+ prereq: BLOCKS,
51
+ context: BLOCKS,
52
+ result: BLOCKS,
53
+ postreq: BLOCKS,
54
+ // Task steps
55
+ steps: ['step', 'stepsection'],
56
+ 'steps-unordered': ['step', 'stepsection'],
57
+ step: ['cmd', 'info', 'substeps', 'stepxmp', 'choices', 'choicetable', 'stepresult', 'steptroubleshooting', 'tutorialinfo'],
58
+ substeps: ['substep'],
59
+ substep: ['cmd', 'info', 'stepxmp', 'choices', 'choicetable', 'stepresult'],
60
+ choices: ['choice'],
61
+ // Lists
62
+ ul: ['li'],
63
+ ol: ['li'],
64
+ sl: ['sli'],
65
+ dl: ['dlhead', 'dlentry'],
66
+ dlentry: ['dt', 'dd'],
67
+ dlhead: ['dthd', 'ddhd'],
68
+ li: MIXED,
69
+ dd: MIXED,
70
+ sli: INLINE,
71
+ // Tables
72
+ table: ['title', 'desc', 'tgroup'],
73
+ tgroup: ['colspec', 'thead', 'tbody'],
74
+ thead: ['row'],
75
+ tbody: ['row'],
76
+ row: ['entry'],
77
+ entry: MIXED,
78
+ simpletable: ['sthead', 'strow'],
79
+ sthead: ['stentry'],
80
+ strow: ['stentry'],
81
+ stentry: MIXED,
82
+ // Figures and blocks that hold mixed content
83
+ fig: ['title', 'desc', 'image', 'figgroup', 'codeblock', 'pre', 'lines', 'simpletable', 'table'],
84
+ note: MIXED,
85
+ p: INLINE,
86
+ title: INLINE,
87
+ shortdesc: INLINE,
88
+ desc: INLINE,
89
+ cmd: INLINE,
90
+ info: MIXED,
91
+ lq: MIXED,
92
+ // Metadata
93
+ prolog: ['author', 'source', 'publisher', 'copyright', 'critdates', 'permissions', 'metadata', 'resourceid', 'data'],
94
+ metadata: ['audience', 'category', 'keywords', 'prodinfo', 'othermeta', 'data'],
95
+ keywords: ['keyword', 'indexterm'],
96
+ prodinfo: ['prodname', 'vrmlist', 'brand', 'component', 'featnum', 'prognum', 'platform', 'series'],
97
+ 'related-links': ['link', 'linklist', 'linkpool'],
98
+ link: ['linktext', 'desc'],
99
+ linklist: ['title', 'desc', 'link', 'linklist'],
100
+ // Maps
101
+ map: ['title', 'topicmeta', 'topicref', 'topichead', 'topicgroup', 'keydef', 'mapref', 'reltable', 'anchor', 'navref', 'topicset', 'data'],
102
+ bookmap: ['booktitle', 'bookmeta', 'frontmatter', 'chapter', 'part', 'appendices', 'appendix', 'backmatter', 'reltable'],
103
+ booktitle: ['mainbooktitle', 'booktitlealt'],
104
+ topicref: MAP_REF_CHILDREN,
105
+ topichead: MAP_REF_CHILDREN,
106
+ topicgroup: ['topicref', 'topichead', 'keydef', 'mapref', 'topicmeta'],
107
+ chapter: MAP_REF_CHILDREN,
108
+ part: [...MAP_REF_CHILDREN, 'chapter'],
109
+ appendix: MAP_REF_CHILDREN,
110
+ appendices: ['appendix', 'topicmeta'],
111
+ keydef: ['topicmeta', 'topicref'],
112
+ mapref: ['topicmeta'],
113
+ topicmeta: ['navtitle', 'linktext', 'shortdesc', 'keywords', 'data', 'othermeta', 'searchtitle', 'resourceid', 'author'],
114
+ reltable: ['relheader', 'relrow'],
115
+ relheader: ['relcolspec'],
116
+ relrow: ['relcell'],
117
+ relcolspec: ['topicref'],
118
+ relcell: ['topicref'],
119
+ };
120
+ /** Roots offered where no element is open yet. */
121
+ exports.ROOT_HINTS = {
122
+ topic: ['concept', 'task', 'reference', 'topic', 'glossentry', 'troubleshooting'],
123
+ map: ['map', 'bookmap'],
124
+ };
125
+ /** Values for enumerated attributes. A `tag:attr` key outranks a bare `attr`. */
126
+ exports.ENUM_VALUES = {
127
+ 'note:type': ['note', 'tip', 'important', 'caution', 'warning', 'danger', 'attention', 'remember', 'restriction', 'fastpath', 'trouble', 'notice', 'other'],
128
+ scope: ['local', 'peer', 'external'],
129
+ format: ['dita', 'ditamap', 'html', 'pdf', 'xml', 'txt'],
130
+ 'processing-role': ['normal', 'resource-only'],
131
+ toc: ['yes', 'no'],
132
+ print: ['yes', 'no', 'printonly'],
133
+ search: ['yes', 'no'],
134
+ locktitle: ['yes', 'no'],
135
+ linking: ['normal', 'targetonly', 'sourceonly', 'none'],
136
+ 'collection-type': ['unordered', 'sequence', 'choice', 'family'],
137
+ type: ['fn', 'section', 'table', 'fig', 'li', 'step', 'topic', 'concept', 'task', 'reference'],
138
+ placement: ['inline', 'break'],
139
+ align: ['left', 'right', 'center', 'current', 'justify'],
140
+ valign: ['top', 'middle', 'bottom'],
141
+ frame: ['all', 'bottom', 'none', 'sides', 'top', 'topbot'],
142
+ colsep: ['0', '1'],
143
+ rowsep: ['0', '1'],
144
+ pgwide: ['0', '1'],
145
+ importance: ['obsolete', 'deprecated', 'optional', 'default', 'low', 'normal', 'high', 'recommended', 'required', 'urgent'],
146
+ status: ['new', 'changed', 'deleted', 'unchanged'],
147
+ translate: ['yes', 'no', '-dita-use-conref-target'],
148
+ 'xml:lang': ['en-US', 'en-GB', 'zh-CN', 'zh-TW', 'ja-JP', 'ko-KR', 'de-DE', 'fr-FR', 'es-ES', 'ru-RU'],
149
+ };
150
+ /** Attributes whose value is a path, and which kind of file it names. */
151
+ exports.FILE_ATTRS = {
152
+ href: 'topic',
153
+ conref: 'topic',
154
+ conrefend: 'topic',
155
+ };
156
+ /** Elements whose `href` points at an image or other binary rather than a topic. */
157
+ exports.IMAGE_HREF_TAGS = new Set(['image', 'object', 'imagemap']);
158
+ exports.IMAGE_EXT = /\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|emf)$/i;
159
+ //# sourceMappingURL=completionData.js.map