svelte-highlight 7.14.1 → 7.15.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.
package/Typewriter.svelte CHANGED
@@ -18,11 +18,15 @@
18
18
  export let play = true;
19
19
 
20
20
  import { createEventDispatcher, onMount } from "svelte";
21
+ import { tokenizeTypewriter as tokenize } from "./typewriter-units.js";
21
22
 
22
23
  const dispatch = createEventDispatcher();
23
24
 
24
- /** Opening or closing tag name. */
25
- const TAG_NAME = /^<\/?\s*([a-zA-Z0-9-]+)/;
25
+ // Above this many visible units, per-unit spans (one element per char)
26
+ // stop paying for themselves; fall back to the old whole-string rebuild.
27
+ const UNIT_THRESHOLD = 20000;
28
+
29
+ const EMPTY_PARTS = { head: "", tail: "" };
26
30
 
27
31
  /** @type {boolean} */
28
32
  let mounted = false;
@@ -42,51 +46,20 @@
42
46
  /** @type {string | undefined} */
43
47
  let prevHighlighted;
44
48
 
45
- /** Split HTML into typing units (tags = 0 chars, text/entities = 1). */
46
- function tokenize(html) {
47
- /** @type {{ raw: string; visible: number; kind?: string; name?: string }[]} */
48
- const units = [];
49
- const n = html.length;
50
- let i = 0;
49
+ /** Container for the per-unit spans (unit-reveal path only). @type {HTMLElement} */
50
+ let contentEl;
51
51
 
52
- while (i < n) {
53
- const ch = html[i];
54
-
55
- if (ch === "<") {
56
- const end = html.indexOf(">", i);
57
- if (end === -1) {
58
- // Unclosed tag: treat as text.
59
- units.push({ raw: html.slice(i), visible: 1 });
60
- break;
61
- }
62
- const raw = html.slice(i, end + 1);
63
- const kind =
64
- raw[1] === "/"
65
- ? "close"
66
- : raw[raw.length - 2] === "/"
67
- ? "self"
68
- : "open";
69
- const match = TAG_NAME.exec(raw);
70
- units.push({ raw, visible: 0, kind, name: match ? match[1] : "" });
71
- i = end + 1;
72
- } else if (ch === "&") {
73
- // One visible char per entity.
74
- const end = html.indexOf(";", i);
75
- if (end !== -1 && end - i <= 10) {
76
- units.push({ raw: html.slice(i, end + 1), visible: 1 });
77
- i = end + 1;
78
- } else {
79
- units.push({ raw: ch, visible: 1 });
80
- i += 1;
81
- }
82
- } else {
83
- units.push({ raw: ch, visible: 1 });
84
- i += 1;
85
- }
86
- }
52
+ /** @type {HTMLElement[]} */
53
+ let unitEls = [];
87
54
 
88
- return units;
89
- }
55
+ /** The `units` array currently painted into `contentEl`. */
56
+ let paintedUnits;
57
+
58
+ /** How many leading units already had `typewriter-hidden` removed. */
59
+ let revealedInDom = 0;
60
+
61
+ /** The unit currently marked with the caret, if any. @type {HTMLElement | undefined} */
62
+ let caretMark;
90
63
 
91
64
  /**
92
65
  * Split at `count` visible chars. Close open tags in `head`, reopen in `tail`.
@@ -124,6 +97,52 @@
124
97
  return { head: head + headClose, tail };
125
98
  }
126
99
 
100
+ /** Render every unit once: tags pass through, each visible unit gets a span. */
101
+ function buildUnitMarkup(list) {
102
+ let html = "";
103
+ for (const unit of list) {
104
+ html +=
105
+ unit.visible === 0
106
+ ? unit.raw
107
+ : `<span class="typewriter-unit typewriter-hidden">${unit.raw}</span>`;
108
+ }
109
+ return html;
110
+ }
111
+
112
+ /**
113
+ * Bring `contentEl` in sync with `units`/`revealed` in O(1) amortized work:
114
+ * a fresh `units` value triggers one full (re)paint; otherwise only the
115
+ * units newly revealed since the last call are touched.
116
+ */
117
+ function syncUnitDom() {
118
+ if (!contentEl) return;
119
+
120
+ if (paintedUnits !== units) {
121
+ contentEl.innerHTML = buildUnitMarkup(units);
122
+ unitEls = Array.from(contentEl.getElementsByClassName("typewriter-unit"));
123
+ paintedUnits = units;
124
+ revealedInDom = 0;
125
+ caretMark = undefined;
126
+ }
127
+
128
+ while (revealedInDom < revealed) {
129
+ unitEls[revealedInDom]?.classList.remove("typewriter-hidden");
130
+ revealedInDom++;
131
+ }
132
+
133
+ if (caretMark) {
134
+ caretMark.classList.remove("typewriter-caret");
135
+ caretMark = undefined;
136
+ }
137
+ if (revealed < total) {
138
+ const next = unitEls[revealed];
139
+ if (next) {
140
+ next.classList.add("typewriter-caret");
141
+ caretMark = next;
142
+ }
143
+ }
144
+ }
145
+
127
146
  function clearTimer() {
128
147
  clearInterval(timerId);
129
148
  timerId = undefined;
@@ -136,8 +155,9 @@
136
155
  }
137
156
  }
138
157
 
139
- function tick() {
158
+ function advance() {
140
159
  if (revealed < total) revealed += 1;
160
+ if (useUnitReveal) syncUnitDom();
141
161
  if (revealed >= total) {
142
162
  clearTimer();
143
163
  fireDone();
@@ -156,8 +176,10 @@
156
176
  return;
157
177
  }
158
178
 
179
+ if (useUnitReveal) syncUnitDom();
180
+
159
181
  if (play && revealed < total) {
160
- timerId = setInterval(tick, Math.max(0, speed));
182
+ timerId = setInterval(advance, Math.max(0, speed));
161
183
  } else if (revealed >= total) {
162
184
  fireDone();
163
185
  }
@@ -165,23 +187,30 @@
165
187
 
166
188
  $: units = tokenize(highlighted);
167
189
  $: total = units.reduce((sum, unit) => sum + unit.visible, 0);
190
+ $: bigInput = total > UNIT_THRESHOLD;
191
+ $: useUnitReveal = mounted && !reducedMotion && !bigInput;
168
192
 
169
193
  // Restart when `highlighted` changes.
170
194
  $: if (highlighted !== prevHighlighted) {
171
195
  prevHighlighted = highlighted;
172
196
  doneFired = false;
173
197
  revealed = reducedMotion ? total : 0;
198
+ void useUnitReveal;
174
199
  sync();
175
200
  }
176
201
 
177
202
  // Re-sync on play/speed/mount/motion. Skip `total` (handled above).
178
203
  $: {
179
- void [play, speed, mounted, reducedMotion];
204
+ void [play, speed, mounted, reducedMotion, useUnitReveal];
180
205
  sync();
181
206
  }
182
207
 
183
- // SSR: full content. After mount, reveal from `revealed`.
184
- $: parts = mounted ? split(units, revealed) : { head: highlighted, tail: "" };
208
+ // SSR / slow-path: full content up front, split() only when actually needed.
209
+ $: parts = useUnitReveal
210
+ ? EMPTY_PARTS
211
+ : mounted
212
+ ? split(units, revealed)
213
+ : { head: highlighted, tail: "" };
185
214
  $: showCaret = mounted && !reducedMotion && revealed < total;
186
215
 
187
216
  onMount(() => {
@@ -201,13 +230,15 @@
201
230
  });
202
231
  </script>
203
232
 
204
- <pre
205
- {...$$restProps}
206
- ><code class:hljs={true}>{@html parts.head}{#if showCaret}<span
207
- class="typewriter-caret"
208
- aria-hidden="true"
209
- ></span>{/if}<span class="typewriter-rest" aria-hidden="true"
210
- >{@html parts.tail}</span></code></pre>
233
+ <pre {...$$restProps}><code class:hljs={true}
234
+ ><span class="typewriter-content" bind:this={contentEl} hidden={!useUnitReveal}
235
+ ></span
236
+ >{#if !useUnitReveal}{@html parts.head}{#if showCaret}<span
237
+ class="typewriter-caret"
238
+ aria-hidden="true"
239
+ ></span>{/if}<span class="typewriter-rest" aria-hidden="true"
240
+ >{@html parts.tail}</span
241
+ >{/if}</code></pre>
211
242
 
212
243
  <style>
213
244
  .typewriter-rest {
@@ -224,8 +255,30 @@
224
255
  animation: typewriter-blink var(--caret-blink, 1s) step-end infinite;
225
256
  }
226
257
 
258
+ /* `.typewriter-unit`/`.typewriter-hidden` only ever exist inside the
259
+ `{@html}`-free, JS-painted `contentEl`, so they're invisible to Svelte's
260
+ static analysis and must stay unscoped. */
261
+ :global(.typewriter-unit.typewriter-hidden) {
262
+ visibility: hidden;
263
+ }
264
+
265
+ /* The caret rides the next-to-reveal (still hidden) unit's ::before, so it
266
+ never requires moving a real DOM node -- one class add/remove per tick. */
267
+ :global(.typewriter-unit.typewriter-caret)::before {
268
+ content: "";
269
+ visibility: visible;
270
+ display: inline-block;
271
+ width: var(--caret-width, 0.6em);
272
+ height: var(--caret-height, 1.1em);
273
+ margin-left: var(--caret-gap, 1px);
274
+ vertical-align: text-bottom;
275
+ background: var(--caret-color, currentColor);
276
+ animation: typewriter-blink var(--caret-blink, 1s) step-end infinite;
277
+ }
278
+
227
279
  @media (prefers-reduced-motion: reduce) {
228
- .typewriter-caret {
280
+ .typewriter-caret,
281
+ :global(.typewriter-unit.typewriter-caret)::before {
229
282
  animation: none;
230
283
  }
231
284
  }
package/action.js CHANGED
@@ -7,13 +7,32 @@ import hljs from "highlight.js/lib/core";
7
7
  * @type {import("svelte/action").Action<HTMLElement, { language: import("./languages").LanguageType<string>; code?: string }>}
8
8
  */
9
9
  export function highlight(node, parameters) {
10
+ // Snapshot the pre-action source once: updates that omit `code` fall back
11
+ // to this instead of `node.textContent`, which after the first highlight
12
+ // pass holds the already-highlighted (and DOM-normalized) output.
13
+ const originalText = node.textContent ?? "";
14
+
10
15
  /** @param {{ language: import("./languages").LanguageType<string>; code?: string }} params */
11
16
  function apply({ language, code }) {
12
- if (!hljs.getLanguage(language.name)) {
13
- hljs.registerLanguage(language.name, language.register);
17
+ const source = code ?? originalText;
18
+ let value;
19
+
20
+ try {
21
+ if (!hljs.getLanguage(language.name)) {
22
+ hljs.registerLanguage(language.name, language.register);
23
+ }
24
+ value = hljs.highlight(source, { language: language.name }).value;
25
+ } catch (error) {
26
+ if (import.meta.env?.DEV) {
27
+ console.warn(
28
+ `[svelte-highlight] failed to highlight with language "${language.name}"; leaving content unchanged.`,
29
+ error,
30
+ );
31
+ }
32
+ return;
14
33
  }
15
- const source = code ?? node.textContent ?? "";
16
- node.innerHTML = hljs.highlight(source, { language: language.name }).value;
34
+
35
+ node.innerHTML = value;
17
36
  node.classList.add("hljs");
18
37
  }
19
38
 
@@ -21,5 +40,9 @@ export function highlight(node, parameters) {
21
40
 
22
41
  return {
23
42
  update: apply,
43
+ destroy() {
44
+ node.classList.remove("hljs");
45
+ node.textContent = originalText;
46
+ },
24
47
  };
25
48
  }
package/ansi.d.ts CHANGED
@@ -16,6 +16,9 @@ export type AnsiStyle = {
16
16
  dim?: boolean | undefined;
17
17
  italic?: boolean | undefined;
18
18
  underline?: boolean | undefined;
19
+ reverse?: boolean | undefined;
20
+ strikethrough?: boolean | undefined;
21
+ conceal?: boolean | undefined;
19
22
  fg?: AnsiColor | undefined;
20
23
  bg?: AnsiColor | undefined;
21
24
  };
@@ -28,8 +31,14 @@ export type AnsiSegment = {
28
31
  dim?: boolean;
29
32
  italic?: boolean;
30
33
  underline?: boolean;
34
+ /** Strikethrough (SGR 9). */
35
+ strikethrough?: boolean;
36
+ /** Text is present for layout/copy but rendered invisible (SGR 8). */
37
+ conceal?: boolean;
31
38
  fg?: AnsiColor;
32
39
  bg?: AnsiColor;
40
+ /** OSC 8 hyperlink target for this run, if any. */
41
+ link?: string;
33
42
  };
34
43
 
35
44
  /** Parse ANSI SGR escape codes into styled segments. Malformed input is dropped. */
package/ansi.js CHANGED
@@ -58,6 +58,9 @@ function applySgr(style, params) {
58
58
  style.dim = undefined;
59
59
  style.italic = undefined;
60
60
  style.underline = undefined;
61
+ style.reverse = undefined;
62
+ style.strikethrough = undefined;
63
+ style.conceal = undefined;
61
64
  style.fg = undefined;
62
65
  style.bg = undefined;
63
66
  } else if (code === 1) {
@@ -68,6 +71,22 @@ function applySgr(style, params) {
68
71
  style.italic = true;
69
72
  } else if (code === 4) {
70
73
  style.underline = true;
74
+ } else if (code === 21) {
75
+ // Spec says "double underline"; several emitters instead use 21 as
76
+ // "bold off". We follow the spec and treat it as underline.
77
+ style.underline = true;
78
+ } else if (code === 7) {
79
+ style.reverse = true;
80
+ } else if (code === 27) {
81
+ style.reverse = undefined;
82
+ } else if (code === 8) {
83
+ style.conceal = true;
84
+ } else if (code === 28) {
85
+ style.conceal = undefined;
86
+ } else if (code === 9) {
87
+ style.strikethrough = true;
88
+ } else if (code === 29) {
89
+ style.strikethrough = undefined;
71
90
  } else if (code === 22) {
72
91
  style.bold = undefined;
73
92
  style.dim = undefined;
@@ -117,17 +136,26 @@ function applySgr(style, params) {
117
136
  * Build a segment from `text` and active fields in `style`.
118
137
  * @param {string} text
119
138
  * @param {AnsiStyle} style
139
+ * @param {string} [link]
120
140
  * @returns {AnsiSegment}
121
141
  */
122
- function toSegment(text, style) {
142
+ function toSegment(text, style, link) {
123
143
  /** @type {AnsiSegment} */
124
144
  const segment = { text };
125
145
  if (style.bold) segment.bold = true;
126
146
  if (style.dim) segment.dim = true;
127
147
  if (style.italic) segment.italic = true;
128
148
  if (style.underline) segment.underline = true;
129
- if (style.fg) segment.fg = style.fg;
130
- if (style.bg) segment.bg = style.bg;
149
+ if (style.strikethrough) segment.strikethrough = true;
150
+ if (style.conceal) segment.conceal = true;
151
+ // Reverse video swaps fg/bg on the emitted segment. `style.fg`/`style.bg`
152
+ // themselves are untouched, so a later SGR 27 (reverse off) restores the
153
+ // original mapping for text that follows.
154
+ const fg = style.reverse ? style.bg : style.fg;
155
+ const bg = style.reverse ? style.fg : style.bg;
156
+ if (fg) segment.fg = fg;
157
+ if (bg) segment.bg = bg;
158
+ if (link) segment.link = link;
131
159
  return segment;
132
160
  }
133
161
 
@@ -147,14 +175,42 @@ export function parseAnsi(text) {
147
175
  /** @type {AnsiStyle} */
148
176
  const style = {};
149
177
  let buffer = "";
178
+ /** @type {string | undefined} */
179
+ let link;
150
180
 
151
181
  const flush = () => {
152
182
  if (buffer) {
153
- segments.push(toSegment(buffer, style));
183
+ segments.push(toSegment(buffer, style, link));
154
184
  buffer = "";
155
185
  }
156
186
  };
157
187
 
188
+ /**
189
+ * Handle a lone `\r`: per-line overwrite semantics. Full last-write-wins
190
+ * per character cell is overkill for a text renderer, so we use a
191
+ * simplification: discard everything back to the start of the current
192
+ * line (the last `\n`) so that subsequent text rebuilds the line fresh.
193
+ */
194
+ const resetLine = () => {
195
+ const bufferBreak = buffer.lastIndexOf("\n");
196
+ if (bufferBreak !== -1) {
197
+ buffer = buffer.slice(0, bufferBreak + 1);
198
+ return;
199
+ }
200
+ buffer = "";
201
+ let last = segments.pop();
202
+ while (last !== undefined) {
203
+ const segmentBreak = last.text.lastIndexOf("\n");
204
+ if (segmentBreak === -1) {
205
+ last = segments.pop();
206
+ continue;
207
+ }
208
+ last.text = last.text.slice(0, segmentBreak + 1);
209
+ segments.push(last);
210
+ return;
211
+ }
212
+ };
213
+
158
214
  let i = 0;
159
215
  while (i < text.length) {
160
216
  const ch = text[i];
@@ -189,6 +245,58 @@ export function parseAnsi(text) {
189
245
  continue;
190
246
  }
191
247
 
248
+ if (ch === ESC && text[i + 1] === "]") {
249
+ // Read an OSC sequence: body up to a BEL or ST (`ESC \`) terminator.
250
+ let j = i + 2;
251
+ let terminatorLength = 0;
252
+ while (j < text.length) {
253
+ if (text[j] === "\x07") {
254
+ terminatorLength = 1;
255
+ break;
256
+ }
257
+ if (text[j] === ESC && text[j + 1] === "\\") {
258
+ terminatorLength = 2;
259
+ break;
260
+ }
261
+ j += 1;
262
+ }
263
+
264
+ if (terminatorLength === 0) {
265
+ // Unterminated: drop the rest.
266
+ break;
267
+ }
268
+
269
+ const body = text.slice(i + 2, j);
270
+ const firstSemi = body.indexOf(";");
271
+ const command = firstSemi === -1 ? body : body.slice(0, firstSemi);
272
+ if (command === "8" && firstSemi !== -1) {
273
+ // OSC 8 hyperlink: `8;params;uri`. An empty uri closes the link.
274
+ const rest = body.slice(firstSemi + 1);
275
+ const secondSemi = rest.indexOf(";");
276
+ if (secondSemi !== -1) {
277
+ flush();
278
+ const uri = rest.slice(secondSemi + 1);
279
+ link = uri || undefined;
280
+ }
281
+ }
282
+ // Other OSC sequences (title/icon sets, unknown commands) carry no
283
+ // rendered state: strip them silently.
284
+ i = j + terminatorLength;
285
+ continue;
286
+ }
287
+
288
+ if (ch === "\r") {
289
+ if (text[i + 1] === "\n") {
290
+ // Treat \r\n as \n.
291
+ buffer += "\n";
292
+ i += 2;
293
+ continue;
294
+ }
295
+ resetLine();
296
+ i += 1;
297
+ continue;
298
+ }
299
+
192
300
  buffer += ch;
193
301
  i += 1;
194
302
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Strip a leading prompt from each line that has one. Lines without a
3
+ * matching prompt (e.g. command output in a multi-command block) are kept
4
+ * as-is.
5
+ */
6
+ export declare function stripPrompts(code: string, prompts?: string[]): string;
7
+
8
+ /**
9
+ * Strip a leading diff marker (`+ `, `- `, or a bare `+`/`-` immediately
10
+ * before content) from each line. Context lines without a marker are left
11
+ * unchanged.
12
+ */
13
+ export declare function stripDiffMarkers(code: string): string;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Composable transforms for `CopyButton`'s `transform` prop, for stripping
3
+ * decoration (shell prompts, REPL markers, diff signs) that should not
4
+ * survive a copy.
5
+ */
6
+
7
+ /**
8
+ * Strip a leading prompt from each line that has one. Lines without a
9
+ * matching prompt (e.g. command output in a multi-command block) are kept
10
+ * as-is.
11
+ * @param {string} code
12
+ * @param {string[]} [prompts]
13
+ * @returns {string}
14
+ */
15
+ export function stripPrompts(code, prompts = ["$ ", "> "]) {
16
+ return code
17
+ .split("\n")
18
+ .map((line) => {
19
+ const prompt = prompts.find((p) => line.startsWith(p));
20
+ return prompt ? line.slice(prompt.length) : line;
21
+ })
22
+ .join("\n");
23
+ }
24
+
25
+ /**
26
+ * Strip a leading diff marker (`+ `, `- `, or a bare `+`/`-` immediately
27
+ * before content) from each line. Context lines without a marker are left
28
+ * unchanged.
29
+ * @param {string} code
30
+ * @returns {string}
31
+ */
32
+ export function stripDiffMarkers(code) {
33
+ return code
34
+ .split("\n")
35
+ .map((line) => {
36
+ if (line.startsWith("+ ") || line.startsWith("- ")) return line.slice(2);
37
+ if (line.startsWith("+") || line.startsWith("-")) return line.slice(1);
38
+ return line;
39
+ })
40
+ .join("\n");
41
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Convert a theme's `.hljs-<scope>` color/background-color rules into
3
+ * `::highlight(hljs-<scope>)` rules. Font-style, font-weight, and any
4
+ * property other than color/background-color are dropped (the API's
5
+ * cross-browser envelope), as are compound and descendant selectors.
6
+ */
7
+ export function highlightRules(theme: string): string;