svelte-highlight 7.23.2 → 7.24.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 (94) hide show
  1. package/AnsiOutput.svelte +33 -6
  2. package/AnsiOutput.svelte.d.ts +8 -0
  3. package/CodeToolbar.svelte +144 -0
  4. package/CodeToolbar.svelte.d.ts +125 -0
  5. package/CodeWindow.svelte +19 -0
  6. package/CodeWindow.svelte.d.ts +10 -0
  7. package/CopyButton.svelte +107 -3
  8. package/CopyButton.svelte.d.ts +17 -1
  9. package/DiffFileList.svelte +523 -0
  10. package/DiffFileList.svelte.d.ts +94 -0
  11. package/DiffFileListItem.svelte +44 -0
  12. package/DiffMinimap.svelte +99 -0
  13. package/DiffMinimap.svelte.d.ts +17 -0
  14. package/DiffStats.svelte +43 -0
  15. package/DiffStats.svelte.d.ts +17 -0
  16. package/DiffView.svelte +1213 -0
  17. package/DiffView.svelte.d.ts +76 -0
  18. package/FileTabs.svelte +2 -5
  19. package/Highlight.svelte +158 -2
  20. package/Highlight.svelte.d.ts +50 -2
  21. package/HighlightAuto.svelte.d.ts +3 -2
  22. package/HighlightAutoLazy.svelte +112 -0
  23. package/HighlightAutoLazy.svelte.d.ts +66 -0
  24. package/HighlightDiff.svelte +162 -0
  25. package/HighlightDiff.svelte.d.ts +102 -0
  26. package/HighlightEditable.svelte +65 -756
  27. package/HighlightEditable.svelte.d.ts +15 -5
  28. package/HighlightStream.svelte +117 -218
  29. package/HighlightStream.svelte.d.ts +8 -0
  30. package/HighlightSvelte.svelte.d.ts +3 -2
  31. package/HighlightVirtual.svelte +41 -8
  32. package/HighlightVirtual.svelte.d.ts +8 -0
  33. package/LangTag.svelte +33 -4
  34. package/LangTag.svelte.d.ts +6 -2
  35. package/LineNumbers.svelte +25 -4
  36. package/LineNumbers.svelte.d.ts +8 -0
  37. package/MarkdownStream.svelte +1 -0
  38. package/README.md +735 -18
  39. package/ToolbarButton.svelte +90 -0
  40. package/ToolbarButton.svelte.d.ts +106 -0
  41. package/Typewriter.svelte +59 -10
  42. package/Typewriter.svelte.d.ts +7 -0
  43. package/WrapToggle.svelte +34 -0
  44. package/WrapToggle.svelte.d.ts +39 -0
  45. package/action.js +7 -3
  46. package/ansi.d.ts +1 -3
  47. package/auto-detect.d.ts +52 -0
  48. package/auto-detect.js +208 -0
  49. package/code-region.d.ts +7 -0
  50. package/code-region.js +20 -0
  51. package/css-highlights.js +115 -0
  52. package/css-walk.js +50 -0
  53. package/diff-controller.d.ts +120 -0
  54. package/diff-controller.js +721 -0
  55. package/diff-edits.d.ts +101 -0
  56. package/diff-edits.js +890 -0
  57. package/diff-html.d.ts +8 -0
  58. package/diff-html.js +60 -0
  59. package/diff-languages.d.ts +4 -0
  60. package/diff-languages.js +73 -0
  61. package/diff.d.ts +161 -0
  62. package/diff.js +1111 -0
  63. package/editable-commands.js +81 -0
  64. package/editable-css-paint.js +5 -3
  65. package/editable-dom-paint.js +1 -1
  66. package/editable-history.js +199 -0
  67. package/editable-line-dom.js +176 -1
  68. package/editable-painter.js +356 -0
  69. package/editable.d.ts +118 -0
  70. package/editable.js +513 -0
  71. package/engine.d.ts +1 -1
  72. package/fence.js +1 -1
  73. package/highlight-cascade.js +679 -0
  74. package/highlight-theme.js +6 -47
  75. package/incremental-tokenize.js +1 -1
  76. package/index.d.ts +39 -6
  77. package/index.js +30 -0
  78. package/languages/detect-index.d.ts +16 -0
  79. package/languages/detect-index.js +6 -0
  80. package/languages/loaders.d.ts +8 -0
  81. package/languages/loaders.js +370 -0
  82. package/package.json +50 -2
  83. package/preprocessor.js +20 -5
  84. package/search.js +2 -2
  85. package/stream-highlighter.js +198 -0
  86. package/stream.css +16 -0
  87. package/stream.d.ts +60 -0
  88. package/stream.js +283 -0
  89. package/style-registry.js +34 -3
  90. package/themes/_base-css.d.ts +1 -0
  91. package/themes/_base-css.js +1 -0
  92. package/typewriter-units.d.ts +3 -0
  93. package/typewriter-units.js +43 -0
  94. package/virtual-window.js +9 -4
@@ -0,0 +1,198 @@
1
+ /**
2
+ * The streaming state behind HighlightStream, with no DOM or framework.
3
+ * Feed it the growing code buffer; it returns sealed HTML chunks, the live
4
+ * tail lines and the full highlighted HTML.
5
+ */
6
+ import { extendLines } from "./engine.js";
7
+ import { ensureRegistered, registry } from "./registry.js";
8
+ import { createFinalHighlighter } from "./stream-final-highlight.js";
9
+ import { createCompletedHtmlBuffer } from "./stream-highlighted.js";
10
+ import { computeStagedTailPreview } from "./stream-preview.js";
11
+ import { regenerate } from "./stream-regenerate.js";
12
+ import {
13
+ buildSealedChunkHtml,
14
+ pushSealedChunk,
15
+ } from "./stream-sealed-chunks.js";
16
+
17
+ // Full chunks become one immutable HTML string, so a renderer only diffs
18
+ // the bounded unsealed tail.
19
+ export const SEAL_CHUNK_LINES = 256;
20
+
21
+ /**
22
+ * @typedef {object} StreamHighlighterState
23
+ * @property {string} highlighted Full highlighted HTML.
24
+ * @property {string[]} sealedChunks Append-only; past entries never change.
25
+ * The same array is returned each time, so copy it to detect changes.
26
+ * @property {number} sealedLineCount Lines inside `sealedChunks`.
27
+ * @property {string[]} tailLines Unsealed completed lines plus the live
28
+ * preview line(s). Line `i` is document line `sealedLineCount + i`.
29
+ */
30
+
31
+ export function createStreamHighlighter() {
32
+ /** @type {ReturnType<typeof registry.createSession> | undefined} */
33
+ let session;
34
+ let sessionLanguageName = "";
35
+ // Prefix of the code already fed to `session`.
36
+ let fedCode = "";
37
+
38
+ let finalizedPendingHtml = "";
39
+ /** @type {string[]} */
40
+ let finalizedOpenScopes = [];
41
+ let renderedCommittedCount = 0;
42
+ /** @type {import("./stream-preview.d.ts").PreviewCache | undefined} */
43
+ let previewCache;
44
+
45
+ /** @type {string[]} */
46
+ let sealedChunks = [];
47
+ let sealedLineCount = 0;
48
+ // Completed lines for `highlighted`, so it isn't rebuilt per update.
49
+ const completedHtml = createCompletedHtmlBuffer();
50
+ const finalHighlighter = createFinalHighlighter();
51
+ // Bounded by SEAL_CHUNK_LINES, so touching it every update stays O(1).
52
+ /** @type {string[]} */
53
+ let unsealedLines = [];
54
+ /** @type {string[]} */
55
+ let tailLines = [];
56
+ let highlighted = "";
57
+
58
+ /** @returns {StreamHighlighterState} */
59
+ function state() {
60
+ return { highlighted, sealedChunks, sealedLineCount, tailLines };
61
+ }
62
+
63
+ /**
64
+ * @param {string} code
65
+ * @param {import("./languages").LanguageType<string>} language
66
+ */
67
+ function ensureSession(code, language) {
68
+ if (
69
+ session &&
70
+ sessionLanguageName === language.name &&
71
+ code.startsWith(fedCode)
72
+ ) {
73
+ return;
74
+ }
75
+ ensureRegistered(language);
76
+ if (session && sessionLanguageName === language.name) {
77
+ // Not a pure append: patch in place rather than lose every sealed chunk.
78
+ const next = regenerate({
79
+ session,
80
+ fedCode,
81
+ code,
82
+ sealedChunks,
83
+ completedHtml,
84
+ chunkLines: SEAL_CHUNK_LINES,
85
+ });
86
+ fedCode = code;
87
+ previewCache = undefined;
88
+ finalizedPendingHtml = next.pendingHtml;
89
+ finalizedOpenScopes = next.openScopes;
90
+ renderedCommittedCount = next.committedCount;
91
+ sealedChunks = next.sealedChunks;
92
+ sealedLineCount = next.sealedLineCount;
93
+ unsealedLines = next.unsealedLines;
94
+ tailLines = unsealedLines;
95
+ return;
96
+ }
97
+ reset();
98
+ session = registry.createSession(language.name);
99
+ sessionLanguageName = language.name;
100
+ }
101
+
102
+ // Also runs after `finish`, so a closed stream keeps only its final HTML;
103
+ // resuming re-feeds the whole buffer.
104
+ function reset() {
105
+ session = undefined;
106
+ sessionLanguageName = "";
107
+ fedCode = "";
108
+ finalizedPendingHtml = "";
109
+ finalizedOpenScopes = [];
110
+ renderedCommittedCount = 0;
111
+ previewCache = undefined;
112
+ sealedChunks = [];
113
+ sealedLineCount = 0;
114
+ completedHtml.reset();
115
+ unsealedLines = [];
116
+ tailLines = [];
117
+ }
118
+
119
+ function sealChunk() {
120
+ const chunkLines = unsealedLines.slice(0, SEAL_CHUNK_LINES);
121
+ sealedChunks = pushSealedChunk(
122
+ sealedChunks,
123
+ buildSealedChunkHtml(chunkLines, sealedLineCount),
124
+ );
125
+ sealedLineCount += chunkLines.length;
126
+ unsealedLines = unsealedLines.slice(SEAL_CHUNK_LINES);
127
+ }
128
+
129
+ return {
130
+ /**
131
+ * Highlights the buffer while it streams. Appends are incremental; any
132
+ * other change patches the sealed output in place.
133
+ * @param {string} code
134
+ * @param {import("./languages").LanguageType<string>} language
135
+ * @returns {StreamHighlighterState}
136
+ */
137
+ update(code, language) {
138
+ ensureSession(code, language);
139
+ const live = /** @type {NonNullable<typeof session>} */ (session);
140
+ if (code.length > fedCode.length) {
141
+ live.append(code.slice(fedCode.length));
142
+ fedCode = code;
143
+ }
144
+
145
+ const committed = live.events();
146
+ if (committed.length > renderedCommittedCount) {
147
+ const result = extendLines(
148
+ committed.slice(renderedCommittedCount),
149
+ finalizedOpenScopes,
150
+ finalizedPendingHtml,
151
+ );
152
+ if (result.completedLines.length > 0) {
153
+ completedHtml.appendLines(result.completedLines);
154
+ unsealedLines = unsealedLines.concat(result.completedLines);
155
+ while (unsealedLines.length >= SEAL_CHUNK_LINES) sealChunk();
156
+ }
157
+ finalizedPendingHtml = result.pendingHtml;
158
+ finalizedOpenScopes = result.openScopes;
159
+ renderedCommittedCount = committed.length;
160
+ }
161
+
162
+ const { previewLines, cache } = computeStagedTailPreview({
163
+ registry,
164
+ language: sessionLanguageName,
165
+ session: live,
166
+ fedCode,
167
+ openScopes: finalizedOpenScopes,
168
+ pendingHtml: finalizedPendingHtml,
169
+ cache: previewCache,
170
+ });
171
+ previewCache = cache;
172
+
173
+ tailLines = [...unsealedLines, ...previewLines];
174
+
175
+ // A trailing empty preview keeps a final `\n` when the stream ends a line.
176
+ const completed = completedHtml.toString();
177
+ highlighted =
178
+ completedHtml.lineCount === 0
179
+ ? previewLines.join("\n")
180
+ : `${completed}\n${previewLines.join("\n")}`;
181
+ return state();
182
+ },
183
+
184
+ /**
185
+ * One full re-parse once the stream is done, for multi-line lookahead
186
+ * (heredocs, etc.). Frees the streaming state.
187
+ * @param {string} code
188
+ * @param {import("./languages").LanguageType<string>} language
189
+ * @returns {StreamHighlighterState}
190
+ */
191
+ finish(code, language) {
192
+ ensureRegistered(language);
193
+ highlighted = finalHighlighter.highlight(registry, code, language.name);
194
+ if (session) reset();
195
+ return state();
196
+ },
197
+ };
198
+ }
package/stream.css ADDED
@@ -0,0 +1,16 @@
1
+ /* The caret `createStreamView` draws at the end of a stream. */
2
+ .highlight-stream-caret {
3
+ display: inline-block;
4
+ width: var(--caret-width, 0.6em);
5
+ height: var(--caret-height, 1.1em);
6
+ margin-left: var(--caret-gap, 1px);
7
+ vertical-align: text-bottom;
8
+ background: var(--caret-color, currentColor);
9
+ animation: highlight-stream-blink var(--caret-blink, 1s) step-end infinite;
10
+ }
11
+
12
+ @keyframes highlight-stream-blink {
13
+ 50% {
14
+ opacity: 0;
15
+ }
16
+ }
package/stream.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { LanguageType } from "./languages";
2
+
3
+ export interface StreamViewSettings {
4
+ /** Language module from `svelte-highlight/languages/*`. */
5
+ language: LanguageType<string>;
6
+ /** Growing code buffer; chunks may split mid-token or mid-line. @default "" */
7
+ code: string;
8
+ /** Stream finished: hides the caret and renders one full highlight. @default false */
9
+ done: boolean;
10
+ /** Show a blinking caret at the end of output while not `done`. @default true */
11
+ caret: boolean;
12
+ /**
13
+ * Keep the element's parent scrolled to the bottom while streaming, unless
14
+ * the user scrolls away. @default false
15
+ */
16
+ autoScroll: boolean;
17
+ }
18
+
19
+ export interface StreamViewOptions extends Partial<StreamViewSettings> {
20
+ language: LanguageType<string>;
21
+ /** Called after each render with the full highlighted HTML. */
22
+ onHighlight?: (highlighted: string) => void;
23
+ /** Called once when `done` renders. Called again if the stream restarts. */
24
+ onDone?: () => void;
25
+ }
26
+
27
+ export interface StreamView {
28
+ /** The latest highlighted HTML. */
29
+ readonly highlighted: string;
30
+ /**
31
+ * Applies changed settings. While streaming, renders on the next animation
32
+ * frame, so bursts of chunks cost one render. `done` renders at once.
33
+ */
34
+ update(settings: Partial<StreamViewSettings>): void;
35
+ /** Stops rendering and removes the scroll listener. Leaves the DOM as is. */
36
+ destroy(): void;
37
+ }
38
+
39
+ /**
40
+ * Streams highlighted code into `element`, with no framework. Use a `<code>`
41
+ * inside a `<pre>`, and import `svelte-highlight/stream.css` for the caret.
42
+ * Renders the first frame at once.
43
+ * @example
44
+ * import { createStreamView } from "svelte-highlight/stream";
45
+ * import typescript from "svelte-highlight/languages/typescript";
46
+ *
47
+ * const view = createStreamView(document.querySelector("code"), {
48
+ * language: typescript,
49
+ * });
50
+ * let code = "";
51
+ * for await (const chunk of response) {
52
+ * code += chunk;
53
+ * view.update({ code });
54
+ * }
55
+ * view.update({ done: true });
56
+ */
57
+ export function createStreamView(
58
+ element: HTMLElement,
59
+ options: StreamViewOptions,
60
+ ): StreamView;
package/stream.js ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Streaming highlighted code into any element, with no framework. This is the
3
+ * client-side rendering behind HighlightStream: it highlights a growing code
4
+ * buffer and keeps the DOM work bounded. Sealed chunks are added once and
5
+ * never rebuilt, tail lines are reused by line number, and `done` swaps in
6
+ * one full highlight. The element should be a `<code>` inside a `<pre>`.
7
+ */
8
+
9
+ import { createStreamHighlighter } from "./stream-highlighter.js";
10
+
11
+ /**
12
+ * @typedef {{
13
+ * language: import("./languages").LanguageType<string>,
14
+ * code: string,
15
+ * done: boolean,
16
+ * caret: boolean,
17
+ * autoScroll: boolean,
18
+ * }} StreamViewSettings
19
+ */
20
+
21
+ /**
22
+ * @typedef {Partial<StreamViewSettings> & {
23
+ * language: import("./languages").LanguageType<string>,
24
+ * onHighlight?: (highlighted: string) => void,
25
+ * onDone?: () => void,
26
+ * }} StreamViewOptions
27
+ */
28
+
29
+ /**
30
+ * @typedef {{ html: string, newline: Text | undefined, span: HTMLElement }} TailLine
31
+ * @typedef {{ html: string, nodes: ChildNode[] }} RenderedChunk
32
+ */
33
+
34
+ // Within this many pixels of the bottom counts as "at the bottom".
35
+ const STICK_THRESHOLD = 4;
36
+
37
+ /**
38
+ * @param {HTMLElement} element
39
+ * @param {StreamViewOptions} options
40
+ */
41
+ export function createStreamView(element, options) {
42
+ const doc = /** @type {Document} */ (element.ownerDocument);
43
+ const scroller = element.parentElement;
44
+ const { onHighlight, onDone } = options;
45
+ /** @type {StreamViewSettings} */
46
+ const settings = {
47
+ language: options.language,
48
+ code: options.code ?? "",
49
+ done: options.done ?? false,
50
+ caret: options.caret ?? true,
51
+ autoScroll: options.autoScroll ?? false,
52
+ };
53
+
54
+ const highlighter = createStreamHighlighter();
55
+ let highlighted = "";
56
+ // Reset when `done` goes false so a restarted stream calls `onDone` again.
57
+ let doneReported = false;
58
+ let stickToBottom = true;
59
+ /** @type {number | undefined} */
60
+ let frame;
61
+ let destroyed = false;
62
+
63
+ /** @type {"none" | "split" | "final"} */
64
+ let mode = "none";
65
+ /** @type {RenderedChunk[]} */
66
+ let chunks = [];
67
+ /** @type {Map<number, TailLine>} */
68
+ const tail = new Map();
69
+ /** @type {HTMLElement | undefined} */
70
+ let caretElement;
71
+
72
+ function onScroll() {
73
+ if (!scroller) return;
74
+ const gap =
75
+ scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;
76
+ stickToBottom = gap <= STICK_THRESHOLD;
77
+ }
78
+ scroller?.addEventListener("scroll", onScroll, { passive: true });
79
+
80
+ function cancelFrame() {
81
+ if (frame === undefined) return;
82
+ cancelAnimationFrame(frame);
83
+ frame = undefined;
84
+ }
85
+
86
+ // Coalesce chunk bursts into one highlight pass per frame.
87
+ function scheduleRender() {
88
+ if (frame !== undefined) return;
89
+ frame = requestAnimationFrame(() => {
90
+ frame = undefined;
91
+ render();
92
+ });
93
+ }
94
+
95
+ function render() {
96
+ const { code, language, done } = settings;
97
+ const state = done
98
+ ? highlighter.finish(code, language)
99
+ : highlighter.update(code, language);
100
+ highlighted = state.highlighted;
101
+ if (done) renderFinal();
102
+ else renderSplit(state);
103
+
104
+ onHighlight?.(highlighted);
105
+ if (done && !doneReported) {
106
+ doneReported = true;
107
+ onDone?.();
108
+ }
109
+ if (settings.autoScroll && stickToBottom && scroller) {
110
+ scroller.scrollTop = scroller.scrollHeight;
111
+ }
112
+ }
113
+
114
+ function renderFinal() {
115
+ element.innerHTML = highlighted;
116
+ mode = "final";
117
+ chunks = [];
118
+ tail.clear();
119
+ }
120
+
121
+ /** @param {import("./stream-highlighter.js").StreamHighlighterState} state */
122
+ function renderSplit(state) {
123
+ if (mode !== "split") {
124
+ element.textContent = "";
125
+ mode = "split";
126
+ }
127
+
128
+ /** @type {ChildNode | null} */
129
+ let before = null;
130
+ if (settings.caret) {
131
+ caretElement ??= createCaret();
132
+ if (element.lastChild !== caretElement) element.append(caretElement);
133
+ before = caretElement;
134
+ } else {
135
+ caretElement?.remove();
136
+ }
137
+
138
+ // Tail lines, keyed by line number: a line's span survives as the
139
+ // stream grows, and only its contents change.
140
+ const first = state.sealedLineCount;
141
+ const end = first + state.tailLines.length;
142
+ for (const [line, entry] of tail) {
143
+ if (line >= first && line < end) continue;
144
+ entry.newline?.remove();
145
+ entry.span.remove();
146
+ tail.delete(line);
147
+ }
148
+ for (let i = state.tailLines.length - 1; i >= 0; i--) {
149
+ const line = first + i;
150
+ const html = /** @type {string} */ (state.tailLines[i]);
151
+ let entry = tail.get(line);
152
+ if (!entry) {
153
+ entry = createTailLine(line);
154
+ tail.set(line, entry);
155
+ }
156
+ if (entry.html !== html) {
157
+ entry.span.innerHTML = html;
158
+ entry.html = html;
159
+ }
160
+ if (
161
+ entry.span.parentNode !== element ||
162
+ entry.span.nextSibling !== before
163
+ ) {
164
+ element.insertBefore(entry.span, before);
165
+ }
166
+ if (entry.newline && entry.newline.nextSibling !== entry.span) {
167
+ element.insertBefore(entry.newline, entry.span);
168
+ }
169
+ before = entry.newline ?? entry.span;
170
+ }
171
+
172
+ // Sealed chunks: appended once. Only a non-append edit (a regenerate)
173
+ // changes or drops one.
174
+ const sealed = state.sealedChunks;
175
+ for (let c = sealed.length; c < chunks.length; c++) {
176
+ for (const node of /** @type {RenderedChunk} */ (chunks[c]).nodes) {
177
+ node.remove();
178
+ }
179
+ }
180
+ chunks.length = Math.min(chunks.length, sealed.length);
181
+ for (let c = 0; c < sealed.length; c++) {
182
+ const html = /** @type {string} */ (sealed[c]);
183
+ const old = chunks[c];
184
+ if (old?.html === html) continue;
185
+ chunks[c] = { html, nodes: insertHtml(html, chunkAnchor(c, before)) };
186
+ if (old) for (const node of old.nodes) node.remove();
187
+ }
188
+ }
189
+
190
+ /**
191
+ * The node a chunk's HTML goes before: the first node of the next rendered
192
+ * chunk, or the start of the tail.
193
+ * @param {number} c
194
+ * @param {ChildNode | null} tailStart
195
+ * @returns {ChildNode | null}
196
+ */
197
+ function chunkAnchor(c, tailStart) {
198
+ for (let k = c; k < chunks.length; k++) {
199
+ const node = /** @type {RenderedChunk} */ (chunks[k]).nodes[0];
200
+ if (node) return node;
201
+ }
202
+ return tailStart;
203
+ }
204
+
205
+ /**
206
+ * @param {string} html
207
+ * @param {ChildNode | null} before
208
+ * @returns {ChildNode[]}
209
+ */
210
+ function insertHtml(html, before) {
211
+ const template = doc.createElement("template");
212
+ template.innerHTML = html;
213
+ const nodes = Array.from(template.content.childNodes);
214
+ element.insertBefore(template.content, before);
215
+ return nodes;
216
+ }
217
+
218
+ /**
219
+ * @param {number} line
220
+ * @returns {TailLine}
221
+ */
222
+ function createTailLine(line) {
223
+ const span = doc.createElement("span");
224
+ span.className = "highlight-stream-line";
225
+ span.setAttribute("data-line", String(line));
226
+ return {
227
+ html: "",
228
+ newline: line > 0 ? doc.createTextNode("\n") : undefined,
229
+ span,
230
+ };
231
+ }
232
+
233
+ function createCaret() {
234
+ const caret = doc.createElement("span");
235
+ caret.className = "highlight-stream-caret";
236
+ caret.setAttribute("aria-hidden", "true");
237
+ return caret;
238
+ }
239
+
240
+ // Draw the first frame now, so the element never shows empty.
241
+ render();
242
+
243
+ return {
244
+ /** The latest highlighted HTML. */
245
+ get highlighted() {
246
+ return highlighted;
247
+ },
248
+
249
+ /**
250
+ * Applies changed settings. While streaming, renders on the next frame;
251
+ * `done` renders at once.
252
+ * @param {Partial<StreamViewSettings>} next
253
+ */
254
+ update(next) {
255
+ if (destroyed) return;
256
+ let changed = false;
257
+ for (const key of /** @type {(keyof StreamViewSettings)[]} */ (
258
+ Object.keys(next)
259
+ )) {
260
+ const value = next[key];
261
+ if (value === undefined || value === settings[key]) continue;
262
+ // @ts-expect-error: `key` and `value` match.
263
+ settings[key] = value;
264
+ changed = true;
265
+ }
266
+ if (!changed) return;
267
+ if (settings.done) {
268
+ cancelFrame();
269
+ render();
270
+ } else {
271
+ doneReported = false;
272
+ scheduleRender();
273
+ }
274
+ },
275
+
276
+ /** Stops rendering and removes the scroll listener. Leaves the DOM as is. */
277
+ destroy() {
278
+ destroyed = true;
279
+ cancelFrame();
280
+ scroller?.removeEventListener("scroll", onScroll);
281
+ },
282
+ };
283
+ }
package/style-registry.js CHANGED
@@ -1,9 +1,40 @@
1
1
  // Owners of HighlightStyle's `<style>` tags, per key, in registration order.
2
2
  // Only the oldest renders; a store lets the rest re-derive a new owner when
3
3
  // it leaves.
4
- import { writable } from "svelte/store";
5
4
 
6
- /** @typedef {import("svelte/store").Writable<symbol[]>} Owners */
5
+ /**
6
+ * A minimal store. It follows the Svelte store contract (`subscribe` calls
7
+ * back at once and returns an unsubscriber), so `$owners` works in Svelte 4
8
+ * and 5, but needs no framework.
9
+ * @typedef {{
10
+ * subscribe(run: (value: symbol[]) => void): () => void,
11
+ * update(fn: (value: symbol[]) => symbol[]): void,
12
+ * }} Owners
13
+ */
14
+
15
+ /** @returns {Owners} */
16
+ function createOwners() {
17
+ /** @type {symbol[]} */
18
+ let value = [];
19
+ /** @type {Set<{ run: (value: symbol[]) => void }>} */
20
+ const subscribers = new Set();
21
+ return {
22
+ subscribe(run) {
23
+ const subscriber = { run };
24
+ subscribers.add(subscriber);
25
+ run(value);
26
+ return () => {
27
+ subscribers.delete(subscriber);
28
+ };
29
+ },
30
+ update(fn) {
31
+ const next = fn(value);
32
+ if (next === value) return;
33
+ value = next;
34
+ for (const subscriber of [...subscribers]) subscriber.run(value);
35
+ },
36
+ };
37
+ }
7
38
 
8
39
  export function createStyleRegistry() {
9
40
  /** @type {Map<string, Owners>} */
@@ -18,7 +49,7 @@ export function createStyleRegistry() {
18
49
  register(key, token) {
19
50
  let owners = registries.get(key);
20
51
  if (!owners) {
21
- owners = writable([]);
52
+ owners = createOwners();
22
53
  registries.set(key, owners);
23
54
  }
24
55
  owners.update((list) => [...list, token]);
@@ -0,0 +1 @@
1
+ export declare const BASE_CSS: string;
@@ -0,0 +1 @@
1
+ export const BASE_CSS = "pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}.hljs{color:var(--shl-fg);background-color:var(--shl-bg);font-weight:var(--shl-font-weight)}.hljs-addition{color:var(--shl-addition);background-color:var(--shl-addition-bg);font-style:var(--shl-addition-font-style)}.hljs-attr{color:var(--shl-attr);font-style:var(--shl-attr-font-style);font-weight:var(--shl-attr-font-weight)}.hljs-attribute{color:var(--shl-attribute);font-weight:var(--shl-attribute-font-weight)}.hljs-built_in{color:var(--shl-built_in);font-style:var(--shl-built_in-font-style);font-weight:var(--shl-built_in-font-weight);text-decoration:var(--shl-built_in-text-decoration)}.hljs-bullet{color:var(--shl-bullet);background-color:var(--shl-bullet-bg);font-style:var(--shl-bullet-font-style)}.hljs-class{color:var(--shl-class);font-weight:var(--shl-class-font-weight)}.hljs-code{color:var(--shl-code);font-style:var(--shl-code-font-style)}.hljs-comment{color:var(--shl-comment);font-style:var(--shl-comment-font-style)}.hljs-constructor{color:var(--shl-constructor)}.hljs-deletion{color:var(--shl-deletion);background-color:var(--shl-deletion-bg);font-style:var(--shl-deletion-font-style)}.hljs-doctag{color:var(--shl-doctag);font-weight:var(--shl-doctag-font-weight);text-decoration:var(--shl-doctag-text-decoration)}.hljs-emphasis{color:var(--shl-emphasis);font-style:var(--shl-emphasis-font-style)}.hljs-formula{color:var(--shl-formula);background-color:var(--shl-formula-bg);font-style:var(--shl-formula-font-style)}.hljs-function{color:var(--shl-function)}.hljs-keyword{color:var(--shl-keyword);font-style:var(--shl-keyword-font-style);font-weight:var(--shl-keyword-font-weight)}.hljs-link{color:var(--shl-link);font-weight:var(--shl-link-font-weight);text-decoration:var(--shl-link-text-decoration)}.hljs-literal{color:var(--shl-literal);font-weight:var(--shl-literal-font-weight)}.hljs-meta{color:var(--shl-meta);font-weight:var(--shl-meta-font-weight)}.hljs-meta-keyword{font-weight:var(--shl-meta-keyword-font-weight)}.hljs-meta-string{color:var(--shl-meta-string)}.hljs-name{color:var(--shl-name);font-weight:var(--shl-name-font-weight)}.hljs-number{color:var(--shl-number);font-weight:var(--shl-number-font-weight)}.hljs-operator{color:var(--shl-operator)}.hljs-params{color:var(--shl-params);font-weight:var(--shl-params-font-weight)}.hljs-pattern-match{color:var(--shl-pattern-match)}.hljs-property{color:var(--shl-property)}.hljs-punctuation{color:var(--shl-punctuation)}.hljs-quote{color:var(--shl-quote);font-style:var(--shl-quote-font-style)}.hljs-regexp{color:var(--shl-regexp);background-color:var(--shl-regexp-bg);font-weight:var(--shl-regexp-font-weight)}.hljs-section{color:var(--shl-section);font-weight:var(--shl-section-font-weight)}.hljs-selector-attr{color:var(--shl-selector-attr);font-style:var(--shl-selector-attr-font-style)}.hljs-selector-class{color:var(--shl-selector-class);font-style:var(--shl-selector-class-font-style);font-weight:var(--shl-selector-class-font-weight)}.hljs-selector-id{color:var(--shl-selector-id);font-weight:var(--shl-selector-id-font-weight)}.hljs-selector-pseudo{color:var(--shl-selector-pseudo);font-style:var(--shl-selector-pseudo-font-style);font-weight:var(--shl-selector-pseudo-font-weight)}.hljs-selector-tag{color:var(--shl-selector-tag);font-weight:var(--shl-selector-tag-font-weight)}.hljs-string{color:var(--shl-string);font-weight:var(--shl-string-font-weight)}.hljs-strong{color:var(--shl-strong);font-weight:var(--shl-strong-font-weight)}.hljs-stronge{font-style:var(--shl-stronge-font-style)}.hljs-subst{color:var(--shl-subst);font-weight:var(--shl-subst-font-weight)}.hljs-subtr{color:var(--shl-subtr)}.hljs-symbol{color:var(--shl-symbol);background-color:var(--shl-symbol-bg);font-style:var(--shl-symbol-font-style)}.hljs-tag{color:var(--shl-tag);background-color:var(--shl-tag-bg);font-weight:var(--shl-tag-font-weight)}.hljs-template-tag{color:var(--shl-template-tag);font-weight:var(--shl-template-tag-font-weight)}.hljs-template-variable{color:var(--shl-template-variable);font-weight:var(--shl-template-variable-font-weight)}.hljs-title{color:var(--shl-title);font-style:var(--shl-title-font-style);font-weight:var(--shl-title-font-weight)}.hljs-type{color:var(--shl-type);font-style:var(--shl-type-font-style);font-weight:var(--shl-type-font-weight)}.hljs-variable{color:var(--shl-variable);font-weight:var(--shl-variable-font-weight)}.hljs-char.escape_{color:var(--shl-char-escape_, var(--shl-char))}.hljs-class .hljs-title{color:var(--shl-class-title, var(--shl-title));font-weight:var(--shl-class-title-font-weight, var(--shl-title-font-weight));text-decoration:var(--shl-class-title-text-decoration, var(--shl-title-text-decoration))}.hljs-code .hljs-selector-class{color:var(--shl-code-selector-class, var(--shl-selector-class))}.hljs-constructor .hljs-string{color:var(--shl-constructor-string, var(--shl-string))}.hljs-function .hljs-params{color:var(--shl-function-params, var(--shl-params))}.hljs-function .hljs-title{color:var(--shl-function-title, var(--shl-title))}.hljs-keyword.hljs-atrule{color:var(--shl-keyword-atrule, var(--shl-keyword))}.hljs-meta .hljs-keyword{color:var(--shl-meta-keyword, var(--shl-keyword));font-weight:var(--shl-meta-keyword-font-weight, var(--shl-keyword-font-weight))}.hljs-meta .hljs-string{color:var(--shl-meta-string, var(--shl-string))}.hljs-module-access .hljs-module{color:var(--shl-module-access-module, var(--shl-module))}.hljs-pattern-match .hljs-constructor{color:var(--shl-pattern-match-constructor, var(--shl-constructor))}.hljs-subst .hljs-link{color:var(--shl-subst-link, var(--shl-link))}.hljs-tag .hljs-attr{color:var(--shl-tag-attr, var(--shl-attr))}.hljs-tag .hljs-name{color:var(--shl-tag-name, var(--shl-name))}.hljs-title.class_{color:var(--shl-title-class_, var(--shl-title));font-weight:var(--shl-title-class_-font-weight, var(--shl-title-font-weight));text-decoration:var(--shl-title-class_-text-decoration, var(--shl-title-text-decoration))}.hljs-title.class_.inherited__{color:var(--shl-title-class_-inherited__, var(--shl-title))}.hljs-title.function_{color:var(--shl-title-function_, var(--shl-title))}.hljs-title.hljs-function{color:var(--shl-title-function, var(--shl-title))}.hljs-variable.constant_{color:var(--shl-variable-constant_, var(--shl-variable))}.hljs-variable.language_{color:var(--shl-variable-language_, var(--shl-variable))}";
@@ -11,6 +11,9 @@ export interface TypewriterUnit {
11
11
  */
12
12
  export declare function tokenizeTypewriter(html: string): TypewriterUnit[];
13
13
 
14
+ /** Visible text of the units, with HTML entities decoded. */
15
+ export declare function unitText(units: TypewriterUnit[]): string;
16
+
14
17
  /** Wraps each visible unit in a `typewriter-unit typewriter-hidden` span. */
15
18
  export declare function buildUnitMarkup(units: TypewriterUnit[]): string;
16
19
 
@@ -65,6 +65,49 @@ export function tokenizeTypewriter(html) {
65
65
  return units;
66
66
  }
67
67
 
68
+ /** @type {Record<string, string>} */
69
+ const NAMED_ENTITIES = {
70
+ "&amp;": "&",
71
+ "&lt;": "<",
72
+ "&gt;": ">",
73
+ "&quot;": '"',
74
+ "&apos;": "'",
75
+ "&nbsp;": " ",
76
+ };
77
+
78
+ const NUMERIC_ENTITY = /^&#(x[0-9a-f]+|[0-9]+);$/i;
79
+
80
+ /** @param {string} raw */
81
+ function decodeEntity(raw) {
82
+ const named = NAMED_ENTITIES[raw];
83
+ if (named !== undefined) return named;
84
+ const match = NUMERIC_ENTITY.exec(raw);
85
+ if (!match) return raw;
86
+ const digits = /** @type {string} */ (match[1]);
87
+ const codePoint =
88
+ digits[0] === "x" || digits[0] === "X"
89
+ ? Number.parseInt(digits.slice(1), 16)
90
+ : Number.parseInt(digits, 10);
91
+ return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : raw;
92
+ }
93
+
94
+ /**
95
+ * Visible text of the units, with HTML entities decoded.
96
+ * @param {TypewriterUnit[]} units
97
+ * @returns {string}
98
+ */
99
+ export function unitText(units) {
100
+ let text = "";
101
+ for (const unit of units) {
102
+ if (unit.visible === 0) continue;
103
+ text +=
104
+ unit.raw.length > 2 && unit.raw[0] === "&"
105
+ ? decodeEntity(unit.raw)
106
+ : unit.raw;
107
+ }
108
+ return text;
109
+ }
110
+
68
111
  /**
69
112
  * @param {TypewriterUnit[]} units
70
113
  * @returns {string}