svelte-highlight 7.16.0 → 7.16.1
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/HighlightEditable.svelte +142 -7
- package/LineNumbers.svelte +2 -1
- package/Typewriter.svelte +10 -39
- package/engine.js +68 -21
- package/package.json +1 -1
- package/preprocessor.js +6 -3
- package/typewriter-units.d.ts +14 -0
- package/typewriter-units.js +69 -0
package/HighlightEditable.svelte
CHANGED
|
@@ -123,16 +123,96 @@
|
|
|
123
123
|
)}</style>`
|
|
124
124
|
: "";
|
|
125
125
|
|
|
126
|
+
// Sum of textContent.length for el's first `count` children — the
|
|
127
|
+
// character width, within el, of a boundary expressed as a child index.
|
|
128
|
+
function sumChildLengths(el, count) {
|
|
129
|
+
let total = 0;
|
|
130
|
+
for (let i = 0; i < count && i < el.childNodes.length; i++) {
|
|
131
|
+
total += el.childNodes[i].textContent.length;
|
|
132
|
+
}
|
|
133
|
+
return total;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Character offset (same coordinate space as lineStartOffset/setSelection)
|
|
137
|
+
// of the boundary (container, offsetInContainer) from a live Selection
|
|
138
|
+
// Range, computed from integers instead of serializing the document.
|
|
139
|
+
// Exploits the fixed editor structure — one <span> per line (lineEls)
|
|
140
|
+
// joined by literal "\n" text nodes — so a boundary's line is derived
|
|
141
|
+
// from its child position rather than a document-wide walk. Returns null
|
|
142
|
+
// whenever that structure doesn't hold (DOM drifted from lineEls/
|
|
143
|
+
// lineLengths ahead of renderLines' self-heal, or an unrecognized node),
|
|
144
|
+
// so the caller can fall back to the exact cloneRange/toString behavior.
|
|
145
|
+
function offsetOfBoundary(container, offsetInContainer) {
|
|
146
|
+
const expectedChildren = lineEls.length === 0 ? 0 : lineEls.length * 2 - 1;
|
|
147
|
+
if (editor.childNodes.length !== expectedChildren) return null;
|
|
148
|
+
|
|
149
|
+
if (container === editor) {
|
|
150
|
+
if (lineEls.length === 0) return offsetInContainer === 0 ? 0 : null;
|
|
151
|
+
const lineIndex = offsetInContainer >> 1;
|
|
152
|
+
if (lineIndex >= lineEls.length) return null;
|
|
153
|
+
return offsetInContainer % 2 === 0
|
|
154
|
+
? lineStartOffset(lineIndex)
|
|
155
|
+
: lineStartOffset(lineIndex) + lineLengths[lineIndex];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Walk up to the top-level child of `editor` containing the boundary.
|
|
159
|
+
let node = container;
|
|
160
|
+
while (node.parentNode !== editor) {
|
|
161
|
+
node = node.parentNode;
|
|
162
|
+
if (!node) return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
let childIndex = 0;
|
|
166
|
+
for (let sib = node.previousSibling; sib; sib = sib.previousSibling) {
|
|
167
|
+
childIndex++;
|
|
168
|
+
}
|
|
169
|
+
const lineIndex = childIndex >> 1;
|
|
170
|
+
|
|
171
|
+
if (childIndex % 2 === 1) {
|
|
172
|
+
// The "\n" separator following line `lineIndex`; it has no children,
|
|
173
|
+
// so `container` must be the separator itself.
|
|
174
|
+
if (container !== node || lineIndex >= lineLengths.length) return null;
|
|
175
|
+
return (
|
|
176
|
+
lineStartOffset(lineIndex) + lineLengths[lineIndex] + offsetInContainer
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const span = node;
|
|
181
|
+
if (lineIndex >= lineEls.length || lineEls[lineIndex] !== span) return null;
|
|
182
|
+
|
|
183
|
+
// Character offset of (container, offsetInContainer) within `span`,
|
|
184
|
+
// walking only its ancestors up to `span` (bounded by that line's size).
|
|
185
|
+
let charOffset =
|
|
186
|
+
container.nodeType === Node.TEXT_NODE
|
|
187
|
+
? offsetInContainer
|
|
188
|
+
: sumChildLengths(container, offsetInContainer);
|
|
189
|
+
let n = container;
|
|
190
|
+
while (n !== span) {
|
|
191
|
+
for (let sib = n.previousSibling; sib; sib = sib.previousSibling) {
|
|
192
|
+
charOffset += sib.textContent.length;
|
|
193
|
+
}
|
|
194
|
+
n = n.parentNode;
|
|
195
|
+
if (!n) return null;
|
|
196
|
+
}
|
|
197
|
+
return lineStartOffset(lineIndex) + charOffset;
|
|
198
|
+
}
|
|
199
|
+
|
|
126
200
|
function getSelectionRange() {
|
|
127
201
|
const selection = window.getSelection();
|
|
128
202
|
if (!selection || selection.rangeCount === 0) return null;
|
|
129
203
|
const range = selection.getRangeAt(0);
|
|
130
204
|
if (!editor.contains(range.commonAncestorContainer)) return null;
|
|
205
|
+
const start = offsetOfBoundary(range.startContainer, range.startOffset);
|
|
206
|
+
const end = offsetOfBoundary(range.endContainer, range.endOffset);
|
|
207
|
+
if (start != null && end != null) return { start, end };
|
|
131
208
|
const pre = range.cloneRange();
|
|
132
209
|
pre.selectNodeContents(editor);
|
|
133
210
|
pre.setEnd(range.startContainer, range.startOffset);
|
|
134
|
-
const
|
|
135
|
-
return {
|
|
211
|
+
const fallbackStart = pre.toString().length;
|
|
212
|
+
return {
|
|
213
|
+
start: fallbackStart,
|
|
214
|
+
end: fallbackStart + range.toString().length,
|
|
215
|
+
};
|
|
136
216
|
}
|
|
137
217
|
|
|
138
218
|
function getCaretOffset() {
|
|
@@ -289,8 +369,23 @@
|
|
|
289
369
|
if (textNode) {
|
|
290
370
|
const lineStart = lineStartOffset(index);
|
|
291
371
|
const lineEnd = lineStart + lineLengths[index];
|
|
292
|
-
|
|
293
|
-
|
|
372
|
+
// `tokenRanges` is sorted by, and disjoint on, `start` (see the
|
|
373
|
+
// comment on `paintAllLineHighlights`), so `end` is monotonically
|
|
374
|
+
// increasing too. Binary-search the first range that can possibly
|
|
375
|
+
// intersect the line instead of scanning the whole document.
|
|
376
|
+
let lo = 0;
|
|
377
|
+
let hi = tokenRanges.length;
|
|
378
|
+
while (lo < hi) {
|
|
379
|
+
const mid = (lo + hi) >>> 1;
|
|
380
|
+
if (tokenRanges[mid].end <= lineStart) lo = mid + 1;
|
|
381
|
+
else hi = mid;
|
|
382
|
+
}
|
|
383
|
+
for (
|
|
384
|
+
let j = lo;
|
|
385
|
+
j < tokenRanges.length && tokenRanges[j].start < lineEnd;
|
|
386
|
+
j++
|
|
387
|
+
) {
|
|
388
|
+
const token = tokenRanges[j];
|
|
294
389
|
const start = Math.max(token.start, lineStart) - lineStart;
|
|
295
390
|
const end = Math.min(token.end, lineEnd) - lineStart;
|
|
296
391
|
if (start === end) continue;
|
|
@@ -304,14 +399,54 @@
|
|
|
304
399
|
lineHighlightRanges[index] = next;
|
|
305
400
|
}
|
|
306
401
|
|
|
402
|
+
// Repaints every line from `tokenRanges` in a single forward sweep rather
|
|
403
|
+
// than rescanning the full (document-sized) range array per line: since
|
|
404
|
+
// `toRanges` emits ranges sorted by, and disjoint on, document offset,
|
|
405
|
+
// `tokenIndex` only ever advances, so total work is O(lines + tokens)
|
|
406
|
+
// instead of O(lines * tokens).
|
|
407
|
+
function paintAllLineHighlights(tokenRanges) {
|
|
408
|
+
let tokenIndex = 0;
|
|
409
|
+
let lineStart = 0;
|
|
410
|
+
for (let i = 0; i < lineEls.length; i++) {
|
|
411
|
+
clearLineHighlights(i);
|
|
412
|
+
const lineEnd = lineStart + lineLengths[i];
|
|
413
|
+
const textNode = lineEls[i].firstChild;
|
|
414
|
+
const next = [];
|
|
415
|
+
if (textNode) {
|
|
416
|
+
while (
|
|
417
|
+
tokenIndex < tokenRanges.length &&
|
|
418
|
+
tokenRanges[tokenIndex].end <= lineStart
|
|
419
|
+
) {
|
|
420
|
+
tokenIndex++;
|
|
421
|
+
}
|
|
422
|
+
for (
|
|
423
|
+
let j = tokenIndex;
|
|
424
|
+
j < tokenRanges.length && tokenRanges[j].start < lineEnd;
|
|
425
|
+
j++
|
|
426
|
+
) {
|
|
427
|
+
const token = tokenRanges[j];
|
|
428
|
+
if (token.end <= lineStart) continue;
|
|
429
|
+
const start = Math.max(token.start, lineStart) - lineStart;
|
|
430
|
+
const end = Math.min(token.end, lineEnd) - lineStart;
|
|
431
|
+
if (start === end) continue;
|
|
432
|
+
const range = new Range();
|
|
433
|
+
range.setStart(textNode, start);
|
|
434
|
+
range.setEnd(textNode, end);
|
|
435
|
+
cssHighlightFor(token.scope).add(range);
|
|
436
|
+
next.push({ scope: token.scope, range });
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
lineHighlightRanges[i] = next;
|
|
440
|
+
lineStart = lineEnd + 1; // +1 for the "\n" separator
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
307
444
|
function paintCssHighlights() {
|
|
308
445
|
const changedIndex = renderLines(code.split("\n"), setText);
|
|
309
446
|
const tokenRanges = toRanges(getEvents());
|
|
310
447
|
|
|
311
448
|
if (changedIndex == null) {
|
|
312
|
-
|
|
313
|
-
paintLineHighlights(i, tokenRanges);
|
|
314
|
-
}
|
|
449
|
+
paintAllLineHighlights(tokenRanges);
|
|
315
450
|
} else {
|
|
316
451
|
paintLineHighlights(changedIndex, tokenRanges);
|
|
317
452
|
}
|
package/LineNumbers.svelte
CHANGED
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
const HIGHLIGHTED_BACKGROUND = "rgba(254, 241, 96, 0.2)";
|
|
28
28
|
|
|
29
29
|
$: lines = splitLines(highlighted);
|
|
30
|
+
$: highlightedLineSet = new Set(highlightedLines);
|
|
30
31
|
$: focusMode = highlightedLines.length > 0;
|
|
31
32
|
$: len_digits = (startingLineNumber + lines.length - 1).toString().length;
|
|
32
33
|
$: len = len_digits - MIN_DIGITS < 1 ? MIN_DIGITS : len_digits;
|
|
@@ -47,7 +48,7 @@
|
|
|
47
48
|
<tbody class:hljs={true}>
|
|
48
49
|
{#each lines as line, i}
|
|
49
50
|
{@const lineNumber = i + startingLineNumber}
|
|
50
|
-
{@const isHighlighted =
|
|
51
|
+
{@const isHighlighted = highlightedLineSet.has(i)}
|
|
51
52
|
<tr class:dimmed={focusMode && !isHighlighted}>
|
|
52
53
|
<td
|
|
53
54
|
class:hljs={true}
|
package/Typewriter.svelte
CHANGED
|
@@ -18,7 +18,10 @@
|
|
|
18
18
|
export let play = true;
|
|
19
19
|
|
|
20
20
|
import { createEventDispatcher, onMount } from "svelte";
|
|
21
|
-
import {
|
|
21
|
+
import {
|
|
22
|
+
createTypewriterSplitter,
|
|
23
|
+
tokenizeTypewriter as tokenize,
|
|
24
|
+
} from "./typewriter-units.js";
|
|
22
25
|
|
|
23
26
|
const dispatch = createEventDispatcher();
|
|
24
27
|
|
|
@@ -61,42 +64,6 @@
|
|
|
61
64
|
/** The unit currently marked with the caret, if any. @type {HTMLElement | undefined} */
|
|
62
65
|
let caretMark;
|
|
63
66
|
|
|
64
|
-
/**
|
|
65
|
-
* Split at `count` visible chars. Close open tags in `head`, reopen in `tail`.
|
|
66
|
-
* Hidden `tail` reserves space so layout doesn't jump.
|
|
67
|
-
*/
|
|
68
|
-
function split(list, count) {
|
|
69
|
-
let head = "";
|
|
70
|
-
let shown = 0;
|
|
71
|
-
/** @type {{ raw: string; name: string }[]} */
|
|
72
|
-
const open = [];
|
|
73
|
-
let i = 0;
|
|
74
|
-
|
|
75
|
-
for (; i < list.length; i++) {
|
|
76
|
-
const unit = list[i];
|
|
77
|
-
if (shown >= count) break;
|
|
78
|
-
head += unit.raw;
|
|
79
|
-
if (unit.visible === 0) {
|
|
80
|
-
if (unit.kind === "open")
|
|
81
|
-
open.push({ raw: unit.raw, name: unit.name ?? "" });
|
|
82
|
-
else if (unit.kind === "close") open.pop();
|
|
83
|
-
} else {
|
|
84
|
-
shown += unit.visible;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// Close open tags in head, reopen them at the start of tail.
|
|
89
|
-
let headClose = "";
|
|
90
|
-
for (let k = open.length - 1; k >= 0; k--)
|
|
91
|
-
headClose += `</${open[k].name}>`;
|
|
92
|
-
|
|
93
|
-
let tail = "";
|
|
94
|
-
for (const tag of open) tail += tag.raw;
|
|
95
|
-
for (; i < list.length; i++) tail += list[i].raw;
|
|
96
|
-
|
|
97
|
-
return { head: head + headClose, tail };
|
|
98
|
-
}
|
|
99
|
-
|
|
100
67
|
/** Render every unit once: tags pass through, each visible unit gets a span. */
|
|
101
68
|
function buildUnitMarkup(list) {
|
|
102
69
|
let html = "";
|
|
@@ -186,6 +153,10 @@
|
|
|
186
153
|
}
|
|
187
154
|
|
|
188
155
|
$: units = tokenize(highlighted);
|
|
156
|
+
// `splitter` must be rebuilt whenever `units` does, from the same
|
|
157
|
+
// `highlighted` string `units` was tokenized from -- both are recomputed
|
|
158
|
+
// together in the same reactive flush whenever `highlighted` changes.
|
|
159
|
+
$: splitter = createTypewriterSplitter(units, highlighted);
|
|
189
160
|
$: total = units.reduce((sum, unit) => sum + unit.visible, 0);
|
|
190
161
|
$: bigInput = total > UNIT_THRESHOLD;
|
|
191
162
|
$: useUnitReveal = mounted && !reducedMotion && !bigInput;
|
|
@@ -205,11 +176,11 @@
|
|
|
205
176
|
sync();
|
|
206
177
|
}
|
|
207
178
|
|
|
208
|
-
// SSR / slow-path: full content up front,
|
|
179
|
+
// SSR / slow-path: full content up front, splitter only when actually needed.
|
|
209
180
|
$: parts = useUnitReveal
|
|
210
181
|
? EMPTY_PARTS
|
|
211
182
|
: mounted
|
|
212
|
-
?
|
|
183
|
+
? splitter.splitAt(revealed)
|
|
213
184
|
: { head: highlighted, tail: "" };
|
|
214
185
|
$: showCaret = mounted && !reducedMotion && revealed < total;
|
|
215
186
|
|
package/engine.js
CHANGED
|
@@ -211,6 +211,13 @@ class Tokenizer {
|
|
|
211
211
|
* @type {(MatchCache | undefined)[]}
|
|
212
212
|
*/
|
|
213
213
|
this.beginCache = [];
|
|
214
|
+
/**
|
|
215
|
+
* Tag names with no `</name` at or after the recorded position. See
|
|
216
|
+
* `hasClosingTag`.
|
|
217
|
+
* @type {Map<string, number>}
|
|
218
|
+
*/
|
|
219
|
+
this.noClosingTag = new Map();
|
|
220
|
+
this.noClosingTagCodeLen = 0;
|
|
214
221
|
}
|
|
215
222
|
|
|
216
223
|
/** @returns {Frame} */
|
|
@@ -409,16 +416,18 @@ class Tokenizer {
|
|
|
409
416
|
}
|
|
410
417
|
|
|
411
418
|
/**
|
|
412
|
-
* Memoized `execValid(re, this.pos,
|
|
419
|
+
* Memoized `execValid(re, this.pos, guardFn())`. Without this, every token
|
|
413
420
|
* boundary re-scans every rule's pattern from scratch. A cached match stays
|
|
414
421
|
* valid until `this.pos` passes it; a cached miss stays valid until the
|
|
415
|
-
* code grows (streaming append).
|
|
422
|
+
* code grows (streaming append). `guardFn` is only called on a cache miss,
|
|
423
|
+
* so guarded rules don't allocate a fresh guard closure on every call once
|
|
424
|
+
* their match is cached.
|
|
416
425
|
* @param {RegExp} re
|
|
417
|
-
* @param {((m: RegExpExecArray) => boolean) | null}
|
|
426
|
+
* @param {() => ((m: RegExpExecArray) => boolean) | null} guardFn
|
|
418
427
|
* @param {MatchCache | undefined} cache
|
|
419
428
|
* @returns {MatchCache}
|
|
420
429
|
*/
|
|
421
|
-
cachedMatch(re,
|
|
430
|
+
cachedMatch(re, guardFn, cache) {
|
|
422
431
|
if (cache) {
|
|
423
432
|
if (cache.match !== null && cache.match.index >= this.pos) return cache;
|
|
424
433
|
if (cache.match === null && cache.codeLen === this.code.length)
|
|
@@ -426,7 +435,7 @@ class Tokenizer {
|
|
|
426
435
|
}
|
|
427
436
|
return {
|
|
428
437
|
codeLen: this.code.length,
|
|
429
|
-
match: this.execValid(re, this.pos,
|
|
438
|
+
match: this.execValid(re, this.pos, guardFn()),
|
|
430
439
|
};
|
|
431
440
|
}
|
|
432
441
|
|
|
@@ -447,6 +456,35 @@ class Tokenizer {
|
|
|
447
456
|
return null;
|
|
448
457
|
}
|
|
449
458
|
|
|
459
|
+
/**
|
|
460
|
+
* Whether `</name` occurs at or after `from`.
|
|
461
|
+
*
|
|
462
|
+
* Misses are memoized per tag name, which makes the common "generic, not a
|
|
463
|
+
* tag" verdict cheap: absence from `from` implies absence from every later
|
|
464
|
+
* position, so one scan settles all of that name's later occurrences. Code
|
|
465
|
+
* dense in generics (`Modify<T>`, `Array<T>`) otherwise rescans the whole
|
|
466
|
+
* remaining source per occurrence, which is quadratic in file size.
|
|
467
|
+
*
|
|
468
|
+
* Keyed on `code.length` like `beginCache`: a tokenizer's `code` only ever
|
|
469
|
+
* grows, so an unchanged length means unchanged content, and appended code
|
|
470
|
+
* can supply a closing tag that was legitimately absent before.
|
|
471
|
+
*
|
|
472
|
+
* @param {string} name
|
|
473
|
+
* @param {number} from
|
|
474
|
+
* @returns {boolean}
|
|
475
|
+
*/
|
|
476
|
+
hasClosingTag(name, from) {
|
|
477
|
+
if (this.noClosingTagCodeLen !== this.code.length) {
|
|
478
|
+
this.noClosingTag.clear();
|
|
479
|
+
this.noClosingTagCodeLen = this.code.length;
|
|
480
|
+
}
|
|
481
|
+
const absentFrom = this.noClosingTag.get(name);
|
|
482
|
+
if (absentFrom !== undefined && from >= absentFrom) return false;
|
|
483
|
+
if (this.code.indexOf(`</${name}`, from) !== -1) return true;
|
|
484
|
+
this.noClosingTag.set(name, from);
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
487
|
+
|
|
450
488
|
/**
|
|
451
489
|
* hljs javascript/typescript JSX-vs-generic disambiguation for a `<Foo`
|
|
452
490
|
* match. Re-evaluated when more code arrives so a streaming closing tag
|
|
@@ -460,10 +498,7 @@ class Tokenizer {
|
|
|
460
498
|
// `Array<Array<number>>`, `<T, A extends keyof T, V>`
|
|
461
499
|
if (nextChar === "<" || nextChar === ",") return false;
|
|
462
500
|
// `<something>` - only a tag if a matching closing tag exists later on.
|
|
463
|
-
if (
|
|
464
|
-
nextChar === ">" &&
|
|
465
|
-
this.code.indexOf(`</${match[0].slice(1)}`, afterIdx) === -1
|
|
466
|
-
) {
|
|
501
|
+
if (nextChar === ">" && !this.hasClosingTag(match[0].slice(1), afterIdx)) {
|
|
467
502
|
return false;
|
|
468
503
|
}
|
|
469
504
|
const after = this.code.slice(afterIdx);
|
|
@@ -515,7 +550,7 @@ class Tokenizer {
|
|
|
515
550
|
const cache = this.cachedMatch(
|
|
516
551
|
// Every state referenced from a `rules` list has a `begin` pattern.
|
|
517
552
|
/** @type {RegExp} */ (child.beginRe),
|
|
518
|
-
this.beginGuard(child),
|
|
553
|
+
() => this.beginGuard(child),
|
|
519
554
|
this.beginCache[ruleIdx],
|
|
520
555
|
);
|
|
521
556
|
this.beginCache[ruleIdx] = cache;
|
|
@@ -527,12 +562,12 @@ class Tokenizer {
|
|
|
527
562
|
// d ranges over [1, frames.length - 1], always in bounds.
|
|
528
563
|
const frame = /** @type {Frame} */ (this.frames[d]);
|
|
529
564
|
if (frame.state.endRe) {
|
|
530
|
-
const guard = frame.state.endSameAsBegin
|
|
531
|
-
? (/** @type {RegExpExecArray} */ m) => m[1] === frame.beginMatch
|
|
532
|
-
: null;
|
|
533
565
|
const cache = this.cachedMatch(
|
|
534
566
|
frame.state.endRe,
|
|
535
|
-
|
|
567
|
+
() =>
|
|
568
|
+
frame.state.endSameAsBegin
|
|
569
|
+
? (/** @type {RegExpExecArray} */ m) => m[1] === frame.beginMatch
|
|
570
|
+
: null,
|
|
536
571
|
frame.endCache,
|
|
537
572
|
);
|
|
538
573
|
frame.endCache = cache;
|
|
@@ -836,17 +871,29 @@ export function extendLines(
|
|
|
836
871
|
const stack = [...openScopes];
|
|
837
872
|
/** @type {string[]} */
|
|
838
873
|
const completedLines = [];
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
874
|
+
// Cache the concatenated open/close tag strings for the current stack so a
|
|
875
|
+
// run of newlines between OPEN/CLOSE events reuses them instead of
|
|
876
|
+
// re-joining the whole stack per line break.
|
|
877
|
+
/** @type {string[]} */
|
|
878
|
+
const tags = stack.map(
|
|
879
|
+
(scope) => `<span class="${scopeToCssClass(scope, classPrefix)}">`,
|
|
880
|
+
);
|
|
881
|
+
let reopen = tags.join("");
|
|
882
|
+
let closeAll = "</span>".repeat(stack.length);
|
|
843
883
|
let current = pendingHtml;
|
|
844
884
|
for (const event of newEvents) {
|
|
845
885
|
if (event.t === OPEN) {
|
|
846
886
|
stack.push(event.s);
|
|
847
|
-
|
|
887
|
+
const tag = `<span class="${scopeToCssClass(event.s, classPrefix)}">`;
|
|
888
|
+
tags.push(tag);
|
|
889
|
+
reopen += tag;
|
|
890
|
+
closeAll += "</span>";
|
|
891
|
+
current += tag;
|
|
848
892
|
} else if (event.t === CLOSE) {
|
|
849
893
|
stack.pop();
|
|
894
|
+
const tag = /** @type {string} */ (tags.pop());
|
|
895
|
+
reopen = reopen.slice(0, reopen.length - tag.length);
|
|
896
|
+
closeAll = closeAll.slice(0, closeAll.length - "</span>".length);
|
|
850
897
|
current += "</span>";
|
|
851
898
|
} else {
|
|
852
899
|
const text = event.v;
|
|
@@ -854,9 +901,9 @@ export function extendLines(
|
|
|
854
901
|
for (let i = 0; i < text.length; i++) {
|
|
855
902
|
if (text.charCodeAt(i) === 10) {
|
|
856
903
|
current += escapeHtml(text.slice(start, i));
|
|
857
|
-
current +=
|
|
904
|
+
current += closeAll;
|
|
858
905
|
completedLines.push(current);
|
|
859
|
-
current =
|
|
906
|
+
current = reopen;
|
|
860
907
|
start = i + 1;
|
|
861
908
|
}
|
|
862
909
|
}
|
package/package.json
CHANGED
package/preprocessor.js
CHANGED
|
@@ -307,7 +307,10 @@ export function highlightStatic(options = {}) {
|
|
|
307
307
|
|
|
308
308
|
const htmlByMatch = await Promise.all(
|
|
309
309
|
matches.map(async (match) => {
|
|
310
|
-
|
|
310
|
+
// Only ever read by the warn() paths below, and locate() scans
|
|
311
|
+
// `content` from the start, so resolve it lazily: computing it up
|
|
312
|
+
// front made the happy path O(content length) per match.
|
|
313
|
+
const line = () => locate(content, match.element.start).line;
|
|
311
314
|
|
|
312
315
|
/** @type {import("./languages").LanguageType<string>} */
|
|
313
316
|
let language;
|
|
@@ -322,7 +325,7 @@ export function highlightStatic(options = {}) {
|
|
|
322
325
|
`could not resolve language module "${match.languageSource}"`,
|
|
323
326
|
{
|
|
324
327
|
filename,
|
|
325
|
-
line,
|
|
328
|
+
line: line(),
|
|
326
329
|
cause,
|
|
327
330
|
},
|
|
328
331
|
);
|
|
@@ -336,7 +339,7 @@ export function highlightStatic(options = {}) {
|
|
|
336
339
|
`highlight.js failed to highlight the code (language "${language.name}")`,
|
|
337
340
|
{
|
|
338
341
|
filename,
|
|
339
|
-
line,
|
|
342
|
+
line: line(),
|
|
340
343
|
cause,
|
|
341
344
|
},
|
|
342
345
|
);
|
package/typewriter-units.d.ts
CHANGED
|
@@ -11,3 +11,17 @@ export interface TypewriterUnit {
|
|
|
11
11
|
* unit (a surrogate pair or an HTML entity counts as a single char).
|
|
12
12
|
*/
|
|
13
13
|
export declare function tokenizeTypewriter(html: string): TypewriterUnit[];
|
|
14
|
+
|
|
15
|
+
export interface TypewriterSplitter {
|
|
16
|
+
splitAt(count: number): { head: string; tail: string };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Stateful incremental splitter: repeated `splitAt(count)` calls with a
|
|
21
|
+
* non-decreasing `count` cost O(n) total instead of O(n^2). A `count` lower
|
|
22
|
+
* than the last one served resets and replays from the start.
|
|
23
|
+
*/
|
|
24
|
+
export declare function createTypewriterSplitter(
|
|
25
|
+
units: TypewriterUnit[],
|
|
26
|
+
html: string,
|
|
27
|
+
): TypewriterSplitter;
|
package/typewriter-units.js
CHANGED
|
@@ -71,3 +71,72 @@ export function tokenizeTypewriter(html) {
|
|
|
71
71
|
|
|
72
72
|
return units;
|
|
73
73
|
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @typedef {Object} TypewriterSplitter
|
|
77
|
+
* @property {(count: number) => { head: string; tail: string }} splitAt
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Stateful incremental version of the old `split(units, count)`: since
|
|
82
|
+
* `units[i].raw` are contiguous, non-overlapping slices exactly partitioning
|
|
83
|
+
* `html` (see `tokenizeTypewriter`), the concatenation of `units[0..i).raw`
|
|
84
|
+
* equals `html.slice(0, rawOffset)` for the matching `rawOffset`, so `head`
|
|
85
|
+
* can be built with a single slice instead of repeated concatenation. A
|
|
86
|
+
* cursor (`i`, `shown`, `rawOffset`, open-tag stack) is kept between calls
|
|
87
|
+
* and only ever advances, so a monotonically increasing sequence of
|
|
88
|
+
* `splitAt(count)` calls costs O(n) total instead of O(n^2). A `count` lower
|
|
89
|
+
* than the last one served resets the cursor and replays from zero.
|
|
90
|
+
* @param {TypewriterUnit[]} units
|
|
91
|
+
* @param {string} html
|
|
92
|
+
* @returns {TypewriterSplitter}
|
|
93
|
+
*/
|
|
94
|
+
export function createTypewriterSplitter(units, html) {
|
|
95
|
+
let i = 0;
|
|
96
|
+
let shown = 0;
|
|
97
|
+
let rawOffset = 0;
|
|
98
|
+
/** @type {{ raw: string; name: string }[]} */
|
|
99
|
+
let open = [];
|
|
100
|
+
let lastCount = 0;
|
|
101
|
+
|
|
102
|
+
function reset() {
|
|
103
|
+
i = 0;
|
|
104
|
+
shown = 0;
|
|
105
|
+
rawOffset = 0;
|
|
106
|
+
open = [];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* @param {number} count
|
|
111
|
+
* @returns {{ head: string; tail: string }}
|
|
112
|
+
*/
|
|
113
|
+
function splitAt(count) {
|
|
114
|
+
if (count < lastCount) reset();
|
|
115
|
+
lastCount = count;
|
|
116
|
+
|
|
117
|
+
for (; i < units.length; i++) {
|
|
118
|
+
const unit = /** @type {TypewriterUnit} */ (units[i]);
|
|
119
|
+
if (shown >= count) break;
|
|
120
|
+
rawOffset += unit.raw.length;
|
|
121
|
+
if (unit.visible === 0) {
|
|
122
|
+
if (unit.kind === "open")
|
|
123
|
+
open.push({ raw: unit.raw, name: unit.name ?? "" });
|
|
124
|
+
else if (unit.kind === "close") open.pop();
|
|
125
|
+
} else {
|
|
126
|
+
shown += unit.visible;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
let headClose = "";
|
|
131
|
+
for (let k = open.length - 1; k >= 0; k--)
|
|
132
|
+
headClose += `</${/** @type {{ raw: string; name: string }} */ (open[k]).name}>`;
|
|
133
|
+
|
|
134
|
+
let tail = "";
|
|
135
|
+
for (const tag of open) tail += tag.raw;
|
|
136
|
+
tail += html.slice(rawOffset);
|
|
137
|
+
|
|
138
|
+
return { head: html.slice(0, rawOffset) + headClose, tail };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return { splitAt };
|
|
142
|
+
}
|