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,385 @@
1
+ <script>
2
+ /** @type {import("./languages").LanguageType<string>} */
3
+ export let language;
4
+
5
+ /** @type {string} */
6
+ export let code = "";
7
+
8
+ /** @type {number} Number of spaces inserted by the Tab key. */
9
+ export let tabSize = 2;
10
+
11
+ /** @type {number} Maximum number of undo snapshots retained. */
12
+ export let historyLimit = 200;
13
+
14
+ import hljs from "highlight.js/lib/core";
15
+ import { createEventDispatcher, onMount } from "svelte";
16
+
17
+ const dispatch = createEventDispatcher();
18
+ const TRAILING_NEWLINE = /\n$/;
19
+
20
+ /** @type {HTMLElement} */
21
+ let editor;
22
+
23
+ // Don't re-highlight during IME composition.
24
+ let composing = false;
25
+ let mounted = false;
26
+ let restoringSelection = false;
27
+
28
+ // Tracks `code` so parent updates vs local edits can be distinguished.
29
+ let internalCode = code;
30
+
31
+ $: hljs.registerLanguage(language.name, language.register);
32
+ $: indentUnit = " ".repeat(tabSize);
33
+ $: if (mounted && code !== internalCode) syncExternal();
34
+
35
+ function getSelectionRange() {
36
+ const selection = window.getSelection();
37
+ if (!selection || selection.rangeCount === 0) return null;
38
+ const range = selection.getRangeAt(0);
39
+ if (!editor.contains(range.commonAncestorContainer)) return null;
40
+ const pre = range.cloneRange();
41
+ pre.selectNodeContents(editor);
42
+ pre.setEnd(range.startContainer, range.startOffset);
43
+ const start = pre.toString().length;
44
+ return { start, end: start + range.toString().length };
45
+ }
46
+
47
+ function getCaretOffset() {
48
+ const sel = getSelectionRange();
49
+ return sel ? sel.end : null;
50
+ }
51
+
52
+ function nodeAtOffset(offset) {
53
+ const walker = document.createTreeWalker(
54
+ editor,
55
+ NodeFilter.SHOW_TEXT,
56
+ null,
57
+ );
58
+ let count = 0;
59
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
60
+ const next = count + node.textContent.length;
61
+ if (offset <= next) return { node, offset: offset - count };
62
+ count = next;
63
+ }
64
+ return null;
65
+ }
66
+
67
+ function setSelection(start, end) {
68
+ const from = nodeAtOffset(start);
69
+ if (!from) return;
70
+ const range = document.createRange();
71
+ range.setStart(from.node, from.offset);
72
+ const to = end != null && end !== start ? nodeAtOffset(end) : null;
73
+ if (to) range.setEnd(to.node, to.offset);
74
+ else range.collapse(true);
75
+ const selection = window.getSelection();
76
+ selection.removeAllRanges();
77
+ selection.addRange(range);
78
+ }
79
+
80
+ function paint() {
81
+ const html = hljs.highlight(code, { language: language.name }).value;
82
+ // Trailing empty line needs a phantom `\n` for caret placement.
83
+ editor.innerHTML = code === "" || code.endsWith("\n") ? `${html}\n` : html;
84
+ }
85
+
86
+ function renderAt(start, end) {
87
+ paint();
88
+ if (start == null) return;
89
+ restoringSelection = true;
90
+ setSelection(start, end);
91
+ restoringSelection = false;
92
+ }
93
+
94
+ function syncCaretToHistory() {
95
+ if (restoringSelection || composing || undoStack.length === 0) return;
96
+ const sel = getSelectionRange();
97
+ if (!sel) return;
98
+ const top = undoStack[undoStack.length - 1];
99
+ if (top.code !== code) return;
100
+ undoStack[undoStack.length - 1] = {
101
+ code: top.code,
102
+ start: sel.start,
103
+ end: sel.end,
104
+ };
105
+ }
106
+
107
+ /** @type {Array<{ code: string; start: number; end: number }>} */
108
+ let undoStack = [];
109
+ /** @type {Array<{ code: string; start: number; end: number }>} */
110
+ let redoStack = [];
111
+ let lastRecord = 0;
112
+
113
+ function emitHistory() {
114
+ const future = redoStack.slice().reverse();
115
+ dispatch("history", {
116
+ entries: [...undoStack, ...future].map((snap) => ({
117
+ size: snap.code.length,
118
+ })),
119
+ index: undoStack.length - 1,
120
+ canUndo: canUndo(),
121
+ canRedo: canRedo(),
122
+ });
123
+ }
124
+
125
+ // Coalesce typing within 250ms; Enter/Tab/paste pass coalesce=false.
126
+ function pushHistory(snap, coalesce) {
127
+ redoStack = [];
128
+ const now = Date.now();
129
+ if (coalesce && undoStack.length > 1 && now - lastRecord < 250) {
130
+ undoStack[undoStack.length - 1] = snap;
131
+ } else {
132
+ undoStack.push(snap);
133
+ const limit = Math.max(1, historyLimit);
134
+ if (undoStack.length > limit) {
135
+ undoStack.splice(0, undoStack.length - limit);
136
+ }
137
+ }
138
+ lastRecord = coalesce ? now : 0;
139
+ emitHistory();
140
+ }
141
+
142
+ function applySnapshot(snap) {
143
+ code = snap.code;
144
+ internalCode = snap.code;
145
+ dispatch("change", { code });
146
+ emitHistory();
147
+ renderAt(snap.start, snap.end);
148
+ }
149
+
150
+ function commit(value, start, end, coalesce) {
151
+ code = value;
152
+ internalCode = value;
153
+ dispatch("change", { code });
154
+ pushHistory({ code: value, start, end }, coalesce);
155
+ renderAt(start, end);
156
+ }
157
+
158
+ function syncExternal() {
159
+ internalCode = code;
160
+ pushHistory({ code, start: code.length, end: code.length }, false);
161
+ paint();
162
+ }
163
+
164
+ function insertText(text) {
165
+ const sel = getSelectionRange();
166
+ if (!sel) return;
167
+ const value = code.slice(0, sel.start) + text + code.slice(sel.end);
168
+ commit(value, sel.start + text.length, undefined, false);
169
+ }
170
+
171
+ // Indent/dedent selected lines; blank lines skipped on indent.
172
+ function shiftIndent(outdent) {
173
+ const sel = getSelectionRange();
174
+ if (!sel) return;
175
+ const blockStart = code.lastIndexOf("\n", sel.start - 1) + 1;
176
+ const lines = code.slice(blockStart, sel.end).split("\n");
177
+
178
+ let firstDelta = 0;
179
+ let totalDelta = 0;
180
+ const next = lines
181
+ .map((line, index) => {
182
+ if (outdent) {
183
+ const leading = line.length - line.trimStart().length;
184
+ const remove = Math.min(tabSize, leading);
185
+ if (index === 0) firstDelta = -remove;
186
+ totalDelta -= remove;
187
+ return line.slice(remove);
188
+ }
189
+ if (line.length === 0) return line;
190
+ if (index === 0) firstDelta = tabSize;
191
+ totalDelta += tabSize;
192
+ return indentUnit + line;
193
+ })
194
+ .join("\n");
195
+
196
+ if (totalDelta === 0) return;
197
+ const value = code.slice(0, blockStart) + next + code.slice(sel.end);
198
+ const start = Math.max(blockStart, sel.start + firstDelta);
199
+ commit(value, start, sel.end + totalDelta, false);
200
+ }
201
+
202
+ function indentCommand() {
203
+ const sel = getSelectionRange();
204
+ if (sel && code.slice(sel.start, sel.end).includes("\n"))
205
+ shiftIndent(false);
206
+ else insertText(indentUnit);
207
+ }
208
+
209
+ function ensureFocus() {
210
+ if (document.activeElement === editor) return;
211
+ // Restore selection after focus; default caret to end.
212
+ const prior = getSelectionRange();
213
+ editor.focus();
214
+ if (prior) setSelection(prior.start, prior.end);
215
+ else setSelection(code.length);
216
+ syncCaretToHistory();
217
+ }
218
+
219
+ export function undo() {
220
+ if (undoStack.length <= 1) return;
221
+ redoStack.push(undoStack.pop());
222
+ applySnapshot(undoStack[undoStack.length - 1]);
223
+ }
224
+
225
+ export function redo() {
226
+ if (redoStack.length === 0) return;
227
+ const snap = redoStack.pop();
228
+ undoStack.push(snap);
229
+ applySnapshot(snap);
230
+ }
231
+
232
+ export function focus() {
233
+ editor.focus();
234
+ }
235
+
236
+ export function selectAll() {
237
+ editor.focus();
238
+ setSelection(0, code.length);
239
+ }
240
+
241
+ export function insert(text) {
242
+ ensureFocus();
243
+ insertText(text);
244
+ }
245
+
246
+ export function indent() {
247
+ ensureFocus();
248
+ indentCommand();
249
+ }
250
+
251
+ export function outdent() {
252
+ ensureFocus();
253
+ shiftIndent(true);
254
+ }
255
+
256
+ export function setCode(value) {
257
+ if (value === code) return;
258
+ internalCode = value;
259
+ code = value;
260
+ dispatch("change", { code });
261
+ pushHistory({ code: value, start: value.length, end: value.length }, false);
262
+ paint();
263
+ }
264
+
265
+ export function clear() {
266
+ setCode("");
267
+ }
268
+
269
+ export function getCode() {
270
+ return code;
271
+ }
272
+
273
+ export function canUndo() {
274
+ return undoStack.length > 1;
275
+ }
276
+
277
+ export function canRedo() {
278
+ return redoStack.length > 0;
279
+ }
280
+
281
+ function onInput() {
282
+ if (composing) return;
283
+ // innerText keeps contenteditable line breaks; textContent doesn't.
284
+ code = editor.innerText.replace(TRAILING_NEWLINE, "");
285
+ internalCode = code;
286
+ const caret = getCaretOffset() ?? code.length;
287
+ dispatch("change", { code });
288
+ pushHistory({ code, start: caret, end: caret }, true);
289
+ renderAt(caret);
290
+ }
291
+
292
+ function onKeydown(event) {
293
+ const mod = event.metaKey || event.ctrlKey;
294
+
295
+ if (mod && event.key === "z" && !event.shiftKey) {
296
+ event.preventDefault();
297
+ undo();
298
+ return;
299
+ }
300
+ if (mod && (event.key === "y" || (event.key === "z" && event.shiftKey))) {
301
+ event.preventDefault();
302
+ redo();
303
+ return;
304
+ }
305
+ if (event.key === "Enter") {
306
+ event.preventDefault();
307
+ insertText("\n");
308
+ return;
309
+ }
310
+ if (event.key === "Tab") {
311
+ event.preventDefault();
312
+ if (event.shiftKey) shiftIndent(true);
313
+ else indentCommand();
314
+ }
315
+ }
316
+
317
+ function onPaste(event) {
318
+ event.preventDefault();
319
+ insertText(event.clipboardData?.getData("text/plain") ?? "");
320
+ }
321
+
322
+ function onBlur() {
323
+ dispatch("blur", { code: getCode() });
324
+ }
325
+
326
+ function onCompositionStart() {
327
+ composing = true;
328
+ }
329
+
330
+ function onCompositionEnd() {
331
+ composing = false;
332
+ onInput();
333
+ }
334
+
335
+ onMount(() => {
336
+ paint();
337
+ undoStack = [{ code, start: 0, end: 0 }];
338
+ mounted = true;
339
+ emitHistory();
340
+
341
+ editor.addEventListener("input", onInput);
342
+ editor.addEventListener("keydown", onKeydown);
343
+ editor.addEventListener("paste", onPaste);
344
+ editor.addEventListener("mouseup", syncCaretToHistory);
345
+ editor.addEventListener("keyup", syncCaretToHistory);
346
+ document.addEventListener("selectionchange", syncCaretToHistory);
347
+ editor.addEventListener("blur", onBlur);
348
+ editor.addEventListener("compositionstart", onCompositionStart);
349
+ editor.addEventListener("compositionend", onCompositionEnd);
350
+
351
+ return () => {
352
+ editor.removeEventListener("input", onInput);
353
+ editor.removeEventListener("keydown", onKeydown);
354
+ editor.removeEventListener("paste", onPaste);
355
+ editor.removeEventListener("mouseup", syncCaretToHistory);
356
+ editor.removeEventListener("keyup", syncCaretToHistory);
357
+ document.removeEventListener("selectionchange", syncCaretToHistory);
358
+ editor.removeEventListener("blur", onBlur);
359
+ editor.removeEventListener("compositionstart", onCompositionStart);
360
+ editor.removeEventListener("compositionend", onCompositionEnd);
361
+ };
362
+ });
363
+ </script>
364
+
365
+ <pre
366
+ style:overflow-x="var(--overflow-x, auto)"
367
+ style:border-radius="var(--border-radius, 0)"
368
+ {...$$restProps}
369
+ ><code
370
+ bind:this={editor}
371
+ class:hljs={true}
372
+ contenteditable="true"
373
+ spellcheck="false"
374
+ ></code></pre>
375
+
376
+ <style>
377
+ code {
378
+ outline: none;
379
+ }
380
+
381
+ code:focus {
382
+ outline: var(--outline-width, 2px) solid var(--outline-color, #4589ff);
383
+ outline-offset: var(--outline-offset, -2px);
384
+ }
385
+ </style>
@@ -0,0 +1,113 @@
1
+ import type { SvelteComponentTyped } from "svelte";
2
+ import type { HTMLAttributes } from "svelte/elements";
3
+ import type { LanguageType } from "./languages";
4
+
5
+ export type HighlightEditableProps = HTMLAttributes<HTMLPreElement> & {
6
+ /**
7
+ * Editable code (`bind:code`).
8
+ */
9
+ code?: string;
10
+
11
+ /**
12
+ * highlight.js language module.
13
+ * Import languages from `svelte-highlight/languages/*`.
14
+ * @example
15
+ * import typescript from "svelte-highlight/languages/typescript";
16
+ */
17
+ language: LanguageType<string>;
18
+
19
+ /**
20
+ * Number of spaces inserted by the Tab key.
21
+ * @default 2
22
+ */
23
+ tabSize?: number;
24
+
25
+ /**
26
+ * Maximum number of undo snapshots retained. Older snapshots are dropped
27
+ * once the limit is exceeded.
28
+ * @default 200
29
+ */
30
+ historyLimit?: number;
31
+
32
+ /**
33
+ * Color of the focus outline.
34
+ * @default "#4589ff"
35
+ */
36
+ "--outline-color"?: string;
37
+
38
+ /**
39
+ * Width of the focus outline.
40
+ * @default "2px"
41
+ */
42
+ "--outline-width"?: string | number;
43
+
44
+ /**
45
+ * Offset of the focus outline.
46
+ * @default "-2px"
47
+ */
48
+ "--outline-offset"?: string | number;
49
+ };
50
+
51
+ export type HighlightEditableEvents = {
52
+ /**
53
+ * Fired on each edit with current plain-text code.
54
+ */
55
+ change: CustomEvent<{ code: string }>;
56
+
57
+ /**
58
+ * Fired when the editor loses focus with the current plain-text code.
59
+ */
60
+ blur: CustomEvent<{ code: string }>;
61
+
62
+ /**
63
+ * Undo/redo history. `entries` is oldest→newest; `index` is current.
64
+ */
65
+ history: CustomEvent<{
66
+ entries: { size: number }[];
67
+ index: number;
68
+ canUndo: boolean;
69
+ canRedo: boolean;
70
+ }>;
71
+ };
72
+
73
+ export default class HighlightEditable extends SvelteComponentTyped<
74
+ HighlightEditableProps,
75
+ HighlightEditableEvents,
76
+ Record<string, never>
77
+ > {
78
+ /** Undo to the previous history snapshot. */
79
+ undo(): void;
80
+
81
+ /** Redo the last undone history snapshot. */
82
+ redo(): void;
83
+
84
+ /** Focus the editor. */
85
+ focus(): void;
86
+
87
+ /** Select the entire document. */
88
+ selectAll(): void;
89
+
90
+ /** Insert text at the caret (replacing any selection). */
91
+ insert(text: string): void;
92
+
93
+ /** Indent the selected lines (or insert one indent at the caret). */
94
+ indent(): void;
95
+
96
+ /** Dedent the selected lines. */
97
+ outdent(): void;
98
+
99
+ /** Replace the entire document, recording it as an undo step. */
100
+ setCode(value: string): void;
101
+
102
+ /** Empty the document. */
103
+ clear(): void;
104
+
105
+ /** Read the current code. */
106
+ getCode(): string;
107
+
108
+ /** Whether an undo step is available. */
109
+ canUndo(): boolean;
110
+
111
+ /** Whether a redo step is available. */
112
+ canRedo(): boolean;
113
+ }
@@ -1,5 +1,5 @@
1
1
  <script>
2
- import { scopeClassFor, scopeStyle } from "./scoped.js";
2
+ import { dualStyle, scopeClassFor, scopeStyle } from "./scoped.js";
3
3
 
4
4
  /**
5
5
  * Theme CSS from `svelte-highlight/styles/<theme>`.
@@ -7,15 +7,30 @@
7
7
  * import a11yDark from "svelte-highlight/styles/a11y-dark";
8
8
  * @type {string}
9
9
  */
10
- export let theme;
10
+ export let theme = undefined;
11
11
 
12
12
  /**
13
- * Wrapper class the scoped selectors target.
14
- * @type {string}
13
+ * Light theme CSS. With `dark`, overrides `theme`.
14
+ * @type {string | undefined}
15
+ */
16
+ export let light = undefined;
17
+
18
+ /** Dark theme CSS; pair with `light`. */
19
+ export let dark = undefined;
20
+
21
+ /**
22
+ * Theme switch: `"auto"` | `"light"` | `"dark"` | CSS selector for dark.
23
+ * @type {"auto" | "light" | "dark" | string}
15
24
  */
16
- export let scopeClass = scopeClassFor(theme);
25
+ export let mode = "auto";
26
+
27
+ /** Scope class for prefixed selectors. */
28
+ export let scopeClass = scopeClassFor(theme ?? `${light}${dark}`);
17
29
 
18
- $: style = scopeStyle(theme, scopeClass);
30
+ $: style =
31
+ light !== undefined && dark !== undefined
32
+ ? dualStyle(light, dark, scopeClass, mode)
33
+ : scopeStyle(theme, scopeClass);
19
34
  </script>
20
35
 
21
36
  <svelte:head> {@html style} </svelte:head>
@@ -7,7 +7,28 @@ export type HighlightStyleProps = HTMLAttributes<HTMLDivElement> & {
7
7
  * @example
8
8
  * import a11yDark from "svelte-highlight/styles/a11y-dark";
9
9
  */
10
- theme: string;
10
+ theme?: string;
11
+
12
+ /**
13
+ * Light theme CSS; pair with `dark` to emit both stylesheets and switch
14
+ * automatically. Takes precedence over `theme` when both `light` and `dark`
15
+ * are provided.
16
+ */
17
+ light?: string;
18
+
19
+ /**
20
+ * Dark theme CSS; pair with `light` to emit both stylesheets.
21
+ */
22
+ dark?: string;
23
+
24
+ /**
25
+ * How to switch between `light` and `dark`:
26
+ * `"auto"` uses `prefers-color-scheme` media queries, `"light"`/`"dark"`
27
+ * force a single theme, and any other string is a CSS selector that gates
28
+ * the dark block (e.g. `[data-theme="dark"]`).
29
+ * @default "auto"
30
+ */
31
+ mode?: "auto" | "light" | "dark" | (string & {});
11
32
 
12
33
  /**
13
34
  * Wrapper class the scoped selectors target.
@@ -5,7 +5,7 @@ import type { LangtagProps } from "./Highlight.svelte";
5
5
  export type HighlightSvelteProps = HTMLAttributes<HTMLPreElement> &
6
6
  LangtagProps & {
7
7
  /**
8
- * Specify the text to highlight.
8
+ * Code to highlight.
9
9
  */
10
10
  code: any;
11
11
  };
@@ -6,17 +6,17 @@ import type { LanguageName } from "./languages";
6
6
  export type LangTagProps = HTMLAttributes<HTMLPreElement> &
7
7
  LangtagProps & {
8
8
  /**
9
- * Specify the text to highlight.
9
+ * Code to highlight.
10
10
  */
11
11
  code: any;
12
12
 
13
13
  /**
14
- * Provide the highlighted code.
14
+ * Highlighted HTML.
15
15
  */
16
16
  highlighted: string;
17
17
 
18
18
  /**
19
- * Provide the language name.
19
+ * Language name.
20
20
  * @default "plaintext"
21
21
  */
22
22
  languageName?: LanguageName | (string & {});
@@ -15,7 +15,7 @@ export type LineNumbersProps = HTMLAttributes<HTMLDivElement> &
15
15
  highlighted: string;
16
16
 
17
17
  /**
18
- * Provide the language name.
18
+ * Language name.
19
19
  * @default "plaintext"
20
20
  */
21
21
  languageName?: LanguageName | (string & {});
@@ -27,7 +27,7 @@ export type LineNumbersProps = HTMLAttributes<HTMLDivElement> &
27
27
  hideBorder?: boolean;
28
28
 
29
29
  /**
30
- * Specify which starting line number should be displayed.
30
+ * Starting line number.
31
31
  * @default 1
32
32
  */
33
33
  startingLineNumber?: number;
@@ -39,14 +39,14 @@ export type LineNumbersProps = HTMLAttributes<HTMLDivElement> &
39
39
  wrapLines?: boolean;
40
40
 
41
41
  /**
42
- * Specify the line indices to highlight.
42
+ * Line indices to highlight.
43
43
  * @default []
44
44
  * @example [0, 1, 9]
45
45
  */
46
46
  highlightedLines?: number[];
47
47
 
48
48
  /**
49
- * Specify the text color for line numbers.
49
+ * Line number text color.
50
50
  * Defaults to the current theme color applied to `.hljs code`.
51
51
  * @default currentColor
52
52
  * @example "pink"
@@ -54,7 +54,7 @@ export type LineNumbersProps = HTMLAttributes<HTMLDivElement> &
54
54
  "--line-number-color"?: string;
55
55
 
56
56
  /**
57
- * Specify the border color.
57
+ * Border color.
58
58
  * Defaults to the current background color applied to `.hljs`.
59
59
  * @default currentColor
60
60
  * @example "#fff"
@@ -62,28 +62,28 @@ export type LineNumbersProps = HTMLAttributes<HTMLDivElement> &
62
62
  "--border-color"?: string;
63
63
 
64
64
  /**
65
- * Specify the left padding for `td` elements.
65
+ * Left cell padding.
66
66
  * @default 1em
67
67
  * @example 0
68
68
  */
69
69
  "--padding-left"?: number | string;
70
70
 
71
71
  /**
72
- * Specify the right padding for `td` elements.
72
+ * Right cell padding.
73
73
  * @default 1em
74
74
  * @example 0
75
75
  */
76
76
  "--padding-right"?: number | string;
77
77
 
78
78
  /**
79
- * Specify the background color of highlighted lines.
79
+ * Highlighted line background.
80
80
  * @default "rgba(254, 241, 96, 0.2)"
81
81
  * @example "#fff"
82
82
  */
83
83
  "--highlighted-background"?: string;
84
84
 
85
85
  /**
86
- * Specify the opacity of un-highlighted lines.
86
+ * Un-highlighted line opacity.
87
87
  * Only applies when `highlightedLines` is non-empty.
88
88
  * @default 1
89
89
  * @example 0.4
@@ -91,7 +91,7 @@ export type LineNumbersProps = HTMLAttributes<HTMLDivElement> &
91
91
  "--unhighlighted-opacity"?: number | string;
92
92
 
93
93
  /**
94
- * Specify a CSS filter for un-highlighted lines.
94
+ * Un-highlighted line filter.
95
95
  * Only applies when `highlightedLines` is non-empty.
96
96
  * @default none
97
97
  * @example "blur(2px)"