@dita-viewer/core 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +90 -58
- package/dist/editor/renderContext.d.ts +7 -0
- package/dist/editor/renderContext.js +24 -0
- package/dist/editor/topicRender.d.ts +9 -0
- package/dist/editor/topicRender.js +4 -2
- package/dist/index.js +3 -3
- package/dist/language/ditaLanguageUtils.js +2 -0
- package/dist/profiling.d.ts +9 -3
- package/dist/profiling.js +12 -6
- package/dist/render/baseTypeMap.js +28 -2
- package/dist/render/mapTypeMap.js +23 -23
- package/dist/render/renderer.d.ts +24 -0
- package/dist/render/renderer.js +36 -9
- package/dist-esm/bookRender.js +145 -0
- package/dist-esm/completion.js +142 -0
- package/dist-esm/completionData.js +155 -0
- package/dist-esm/diagnostics.js +378 -0
- package/dist-esm/editor/conkeyref.js +104 -0
- package/dist-esm/editor/keySpace.js +201 -0
- package/dist-esm/editor/refResolvers.js +633 -0
- package/dist-esm/editor/renderContext.js +138 -0
- package/dist-esm/editor/sourceText.js +142 -0
- package/dist-esm/editor/topicRender.js +328 -0
- package/dist-esm/index.js +66 -0
- package/dist-esm/keyMapForDocument.js +23 -0
- package/dist-esm/language/ditaLanguageUtils.js +659 -0
- package/dist-esm/language/referenceableFiles.js +108 -0
- package/dist-esm/mapRender.js +24 -0
- package/dist-esm/package.json +1 -0
- package/dist-esm/parser/ditaParser.js +409 -0
- package/dist-esm/parser/domTypes.js +1 -0
- package/dist-esm/parser/mapTagMap.js +77 -0
- package/dist-esm/parser/namedEntities.js +321 -0
- package/dist-esm/parser/standardTagMap.js +393 -0
- package/dist-esm/profiling.js +224 -0
- package/dist-esm/render/baseTypeMap.js +1057 -0
- package/dist-esm/render/cjkSpacing.js +94 -0
- package/dist-esm/render/mapTypeMap.js +568 -0
- package/dist-esm/render/renderer.js +519 -0
- package/dist-esm/siteRender.js +261 -0
- package/package.json +55 -53
- package/styles/TOKENS.md +59 -38
- package/styles/dita-content.css +1171 -1157
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
// Reference-resolution primitives, split out of ditaRenderUtils.ts.
|
|
2
|
+
//
|
|
3
|
+
// This is a LEAF module: it imports only the parser, the render tag maps,
|
|
4
|
+
// source text and Node fs/path -- never renderContext or ditaRenderUtils.
|
|
5
|
+
// Pulling these helpers down here is what unties the renderContext <->
|
|
6
|
+
// ditaRenderUtils cycle (P2/P3 introduced renderContext; the resolvers it
|
|
7
|
+
// needs lived in the giant file that also builds render contexts, so the two
|
|
8
|
+
// imported each other -- directly, and transitively through keySpace ->
|
|
9
|
+
// expandDitamapRefs). renderContext, keySpace and ditaRenderUtils now all sit
|
|
10
|
+
// ABOVE this module; nothing below reaches back up. Behaviour is unchanged --
|
|
11
|
+
// this is a pure move of code lifted verbatim from ditaRenderUtils.ts.
|
|
12
|
+
import { existsSync, openSync, readSync, closeSync, statSync } from 'fs';
|
|
13
|
+
import { resolve, isAbsolute, extname, dirname, relative, normalize } from 'path';
|
|
14
|
+
import { parseDita, parseDitamap, preprocessEntities } from '../parser/ditaParser';
|
|
15
|
+
import { extractText, getMapTitleText, isDitamapRef } from '../render/mapTypeMap';
|
|
16
|
+
import { readSourceText } from './sourceText';
|
|
17
|
+
// ── Image dimensions (for reserving layout space before the image loads) ──
|
|
18
|
+
//
|
|
19
|
+
// <img loading="lazy"> with no width/height reserves zero space until the
|
|
20
|
+
// browser actually decodes the file, then snaps the surrounding content
|
|
21
|
+
// down to make room -- barely noticeable for a single image in the topic
|
|
22
|
+
// preview, but Book mode composites many topics' worth of images into one
|
|
23
|
+
// long page, so scrolling through it means repeatedly landing on a fresh
|
|
24
|
+
// batch of not-yet-loaded images and watching everything below them lurch
|
|
25
|
+
// as each one finally loads. Reading real width/height from the file
|
|
26
|
+
// (only the header, not the whole image -- a bounded 64KB read handles
|
|
27
|
+
// every format below even for a multi-MB JPEG with a large EXIF/ICC
|
|
28
|
+
// profile before its SOF marker) lets width/height attributes go on the
|
|
29
|
+
// <img> tag, which combined with this project's existing img{height:auto}
|
|
30
|
+
// makes the browser reserve the correct *aspect ratio* box immediately,
|
|
31
|
+
// still scaling responsively via max-width -- not a fixed pixel size.
|
|
32
|
+
// This only fills a gap: an explicit @width/@height on the DITA <image>
|
|
33
|
+
// element itself always wins (see the image renderer in baseTypeMap.ts).
|
|
34
|
+
const IMAGE_HEADER_READ_BYTES = 65536;
|
|
35
|
+
function readHeaderBytes(filePath, maxBytes) {
|
|
36
|
+
let fd;
|
|
37
|
+
try {
|
|
38
|
+
fd = openSync(filePath, 'r');
|
|
39
|
+
const buf = Buffer.alloc(maxBytes);
|
|
40
|
+
const bytesRead = readSync(fd, buf, 0, maxBytes, 0);
|
|
41
|
+
return buf.subarray(0, bytesRead);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
if (fd !== undefined) {
|
|
48
|
+
try {
|
|
49
|
+
closeSync(fd);
|
|
50
|
+
}
|
|
51
|
+
catch { /* already closed / never opened */ }
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function readPngDimensions(buf) {
|
|
56
|
+
// 8-byte signature, then a 4-byte chunk length + "IHDR" + width (4B BE) + height (4B BE)
|
|
57
|
+
if (buf.length < 24)
|
|
58
|
+
return undefined;
|
|
59
|
+
if (buf.readUInt32BE(0) !== 0x89504e47 || buf.readUInt32BE(4) !== 0x0d0a1a0a)
|
|
60
|
+
return undefined;
|
|
61
|
+
if (buf.toString('ascii', 12, 16) !== 'IHDR')
|
|
62
|
+
return undefined;
|
|
63
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
64
|
+
}
|
|
65
|
+
function readGifDimensions(buf) {
|
|
66
|
+
if (buf.length < 10)
|
|
67
|
+
return undefined;
|
|
68
|
+
const sig = buf.toString('ascii', 0, 6);
|
|
69
|
+
if (sig !== 'GIF87a' && sig !== 'GIF89a')
|
|
70
|
+
return undefined;
|
|
71
|
+
return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
|
|
72
|
+
}
|
|
73
|
+
function readBmpDimensions(buf) {
|
|
74
|
+
if (buf.length < 26)
|
|
75
|
+
return undefined;
|
|
76
|
+
if (buf.toString('ascii', 0, 2) !== 'BM')
|
|
77
|
+
return undefined;
|
|
78
|
+
const width = buf.readInt32LE(18);
|
|
79
|
+
const height = buf.readInt32LE(22);
|
|
80
|
+
// A negative height means a top-down (rather than the default
|
|
81
|
+
// bottom-up) bitmap -- the magnitude is still the real pixel height.
|
|
82
|
+
return { width: Math.abs(width), height: Math.abs(height) };
|
|
83
|
+
}
|
|
84
|
+
function readJpegDimensions(buf) {
|
|
85
|
+
if (buf.length < 4 || buf.readUInt16BE(0) !== 0xffd8)
|
|
86
|
+
return undefined;
|
|
87
|
+
let offset = 2;
|
|
88
|
+
while (offset + 4 <= buf.length) {
|
|
89
|
+
if (buf[offset] !== 0xff) {
|
|
90
|
+
offset++;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const marker = buf[offset + 1];
|
|
94
|
+
// Markers with no payload to skip over
|
|
95
|
+
if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
|
|
96
|
+
offset += 2;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (offset + 4 > buf.length)
|
|
100
|
+
break;
|
|
101
|
+
const segmentLength = buf.readUInt16BE(offset + 2);
|
|
102
|
+
const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
|
|
103
|
+
if (isSof) {
|
|
104
|
+
if (offset + 9 > buf.length)
|
|
105
|
+
return undefined; // truncated read -- header didn't fit in what we sampled
|
|
106
|
+
return { height: buf.readUInt16BE(offset + 5), width: buf.readUInt16BE(offset + 7) };
|
|
107
|
+
}
|
|
108
|
+
if (marker === 0xda)
|
|
109
|
+
return undefined; // Start of Scan reached with no SOF found
|
|
110
|
+
offset += 2 + segmentLength;
|
|
111
|
+
}
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
function readSvgDimensions(buf) {
|
|
115
|
+
const text = buf.toString('utf-8');
|
|
116
|
+
const svgTagMatch = text.match(/<svg\b[^>]*>/);
|
|
117
|
+
if (!svgTagMatch)
|
|
118
|
+
return undefined;
|
|
119
|
+
const tag = svgTagMatch[0];
|
|
120
|
+
const widthMatch = tag.match(/\bwidth="([\d.]+)(?:px)?"/);
|
|
121
|
+
const heightMatch = tag.match(/\bheight="([\d.]+)(?:px)?"/);
|
|
122
|
+
if (widthMatch && heightMatch) {
|
|
123
|
+
const width = parseFloat(widthMatch[1]);
|
|
124
|
+
const height = parseFloat(heightMatch[1]);
|
|
125
|
+
if (width > 0 && height > 0)
|
|
126
|
+
return { width, height };
|
|
127
|
+
}
|
|
128
|
+
// Percentage/unitless width+height, or neither present -- fall back to
|
|
129
|
+
// viewBox, which every real-world SVG has anyway and gives an aspect
|
|
130
|
+
// ratio even when absolute pixel dimensions weren't authored at all.
|
|
131
|
+
const viewBoxMatch = tag.match(/\bviewBox="\s*[\d.-]+\s+[\d.-]+\s+([\d.]+)\s+([\d.]+)\s*"/);
|
|
132
|
+
if (viewBoxMatch) {
|
|
133
|
+
const width = parseFloat(viewBoxMatch[1]);
|
|
134
|
+
const height = parseFloat(viewBoxMatch[2]);
|
|
135
|
+
if (width > 0 && height > 0)
|
|
136
|
+
return { width, height };
|
|
137
|
+
}
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
const IMAGE_DIMENSION_READERS = {
|
|
141
|
+
'.png': readPngDimensions,
|
|
142
|
+
'.gif': readGifDimensions,
|
|
143
|
+
'.bmp': readBmpDimensions,
|
|
144
|
+
'.jpg': readJpegDimensions,
|
|
145
|
+
'.jpeg': readJpegDimensions,
|
|
146
|
+
'.svg': readSvgDimensions,
|
|
147
|
+
};
|
|
148
|
+
/**
|
|
149
|
+
* Reads just enough of an image file to determine its natural pixel
|
|
150
|
+
* dimensions, without loading or decoding the whole file. Returns
|
|
151
|
+
* undefined for anything unreadable, unrecognized, or corrupt -- callers
|
|
152
|
+
* treat that as "no dimensions available" and fall back to the previous
|
|
153
|
+
* behavior (no width/height reserved), never an error.
|
|
154
|
+
*
|
|
155
|
+
* Cached by path + mtime: every source edit re-renders the whole topic
|
|
156
|
+
* (see postContentUpdate in DitaViewerProvider.ts/MapViewerProvider.ts),
|
|
157
|
+
* which calls this again for every image in it regardless of whether that
|
|
158
|
+
* particular image had anything to do with what was just typed. A cheap
|
|
159
|
+
* stat() to check mtime, versus re-opening and re-parsing the header, is
|
|
160
|
+
* the difference that matters for a topic with a lot of images -- the
|
|
161
|
+
* common case is the same unchanged images on every keystroke, not new
|
|
162
|
+
* ones. Bounded by IMAGE_DIMENSIONS_CACHE_MAX with oldest-unused-first
|
|
163
|
+
* eviction (a cache hit re-inserts the entry, so it counts as recently
|
|
164
|
+
* used), keeping long sessions that preview many distinct images from
|
|
165
|
+
* growing the Map without limit -- entries are tiny (a path plus two
|
|
166
|
+
* numbers), but the project's rule is that every cache stays bounded and
|
|
167
|
+
* clearable, and this one is cleared alongside the rest on deactivation.
|
|
168
|
+
*/
|
|
169
|
+
const imageDimensionsCache = new Map();
|
|
170
|
+
// One entry per distinct image file ever previewed; bound it the same way
|
|
171
|
+
// keyMapCache is bounded in DitaViewerProvider.ts.
|
|
172
|
+
export const IMAGE_DIMENSIONS_CACHE_MAX = 1000;
|
|
173
|
+
export function clearImageDimensionsCache() {
|
|
174
|
+
imageDimensionsCache.clear();
|
|
175
|
+
}
|
|
176
|
+
export function readImageDimensions(filePath) {
|
|
177
|
+
let mtimeMs;
|
|
178
|
+
try {
|
|
179
|
+
mtimeMs = statSync(filePath).mtimeMs;
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
// Not statable (doesn't exist, permissions, ...) -- nothing to read,
|
|
183
|
+
// and any previous cache entry for this path is now stale.
|
|
184
|
+
imageDimensionsCache.delete(filePath);
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
const cached = imageDimensionsCache.get(filePath);
|
|
188
|
+
if (cached && cached.mtimeMs === mtimeMs) {
|
|
189
|
+
// Re-insert so a cache hit keeps the entry from being the oldest
|
|
190
|
+
// (and therefore first-evicted) candidate.
|
|
191
|
+
imageDimensionsCache.delete(filePath);
|
|
192
|
+
imageDimensionsCache.set(filePath, cached);
|
|
193
|
+
return cached.dimensions;
|
|
194
|
+
}
|
|
195
|
+
const reader = IMAGE_DIMENSION_READERS[extname(filePath).toLowerCase()];
|
|
196
|
+
let dimensions;
|
|
197
|
+
if (reader) {
|
|
198
|
+
const buf = readHeaderBytes(filePath, IMAGE_HEADER_READ_BYTES);
|
|
199
|
+
if (buf) {
|
|
200
|
+
try {
|
|
201
|
+
dimensions = reader(buf);
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
dimensions = undefined;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (imageDimensionsCache.size >= IMAGE_DIMENSIONS_CACHE_MAX) {
|
|
209
|
+
const oldest = imageDimensionsCache.keys().next().value;
|
|
210
|
+
if (oldest !== undefined)
|
|
211
|
+
imageDimensionsCache.delete(oldest);
|
|
212
|
+
}
|
|
213
|
+
imageDimensionsCache.set(filePath, { mtimeMs, dimensions });
|
|
214
|
+
return dimensions;
|
|
215
|
+
}
|
|
216
|
+
export function makeFileCache(docDir) {
|
|
217
|
+
const cache = new Map();
|
|
218
|
+
// Which file each resolved target element came from. A reference chain
|
|
219
|
+
// (A -> B -> C) needs it: B's own conref is relative to B's file, and a
|
|
220
|
+
// same-file "#id" in B points into B, not into the document being rendered.
|
|
221
|
+
const origins = new WeakMap();
|
|
222
|
+
function noteOrigin(el, origin) {
|
|
223
|
+
origins.set(el, origin);
|
|
224
|
+
}
|
|
225
|
+
function originOf(el) {
|
|
226
|
+
return origins.get(el);
|
|
227
|
+
}
|
|
228
|
+
function loadFile(filePath) {
|
|
229
|
+
return loadAbsPath(resolve(docDir, decodeHrefPart(filePath)));
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Parse-and-cache a file already addressed by absolute path. loadFile is the
|
|
233
|
+
* docDir-relative convenience wrapper; conkeyref needs this directly because
|
|
234
|
+
* a key's href resolves against the *defining map's* directory, not the topic
|
|
235
|
+
* being rendered. Sharing one cache keeps a conkeyref target and a conref
|
|
236
|
+
* target of the same file parsed once, and lands both in touchedFiles.
|
|
237
|
+
*/
|
|
238
|
+
function loadAbsPath(absPath) {
|
|
239
|
+
if (cache.has(absPath))
|
|
240
|
+
return cache.get(absPath);
|
|
241
|
+
if (!existsSync(absPath)) {
|
|
242
|
+
cache.set(absPath, undefined);
|
|
243
|
+
return undefined;
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
const content = readSourceText(absPath, 'utf-8');
|
|
247
|
+
// A .ditamap parses with the map tag table: without it, a map's own
|
|
248
|
+
// <title>/<booktitle> would carry the topic parser's baseTypes and
|
|
249
|
+
// map-title consumers (the Explorer tree's submap rows, via
|
|
250
|
+
// makeFileTitleResolver) would see nothing they recognize.
|
|
251
|
+
const doc = /\.ditamap$/i.test(absPath)
|
|
252
|
+
? parseDitamap(preprocessEntities(content))
|
|
253
|
+
: parseDita(preprocessEntities(content));
|
|
254
|
+
cache.set(absPath, doc.root);
|
|
255
|
+
return doc.root;
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
cache.set(absPath, undefined);
|
|
259
|
+
return undefined;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
function findElementById(root, targetId) {
|
|
263
|
+
if (root.attributes?.id === targetId)
|
|
264
|
+
return root;
|
|
265
|
+
for (const child of root.children || []) {
|
|
266
|
+
const found = findElementById(child, targetId);
|
|
267
|
+
if (found)
|
|
268
|
+
return found;
|
|
269
|
+
}
|
|
270
|
+
return undefined;
|
|
271
|
+
}
|
|
272
|
+
function findTitleOfElement(root, elementId, resolveKey) {
|
|
273
|
+
const el = findElementById(root, elementId);
|
|
274
|
+
if (!el)
|
|
275
|
+
return undefined;
|
|
276
|
+
const titleChild = (el.children || []).find((c) => c.type === 'element' && c.baseType === 'topic/title');
|
|
277
|
+
if (!titleChild)
|
|
278
|
+
return undefined;
|
|
279
|
+
return extractText(titleChild, resolveKey);
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Every absolute path this cache was asked for, including ones that turned
|
|
283
|
+
* out not to exist (those are memoized as undefined). Callers use it as the
|
|
284
|
+
* dependency set of a render: rendered HTML can only be reused for as long
|
|
285
|
+
* as none of these files changes. A missing file has to be reported as
|
|
286
|
+
* carefully as a present one, since creating it later is exactly the kind
|
|
287
|
+
* of change that must invalidate.
|
|
288
|
+
*/
|
|
289
|
+
function touchedFiles() {
|
|
290
|
+
return [...cache.keys()];
|
|
291
|
+
}
|
|
292
|
+
return { loadFile, loadAbsPath, findElementById, findTitleOfElement, touchedFiles, noteOrigin, originOf };
|
|
293
|
+
}
|
|
294
|
+
export function makeConrefResolver(docDir, ownRoot, sharedCache) {
|
|
295
|
+
const cache = sharedCache ?? makeFileCache(docDir);
|
|
296
|
+
/**
|
|
297
|
+
* `from` is the element that carries the conref when it is a hop inside a
|
|
298
|
+
* chain: its origin decides what a relative path or a same-file "#id" is
|
|
299
|
+
* relative to. Without it the reference belongs to the document being rendered.
|
|
300
|
+
*/
|
|
301
|
+
return (conref, from) => {
|
|
302
|
+
const hashIdx = conref.indexOf('#');
|
|
303
|
+
if (hashIdx < 0)
|
|
304
|
+
return undefined;
|
|
305
|
+
const filePath = conref.substring(0, hashIdx);
|
|
306
|
+
const idPart = conref.substring(hashIdx + 1);
|
|
307
|
+
const parts = idPart.split('/');
|
|
308
|
+
const elementId = parts.length > 1 ? parts[1] : parts[0];
|
|
309
|
+
if (!elementId)
|
|
310
|
+
return undefined;
|
|
311
|
+
const origin = from ? cache.originOf(from) : undefined;
|
|
312
|
+
if (from && !origin)
|
|
313
|
+
return undefined; // cannot place the hop: stop the chain here
|
|
314
|
+
const selfRoot = origin ? origin.root : ownRoot;
|
|
315
|
+
const selfFile = origin?.file;
|
|
316
|
+
// No file path before "#" -- a same-document reference, e.g.
|
|
317
|
+
// conref="#noteId" or the "#./noteId" shorthand some authors use
|
|
318
|
+
// (treating the current file as if it were "./" of itself). docDir on
|
|
319
|
+
// its own resolves to a *directory*, not a file, so handing an empty
|
|
320
|
+
// filePath to loadFile always failed here: existsSync passed (the
|
|
321
|
+
// directory exists), but reading a directory as a file then threw and
|
|
322
|
+
// got silently cached as "not found". Search the document already
|
|
323
|
+
// being rendered instead of touching the filesystem at all.
|
|
324
|
+
if (!filePath) {
|
|
325
|
+
if (!selfRoot)
|
|
326
|
+
return undefined;
|
|
327
|
+
const el = cache.findElementById(selfRoot, elementId);
|
|
328
|
+
if (el)
|
|
329
|
+
cache.noteOrigin(el, { file: selfFile, root: selfRoot });
|
|
330
|
+
return el;
|
|
331
|
+
}
|
|
332
|
+
const baseDir = selfFile ? dirname(selfFile) : docDir;
|
|
333
|
+
const abs = resolve(baseDir, decodeHrefPart(filePath));
|
|
334
|
+
const root = cache.loadAbsPath(abs);
|
|
335
|
+
if (!root)
|
|
336
|
+
return undefined;
|
|
337
|
+
const el = cache.findElementById(root, elementId);
|
|
338
|
+
if (!el)
|
|
339
|
+
return undefined;
|
|
340
|
+
cache.noteOrigin(el, { file: abs, root });
|
|
341
|
+
// Return the entire target element so its tag/baseType is preserved.
|
|
342
|
+
// resolveConrefForNode in the renderer decides whether to replace just
|
|
343
|
+
// the children (same-type conref) or the entire element (cross-type).
|
|
344
|
+
return el;
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
// conrefend extends a conref reference from a single element to a run of
|
|
348
|
+
// elements: everything from the conref target through the conrefend target,
|
|
349
|
+
// inclusive, in source-document order. Per the DITA spec this only applies
|
|
350
|
+
// when both ids resolve to elements that are siblings under the same
|
|
351
|
+
// parent — Oxygen's own conrefend support has the same restriction — so
|
|
352
|
+
// this returns undefined (letting the caller fall back to normal
|
|
353
|
+
// single-target conref handling) rather than guessing at some other
|
|
354
|
+
// relationship when that's not the case.
|
|
355
|
+
export function makeConrefRangeResolver(docDir, ownRoot, sharedCache) {
|
|
356
|
+
const cache = sharedCache ?? makeFileCache(docDir);
|
|
357
|
+
function resolveRef(ref) {
|
|
358
|
+
const hashIdx = ref.indexOf('#');
|
|
359
|
+
if (hashIdx < 0)
|
|
360
|
+
return undefined;
|
|
361
|
+
const filePath = ref.substring(0, hashIdx);
|
|
362
|
+
// Strip the "./" same-document marker before splitting on "/" so a
|
|
363
|
+
// topic-scoped same-document range (e.g. "#./topicId/elementId") lands
|
|
364
|
+
// on the real topic/element pair instead of misreading "." as the
|
|
365
|
+
// topic id and folding the rest of the fragment into a single
|
|
366
|
+
// (unmatchable) id.
|
|
367
|
+
const idPart = ref.substring(hashIdx + 1).replace(/^\.\/+/, '');
|
|
368
|
+
const parts = idPart.split('/');
|
|
369
|
+
const id = parts.length > 1 ? parts[1] : parts[0];
|
|
370
|
+
// No file path before "#" -- a same-document reference, same as the
|
|
371
|
+
// single-target makeConrefResolver above. docDir on its own resolves
|
|
372
|
+
// to a *directory*, not a file, so handing an empty filePath to
|
|
373
|
+
// loadFile always failed here the same way: existsSync passed, but
|
|
374
|
+
// reading a directory as a file then threw and got silently cached as
|
|
375
|
+
// "not found". Search the document already being rendered instead of
|
|
376
|
+
// touching the filesystem at all.
|
|
377
|
+
if (!filePath) {
|
|
378
|
+
if (!ownRoot)
|
|
379
|
+
return undefined;
|
|
380
|
+
return { root: ownRoot, id };
|
|
381
|
+
}
|
|
382
|
+
const root = cache.loadFile(filePath);
|
|
383
|
+
if (!root)
|
|
384
|
+
return undefined;
|
|
385
|
+
return { root, id, file: resolve(docDir, decodeHrefPart(filePath)) };
|
|
386
|
+
}
|
|
387
|
+
function findWithParent(node, targetId, parent) {
|
|
388
|
+
if (node.attributes?.id === targetId && parent)
|
|
389
|
+
return { el: node, parent };
|
|
390
|
+
for (const child of node.children || []) {
|
|
391
|
+
const found = findWithParent(child, targetId, node);
|
|
392
|
+
if (found)
|
|
393
|
+
return found;
|
|
394
|
+
}
|
|
395
|
+
return undefined;
|
|
396
|
+
}
|
|
397
|
+
return (conref, conrefend) => {
|
|
398
|
+
const start = resolveRef(conref);
|
|
399
|
+
const end = resolveRef(conrefend);
|
|
400
|
+
if (!start || !end)
|
|
401
|
+
return undefined;
|
|
402
|
+
const startFound = findWithParent(start.root, start.id, undefined);
|
|
403
|
+
const endFound = findWithParent(end.root, end.id, undefined);
|
|
404
|
+
if (!startFound || !endFound)
|
|
405
|
+
return undefined;
|
|
406
|
+
if (startFound.parent !== endFound.parent)
|
|
407
|
+
return undefined;
|
|
408
|
+
// Filter to element children before indexing: the parser preserves
|
|
409
|
+
// whitespace-only text nodes between sibling elements (parsed with
|
|
410
|
+
// trim:false), which would otherwise get swept into the slice and
|
|
411
|
+
// thrown into the returned range as extra, attribute-less entries.
|
|
412
|
+
// "Sibling" here means sibling *element*, matching what conref/
|
|
413
|
+
// conrefend actually identify (elements with ids), not raw text runs.
|
|
414
|
+
const siblings = (startFound.parent.children || []).filter((c) => c.type === 'element');
|
|
415
|
+
const startIdx = siblings.indexOf(startFound.el);
|
|
416
|
+
const endIdx = siblings.indexOf(endFound.el);
|
|
417
|
+
if (startIdx < 0 || endIdx < 0 || endIdx < startIdx)
|
|
418
|
+
return undefined;
|
|
419
|
+
const run = siblings.slice(startIdx, endIdx + 1);
|
|
420
|
+
// Record where the run lives, so the preview can offer a jump to it. The
|
|
421
|
+
// run sits under one parent (checked above), hence in one file.
|
|
422
|
+
for (const el of run)
|
|
423
|
+
cache.noteOrigin(el, { file: start.file, root: start.root });
|
|
424
|
+
return run;
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
export function makeFileTitleResolver(docDir, sharedCache, resolveKey) {
|
|
428
|
+
const cache = sharedCache ?? makeFileCache(docDir);
|
|
429
|
+
return (href) => {
|
|
430
|
+
// Only local relative references can be resolved from disk — never probe
|
|
431
|
+
// the filesystem for external URLs or absolute paths (on Windows an
|
|
432
|
+
// https:// href would otherwise resolve to a junk docDir\https:\ path).
|
|
433
|
+
if (!href || URL_SCHEME_RE.test(href) || isAbsolute(href))
|
|
434
|
+
return undefined;
|
|
435
|
+
const hashIdx = href.indexOf('#');
|
|
436
|
+
if (hashIdx < 0) {
|
|
437
|
+
// No fragment: only hrefs that look like DITA files get file-level
|
|
438
|
+
// resolution — bare ids (unmatched local anchors that callers pass
|
|
439
|
+
// through) must not be probed as filenames. .ditamap resolves the
|
|
440
|
+
// same way (its own <title>/<mainbooktitle> rather than a topic
|
|
441
|
+
// <title>): the Explorer tree names submap rows by the referenced
|
|
442
|
+
// map's own title, including a duplicate mapref whose children were
|
|
443
|
+
// never spliced in.
|
|
444
|
+
if (!/\.(dita|xml|ditamap)$/i.test(href))
|
|
445
|
+
return undefined;
|
|
446
|
+
const root = cache.loadFile(href);
|
|
447
|
+
if (!root)
|
|
448
|
+
return undefined;
|
|
449
|
+
if (/\.ditamap$/i.test(href))
|
|
450
|
+
return getMapTitleText(root, resolveKey);
|
|
451
|
+
const titleChild = (root.children || []).find((c) => c.type === 'element' && c.baseType === 'topic/title');
|
|
452
|
+
// extractText rather than collectText: a title whose product name or
|
|
453
|
+
// version number is a keyref (the software-manual pattern) must show
|
|
454
|
+
// the key's value, not drop it.
|
|
455
|
+
return titleChild ? extractText(titleChild, resolveKey) : undefined;
|
|
456
|
+
}
|
|
457
|
+
const filePath = href.substring(0, hashIdx);
|
|
458
|
+
const idPart = href.substring(hashIdx + 1);
|
|
459
|
+
const topicId = idPart.split('/')[0];
|
|
460
|
+
const root = cache.loadFile(filePath);
|
|
461
|
+
if (!root)
|
|
462
|
+
return undefined;
|
|
463
|
+
return cache.findTitleOfElement(root, topicId, resolveKey);
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
// ── Default note labels ──
|
|
467
|
+
// Values follow DITA-OT's own strings-en-us.xml / strings-zh-cn.xml bundles
|
|
468
|
+
// (org.dita.base/xsl/common) so the preview matches what a real DITA-OT
|
|
469
|
+
// publish would show. Two intentional deviations from DITA-OT's exact
|
|
470
|
+
// casing, kept for visual consistency across the 13 note types in this
|
|
471
|
+
// project's own UI (DITA-OT itself is inconsistent here — only Caution and
|
|
472
|
+
// Danger are upper-cased there, Warning is not):
|
|
473
|
+
// - Caution/Danger are title case here, not DITA-OT's "CAUTION"/"DANGER"
|
|
474
|
+
// - zh-cn "Notice" is left untranslated even in DITA-OT's own bundle
|
|
475
|
+
// (literally has a `<!--TODO:Notice-->` in the source); this project
|
|
476
|
+
// already ships '注意' for it, kept as-is here.
|
|
477
|
+
// Covers the full DITA 1.3 note/@type enumeration (13 values); 'other' is
|
|
478
|
+
// handled separately via @othertype in the topic/note renderer, since its
|
|
479
|
+
// label isn't a fixed string.
|
|
480
|
+
//
|
|
481
|
+
// zh-cn deviations from a literal DITA-OT mirror (both fixes, not stylistic):
|
|
482
|
+
// - attention/caution previously collided with notice/warning (all four
|
|
483
|
+
// rendered '注意'/'警告'), making the two pairs visually indistinguishable
|
|
484
|
+
// in the preview. attention -> '留意', caution -> '小心' to disambiguate;
|
|
485
|
+
// '小心'/'警告'/'危险' also matches the conventional CN safety-signage
|
|
486
|
+
// triad for Caution/Warning/Danger.
|
|
487
|
+
// - trouble -> '故障排除' ("troubleshooting"), not '故障' ("fault"); the
|
|
488
|
+
// DITA semantic is remedy guidance, which '故障' alone doesn't convey.
|
|
489
|
+
export const DEFAULT_NOTE_LABELS = {
|
|
490
|
+
note: 'Note', notice: 'Notice', warning: 'Warning', danger: 'Danger',
|
|
491
|
+
important: 'Important', tip: 'Tip', restriction: 'Restriction',
|
|
492
|
+
attention: 'Attention', caution: 'Caution', fastpath: 'Fastpath',
|
|
493
|
+
remember: 'Remember', trouble: 'Trouble',
|
|
494
|
+
};
|
|
495
|
+
export const ZH_NOTE_LABELS = {
|
|
496
|
+
note: '注', notice: '注意', warning: '警告', danger: '危险',
|
|
497
|
+
important: '重要', tip: '提示', restriction: '限制',
|
|
498
|
+
attention: '留意', caution: '小心', fastpath: '捷径',
|
|
499
|
+
remember: '切记', trouble: '故障排除',
|
|
500
|
+
};
|
|
501
|
+
export function detectNoteLabels(root, uiLanguage) {
|
|
502
|
+
const lang = root.attributes?.['xml:lang'] || uiLanguage || '';
|
|
503
|
+
return lang.startsWith('zh') ? ZH_NOTE_LABELS : DEFAULT_NOTE_LABELS;
|
|
504
|
+
}
|
|
505
|
+
/** Same xml:lang-first, uiLanguage-fallback resolution as detectNoteLabels,
|
|
506
|
+
* for the "Index" label shown in indexterm chip tooltips. Kept separate
|
|
507
|
+
* rather than folded into noteLabels since it isn't a note type and has
|
|
508
|
+
* its own (much smaller) two-language set. */
|
|
509
|
+
export function detectIndexLabel(root, uiLanguage) {
|
|
510
|
+
const lang = root.attributes?.['xml:lang'] || uiLanguage || '';
|
|
511
|
+
return lang.startsWith('zh') ? '\u7d22\u5f15' : 'Index';
|
|
512
|
+
}
|
|
513
|
+
export const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
|
|
514
|
+
/**
|
|
515
|
+
* Builds the render context's isInCurrentBook resolver: given a cross-file
|
|
516
|
+
* xref's raw href, return the absolute path of the target IF it is one of
|
|
517
|
+
* the book's members, else undefined. Same local-reference guard the
|
|
518
|
+
* inline version (renderTopicXml) applied before ever touching the file
|
|
519
|
+
* system: never probe a URL-scheme or absolute href, and a fragment-only
|
|
520
|
+
* href has no file part to resolve. Extracted for the shared
|
|
521
|
+
* buildRenderContext factory (renderContext.ts) so the three render paths
|
|
522
|
+
* agree on one implementation.
|
|
523
|
+
*/
|
|
524
|
+
export function makeIsInCurrentBook(docDir, bookMembers) {
|
|
525
|
+
return (href) => {
|
|
526
|
+
if (!href || URL_SCHEME_RE.test(href) || isAbsolute(href))
|
|
527
|
+
return undefined;
|
|
528
|
+
const pathPart = href.split('#')[0];
|
|
529
|
+
if (!pathPart)
|
|
530
|
+
return undefined;
|
|
531
|
+
const absPath = resolve(docDir, decodeHrefPart(pathPart));
|
|
532
|
+
return bookMembers.has(absPath) ? absPath : undefined;
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* Percent-decodes an href path segment for filesystem lookups. DITA tools
|
|
537
|
+
* URL-encode spaces and special characters in hrefs (e.g. "my%20image.png"),
|
|
538
|
+
* but the file on disk keeps the literal name. Malformed escape sequences
|
|
539
|
+
* are returned unchanged.
|
|
540
|
+
*/
|
|
541
|
+
export function decodeHrefPart(part) {
|
|
542
|
+
if (!part.includes('%'))
|
|
543
|
+
return part;
|
|
544
|
+
try {
|
|
545
|
+
return decodeURIComponent(part);
|
|
546
|
+
}
|
|
547
|
+
catch {
|
|
548
|
+
return part;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
function isLocalHref(href, scope) {
|
|
552
|
+
if (!href || href.startsWith('#'))
|
|
553
|
+
return false;
|
|
554
|
+
if (scope === 'external' || scope === 'peer')
|
|
555
|
+
return false;
|
|
556
|
+
if (URL_SCHEME_RE.test(href))
|
|
557
|
+
return false;
|
|
558
|
+
if (isAbsolute(href))
|
|
559
|
+
return false;
|
|
560
|
+
return true;
|
|
561
|
+
}
|
|
562
|
+
// Hrefs inside a referenced map are relative to that map's own folder.
|
|
563
|
+
// When its children are inlined into the root map's tree, rewrite them so
|
|
564
|
+
// they stay valid relative to the root map's folder — otherwise nested
|
|
565
|
+
// keydef maps, sub-map topics and navigation all resolve to wrong paths.
|
|
566
|
+
function rebaseHrefs(node, fromDir, toDir) {
|
|
567
|
+
if (node.type !== 'element')
|
|
568
|
+
return;
|
|
569
|
+
const href = node.attributes?.href;
|
|
570
|
+
if (href && node.attributes && isLocalHref(href, node.attributes.scope)) {
|
|
571
|
+
const hashIdx = href.indexOf('#');
|
|
572
|
+
const pathPart = hashIdx >= 0 ? href.substring(0, hashIdx) : href;
|
|
573
|
+
const fragment = hashIdx >= 0 ? href.substring(hashIdx) : '';
|
|
574
|
+
if (pathPart) {
|
|
575
|
+
const abs = resolve(fromDir, pathPart);
|
|
576
|
+
node.attributes.href = normalize(relative(toDir, abs)).replace(/\\/g, '/') + fragment;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
for (const child of node.children || [])
|
|
580
|
+
rebaseHrefs(child, fromDir, toDir);
|
|
581
|
+
}
|
|
582
|
+
export function expandDitamapRefs(node, docDir, readFile = readSourceText, ancestry) {
|
|
583
|
+
if (node.type !== 'element')
|
|
584
|
+
return;
|
|
585
|
+
if (isDitamapRef(node)) {
|
|
586
|
+
const href = node.attributes.href;
|
|
587
|
+
const targetPath = resolve(docDir, decodeHrefPart(href.split('#')[0]));
|
|
588
|
+
if (!ancestry)
|
|
589
|
+
ancestry = new Set();
|
|
590
|
+
// Scoped to the current chain of ancestor submaps (added on the way
|
|
591
|
+
// down, removed on the way back up), NOT every submap expanded
|
|
592
|
+
// anywhere else in the tree -- this guards only against a map that
|
|
593
|
+
// (directly, or through a chain of further submaps) refers back to
|
|
594
|
+
// one of its own ancestors, which would otherwise recurse forever. It
|
|
595
|
+
// deliberately does NOT block the same submap being referenced twice
|
|
596
|
+
// from two different topicrefs elsewhere in the map, which is a
|
|
597
|
+
// legitimate, supported DITA pattern (e.g. a shared appendix or legal-
|
|
598
|
+
// notices submap pulled into two different chapters) -- each such
|
|
599
|
+
// reference gets its own independent expansion.
|
|
600
|
+
if (!ancestry.has(targetPath)) {
|
|
601
|
+
ancestry.add(targetPath);
|
|
602
|
+
try {
|
|
603
|
+
const content = readFile(targetPath, 'utf-8');
|
|
604
|
+
const doc = parseDitamap(preprocessEntities(content));
|
|
605
|
+
const refChildren = (doc.root.children || []).filter((c) => c.type === 'element');
|
|
606
|
+
if (refChildren.length > 0) {
|
|
607
|
+
const refDir = dirname(targetPath);
|
|
608
|
+
if (refDir !== resolve(docDir)) {
|
|
609
|
+
for (const rc of refChildren)
|
|
610
|
+
rebaseHrefs(rc, refDir, docDir);
|
|
611
|
+
}
|
|
612
|
+
if (!node.children)
|
|
613
|
+
node.children = [];
|
|
614
|
+
node.children.push(...refChildren);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
catch {
|
|
618
|
+
// file not found or parse error — skip silently
|
|
619
|
+
}
|
|
620
|
+
// Recurse into this node's now-spliced-in children (and any it
|
|
621
|
+
// already had) while targetPath is still on the ancestry chain, so a
|
|
622
|
+
// nested submap-of-a-submap is still cycle-checked correctly.
|
|
623
|
+
for (const child of node.children || []) {
|
|
624
|
+
expandDitamapRefs(child, docDir, readFile, ancestry);
|
|
625
|
+
}
|
|
626
|
+
ancestry.delete(targetPath);
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
for (const child of node.children || []) {
|
|
631
|
+
expandDitamapRefs(child, docDir, readFile, ancestry);
|
|
632
|
+
}
|
|
633
|
+
}
|