@dita-viewer/core 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +90 -58
  3. package/dist/editor/renderContext.d.ts +7 -0
  4. package/dist/editor/renderContext.js +24 -0
  5. package/dist/editor/topicRender.d.ts +9 -0
  6. package/dist/editor/topicRender.js +4 -2
  7. package/dist/index.js +3 -3
  8. package/dist/language/ditaLanguageUtils.js +2 -0
  9. package/dist/profiling.d.ts +9 -3
  10. package/dist/profiling.js +12 -6
  11. package/dist/render/baseTypeMap.js +28 -2
  12. package/dist/render/mapTypeMap.js +23 -23
  13. package/dist/render/renderer.d.ts +24 -0
  14. package/dist/render/renderer.js +36 -9
  15. package/dist-esm/bookRender.js +145 -0
  16. package/dist-esm/completion.js +142 -0
  17. package/dist-esm/completionData.js +155 -0
  18. package/dist-esm/diagnostics.js +378 -0
  19. package/dist-esm/editor/conkeyref.js +104 -0
  20. package/dist-esm/editor/keySpace.js +201 -0
  21. package/dist-esm/editor/refResolvers.js +633 -0
  22. package/dist-esm/editor/renderContext.js +138 -0
  23. package/dist-esm/editor/sourceText.js +142 -0
  24. package/dist-esm/editor/topicRender.js +328 -0
  25. package/dist-esm/index.js +66 -0
  26. package/dist-esm/keyMapForDocument.js +23 -0
  27. package/dist-esm/language/ditaLanguageUtils.js +659 -0
  28. package/dist-esm/language/referenceableFiles.js +108 -0
  29. package/dist-esm/mapRender.js +24 -0
  30. package/dist-esm/package.json +1 -0
  31. package/dist-esm/parser/ditaParser.js +409 -0
  32. package/dist-esm/parser/domTypes.js +1 -0
  33. package/dist-esm/parser/mapTagMap.js +77 -0
  34. package/dist-esm/parser/namedEntities.js +321 -0
  35. package/dist-esm/parser/standardTagMap.js +393 -0
  36. package/dist-esm/profiling.js +224 -0
  37. package/dist-esm/render/baseTypeMap.js +1057 -0
  38. package/dist-esm/render/cjkSpacing.js +94 -0
  39. package/dist-esm/render/mapTypeMap.js +568 -0
  40. package/dist-esm/render/renderer.js +519 -0
  41. package/dist-esm/siteRender.js +261 -0
  42. package/package.json +55 -53
  43. package/styles/TOKENS.md +59 -38
  44. package/styles/dita-content.css +1171 -1157
@@ -0,0 +1,261 @@
1
+ // Render one page of a .ditamap as a small site: the current topic plus a
2
+ // sidebar manifest of every topic in the map.
3
+ //
4
+ // The manifest is built from the same flattened entries bookRender uses, so
5
+ // the sidebar and the pages agree on which topics are members and in what
6
+ // order. Only the pages themselves are rendered one at a time; when the map
7
+ // leaves an entry unnamed, the sidebar sniffs that topic's own <title> for a
8
+ // readable label (explicit navtitles/linktext win and cost no read). Book view
9
+ // still shows every topic's title because it renders every page.
10
+ //
11
+ // The page wrapper carries data-dita-book-file, exactly like a book section,
12
+ // so the host can open relative links and "reveal in source" against the
13
+ // topic that contains them. A cross-file xref renders as
14
+ // data-dita-book-xref="path#id" (see baseTypeMap.ts); the host uses this
15
+ // manifest to switch pages before scrolling to the anchor.
16
+ import { statSync } from 'fs';
17
+ import { dirname, resolve } from 'path';
18
+ import { parseDitamap, preprocessEntities } from './parser/ditaParser';
19
+ import { decodeHrefPart, expandDitamapRefs } from './editor/refResolvers';
20
+ import { readSourceText } from './editor/sourceText';
21
+ import { renderTopicXml } from './editor/topicRender';
22
+ import { collectMapEntries, getMapTitleText } from './render/mapTypeMap';
23
+ import { topicPathOf } from './bookRender';
24
+ import { pruneExcluded } from './profiling';
25
+ function escapeHtml(s) {
26
+ return s
27
+ .replace(/&/g, '&amp;')
28
+ .replace(/</g, '&lt;')
29
+ .replace(/>/g, '&gt;')
30
+ .replace(/"/g, '&quot;')
31
+ .replace(/'/g, '&#39;');
32
+ }
33
+ function roleHtml(entry) {
34
+ return entry?.role ? `<p class="dita-site-role">${escapeHtml(entry.role)}</p>` : '';
35
+ }
36
+ function decodeXmlText(s) {
37
+ return s.replace(/&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);/gi, (all, name) => {
38
+ const lower = name.toLowerCase();
39
+ if (lower === 'amp')
40
+ return '&';
41
+ if (lower === 'lt')
42
+ return '<';
43
+ if (lower === 'gt')
44
+ return '>';
45
+ if (lower === 'quot')
46
+ return '"';
47
+ if (lower === 'apos')
48
+ return "'";
49
+ const code = lower.startsWith('#x') ? parseInt(lower.slice(2), 16) : parseInt(lower.slice(1), 10);
50
+ return Number.isFinite(code) ? String.fromCodePoint(code) : all;
51
+ });
52
+ }
53
+ /**
54
+ * A topic file's first <title>, cheaply -- no DOM and no render. The sidebar
55
+ * only needs a label, and maps routinely leave entries unnamed. Explicit map
56
+ * navtitles win (buildSiteNav only calls this when the map named nothing), so
57
+ * a well-authored map pays no file reads here. Keyrefs in a title are filled
58
+ * from the map's key space before tags are stripped.
59
+ */
60
+ /** The first <title>'s markup, before keyrefs are filled; undefined if there is none. */
61
+ function rawTitleFromXml(xml) {
62
+ let text;
63
+ try {
64
+ text = preprocessEntities(xml);
65
+ }
66
+ catch {
67
+ return undefined;
68
+ }
69
+ const withoutComments = text.replace(/<!--[\s\S]*?-->/g, '');
70
+ return /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(withoutComments)?.[1];
71
+ }
72
+ function finishTitle(raw, resolveKey) {
73
+ const withKeys = raw.replace(/<[^>]*\bkeyref=(?:"([^"]+)"|'([^']+)')[^>]*\/?>/gi, (all, doubleQuoted, singleQuoted) => resolveKey(decodeXmlText(doubleQuoted ?? singleQuoted ?? '')) ?? all);
74
+ const plain = decodeXmlText(withKeys
75
+ .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1')
76
+ .replace(/<[^>]+>/g, ''))
77
+ .replace(/\s+/g, ' ')
78
+ .trim();
79
+ return plain || undefined;
80
+ }
81
+ /** modified time + size, or undefined when the file cannot be statted (then nothing is cached). */
82
+ function fileStamp(absPath) {
83
+ try {
84
+ const st = statSync(absPath);
85
+ return `${st.mtimeMs}:${st.size}`;
86
+ }
87
+ catch {
88
+ return undefined;
89
+ }
90
+ }
91
+ function pageOpen(absPath, depth) {
92
+ const depthAttr = depth === undefined ? '' : ` data-depth="${depth}"`;
93
+ return `<article class="dita-site-page" data-dita-book-file="${escapeHtml(absPath)}"${depthAttr}>`;
94
+ }
95
+ /**
96
+ * Builds the sidebar manifest. Depth is compacted: an entry dropped here
97
+ * (resource-only, duplicate topic, or a childless href-less entry) leaves no
98
+ * hole above its surviving descendants. The caller resolves the current page
99
+ * from `members`.
100
+ */
101
+ function buildSiteNav(entries, docDir, readFile, resolveKey, dependencies, titleCache) {
102
+ const nav = [];
103
+ const members = [];
104
+ const seen = new Set();
105
+ const survivingAncestors = [];
106
+ for (let i = 0; i < entries.length; i++) {
107
+ const entry = entries[i];
108
+ while (survivingAncestors.length > 0 &&
109
+ survivingAncestors[survivingAncestors.length - 1] >= entry.depth) {
110
+ survivingAncestors.pop();
111
+ }
112
+ const depth = survivingAncestors.length;
113
+ if (entry.resourceOnly)
114
+ continue;
115
+ const absPath = topicPathOf(entry, docDir);
116
+ if (absPath) {
117
+ if (seen.has(absPath))
118
+ continue;
119
+ seen.add(absPath);
120
+ members.push(absPath);
121
+ dependencies.add(absPath);
122
+ let title = entry.displayName;
123
+ if (!entry.displayNameExplicit) {
124
+ try {
125
+ const stamp = titleCache ? fileStamp(absPath) : undefined;
126
+ const hit = stamp !== undefined ? titleCache?.get(absPath) : undefined;
127
+ let raw;
128
+ if (hit && hit.stamp === stamp) {
129
+ raw = hit.title;
130
+ }
131
+ else {
132
+ raw = rawTitleFromXml(readFile(absPath)) ?? null;
133
+ if (stamp !== undefined)
134
+ titleCache?.set(absPath, { stamp, title: raw });
135
+ }
136
+ title = (raw === null ? undefined : finishTitle(raw, resolveKey)) ?? title;
137
+ }
138
+ catch {
139
+ // Missing or unreadable: the map's own fallback label is still
140
+ // better than dropping the page from the sidebar.
141
+ }
142
+ }
143
+ nav.push({
144
+ absPath,
145
+ title,
146
+ depth,
147
+ role: entry.role,
148
+ href: entry.href,
149
+ });
150
+ survivingAncestors.push(entry.depth);
151
+ continue;
152
+ }
153
+ // A href that resolved to nothing is an external link, a PDF, a .ditamap
154
+ // that wasn't expanded, or a fragment-only reference. None is a page.
155
+ if (entry.href)
156
+ continue;
157
+ if (!entry.displayName)
158
+ continue;
159
+ const hasChildren = i + 1 < entries.length && entries[i + 1].depth > entry.depth;
160
+ if (!hasChildren)
161
+ continue;
162
+ nav.push({
163
+ title: entry.displayName,
164
+ depth,
165
+ role: entry.role,
166
+ isGroup: true,
167
+ });
168
+ survivingAncestors.push(entry.depth);
169
+ }
170
+ return { entries: nav, members };
171
+ }
172
+ export function renderSiteXml(input) {
173
+ const doc = parseDitamap(preprocessEntities(input.xml));
174
+ const dependencies = input.collectDependencies ?? new Set();
175
+ const readFile = input.readFile ?? ((path) => readSourceText(path, 'utf-8'));
176
+ const read = (path, _enc) => {
177
+ dependencies.add(resolve(path));
178
+ return readFile(path);
179
+ };
180
+ expandDitamapRefs(doc.root, input.docDir, read);
181
+ pruneExcluded(doc.root, input.filter);
182
+ const keyMap = input.keyMap ?? new Map();
183
+ const resolveKey = (key) => keyMap.get(key);
184
+ const mapEntries = collectMapEntries(doc.root, resolveKey, input.roleFormat);
185
+ const title = getMapTitleText(doc.root, resolveKey);
186
+ const { entries, members } = buildSiteNav(mapEntries, input.docDir, readFile, resolveKey, dependencies, input.titleCache);
187
+ // The page is a dependency whether it exists or not: creating a missing
188
+ // topic should make the site re-render, just like editing an existing one.
189
+ for (const member of members)
190
+ dependencies.add(member);
191
+ const requested = input.current ? resolve(input.current) : undefined;
192
+ const current = requested && members.includes(requested) ? requested : members[0];
193
+ const currentEntry = entries.find((entry) => entry.absPath === current);
194
+ if (!current) {
195
+ const empty = input.labels?.noTopics ?? 'This map has no topics.';
196
+ return {
197
+ html: `<article class="dita-site-page dita-site-empty">` +
198
+ `<p class="dita-site-empty-text">${escapeHtml(empty)}</p></article>`,
199
+ title,
200
+ entries,
201
+ members,
202
+ };
203
+ }
204
+ let xml;
205
+ try {
206
+ xml = readFile(current);
207
+ }
208
+ catch {
209
+ const missing = input.labels?.missingTopic ?? 'Missing topic';
210
+ return {
211
+ html: pageOpen(current, currentEntry?.depth) +
212
+ `${roleHtml(currentEntry)}` +
213
+ `<p class="dita-site-missing">${escapeHtml(missing)}: ` +
214
+ `<code>${escapeHtml(currentEntry?.href ?? current)}</code></p></article>`,
215
+ title,
216
+ entries,
217
+ members,
218
+ current,
219
+ };
220
+ }
221
+ const topicDir = dirname(current);
222
+ const asWebviewUri = (relPath) => {
223
+ if (!input.toResourceUrl)
224
+ return '';
225
+ return input.toResourceUrl(resolve(topicDir, decodeHrefPart(relPath)));
226
+ };
227
+ const result = renderTopicXml({
228
+ xml,
229
+ docDir: topicDir,
230
+ keyMap,
231
+ asWebviewUri,
232
+ // One topic per page: every topic is a top-level heading here, whatever
233
+ // its nesting depth in the map (that depth is the sidebar's business).
234
+ headingLevel: 1,
235
+ uiLanguage: input.uiLanguage,
236
+ collectDependencies: dependencies,
237
+ bookMembers: new Set(members),
238
+ docFile: current,
239
+ markConrefs: true,
240
+ });
241
+ if (result.error !== undefined) {
242
+ return {
243
+ html: pageOpen(current, currentEntry?.depth) +
244
+ `${roleHtml(currentEntry)}` +
245
+ `<p class="dita-site-error">${escapeHtml(result.error)}</p></article>`,
246
+ title,
247
+ entries,
248
+ members,
249
+ current,
250
+ };
251
+ }
252
+ return {
253
+ html: pageOpen(current, currentEntry?.depth) +
254
+ `${roleHtml(currentEntry)}${result.html}</article>`,
255
+ title,
256
+ topicTitle: result.title,
257
+ entries,
258
+ members,
259
+ current,
260
+ };
261
+ }
package/package.json CHANGED
@@ -1,53 +1,55 @@
1
- {
2
- "name": "@dita-viewer/core",
3
- "version": "0.2.0",
4
- "description": "Host-neutral DITA parsing and HTML rendering core, shared by the VS Code DITA Viewer and obsidian-dita.",
5
- "keywords": [
6
- "dita",
7
- "dita-ot",
8
- "xml",
9
- "documentation",
10
- "renderer",
11
- "obsidian",
12
- "vscode"
13
- ],
14
- "homepage": "https://github.com/aREversez/obsidian-dita/tree/main/packages/dita-core#readme",
15
- "bugs": {
16
- "url": "https://github.com/aREversez/obsidian-dita/issues"
17
- },
18
- "repository": {
19
- "type": "git",
20
- "url": "git+https://github.com/aREversez/obsidian-dita.git",
21
- "directory": "packages/dita-core"
22
- },
23
- "license": "MIT",
24
- "author": "aREversez",
25
- "main": "./dist/index.js",
26
- "types": "./dist/index.d.ts",
27
- "exports": {
28
- ".": {
29
- "types": "./dist/index.d.ts",
30
- "default": "./dist/index.js"
31
- },
32
- "./styles/dita-content.css": "./styles/dita-content.css",
33
- "./styles/TOKENS.md": "./styles/TOKENS.md"
34
- },
35
- "files": [
36
- "dist",
37
- "styles",
38
- "!dist/**/*.map"
39
- ],
40
- "scripts": {
41
- "typecheck": "tsc --noEmit -p tsconfig.json",
42
- "build": "tsc -p tsconfig.build.json",
43
- "pretest": "node -e \"require('fs').rmSync('dist-test',{recursive:true,force:true})\" && tsc -p tsconfig.test.json",
44
- "test": "mocha --config .mocharc.json",
45
- "prepublishOnly": "npm run build"
46
- },
47
- "dependencies": {
48
- "sax": "^1.4.1"
49
- },
50
- "publishConfig": {
51
- "access": "public"
52
- }
53
- }
1
+ {
2
+ "name": "@dita-viewer/core",
3
+ "version": "0.2.2",
4
+ "description": "Host-neutral DITA parsing and HTML rendering core, shared by the VS Code DITA Viewer and obsidian-dita.",
5
+ "keywords": [
6
+ "dita",
7
+ "dita-ot",
8
+ "xml",
9
+ "documentation",
10
+ "renderer",
11
+ "obsidian",
12
+ "vscode"
13
+ ],
14
+ "homepage": "https://github.com/aREversez/VS-Code-DITA-Viewer/tree/main/packages/core#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/aREversez/VS-Code-DITA-Viewer/issues"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/aREversez/VS-Code-DITA-Viewer.git",
21
+ "directory": "packages/core"
22
+ },
23
+ "license": "MIT",
24
+ "author": "aREversez",
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "module": "./dist-esm/index.js",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "./styles/dita-content.css": "./styles/dita-content.css",
34
+ "./styles/TOKENS.md": "./styles/TOKENS.md"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "dist-esm",
39
+ "styles",
40
+ "!dist/**/*.map"
41
+ ],
42
+ "scripts": {
43
+ "typecheck": "tsc --noEmit -p tsconfig.json",
44
+ "build": "tsc -p tsconfig.build.json && tsc -p tsconfig.esm.json && node scripts/mark-esm.cjs",
45
+ "pretest": "node -e \"require('fs').rmSync('dist-test',{recursive:true,force:true})\" && tsc -p tsconfig.test.json",
46
+ "test": "mocha --config .mocharc.json",
47
+ "prepublishOnly": "npm run build"
48
+ },
49
+ "dependencies": {
50
+ "sax": "^1.4.1"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ }
55
+ }
package/styles/TOKENS.md CHANGED
@@ -1,38 +1,59 @@
1
- # Host tokens
2
-
3
- `dita-content.css` does not know which application shows the rendered DITA. It
4
- reads the custom properties below; the host defines them on the element that
5
- carries the content (`:host` for a Shadow DOM, `:root` for a document).
6
-
7
- | Token | Meaning |
8
- | --- | --- |
9
- | `--dita-fg` | Body text colour |
10
- | `--dita-fg-muted` | Secondary text (shortdesc, captions, hints) |
11
- | `--dita-bg` | Page background |
12
- | `--dita-bg-elevated` | Background of floating chrome (menus, toasts) |
13
- | `--dita-border` | Rules, table borders, dividers |
14
- | `--dita-focus` | Focus ring and progress accent |
15
- | `--dita-hover-bg` | Hover / highlighted row background |
16
- | `--dita-selected-fg` | Text on a selected row |
17
- | `--dita-link` | Link colour |
18
- | `--dita-code-bg` | Code block background |
19
- | `--dita-code-inline-bg` | Inline code and language-label background |
20
- | `--dita-font` | Body font family |
21
-
22
- Every use inside the stylesheet carries a fallback, so a host that defines only
23
- some tokens still renders legibly.
24
-
25
- ## The palette
26
-
27
- Callouts, profiling highlights, index chips and conref tints use `--color-*`
28
- variables (`--color-note-bg`, `--color-warning-border`, `--color-profiling-bg`,
29
- …). The stylesheet ships light and dark defaults for them. A host may redefine
30
- any of them; deriving them from its own palette (for example with `color-mix`
31
- against `--dita-bg`) is what makes them follow the active theme, in both light
32
- and dark, without a per-theme list.
33
-
34
- ## Dark mode
35
-
36
- Hosts that cannot express a colour as a function of their own variables may use
37
- the scheme switch: `.vscode-dark` on the document root, or
38
- `data-scheme="dark"` on a Shadow DOM host.
1
+ # Host tokens
2
+
3
+ `dita-content.css` does not know which application shows the rendered DITA. It
4
+ reads the custom properties below; the host defines them on the element that
5
+ carries the content (`:host` for a Shadow DOM, `:root` for a document).
6
+
7
+ | Token | Meaning |
8
+ | --- | --- |
9
+ | `--dita-fg` | Body text colour |
10
+ | `--dita-fg-muted` | Secondary text (shortdesc, captions, hints) |
11
+ | `--dita-bg` | Page background |
12
+ | `--dita-bg-elevated` | Background of floating chrome (menus, toasts) |
13
+ | `--dita-border` | Rules, table borders, dividers |
14
+ | `--dita-focus` | Focus ring and progress accent |
15
+ | `--dita-hover-bg` | Hover / highlighted row background |
16
+ | `--dita-selected-fg` | Text on a selected row |
17
+ | `--dita-link` | Link colour |
18
+ | `--dita-code-bg` | Code block background |
19
+ | `--dita-code-inline-bg` | Inline code and language-label background |
20
+ | `--dita-font` | Body font family |
21
+
22
+ Every use inside the stylesheet carries a fallback, so a host that defines only
23
+ some tokens still renders legibly.
24
+
25
+ ## Optional tokens for floating chrome
26
+
27
+ The image button, the right-click menu and the copy toast can be coloured
28
+ separately from the rest. A host that has no separate colours defines none of
29
+ these: each one falls back to the token in the last column, which is what the
30
+ stylesheet used before they existed.
31
+
32
+ | Token | Meaning | Falls back to |
33
+ | --- | --- | --- |
34
+ | `--dita-btn-border` | Border of the image toolbar buttons | `--dita-border` |
35
+ | `--dita-btn-fg` | Text of the image toolbar buttons | `--dita-fg` |
36
+ | `--dita-menu-bg` | Context menu background | `--dita-bg-elevated`, then `--dita-bg` |
37
+ | `--dita-menu-border` | Context menu border | `--dita-border` |
38
+ | `--dita-menu-fg` | Context menu item text | `--dita-fg` |
39
+ | `--dita-menu-hover-bg` | Hovered or focused menu item background | `--dita-hover-bg` |
40
+ | `--dita-menu-hover-fg` | Hovered or focused menu item text | `--dita-selected-fg`, then `--dita-fg` |
41
+ | `--dita-menu-sep` | Divider between menu groups | `--dita-border` |
42
+ | `--dita-toast-bg` | Copy toast background | `--dita-bg-elevated`, then `--dita-bg` |
43
+ | `--dita-toast-border` | Copy toast border | `--dita-border` |
44
+ | `--dita-toast-fg` | Copy toast text | `--dita-fg` |
45
+
46
+ ## The palette
47
+
48
+ Callouts, profiling highlights, index chips and conref tints use `--color-*`
49
+ variables (`--color-note-bg`, `--color-warning-border`, `--color-profiling-bg`,
50
+ …). The stylesheet ships light and dark defaults for them. A host may redefine
51
+ any of them; deriving them from its own palette (for example with `color-mix`
52
+ against `--dita-bg`) is what makes them follow the active theme, in both light
53
+ and dark, without a per-theme list.
54
+
55
+ ## Dark mode
56
+
57
+ Hosts that cannot express a colour as a function of their own variables may use
58
+ the scheme switch: `.vscode-dark` on the document root, or
59
+ `data-scheme="dark"` on a Shadow DOM host.