svelte-highlight 7.12.0 → 7.13.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.
@@ -0,0 +1,238 @@
1
+ <script>
2
+ /**
3
+ * Highlighted HTML from `Highlight`'s `highlighted` slot.
4
+ * @type {string}
5
+ */
6
+ export let highlighted = "";
7
+
8
+ /**
9
+ * Milliseconds between characters.
10
+ * @type {number}
11
+ */
12
+ export let speed = 30;
13
+
14
+ /**
15
+ * Pause with `false`; resume picks up where it left off.
16
+ * @type {boolean}
17
+ */
18
+ export let play = true;
19
+
20
+ import { createEventDispatcher, onMount } from "svelte";
21
+
22
+ const dispatch = createEventDispatcher();
23
+
24
+ /** Opening or closing tag name. */
25
+ const TAG_NAME = /^<\/?\s*([a-zA-Z0-9-]+)/;
26
+
27
+ /** @type {boolean} */
28
+ let mounted = false;
29
+
30
+ /** @type {boolean} */
31
+ let reducedMotion = false;
32
+
33
+ /** @type {boolean} */
34
+ let doneFired = false;
35
+
36
+ /** Number of visible characters currently revealed. @type {number} */
37
+ let revealed = 0;
38
+
39
+ /** @type {ReturnType<typeof setInterval> | undefined} */
40
+ let timerId;
41
+
42
+ /** @type {string | undefined} */
43
+ let prevHighlighted;
44
+
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;
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
+ }
87
+
88
+ return units;
89
+ }
90
+
91
+ /**
92
+ * Split at `count` visible chars. Close open tags in `head`, reopen in `tail`.
93
+ * Hidden `tail` reserves space so layout doesn't jump.
94
+ */
95
+ function split(list, count) {
96
+ let head = "";
97
+ let shown = 0;
98
+ /** @type {{ raw: string; name: string }[]} */
99
+ const open = [];
100
+ let i = 0;
101
+
102
+ for (; i < list.length; i++) {
103
+ const unit = list[i];
104
+ if (shown >= count) break;
105
+ head += unit.raw;
106
+ if (unit.visible === 0) {
107
+ if (unit.kind === "open")
108
+ open.push({ raw: unit.raw, name: unit.name ?? "" });
109
+ else if (unit.kind === "close") open.pop();
110
+ } else {
111
+ shown += unit.visible;
112
+ }
113
+ }
114
+
115
+ // Close open tags in head, reopen them at the start of tail.
116
+ let headClose = "";
117
+ for (let k = open.length - 1; k >= 0; k--)
118
+ headClose += `</${open[k].name}>`;
119
+
120
+ let tail = "";
121
+ for (const tag of open) tail += tag.raw;
122
+ for (; i < list.length; i++) tail += list[i].raw;
123
+
124
+ return { head: head + headClose, tail };
125
+ }
126
+
127
+ function clearTimer() {
128
+ clearInterval(timerId);
129
+ timerId = undefined;
130
+ }
131
+
132
+ function fireDone() {
133
+ if (!doneFired && total > 0 && revealed >= total) {
134
+ doneFired = true;
135
+ dispatch("done");
136
+ }
137
+ }
138
+
139
+ function tick() {
140
+ if (revealed < total) revealed += 1;
141
+ if (revealed >= total) {
142
+ clearTimer();
143
+ fireDone();
144
+ }
145
+ }
146
+
147
+ /** Start/stop/retime the typing interval. */
148
+ function sync() {
149
+ clearTimer();
150
+ if (!mounted) return;
151
+
152
+ if (reducedMotion) {
153
+ // Reduced motion: show all at once.
154
+ if (revealed !== total) revealed = total;
155
+ fireDone();
156
+ return;
157
+ }
158
+
159
+ if (play && revealed < total) {
160
+ timerId = setInterval(tick, Math.max(0, speed));
161
+ } else if (revealed >= total) {
162
+ fireDone();
163
+ }
164
+ }
165
+
166
+ $: units = tokenize(highlighted);
167
+ $: total = units.reduce((sum, unit) => sum + unit.visible, 0);
168
+
169
+ // Restart when `highlighted` changes.
170
+ $: if (highlighted !== prevHighlighted) {
171
+ prevHighlighted = highlighted;
172
+ doneFired = false;
173
+ revealed = reducedMotion ? total : 0;
174
+ sync();
175
+ }
176
+
177
+ // Re-sync on play/speed/mount/motion. Skip `total` (handled above).
178
+ $: {
179
+ void [play, speed, mounted, reducedMotion];
180
+ sync();
181
+ }
182
+
183
+ // SSR: full content. After mount, reveal from `revealed`.
184
+ $: parts = mounted ? split(units, revealed) : { head: highlighted, tail: "" };
185
+ $: showCaret = mounted && !reducedMotion && revealed < total;
186
+
187
+ onMount(() => {
188
+ mounted = true;
189
+
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
+ return () => {
198
+ query.removeEventListener?.("change", onChange);
199
+ clearTimer();
200
+ };
201
+ });
202
+ </script>
203
+
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>
211
+
212
+ <style>
213
+ .typewriter-rest {
214
+ visibility: hidden;
215
+ }
216
+
217
+ .typewriter-caret {
218
+ display: inline-block;
219
+ width: var(--caret-width, 0.6em);
220
+ height: var(--caret-height, 1.1em);
221
+ margin-left: var(--caret-gap, 1px);
222
+ vertical-align: text-bottom;
223
+ background: var(--caret-color, currentColor);
224
+ animation: typewriter-blink var(--caret-blink, 1s) step-end infinite;
225
+ }
226
+
227
+ @media (prefers-reduced-motion: reduce) {
228
+ .typewriter-caret {
229
+ animation: none;
230
+ }
231
+ }
232
+
233
+ @keyframes typewriter-blink {
234
+ 50% {
235
+ opacity: 0;
236
+ }
237
+ }
238
+ </style>
@@ -0,0 +1,65 @@
1
+ import type { SvelteComponentTyped } from "svelte";
2
+ import type { HTMLAttributes } from "svelte/elements";
3
+
4
+ export type TypewriterProps = HTMLAttributes<HTMLPreElement> & {
5
+ /**
6
+ * Highlighted HTML from `Highlight`'s `highlighted` slot.
7
+ * @default ""
8
+ */
9
+ highlighted?: string;
10
+
11
+ /**
12
+ * Milliseconds between characters.
13
+ * @default 30
14
+ */
15
+ speed?: number;
16
+
17
+ /**
18
+ * Pause with `false`; resume picks up where it left off.
19
+ * @default true
20
+ */
21
+ play?: boolean;
22
+
23
+ /**
24
+ * Width of the blinking caret.
25
+ * @default "0.6em"
26
+ */
27
+ "--caret-width"?: string;
28
+
29
+ /**
30
+ * Height of the blinking caret.
31
+ * @default "1.1em"
32
+ */
33
+ "--caret-height"?: string;
34
+
35
+ /**
36
+ * Gap between typed text and the caret.
37
+ * @default "1px"
38
+ */
39
+ "--caret-gap"?: string;
40
+
41
+ /**
42
+ * Color of the blinking caret.
43
+ * @default "currentColor"
44
+ */
45
+ "--caret-color"?: string;
46
+
47
+ /**
48
+ * Duration of one caret blink cycle.
49
+ * @default "1s"
50
+ */
51
+ "--caret-blink"?: string;
52
+ };
53
+
54
+ export type TypewriterEvents = {
55
+ /**
56
+ * Fires when typing finishes (or immediately with reduced motion).
57
+ */
58
+ done: CustomEvent<null>;
59
+ };
60
+
61
+ export default class Typewriter extends SvelteComponentTyped<
62
+ TypewriterProps,
63
+ TypewriterEvents,
64
+ Record<string, never>
65
+ > {}
package/action.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { Action } from "svelte/action";
2
+ import type { LanguageType } from "./languages";
3
+
4
+ export type HighlightActionParameters = {
5
+ /**
6
+ * Language used to highlight the element's contents.
7
+ */
8
+ language: LanguageType<string>;
9
+
10
+ /**
11
+ * Code to highlight. When omitted, the element's
12
+ * current `textContent` is highlighted.
13
+ */
14
+ code?: string;
15
+ };
16
+
17
+ /**
18
+ * Highlight element contents in place with highlight.js.
19
+ */
20
+ export declare const highlight: Action<HTMLElement, HighlightActionParameters>;
package/action.js ADDED
@@ -0,0 +1,25 @@
1
+ import hljs from "highlight.js/lib/core";
2
+
3
+ /**
4
+ * Highlight an element in place with highlight.js.
5
+ * Omits `code` to highlight existing `textContent`.
6
+ *
7
+ * @type {import("svelte/action").Action<HTMLElement, { language: import("./languages").LanguageType<string>; code?: string }>}
8
+ */
9
+ export function highlight(node, parameters) {
10
+ /** @param {{ language: import("./languages").LanguageType<string>; code?: string }} params */
11
+ function apply({ language, code }) {
12
+ if (!hljs.getLanguage(language.name)) {
13
+ hljs.registerLanguage(language.name, language.register);
14
+ }
15
+ const source = code ?? node.textContent ?? "";
16
+ node.innerHTML = hljs.highlight(source, { language: language.name }).value;
17
+ node.classList.add("hljs");
18
+ }
19
+
20
+ apply(parameters);
21
+
22
+ return {
23
+ update: apply,
24
+ };
25
+ }
package/ansi.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * A parsed ANSI color.
3
+ *
4
+ * - `name`: one of the 16 themable base colors (e.g. `"red"`, `"bright-red"`).
5
+ * - `index`: a 256-color palette index (16-255); 0-15 are normalized to `name`.
6
+ * - `rgb`: a 24-bit truecolor triple.
7
+ */
8
+ export type AnsiColor =
9
+ | { name: string }
10
+ | { index: number }
11
+ | { rgb: [number, number, number] };
12
+
13
+ /** Active styling while parsing. */
14
+ export type AnsiStyle = {
15
+ bold?: boolean | undefined;
16
+ dim?: boolean | undefined;
17
+ italic?: boolean | undefined;
18
+ underline?: boolean | undefined;
19
+ fg?: AnsiColor | undefined;
20
+ bg?: AnsiColor | undefined;
21
+ };
22
+
23
+ /** Text run with styling. Omitted fields are inactive. */
24
+ export type AnsiSegment = {
25
+ /** Literal text (escape codes stripped). */
26
+ text: string;
27
+ bold?: boolean;
28
+ dim?: boolean;
29
+ italic?: boolean;
30
+ underline?: boolean;
31
+ fg?: AnsiColor;
32
+ bg?: AnsiColor;
33
+ };
34
+
35
+ /** Parse ANSI SGR escape codes into styled segments. Malformed input is dropped. */
36
+ export declare function parseAnsi(text: string): AnsiSegment[];
package/ansi.js ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Parse ANSI SGR escape codes into styled text segments.
3
+ * Malformed sequences are dropped, not thrown.
4
+ */
5
+
6
+ // The 8 standard color names, indexed by their SGR offset (30-37 / 40-47).
7
+ const COLOR_NAMES = [
8
+ "black",
9
+ "red",
10
+ "green",
11
+ "yellow",
12
+ "blue",
13
+ "magenta",
14
+ "cyan",
15
+ "white",
16
+ ];
17
+
18
+ /** @typedef {import("./ansi").AnsiColor} AnsiColor */
19
+ /** @typedef {import("./ansi").AnsiSegment} AnsiSegment */
20
+ /** @typedef {import("./ansi").AnsiStyle} AnsiStyle */
21
+
22
+ /**
23
+ * The themable name for a standard color offset (0-7).
24
+ * @param {number} offset
25
+ * @returns {string}
26
+ */
27
+ function standardName(offset) {
28
+ return COLOR_NAMES[offset] ?? "white";
29
+ }
30
+
31
+ /**
32
+ * Map a 256-color index (0-15 → name, 16+ → index).
33
+ * @param {number} index
34
+ * @returns {AnsiColor}
35
+ */
36
+ function paletteColor(index) {
37
+ if (index < 8) return { name: standardName(index) };
38
+ if (index < 16) return { name: `bright-${standardName(index - 8)}` };
39
+ return { index };
40
+ }
41
+
42
+ /**
43
+ * Apply SGR parameters to `style`.
44
+ * @param {AnsiStyle} style
45
+ * @param {number[]} params
46
+ */
47
+ function applySgr(style, params) {
48
+ // Empty params (`ESC[m`) reset everything.
49
+ const list = params.length === 0 ? [0] : params;
50
+
51
+ for (let i = 0; i < list.length; i += 1) {
52
+ const code = list[i];
53
+ if (code === undefined) continue;
54
+
55
+ if (code === 0) {
56
+ // Reset all attributes.
57
+ style.bold = undefined;
58
+ style.dim = undefined;
59
+ style.italic = undefined;
60
+ style.underline = undefined;
61
+ style.fg = undefined;
62
+ style.bg = undefined;
63
+ } else if (code === 1) {
64
+ style.bold = true;
65
+ } else if (code === 2) {
66
+ style.dim = true;
67
+ } else if (code === 3) {
68
+ style.italic = true;
69
+ } else if (code === 4) {
70
+ style.underline = true;
71
+ } else if (code === 22) {
72
+ style.bold = undefined;
73
+ style.dim = undefined;
74
+ } else if (code === 23) {
75
+ style.italic = undefined;
76
+ } else if (code === 24) {
77
+ style.underline = undefined;
78
+ } else if (code >= 30 && code <= 37) {
79
+ style.fg = { name: standardName(code - 30) };
80
+ } else if (code >= 40 && code <= 47) {
81
+ style.bg = { name: standardName(code - 40) };
82
+ } else if (code >= 90 && code <= 97) {
83
+ style.fg = { name: `bright-${standardName(code - 90)}` };
84
+ } else if (code >= 100 && code <= 107) {
85
+ style.bg = { name: `bright-${standardName(code - 100)}` };
86
+ } else if (code === 39) {
87
+ style.fg = undefined;
88
+ } else if (code === 49) {
89
+ style.bg = undefined;
90
+ } else if (code === 38 || code === 48) {
91
+ // Extended color: `38;5;n` (256-color) or `38;2;r;g;b` (truecolor).
92
+ const key = code === 38 ? "fg" : "bg";
93
+ const mode = list[i + 1];
94
+ if (mode === 5) {
95
+ const index = list[i + 2];
96
+ if (typeof index === "number") style[key] = paletteColor(index);
97
+ i += 2;
98
+ } else if (mode === 2) {
99
+ const r = list[i + 2];
100
+ const g = list[i + 3];
101
+ const b = list[i + 4];
102
+ if (
103
+ typeof r === "number" &&
104
+ typeof g === "number" &&
105
+ typeof b === "number"
106
+ ) {
107
+ style[key] = { rgb: [r, g, b] };
108
+ }
109
+ i += 4;
110
+ }
111
+ }
112
+ // Unknown codes: ignore.
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Build a segment from `text` and active fields in `style`.
118
+ * @param {string} text
119
+ * @param {AnsiStyle} style
120
+ * @returns {AnsiSegment}
121
+ */
122
+ function toSegment(text, style) {
123
+ /** @type {AnsiSegment} */
124
+ const segment = { text };
125
+ if (style.bold) segment.bold = true;
126
+ if (style.dim) segment.dim = true;
127
+ if (style.italic) segment.italic = true;
128
+ if (style.underline) segment.underline = true;
129
+ if (style.fg) segment.fg = style.fg;
130
+ if (style.bg) segment.bg = style.bg;
131
+ return segment;
132
+ }
133
+
134
+ const ESC = "\x1b";
135
+
136
+ /**
137
+ * Parse ANSI-escaped terminal output into styled segments.
138
+ *
139
+ * @param {string} text Raw terminal output.
140
+ * @returns {AnsiSegment[]} Styled text segments, in order.
141
+ */
142
+ export function parseAnsi(text) {
143
+ if (!text) return [];
144
+
145
+ /** @type {AnsiSegment[]} */
146
+ const segments = [];
147
+ /** @type {AnsiStyle} */
148
+ const style = {};
149
+ let buffer = "";
150
+
151
+ const flush = () => {
152
+ if (buffer) {
153
+ segments.push(toSegment(buffer, style));
154
+ buffer = "";
155
+ }
156
+ };
157
+
158
+ let i = 0;
159
+ while (i < text.length) {
160
+ const ch = text[i];
161
+
162
+ if (ch === ESC && text[i + 1] === "[") {
163
+ // Read a CSI sequence: parameters up to a final byte (0x40-0x7e).
164
+ let j = i + 2;
165
+ while (j < text.length) {
166
+ const code = text.charCodeAt(j);
167
+ if (code >= 0x40 && code <= 0x7e) break;
168
+ j += 1;
169
+ }
170
+
171
+ if (j >= text.length) {
172
+ // Unterminated: drop the rest.
173
+ break;
174
+ }
175
+
176
+ const final = text[j];
177
+ if (final === "m") {
178
+ // SGR applies to text that follows.
179
+ flush();
180
+ const body = text.slice(i + 2, j);
181
+ const params = body
182
+ .split(";")
183
+ .map((part) => (part === "" ? 0 : Number(part)))
184
+ .filter((n) => Number.isInteger(n));
185
+ applySgr(style, params);
186
+ }
187
+ // Non-SGR CSI sequences (cursor moves, etc.) are skipped.
188
+ i = j + 1;
189
+ continue;
190
+ }
191
+
192
+ buffer += ch;
193
+ i += 1;
194
+ }
195
+
196
+ flush();
197
+ return segments;
198
+ }
package/index.d.ts CHANGED
@@ -1,7 +1,17 @@
1
+ export { default as AnsiOutput } from "./AnsiOutput.svelte";
2
+ export type { HighlightActionParameters } from "./action";
3
+ export { highlight } from "./action";
4
+ export type { AnsiColor, AnsiSegment, AnsiStyle } from "./ansi";
5
+ export { parseAnsi } from "./ansi";
6
+ export { default as CodeWindow } from "./CodeWindow.svelte";
1
7
  export { default as CopyButton } from "./CopyButton.svelte";
8
+ export { default as FileTabs } from "./FileTabs.svelte";
2
9
  export { default as Highlight, default } from "./Highlight.svelte";
3
10
  export { default as HighlightAuto } from "./HighlightAuto.svelte";
11
+ export { default as HighlightEditable } from "./HighlightEditable.svelte";
4
12
  export { default as HighlightStyle } from "./HighlightStyle.svelte";
5
13
  export { default as HighlightSvelte } from "./HighlightSvelte.svelte";
6
14
  export { default as LineNumbers } from "./LineNumbers.svelte";
7
15
  export type { LanguageName, LanguageType } from "./languages";
16
+ export { loadLanguage } from "./load-language";
17
+ export { default as Typewriter } from "./Typewriter.svelte";
package/index.js CHANGED
@@ -1,6 +1,14 @@
1
+ export { default as AnsiOutput } from "./AnsiOutput.svelte";
2
+ export { highlight } from "./action.js";
3
+ export { parseAnsi } from "./ansi.js";
4
+ export { default as CodeWindow } from "./CodeWindow.svelte";
1
5
  export { default as CopyButton } from "./CopyButton.svelte";
6
+ export { default as FileTabs } from "./FileTabs.svelte";
2
7
  export { default, default as Highlight } from "./Highlight.svelte";
3
8
  export { default as HighlightAuto } from "./HighlightAuto.svelte";
9
+ export { default as HighlightEditable } from "./HighlightEditable.svelte";
4
10
  export { default as HighlightStyle } from "./HighlightStyle.svelte";
5
11
  export { default as HighlightSvelte } from "./HighlightSvelte.svelte";
6
12
  export { default as LineNumbers } from "./LineNumbers.svelte";
13
+ export { loadLanguage } from "./load-language.js";
14
+ export { default as Typewriter } from "./Typewriter.svelte";
@@ -0,0 +1,9 @@
1
+ import type { LanguageName, LanguageType } from "./languages";
2
+
3
+ /**
4
+ * Load a highlight.js grammar by name at runtime.
5
+ * Prefer a static import when the language is known up front.
6
+ */
7
+ export declare function loadLanguage(
8
+ name: LanguageName,
9
+ ): Promise<LanguageType<string>>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Load a highlight.js grammar by name at runtime.
3
+ * Prefer a static import when the language is known up front.
4
+ *
5
+ * @param {import("./languages").LanguageName} name
6
+ * @returns {Promise<import("./languages").LanguageType<string>>}
7
+ */
8
+ export async function loadLanguage(name) {
9
+ try {
10
+ const module = await import(`./languages/${name}.js`);
11
+ return module.default;
12
+ } catch (cause) {
13
+ throw new Error(`Unknown language: "${name}"`, { cause });
14
+ }
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-highlight",
3
- "version": "7.12.0",
3
+ "version": "7.13.0",
4
4
  "license": "MIT",
5
5
  "description": "Svelte component library for highlighting code using highlight.js",
6
6
  "author": "Eric Liu (https://github.com/metonym)",
package/scoped.d.ts CHANGED
@@ -7,5 +7,17 @@ export declare function scopeSelectors(
7
7
  transform: (selector: string) => string,
8
8
  ): string;
9
9
 
10
+ /**
11
+ * Build a combined light/dark stylesheet scoped under `.scope`. `mode` is
12
+ * `"auto"` (prefers-color-scheme media queries), `"light"`/`"dark"` (single
13
+ * theme), or any CSS selector that gates the dark block.
14
+ */
15
+ export declare function dualStyle(
16
+ light: string,
17
+ dark: string,
18
+ scope: string,
19
+ mode?: string,
20
+ ): string;
21
+
10
22
  /** Hash of the theme string. Same theme gives the same class (SSR-safe). */
11
23
  export declare function scopeClassFor(theme: string, prefix?: string): string;