svelte-highlight 7.14.0 → 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.
Files changed (46) hide show
  1. package/AnsiOutput.svelte +22 -3
  2. package/CopyButton.svelte +10 -2
  3. package/CopyButton.svelte.d.ts +8 -1
  4. package/FileTabs.svelte +2 -1
  5. package/Highlight.svelte +26 -15
  6. package/HighlightAuto.svelte +25 -20
  7. package/HighlightEditable.svelte +434 -43
  8. package/HighlightEditable.svelte.d.ts +31 -0
  9. package/HighlightStream.svelte +154 -0
  10. package/HighlightStream.svelte.d.ts +90 -0
  11. package/HighlightStyle.svelte +70 -5
  12. package/HighlightSvelte.svelte +24 -15
  13. package/LineNumbers.svelte +4 -2
  14. package/README.md +119 -3
  15. package/Typewriter.svelte +111 -58
  16. package/action.js +29 -3
  17. package/ansi.d.ts +9 -0
  18. package/ansi.js +112 -4
  19. package/copy-transforms.d.ts +13 -0
  20. package/copy-transforms.js +41 -0
  21. package/highlight-theme.d.ts +7 -0
  22. package/highlight-theme.js +176 -0
  23. package/index.d.ts +8 -0
  24. package/index.js +8 -0
  25. package/languages/astro.js +6 -0
  26. package/languages/hcl.js +4 -4
  27. package/languages/hlsl.js +6 -2
  28. package/languages/jq.js +2 -2
  29. package/languages/just.js +1 -1
  30. package/languages/kql.js +1 -0
  31. package/languages/rescript.js +3 -2
  32. package/languages/solidity.js +1 -1
  33. package/languages/svelte.js +6 -5
  34. package/languages/wgsl.js +32 -6
  35. package/languages/zig.js +2 -2
  36. package/package.json +19 -3
  37. package/split-lines.d.ts +6 -0
  38. package/split-lines.js +50 -0
  39. package/text-diff.d.ts +8 -0
  40. package/text-diff.js +46 -0
  41. package/token-ranges.d.ts +18 -0
  42. package/token-ranges.js +112 -0
  43. package/typewriter-units.d.ts +13 -0
  44. package/typewriter-units.js +73 -0
  45. package/core.js +0 -22
  46. package/highlighter.svelte.js +0 -22
@@ -1,3 +1,10 @@
1
+ <script context="module">
2
+ let instanceCount = 0;
3
+ function nextInstanceId() {
4
+ return ++instanceCount;
5
+ }
6
+ </script>
7
+
1
8
  <script>
2
9
  /** @type {import("./languages").LanguageType<string>} */
3
10
  export let language;
@@ -11,11 +18,35 @@
11
18
  /** @type {number} Maximum number of undo snapshots retained. */
12
19
  export let historyLimit = 200;
13
20
 
21
+ /**
22
+ * Rendering engine. `"css-highlights"` (experimental) paints tokens via
23
+ * the CSS Custom Highlight API over plain-text line nodes instead of
24
+ * wrapping them in `<span>`s, so a repaint never replaces DOM the caret
25
+ * could be sitting in. Falls back to `"dom"` silently where
26
+ * `CSS.highlights` is unavailable; check the resolved engine with the
27
+ * exported `resolvedEngine()` method.
28
+ * @type {"dom" | "css-highlights"}
29
+ */
30
+ export let engine = "dom";
31
+
32
+ /**
33
+ * Theme CSS from `svelte-highlight/styles/<theme>`, used only in
34
+ * `"css-highlights"` mode to generate `::highlight()` rules. Colors only
35
+ * (`color`/`background-color`); other declarations are dropped.
36
+ * @type {string | undefined}
37
+ */
38
+ export let theme = undefined;
39
+
14
40
  import hljs from "highlight.js/lib/core";
15
41
  import { createEventDispatcher, onMount } from "svelte";
42
+ import { highlightRules } from "./highlight-theme.js";
43
+ import { splitLines } from "./split-lines.js";
44
+ import { diffText } from "./text-diff.js";
45
+ import { tokenize } from "./token-ranges.js";
16
46
 
17
47
  const dispatch = createEventDispatcher();
18
48
  const TRAILING_NEWLINE = /\n$/;
49
+ const instanceId = nextInstanceId();
19
50
 
20
51
  /** @type {HTMLElement} */
21
52
  let editor;
@@ -25,12 +56,48 @@
25
56
  let mounted = false;
26
57
  let restoringSelection = false;
27
58
 
59
+ // One <span> per line, painted incrementally (see `renderLines`).
60
+ /** @type {HTMLSpanElement[]} */
61
+ let lineEls = [];
62
+ /** @type {number[]} Rendered (plain-text) length of each line element. */
63
+ let lineLengths = [];
64
+ /** @type {string[]} Line HTML currently reflected in `lineEls`. */
65
+ let renderedLines = [];
66
+
28
67
  // Tracks `code` so parent updates vs local edits can be distinguished.
29
68
  let internalCode = code;
30
69
 
31
- $: hljs.registerLanguage(language.name, language.register);
70
+ $: resolvedEngineValue =
71
+ engine === "css-highlights" &&
72
+ typeof CSS !== "undefined" &&
73
+ typeof CSS.highlights !== "undefined"
74
+ ? "css-highlights"
75
+ : "dom";
76
+
77
+ let previousLanguageName;
78
+ let previousEngine;
79
+ $: {
80
+ hljs.registerLanguage(language.name, language.register);
81
+ if (
82
+ mounted &&
83
+ (language.name !== previousLanguageName ||
84
+ resolvedEngineValue !== previousEngine)
85
+ ) {
86
+ if (previousEngine === "css-highlights") clearCssHighlights();
87
+ repaintForLanguageChange();
88
+ }
89
+ previousLanguageName = language.name;
90
+ previousEngine = resolvedEngineValue;
91
+ }
32
92
  $: indentUnit = " ".repeat(tabSize);
33
93
  $: if (mounted && code !== internalCode) syncExternal();
94
+ $: cssHighlightStyle =
95
+ resolvedEngineValue === "css-highlights" && theme !== undefined
96
+ ? `<style>${highlightRules(theme).replaceAll(
97
+ "::highlight(hljs-",
98
+ `::highlight(hljs-${instanceId}-`,
99
+ )}</style>`
100
+ : "";
34
101
 
35
102
  function getSelectionRange() {
36
103
  const selection = window.getSelection();
@@ -49,12 +116,8 @@
49
116
  return sel ? sel.end : null;
50
117
  }
51
118
 
52
- function nodeAtOffset(offset) {
53
- const walker = document.createTreeWalker(
54
- editor,
55
- NodeFilter.SHOW_TEXT,
56
- null,
57
- );
119
+ function nodeAtOffset(offset, root = editor) {
120
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
58
121
  let count = 0;
59
122
  for (let node = walker.nextNode(); node; node = walker.nextNode()) {
60
123
  const next = count + node.textContent.length;
@@ -64,49 +127,238 @@
64
127
  return null;
65
128
  }
66
129
 
67
- function setSelection(start, end) {
68
- const from = nodeAtOffset(start);
130
+ // Firefox's contenteditable undo manager treats a boundary set exactly at
131
+ // a text node's start/end (setStart/setEnd with a text node + offset)
132
+ // differently from the equivalent boundary expressed via the parent's
133
+ // child index (setStartBefore/After): after our repaint rebuilds the text
134
+ // node, the former leaves Firefox unable to recognize a later native
135
+ // undo (execCommand/Edit menu), which then silently does nothing. Prefer
136
+ // the parent-anchored form whenever the offset lands on a node edge.
137
+ function setRangeBoundary(range, side, node, offset) {
138
+ if (offset === 0) range[`set${side}Before`](node);
139
+ else if (offset === node.textContent.length) range[`set${side}After`](node);
140
+ else range[side === "Start" ? "setStart" : "setEnd"](node, offset);
141
+ }
142
+
143
+ function setSelection(start, end, root = editor) {
144
+ const from = nodeAtOffset(start, root);
69
145
  if (!from) return;
70
146
  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);
147
+ setRangeBoundary(range, "Start", from.node, from.offset);
148
+ const to = end != null && end !== start ? nodeAtOffset(end, root) : null;
149
+ if (to) setRangeBoundary(range, "End", to.node, to.offset);
74
150
  else range.collapse(true);
75
151
  const selection = window.getSelection();
76
152
  selection.removeAllRanges();
77
153
  selection.addRange(range);
78
154
  }
79
155
 
156
+ // Character offset (in the same space as getSelectionRange/setSelection)
157
+ // where line `index` starts.
158
+ function lineStartOffset(index) {
159
+ let start = index; // one "\n" separator per preceding line
160
+ for (let i = 0; i < index; i++) start += lineLengths[i];
161
+ return start;
162
+ }
163
+
164
+ const setHtml = (el, line) => {
165
+ el.innerHTML = line;
166
+ };
167
+ const setText = (el, line) => {
168
+ el.textContent = line;
169
+ };
170
+
171
+ // Patches `editor` to match `lines` (one <span> per line, joined by literal
172
+ // "\n" text nodes so caret offset math stays identical to a flat paint).
173
+ // Only lines whose content actually changed touch the DOM (assigned via
174
+ // `setContent`: innerHTML for the "dom" engine, textContent for
175
+ // "css-highlights"). Returns the index of the single changed line when
176
+ // nothing else shifted (used to scope caret restoration), or null.
177
+ function renderLines(lines, setContent) {
178
+ // Some browsers can place a native selection boundary just outside a
179
+ // line's <span> (e.g. Firefox collapsing a select-all there); typing at
180
+ // that point inserts a stray sibling text node our diffing never touches.
181
+ // Detect the drift by child count and self-heal with a full rebuild.
182
+ const expectedChildren = lineEls.length === 0 ? 0 : lineEls.length * 2 - 1;
183
+ if (editor.childNodes.length !== expectedChildren) {
184
+ editor.textContent = "";
185
+ lineEls = [];
186
+ lineLengths = [];
187
+ renderedLines = [];
188
+ clearCssHighlights();
189
+ }
190
+
191
+ const prevLen = lineEls.length;
192
+ const newLen = lines.length;
193
+ const commonLen = Math.min(prevLen, newLen);
194
+
195
+ let changedIndex = null;
196
+ let changedCount = 0;
197
+ for (let i = 0; i < commonLen; i++) {
198
+ if (renderedLines[i] === lines[i]) continue;
199
+ setContent(lineEls[i], lines[i]);
200
+ lineLengths[i] = lineEls[i].textContent.length;
201
+ changedIndex = i;
202
+ changedCount++;
203
+ }
204
+
205
+ for (let i = prevLen; i < newLen; i++) {
206
+ if (lineEls.length > 0) editor.appendChild(document.createTextNode("\n"));
207
+ const span = document.createElement("span");
208
+ setContent(span, lines[i]);
209
+ editor.appendChild(span);
210
+ lineEls.push(span);
211
+ lineLengths.push(span.textContent.length);
212
+ }
213
+
214
+ while (lineEls.length > newLen) {
215
+ editor.removeChild(lineEls.pop());
216
+ lineLengths.pop();
217
+ clearLineHighlights(lineHighlightRanges.length - 1);
218
+ lineHighlightRanges.pop();
219
+ // Drop the separator that used to precede the removed line.
220
+ if (lineEls.length > 0) editor.removeChild(editor.lastChild);
221
+ }
222
+
223
+ renderedLines = lines;
224
+ return prevLen === newLen && changedCount === 1 ? changedIndex : null;
225
+ }
226
+
227
+ /** @type {Map<string, InstanceType<typeof Highlight>>} scope -> registered Highlight. */
228
+ let cssHighlights = new Map();
229
+ /** @type {{ scope: string; range: Range }[][]} Ranges registered per line. */
230
+ let lineHighlightRanges = [];
231
+
232
+ function cssHighlightFor(scope) {
233
+ let highlight = cssHighlights.get(scope);
234
+ if (!highlight) {
235
+ highlight = new Highlight();
236
+ cssHighlights.set(scope, highlight);
237
+ CSS.highlights.set(`hljs-${instanceId}-${scope}`, highlight);
238
+ }
239
+ return highlight;
240
+ }
241
+
242
+ function clearLineHighlights(index) {
243
+ const previous = lineHighlightRanges[index];
244
+ if (!previous) return;
245
+ for (const { scope, range } of previous) {
246
+ cssHighlights.get(scope)?.delete(range);
247
+ }
248
+ }
249
+
250
+ function clearCssHighlights() {
251
+ for (const scope of cssHighlights.keys()) {
252
+ CSS.highlights.delete(`hljs-${instanceId}-${scope}`);
253
+ }
254
+ cssHighlights = new Map();
255
+ lineHighlightRanges = [];
256
+ }
257
+
258
+ // Rebuilds only line `index`'s Highlight Range registrations from
259
+ // `tokenRanges` (absolute offsets into the full document); the line's text
260
+ // node itself is untouched by this, so it never disturbs the caret.
261
+ function paintLineHighlights(index, tokenRanges) {
262
+ clearLineHighlights(index);
263
+ const textNode = lineEls[index].firstChild;
264
+ const next = [];
265
+ if (textNode) {
266
+ const lineStart = lineStartOffset(index);
267
+ const lineEnd = lineStart + lineLengths[index];
268
+ for (const token of tokenRanges) {
269
+ if (token.end <= lineStart || token.start >= lineEnd) continue;
270
+ const start = Math.max(token.start, lineStart) - lineStart;
271
+ const end = Math.min(token.end, lineEnd) - lineStart;
272
+ if (start === end) continue;
273
+ const range = new Range();
274
+ range.setStart(textNode, start);
275
+ range.setEnd(textNode, end);
276
+ cssHighlightFor(token.scope).add(range);
277
+ next.push({ scope: token.scope, range });
278
+ }
279
+ }
280
+ lineHighlightRanges[index] = next;
281
+ }
282
+
283
+ function paintCssHighlights() {
284
+ const changedIndex = renderLines(code.split("\n"), setText);
285
+ const tokenRanges = tokenize(code, language.name);
286
+
287
+ if (changedIndex == null) {
288
+ for (let i = 0; i < lineEls.length; i++) {
289
+ paintLineHighlights(i, tokenRanges);
290
+ }
291
+ } else {
292
+ paintLineHighlights(changedIndex, tokenRanges);
293
+ }
294
+ return changedIndex;
295
+ }
296
+
80
297
  function paint() {
298
+ if (resolvedEngineValue === "css-highlights") return paintCssHighlights();
81
299
  const html = hljs.highlight(code, { language: language.name }).value;
82
300
  // Trailing empty line needs a phantom `\n` for caret placement.
83
- editor.innerHTML = code === "" || code.endsWith("\n") ? `${html}\n` : html;
301
+ const paintHtml = code === "" || code.endsWith("\n") ? `${html}\n` : html;
302
+ return renderLines(splitLines(paintHtml), setHtml);
84
303
  }
85
304
 
86
305
  function renderAt(start, end) {
87
- paint();
306
+ const changedIndex = paint();
88
307
  if (start == null) return;
89
308
  restoringSelection = true;
309
+ if (changedIndex != null) {
310
+ const lineStart = lineStartOffset(changedIndex);
311
+ const lineEnd = lineStart + lineLengths[changedIndex];
312
+ const inLine = (offset) =>
313
+ offset == null || (offset >= lineStart && offset <= lineEnd);
314
+ if (start >= lineStart && start <= lineEnd && inLine(end)) {
315
+ setSelection(
316
+ start - lineStart,
317
+ end == null ? end : end - lineStart,
318
+ lineEls[changedIndex],
319
+ );
320
+ restoringSelection = false;
321
+ return;
322
+ }
323
+ }
90
324
  setSelection(start, end);
91
325
  restoringSelection = false;
92
326
  }
93
327
 
328
+ function repaintForLanguageChange() {
329
+ const caret = document.activeElement === editor ? getCaretOffset() : null;
330
+ if (caret == null) paint();
331
+ else renderAt(caret, caret);
332
+ }
333
+
94
334
  function syncCaretToHistory() {
335
+ if (!editor.contains(document.activeElement)) return;
95
336
  if (restoringSelection || composing || undoStack.length === 0) return;
96
337
  const sel = getSelectionRange();
97
338
  if (!sel) return;
98
339
  const top = undoStack[undoStack.length - 1];
99
- if (top.code !== code) return;
340
+ if (top.resultLength !== code.length) return;
100
341
  undoStack[undoStack.length - 1] = {
101
- code: top.code,
102
- start: sel.start,
103
- end: sel.end,
342
+ ...top,
343
+ selectionAfter: { start: sel.start, end: sel.end },
104
344
  };
105
345
  }
106
346
 
107
- /** @type {Array<{ code: string; start: number; end: number }>} */
347
+ /**
348
+ * @typedef {{ start: number; end: number }} Selection
349
+ * @typedef {{
350
+ * start: number;
351
+ * removed: string;
352
+ * inserted: string;
353
+ * resultLength: number;
354
+ * selectionBefore: Selection;
355
+ * selectionAfter: Selection;
356
+ * }} HistoryEntry
357
+ */
358
+
359
+ /** @type {HistoryEntry[]} */
108
360
  let undoStack = [];
109
- /** @type {Array<{ code: string; start: number; end: number }>} */
361
+ /** @type {HistoryEntry[]} */
110
362
  let redoStack = [];
111
363
  let lastRecord = 0;
112
364
 
@@ -114,7 +366,7 @@
114
366
  const future = redoStack.slice().reverse();
115
367
  dispatch("history", {
116
368
  entries: [...undoStack, ...future].map((snap) => ({
117
- size: snap.code.length,
369
+ size: snap.resultLength,
118
370
  })),
119
371
  index: undoStack.length - 1,
120
372
  canUndo: canUndo(),
@@ -122,14 +374,46 @@
122
374
  });
123
375
  }
124
376
 
377
+ /** @returns {HistoryEntry} */
378
+ function makeEntry(before, after, selectionBefore, selectionAfter) {
379
+ const { start, removed, inserted } = diffText(before, after);
380
+ return {
381
+ start,
382
+ removed,
383
+ inserted,
384
+ resultLength: after.length,
385
+ selectionBefore,
386
+ selectionAfter,
387
+ };
388
+ }
389
+
390
+ // The code an entry transformed *from*, given the code it produced.
391
+ function beforeCodeOf(entry, resultCode) {
392
+ return (
393
+ resultCode.slice(0, entry.start) +
394
+ entry.removed +
395
+ resultCode.slice(entry.start + entry.inserted.length)
396
+ );
397
+ }
398
+
125
399
  // Coalesce typing within 250ms; Enter/Tab/paste pass coalesce=false.
126
- function pushHistory(snap, coalesce) {
400
+ function pushHistory(previousCode, newCode, selectionAfter, coalesce) {
127
401
  redoStack = [];
128
402
  const now = Date.now();
403
+ const top = undoStack[undoStack.length - 1];
404
+
129
405
  if (coalesce && undoStack.length > 1 && now - lastRecord < 250) {
130
- undoStack[undoStack.length - 1] = snap;
406
+ const burstStart = beforeCodeOf(top, previousCode);
407
+ undoStack[undoStack.length - 1] = makeEntry(
408
+ burstStart,
409
+ newCode,
410
+ top.selectionBefore,
411
+ selectionAfter,
412
+ );
131
413
  } else {
132
- undoStack.push(snap);
414
+ undoStack.push(
415
+ makeEntry(previousCode, newCode, top.selectionAfter, selectionAfter),
416
+ );
133
417
  const limit = Math.max(1, historyLimit);
134
418
  if (undoStack.length > limit) {
135
419
  undoStack.splice(0, undoStack.length - limit);
@@ -139,25 +423,37 @@
139
423
  emitHistory();
140
424
  }
141
425
 
142
- function applySnapshot(snap) {
143
- code = snap.code;
144
- internalCode = snap.code;
426
+ function applyHistoryMove(newCode, selection) {
427
+ code = newCode;
428
+ internalCode = newCode;
145
429
  dispatch("change", { code });
146
430
  emitHistory();
147
- renderAt(snap.start, snap.end);
431
+ renderAt(selection.start, selection.end);
148
432
  }
149
433
 
150
434
  function commit(value, start, end, coalesce) {
435
+ const previousCode = code;
151
436
  code = value;
152
437
  internalCode = value;
153
438
  dispatch("change", { code });
154
- pushHistory({ code: value, start, end }, coalesce);
439
+ pushHistory(
440
+ previousCode,
441
+ value,
442
+ { start, end: end == null ? start : end },
443
+ coalesce,
444
+ );
155
445
  renderAt(start, end);
156
446
  }
157
447
 
158
448
  function syncExternal() {
449
+ const previousCode = internalCode;
159
450
  internalCode = code;
160
- pushHistory({ code, start: code.length, end: code.length }, false);
451
+ pushHistory(
452
+ previousCode,
453
+ code,
454
+ { start: code.length, end: code.length },
455
+ false,
456
+ );
161
457
  paint();
162
458
  }
163
459
 
@@ -218,15 +514,20 @@
218
514
 
219
515
  export function undo() {
220
516
  if (undoStack.length <= 1) return;
221
- redoStack.push(undoStack.pop());
222
- applySnapshot(undoStack[undoStack.length - 1]);
517
+ const entry = undoStack.pop();
518
+ redoStack.push(entry);
519
+ applyHistoryMove(beforeCodeOf(entry, code), entry.selectionBefore);
223
520
  }
224
521
 
225
522
  export function redo() {
226
523
  if (redoStack.length === 0) return;
227
- const snap = redoStack.pop();
228
- undoStack.push(snap);
229
- applySnapshot(snap);
524
+ const entry = redoStack.pop();
525
+ const nextCode =
526
+ code.slice(0, entry.start) +
527
+ entry.inserted +
528
+ code.slice(entry.start + entry.removed.length);
529
+ undoStack.push(entry);
530
+ applyHistoryMove(nextCode, entry.selectionAfter);
230
531
  }
231
532
 
232
533
  export function focus() {
@@ -255,10 +556,16 @@
255
556
 
256
557
  export function setCode(value) {
257
558
  if (value === code) return;
559
+ const previousCode = code;
258
560
  internalCode = value;
259
561
  code = value;
260
562
  dispatch("change", { code });
261
- pushHistory({ code: value, start: value.length, end: value.length }, false);
563
+ pushHistory(
564
+ previousCode,
565
+ value,
566
+ { start: value.length, end: value.length },
567
+ false,
568
+ );
262
569
  paint();
263
570
  }
264
571
 
@@ -278,14 +585,53 @@
278
585
  return redoStack.length > 0;
279
586
  }
280
587
 
281
- function onInput() {
588
+ /** The engine actually in use: `engine`, or `"dom"` if it was requested but unsupported. */
589
+ export function resolvedEngine() {
590
+ return resolvedEngineValue;
591
+ }
592
+
593
+ // WebKit dispatches a second beforeinput historyUndo/historyRedo shortly
594
+ // after the first for a single execCommand call; without this guard the
595
+ // second dispatch pops an extra history entry. The reset is deferred past
596
+ // the current task so a genuinely separate later undo still goes through.
597
+ let handlingNativeHistory = false;
598
+ function runNativeHistory(action) {
599
+ if (handlingNativeHistory) return;
600
+ handlingNativeHistory = true;
601
+ action();
602
+ setTimeout(() => {
603
+ handlingNativeHistory = false;
604
+ }, 0);
605
+ }
606
+
607
+ function onInput(event) {
282
608
  if (composing) return;
283
- // innerText keeps contenteditable line breaks; textContent doesn't.
284
- code = editor.innerText.replace(TRAILING_NEWLINE, "");
609
+ // Some engines (e.g. Chromium's execCommand path) never dispatch a
610
+ // cancelable beforeinput for native undo/redo, only this input event
611
+ // after the DOM already mutated. Re-render from our own snapshot rather
612
+ // than recording the browser's mutation as new typed content.
613
+ if (event?.inputType === "historyUndo") {
614
+ runNativeHistory(undo);
615
+ return;
616
+ }
617
+ if (event?.inputType === "historyRedo") {
618
+ runNativeHistory(redo);
619
+ return;
620
+ }
621
+ const previousCode = code;
622
+ // textContent (not innerText): innerText forces a synchronous layout
623
+ // and Firefox can return a stale value immediately after editing a text
624
+ // node last written via `textContent` (see setText in
625
+ // paintCssHighlights), losing the just-typed content. The `<pre>`
626
+ // wrapper's `white-space: pre` means every native text-insertion path
627
+ // (typing, execCommand insertText, paste/drop as plain text) already
628
+ // uses literal "\n" characters rather than <br> elements, so
629
+ // textContent loses nothing textContent would have kept anyway.
630
+ code = editor.textContent.replace(TRAILING_NEWLINE, "");
285
631
  internalCode = code;
286
632
  const caret = getCaretOffset() ?? code.length;
287
633
  dispatch("change", { code });
288
- pushHistory({ code, start: caret, end: caret }, true);
634
+ pushHistory(previousCode, code, { start: caret, end: caret }, true);
289
635
  renderAt(caret);
290
636
  }
291
637
 
@@ -319,10 +665,34 @@
319
665
  insertText(event.clipboardData?.getData("text/plain") ?? "");
320
666
  }
321
667
 
668
+ // Edit-menu / execCommand undo-redo bypass onKeydown; intercept here so the
669
+ // browser doesn't mutate DOM that paint() has already rebuilt.
670
+ function onBeforeInput(event) {
671
+ if (event.inputType === "historyUndo") {
672
+ event.preventDefault();
673
+ runNativeHistory(undo);
674
+ } else if (event.inputType === "historyRedo") {
675
+ event.preventDefault();
676
+ runNativeHistory(redo);
677
+ }
678
+ }
679
+
322
680
  function onBlur() {
323
681
  dispatch("blur", { code: getCode() });
324
682
  }
325
683
 
684
+ // Selection changes can only affect this editor while it holds focus, so
685
+ // only pay for the document-wide listener (range clone + full-content
686
+ // toString()) during that window instead of for the component's whole
687
+ // lifetime.
688
+ function onFocusIn() {
689
+ document.addEventListener("selectionchange", syncCaretToHistory);
690
+ }
691
+
692
+ function onFocusOut() {
693
+ document.removeEventListener("selectionchange", syncCaretToHistory);
694
+ }
695
+
326
696
  function onCompositionStart() {
327
697
  composing = true;
328
698
  }
@@ -334,16 +704,27 @@
334
704
 
335
705
  onMount(() => {
336
706
  paint();
337
- undoStack = [{ code, start: 0, end: 0 }];
707
+ undoStack = [
708
+ {
709
+ start: 0,
710
+ removed: "",
711
+ inserted: code,
712
+ resultLength: code.length,
713
+ selectionBefore: { start: 0, end: 0 },
714
+ selectionAfter: { start: 0, end: 0 },
715
+ },
716
+ ];
338
717
  mounted = true;
339
718
  emitHistory();
340
719
 
341
720
  editor.addEventListener("input", onInput);
342
721
  editor.addEventListener("keydown", onKeydown);
722
+ editor.addEventListener("beforeinput", onBeforeInput);
343
723
  editor.addEventListener("paste", onPaste);
344
724
  editor.addEventListener("mouseup", syncCaretToHistory);
345
725
  editor.addEventListener("keyup", syncCaretToHistory);
346
- document.addEventListener("selectionchange", syncCaretToHistory);
726
+ editor.addEventListener("focusin", onFocusIn);
727
+ editor.addEventListener("focusout", onFocusOut);
347
728
  editor.addEventListener("blur", onBlur);
348
729
  editor.addEventListener("compositionstart", onCompositionStart);
349
730
  editor.addEventListener("compositionend", onCompositionEnd);
@@ -351,17 +732,27 @@
351
732
  return () => {
352
733
  editor.removeEventListener("input", onInput);
353
734
  editor.removeEventListener("keydown", onKeydown);
735
+ editor.removeEventListener("beforeinput", onBeforeInput);
354
736
  editor.removeEventListener("paste", onPaste);
355
737
  editor.removeEventListener("mouseup", syncCaretToHistory);
356
738
  editor.removeEventListener("keyup", syncCaretToHistory);
739
+ editor.removeEventListener("focusin", onFocusIn);
740
+ editor.removeEventListener("focusout", onFocusOut);
357
741
  document.removeEventListener("selectionchange", syncCaretToHistory);
358
742
  editor.removeEventListener("blur", onBlur);
359
743
  editor.removeEventListener("compositionstart", onCompositionStart);
360
744
  editor.removeEventListener("compositionend", onCompositionEnd);
745
+ clearCssHighlights();
361
746
  };
362
747
  });
363
748
  </script>
364
749
 
750
+ <svelte:head
751
+ >{#if cssHighlightStyle}
752
+ {@html cssHighlightStyle}
753
+ {/if}</svelte:head
754
+ >
755
+
365
756
  <pre
366
757
  style:overflow-x="var(--overflow-x, auto)"
367
758
  style:border-radius="var(--border-radius, 0)"
@@ -371,7 +762,7 @@
371
762
  class:hljs={true}
372
763
  contenteditable="true"
373
764
  spellcheck="false"
374
- ></code></pre>
765
+ >{code}</code></pre>
375
766
 
376
767
  <style>
377
768
  code {