svelte-highlight 7.17.0 → 7.18.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/AnsiOutput.svelte CHANGED
@@ -9,147 +9,14 @@
9
9
  export let autoContrast = true;
10
10
 
11
11
  import { parseAnsi } from "./ansi.js";
12
-
13
- // Default foreground and minimum WCAG contrast ratio against backgrounds.
14
- const FOREGROUND_FALLBACK = "#d4d4d4";
15
- const CONTRAST_TARGET = 4.5;
16
- /** @type {[number, number, number]} */
17
- const BLACK = [0, 0, 0];
18
- /** @type {[number, number, number]} */
19
- const WHITE = [255, 255, 255];
20
-
21
- // 16-color xterm defaults, each overridable via `--ansi-<name>`.
22
- const DEFAULTS = {
23
- black: "#000000",
24
- red: "#cd0000",
25
- green: "#00cd00",
26
- yellow: "#cdcd00",
27
- blue: "#0000ee",
28
- magenta: "#cd00cd",
29
- cyan: "#00cdcd",
30
- white: "#e5e5e5",
31
- "bright-black": "#7f7f7f",
32
- "bright-red": "#ff0000",
33
- "bright-green": "#00ff00",
34
- "bright-yellow": "#ffff00",
35
- "bright-blue": "#5c5cff",
36
- "bright-magenta": "#ff00ff",
37
- "bright-cyan": "#00ffff",
38
- "bright-white": "#ffffff",
39
- };
40
-
41
- // 256-color cube steps (6×6×6).
42
- const CUBE = [0, 95, 135, 175, 215, 255];
43
-
44
- /** 256-color index → hex. */
45
- function indexedHex(index) {
46
- if (index >= 232) {
47
- const value = (index - 232) * 10 + 8;
48
- const hex = value.toString(16).padStart(2, "0");
49
- return `#${hex}${hex}${hex}`;
50
- }
51
- const n = index - 16;
52
- const r = CUBE[Math.floor(n / 36) % 6];
53
- const g = CUBE[Math.floor(n / 6) % 6];
54
- const b = CUBE[n % 6];
55
- return `#${[r, g, b].map((c) => c.toString(16).padStart(2, "0")).join("")}`;
56
- }
57
-
58
- /** Parsed color → CSS (named colors use `--ansi-*` vars). */
59
- function cssColor(color) {
60
- if ("name" in color) {
61
- return `var(--ansi-${color.name}, ${DEFAULTS[color.name]})`;
62
- }
63
- if ("rgb" in color) {
64
- return `rgb(${color.rgb[0]}, ${color.rgb[1]}, ${color.rgb[2]})`;
65
- }
66
- return indexedHex(color.index);
67
- }
68
-
69
- /**
70
- * @param {string} hex A `#rrggbb` string.
71
- * @returns {[number, number, number]}
72
- */
73
- function hexToRgb(hex) {
74
- const value = hex.replace("#", "");
75
- return [
76
- Number.parseInt(value.slice(0, 2), 16),
77
- Number.parseInt(value.slice(2, 4), 16),
78
- Number.parseInt(value.slice(4, 6), 16),
79
- ];
80
- }
81
-
82
- /** Named colors use the default palette (theme overrides aren't known here). */
83
- function colorToRgb(color) {
84
- if ("name" in color) return hexToRgb(DEFAULTS[color.name] ?? "#000000");
85
- if ("rgb" in color) return color.rgb;
86
- return hexToRgb(indexedHex(color.index));
87
- }
88
-
89
- /** WCAG relative luminance. */
90
- function luminance([r, g, b]) {
91
- const channels = [r, g, b].map((c) => {
92
- const v = c / 255;
93
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
94
- });
95
- return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
96
- }
97
-
98
- /** WCAG contrast ratio. */
99
- function contrastRatio(a, b) {
100
- const la = luminance(a);
101
- const lb = luminance(b);
102
- return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
103
- }
104
-
105
- /** Black or white, whichever contrasts more with `bg`. */
106
- function readableForeground(bg) {
107
- return contrastRatio(BLACK, bg) >= contrastRatio(WHITE, bg)
108
- ? "#000000"
109
- : "#ffffff";
110
- }
111
-
112
- /** Foreground CSS, with auto-contrast override when needed. */
113
- function foregroundCss(segment) {
114
- // Concealed text is rendered transparent (layout and copy text stay).
115
- if (segment.conceal) return "transparent";
116
- if (autoContrast && segment.bg) {
117
- const bg = colorToRgb(segment.bg);
118
- const fg = segment.fg
119
- ? colorToRgb(segment.fg)
120
- : hexToRgb(FOREGROUND_FALLBACK);
121
- if (contrastRatio(fg, bg) < CONTRAST_TARGET)
122
- return readableForeground(bg);
123
- }
124
- return segment.fg ? cssColor(segment.fg) : undefined;
125
- }
126
-
127
- /** @param {import("./ansi").AnsiSegment} segment */
128
- function classNames(segment) {
129
- const names = [];
130
- if (segment.bold) names.push("bold");
131
- if (segment.dim) names.push("dim");
132
- if (segment.italic) names.push("italic");
133
- if (segment.underline) names.push("underline");
134
- if (segment.strikethrough) names.push("strikethrough");
135
- return names.length ? names.join(" ") : undefined;
136
- }
137
-
138
- /** @param {import("./ansi").AnsiSegment} segment */
139
- function inlineStyle(segment) {
140
- let style = "";
141
- if (segment.bg) style += `background-color:${cssColor(segment.bg)};`;
142
- const fg = foregroundCss(segment);
143
- if (fg) style += `color:${fg};`;
144
- return style || undefined;
145
- }
12
+ import { classNames, inlineStyle } from "./ansi-color.js";
146
13
 
147
14
  // Precompute class/style per segment. Parse only when `text` changes.
148
15
  $: parsed = parseAnsi(text);
149
16
  $: segments = parsed.map((segment) => ({
150
17
  text: segment.text,
151
18
  class: classNames(segment),
152
- style: inlineStyle(segment),
19
+ style: inlineStyle(segment, autoContrast),
153
20
  link: segment.link,
154
21
  }));
155
22
  </script>
@@ -59,6 +59,10 @@
59
59
  import { extendLines } from "./engine.js";
60
60
  import { ensureRegistered, registry } from "./registry.js";
61
61
  import { createCompletedHtmlBuffer } from "./stream-highlighted.js";
62
+ import {
63
+ buildSealedChunkHtml,
64
+ pushSealedChunk,
65
+ } from "./stream-sealed-chunks.js";
62
66
  import { createTokenizedDocument } from "./tokenized-document.js";
63
67
  import { watchLineHeight, windowRange } from "./virtual-window.js";
64
68
 
@@ -172,14 +176,10 @@
172
176
  // as many full chunks as are ready.
173
177
  function sealChunk() {
174
178
  const chunkLines = unsealedLines.slice(0, SEAL_CHUNK_LINES);
175
- let domHtml = "";
176
- for (let li = 0; li < chunkLines.length; li++) {
177
- const i = sealedLineCount + li;
178
- const sep = i > 0 ? "\n" : "";
179
- domHtml += `${sep}<span class="highlight-stream-line" data-line="${i}">${chunkLines[li]}</span>`;
180
- }
181
- sealedChunks.push(domHtml);
182
- sealedChunks = sealedChunks;
179
+ sealedChunks = pushSealedChunk(
180
+ sealedChunks,
181
+ buildSealedChunkHtml(chunkLines, sealedLineCount),
182
+ );
183
183
  sealedLineCount += chunkLines.length;
184
184
  unsealedLines = unsealedLines.slice(SEAL_CHUNK_LINES);
185
185
  }
@@ -478,12 +478,6 @@
478
478
  animation: highlight-stream-blink var(--caret-blink, 1s) step-end infinite;
479
479
  }
480
480
 
481
- @media (prefers-reduced-motion: reduce) {
482
- .highlight-stream-caret {
483
- animation: none;
484
- }
485
- }
486
-
487
481
  @keyframes highlight-stream-blink {
488
482
  50% {
489
483
  opacity: 0;
package/README.md CHANGED
@@ -1333,7 +1333,22 @@ Set `speed` (milliseconds per character) and pause with `play`. Turn `play` back
1333
1333
  </Highlight>
1334
1334
  ```
1335
1335
 
1336
- With `prefers-reduced-motion`, the full block shows immediately and `on:done` runs right away. Customize the caret with `--caret-width`, `--caret-height`, `--caret-gap`, `--caret-color`, and `--caret-blink`.
1336
+ Control the pacing curve with `easing`: a function mapping elapsed-time fraction (`0`-`1`) to revealed-fraction (`0`-`1`). It defaults to `linear`; import a named curve or pass your own. Total typing duration is always `speed` × character count, no matter the curve -- only the pacing within that duration changes.
1337
+
1338
+ ```svelte
1339
+ <script>
1340
+ import Highlight, { Typewriter, easeOutCubic } from "svelte-highlight";
1341
+ </script>
1342
+
1343
+ <Highlight language={typescript} {code} let:highlighted>
1344
+ <Typewriter {highlighted} easing={easeOutCubic} />
1345
+ </Highlight>
1346
+ ```
1347
+
1348
+ Named curves: `linear` (default), `easeInQuad`/`easeOutQuad`/`easeInOutQuad`, `easeInCubic`/`easeOutCubic`/`easeInOutCubic`, `easeInSine`/`easeOutSine`/`easeInOutSine`.
1349
+
1350
+ `Typewriter` doesn't gate itself on `prefers-reduced-motion` -- if you want to honor it, check `matchMedia("(prefers-reduced-motion: reduce)")` yourself and skip rendering `Typewriter` (or set a very low `speed`). Customize the caret with `--caret-width`, `--caret-height`, `--caret-gap`, `--caret-color`, and `--caret-blink`.
1351
+
1337
1352
 
1338
1353
  Each tick reveals one already-rendered unit rather than re-rendering the block, so animating stays smooth up to tens of thousands of characters; past that it falls back to the coarser whole-block reveal.
1339
1354
 
@@ -1815,17 +1830,18 @@ See [Large documents](#large-documents) above.
1815
1830
 
1816
1831
  #### Props
1817
1832
 
1818
- | Name | Type | Default value |
1819
- | :---------- | :-------- | :------------ |
1820
- | highlighted | `string` | `""` |
1821
- | speed | `number` | `30` |
1822
- | play | `boolean` | `true` |
1833
+ | Name | Type | Default value |
1834
+ | :---------- | :----------------------- | :------------ |
1835
+ | highlighted | `string` | `""` |
1836
+ | speed | `number` | `30` |
1837
+ | play | `boolean` | `true` |
1838
+ | easing | `(t: number) => number` | `linear` |
1823
1839
 
1824
1840
  `$$restProps` are forwarded to the top-level `pre` element.
1825
1841
 
1826
1842
  #### Dispatched Events
1827
1843
 
1828
- - **on:done**: fires when typing finishes, or immediately when reduced motion is on
1844
+ - **on:done**: fires when typing finishes
1829
1845
 
1830
1846
  ```svelte
1831
1847
  <Highlight language={typescript} {code} let:highlighted>
package/Typewriter.svelte CHANGED
@@ -18,11 +18,23 @@
18
18
  export let play = true;
19
19
 
20
20
  import { createEventDispatcher, onMount } from "svelte";
21
+ import { linear } from "./typewriter-easing.js";
21
22
  import {
23
+ buildUnitMarkup,
22
24
  createTypewriterSplitter,
23
25
  tokenizeTypewriter as tokenize,
24
26
  } from "./typewriter-units.js";
25
27
 
28
+ /**
29
+ * Reveal-progress curve: maps elapsed-time fraction (0-1) to
30
+ * revealed-fraction (0-1). Total typing duration is always
31
+ * `speed * <visible character count>` regardless of curve -- only the
32
+ * pacing within that duration changes. Import a named curve
33
+ * (`easeOutQuad`, `easeInOutCubic`, ...) or pass your own function.
34
+ * @type {(t: number) => number}
35
+ */
36
+ export let easing = linear;
37
+
26
38
  const dispatch = createEventDispatcher();
27
39
 
28
40
  // Above this many visible units, per-unit spans (one element per char)
@@ -34,17 +46,20 @@
34
46
  /** @type {boolean} */
35
47
  let mounted = false;
36
48
 
37
- /** @type {boolean} */
38
- let reducedMotion = false;
39
-
40
49
  /** @type {boolean} */
41
50
  let doneFired = false;
42
51
 
43
52
  /** Number of visible characters currently revealed. @type {number} */
44
53
  let revealed = 0;
45
54
 
46
- /** @type {ReturnType<typeof setInterval> | undefined} */
47
- let timerId;
55
+ /** @type {number | undefined} */
56
+ let rafId;
57
+
58
+ /** Active ms elapsed for the current run (excludes paused time). @type {number} */
59
+ let elapsedMs = 0;
60
+
61
+ /** `performance.now()` at the last tick, or `undefined` right after a (re)start. @type {number | undefined} */
62
+ let frameTime;
48
63
 
49
64
  /** @type {string | undefined} */
50
65
  let prevHighlighted;
@@ -64,18 +79,6 @@
64
79
  /** The unit currently marked with the caret, if any. @type {HTMLElement | undefined} */
65
80
  let caretMark;
66
81
 
67
- /** Render every unit once: tags pass through, each visible unit gets a span. */
68
- function buildUnitMarkup(list) {
69
- let html = "";
70
- for (const unit of list) {
71
- html +=
72
- unit.visible === 0
73
- ? unit.raw
74
- : `<span class="typewriter-unit typewriter-hidden">${unit.raw}</span>`;
75
- }
76
- return html;
77
- }
78
-
79
82
  /**
80
83
  * Bring `contentEl` in sync with `units`/`revealed` in O(1) amortized work:
81
84
  * a fresh `units` value triggers one full (re)paint; otherwise only the
@@ -90,6 +93,15 @@
90
93
  paintedUnits = units;
91
94
  revealedInDom = 0;
92
95
  caretMark = undefined;
96
+ // Resolve `currentColor` to a literal value now, while `contentEl`
97
+ // itself carries the theme's base foreground (nothing has recolored
98
+ // it yet). Stored as a custom property, it stays correct even once
99
+ // the caret mark lands inside a colored hljs token span, where a live
100
+ // `currentColor` would pick up that token's color instead.
101
+ contentEl.style.setProperty(
102
+ "--typewriter-caret-fg",
103
+ getComputedStyle(contentEl).color,
104
+ );
93
105
  }
94
106
 
95
107
  while (revealedInDom < revealed) {
@@ -110,9 +122,9 @@
110
122
  }
111
123
  }
112
124
 
113
- function clearTimer() {
114
- clearInterval(timerId);
115
- timerId = undefined;
125
+ function stopLoop() {
126
+ if (rafId !== undefined) cancelAnimationFrame(rafId);
127
+ rafId = undefined;
116
128
  }
117
129
 
118
130
  function fireDone() {
@@ -122,31 +134,50 @@
122
134
  }
123
135
  }
124
136
 
125
- function advance() {
126
- if (revealed < total) revealed += 1;
137
+ /**
138
+ * One animation frame: advance `elapsedMs` by the real time since the last
139
+ * frame (zero on the first frame after a start/resume, so pausing never
140
+ * counts the paused gap), then derive `revealed` from `easing` applied to
141
+ * the elapsed fraction of the total duration. Total duration is always
142
+ * `speed * total`, so only the pacing within it -- not its length --
143
+ * depends on `easing`. Clamped to `[0, total]` since a custom `easing` may
144
+ * overshoot outside `[0, 1]` (e.g. a "back"/"elastic" curve).
145
+ * @param {number} now
146
+ */
147
+ function tick(now) {
148
+ if (frameTime !== undefined) elapsedMs += now - frameTime;
149
+ frameTime = now;
150
+
151
+ const duration = Math.max(0, speed) * total;
152
+ const t = duration > 0 ? Math.min(1, elapsedMs / duration) : 1;
153
+ const target = Math.round(easing(t) * total);
154
+ const next = Math.min(total, Math.max(0, target));
155
+ if (next > revealed) revealed = next;
156
+
127
157
  if (useUnitReveal) syncUnitDom();
158
+
128
159
  if (revealed >= total) {
129
- clearTimer();
160
+ stopLoop();
130
161
  fireDone();
162
+ return;
131
163
  }
164
+ rafId = requestAnimationFrame(tick);
165
+ }
166
+
167
+ function startLoop() {
168
+ frameTime = undefined;
169
+ rafId = requestAnimationFrame(tick);
132
170
  }
133
171
 
134
- /** Start/stop/retime the typing interval. */
172
+ /** Start/stop/retime the typing loop. */
135
173
  function sync() {
136
- clearTimer();
174
+ stopLoop();
137
175
  if (!mounted) return;
138
176
 
139
- if (reducedMotion) {
140
- // Reduced motion: show all at once.
141
- if (revealed !== total) revealed = total;
142
- fireDone();
143
- return;
144
- }
145
-
146
177
  if (useUnitReveal) syncUnitDom();
147
178
 
148
179
  if (play && revealed < total) {
149
- timerId = setInterval(advance, Math.max(0, speed));
180
+ startLoop();
150
181
  } else if (revealed >= total) {
151
182
  fireDone();
152
183
  }
@@ -159,20 +190,21 @@
159
190
  $: splitter = createTypewriterSplitter(units, highlighted);
160
191
  $: total = units.reduce((sum, unit) => sum + unit.visible, 0);
161
192
  $: bigInput = total > UNIT_THRESHOLD;
162
- $: useUnitReveal = mounted && !reducedMotion && !bigInput;
193
+ $: useUnitReveal = mounted && !bigInput;
163
194
 
164
195
  // Restart when `highlighted` changes.
165
196
  $: if (highlighted !== prevHighlighted) {
166
197
  prevHighlighted = highlighted;
167
198
  doneFired = false;
168
- revealed = reducedMotion ? total : 0;
199
+ elapsedMs = 0;
200
+ revealed = 0;
169
201
  void useUnitReveal;
170
202
  sync();
171
203
  }
172
204
 
173
- // Re-sync on play/speed/mount/motion. Skip `total` (handled above).
205
+ // Re-sync on play/speed/easing/mount. Skip `total` (handled above).
174
206
  $: {
175
- void [play, speed, mounted, reducedMotion, useUnitReveal];
207
+ void [play, speed, easing, mounted, useUnitReveal];
176
208
  sync();
177
209
  }
178
210
 
@@ -182,21 +214,13 @@
182
214
  : mounted
183
215
  ? splitter.splitAt(revealed)
184
216
  : { head: highlighted, tail: "" };
185
- $: showCaret = mounted && !reducedMotion && revealed < total;
217
+ $: showCaret = mounted && revealed < total;
186
218
 
187
219
  onMount(() => {
188
220
  mounted = true;
189
221
 
190
- const query = window.matchMedia("(prefers-reduced-motion: reduce)");
191
- reducedMotion = query.matches;
192
- const onChange = (event) => {
193
- reducedMotion = event.matches;
194
- };
195
- query.addEventListener?.("change", onChange);
196
-
197
222
  return () => {
198
- query.removeEventListener?.("change", onChange);
199
- clearTimer();
223
+ stopLoop();
200
224
  };
201
225
  });
202
226
  </script>
@@ -234,7 +258,13 @@
234
258
  }
235
259
 
236
260
  /* The caret rides the next-to-reveal (still hidden) unit's ::before, so it
237
- never requires moving a real DOM node -- one class add/remove per tick. */
261
+ never requires moving a real DOM node -- one class add/remove per tick.
262
+ That unit can land inside a still-open hljs token span (e.g. mid-
263
+ keyword), where `currentColor` would resolve to that token's color
264
+ instead of the theme's base foreground. `--typewriter-caret-fg` is set
265
+ on `contentEl` as a literal resolved color (not the `currentColor`
266
+ keyword) in `syncUnitDom`, so it survives that nesting unaffected by
267
+ descendant `color` overrides. */
238
268
  :global(.typewriter-unit.typewriter-caret)::before {
239
269
  content: "";
240
270
  visibility: visible;
@@ -243,17 +273,10 @@
243
273
  height: var(--caret-height, 1.1em);
244
274
  margin-left: var(--caret-gap, 1px);
245
275
  vertical-align: text-bottom;
246
- background: var(--caret-color, currentColor);
276
+ background: var(--caret-color, var(--typewriter-caret-fg, currentColor));
247
277
  animation: typewriter-blink var(--caret-blink, 1s) step-end infinite;
248
278
  }
249
279
 
250
- @media (prefers-reduced-motion: reduce) {
251
- .typewriter-caret,
252
- :global(.typewriter-unit.typewriter-caret)::before {
253
- animation: none;
254
- }
255
- }
256
-
257
280
  @keyframes typewriter-blink {
258
281
  50% {
259
282
  opacity: 0;
@@ -20,6 +20,15 @@ export type TypewriterProps = HTMLAttributes<HTMLPreElement> & {
20
20
  */
21
21
  play?: boolean;
22
22
 
23
+ /**
24
+ * Reveal-progress curve: maps elapsed-time fraction (0-1) to
25
+ * revealed-fraction (0-1). Total typing duration is always
26
+ * `speed * <visible character count>` regardless of curve. Import a named
27
+ * curve (`easeOutQuad`, `easeInOutCubic`, ...) or pass your own function.
28
+ * @default linear
29
+ */
30
+ easing?: (t: number) => number;
31
+
23
32
  /**
24
33
  * Width of the blinking caret.
25
34
  * @default "0.6em"
@@ -53,7 +62,7 @@ export type TypewriterProps = HTMLAttributes<HTMLPreElement> & {
53
62
 
54
63
  export type TypewriterEvents = {
55
64
  /**
56
- * Fires when typing finishes (or immediately with reduced motion).
65
+ * Fires when typing finishes.
57
66
  */
58
67
  done: CustomEvent<null>;
59
68
  };