svelte-highlight 7.23.2 → 7.24.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 (94) hide show
  1. package/AnsiOutput.svelte +33 -6
  2. package/AnsiOutput.svelte.d.ts +8 -0
  3. package/CodeToolbar.svelte +144 -0
  4. package/CodeToolbar.svelte.d.ts +125 -0
  5. package/CodeWindow.svelte +19 -0
  6. package/CodeWindow.svelte.d.ts +10 -0
  7. package/CopyButton.svelte +107 -3
  8. package/CopyButton.svelte.d.ts +17 -1
  9. package/DiffFileList.svelte +523 -0
  10. package/DiffFileList.svelte.d.ts +94 -0
  11. package/DiffFileListItem.svelte +44 -0
  12. package/DiffMinimap.svelte +99 -0
  13. package/DiffMinimap.svelte.d.ts +17 -0
  14. package/DiffStats.svelte +43 -0
  15. package/DiffStats.svelte.d.ts +17 -0
  16. package/DiffView.svelte +1213 -0
  17. package/DiffView.svelte.d.ts +76 -0
  18. package/FileTabs.svelte +2 -5
  19. package/Highlight.svelte +158 -2
  20. package/Highlight.svelte.d.ts +50 -2
  21. package/HighlightAuto.svelte.d.ts +3 -2
  22. package/HighlightAutoLazy.svelte +112 -0
  23. package/HighlightAutoLazy.svelte.d.ts +66 -0
  24. package/HighlightDiff.svelte +162 -0
  25. package/HighlightDiff.svelte.d.ts +102 -0
  26. package/HighlightEditable.svelte +65 -756
  27. package/HighlightEditable.svelte.d.ts +15 -5
  28. package/HighlightStream.svelte +117 -218
  29. package/HighlightStream.svelte.d.ts +8 -0
  30. package/HighlightSvelte.svelte.d.ts +3 -2
  31. package/HighlightVirtual.svelte +41 -8
  32. package/HighlightVirtual.svelte.d.ts +8 -0
  33. package/LangTag.svelte +33 -4
  34. package/LangTag.svelte.d.ts +6 -2
  35. package/LineNumbers.svelte +25 -4
  36. package/LineNumbers.svelte.d.ts +8 -0
  37. package/MarkdownStream.svelte +1 -0
  38. package/README.md +735 -18
  39. package/ToolbarButton.svelte +90 -0
  40. package/ToolbarButton.svelte.d.ts +106 -0
  41. package/Typewriter.svelte +59 -10
  42. package/Typewriter.svelte.d.ts +7 -0
  43. package/WrapToggle.svelte +34 -0
  44. package/WrapToggle.svelte.d.ts +39 -0
  45. package/action.js +7 -3
  46. package/ansi.d.ts +1 -3
  47. package/auto-detect.d.ts +52 -0
  48. package/auto-detect.js +208 -0
  49. package/code-region.d.ts +7 -0
  50. package/code-region.js +20 -0
  51. package/css-highlights.js +115 -0
  52. package/css-walk.js +50 -0
  53. package/diff-controller.d.ts +120 -0
  54. package/diff-controller.js +721 -0
  55. package/diff-edits.d.ts +101 -0
  56. package/diff-edits.js +890 -0
  57. package/diff-html.d.ts +8 -0
  58. package/diff-html.js +60 -0
  59. package/diff-languages.d.ts +4 -0
  60. package/diff-languages.js +73 -0
  61. package/diff.d.ts +161 -0
  62. package/diff.js +1111 -0
  63. package/editable-commands.js +81 -0
  64. package/editable-css-paint.js +5 -3
  65. package/editable-dom-paint.js +1 -1
  66. package/editable-history.js +199 -0
  67. package/editable-line-dom.js +176 -1
  68. package/editable-painter.js +356 -0
  69. package/editable.d.ts +118 -0
  70. package/editable.js +513 -0
  71. package/engine.d.ts +1 -1
  72. package/fence.js +1 -1
  73. package/highlight-cascade.js +679 -0
  74. package/highlight-theme.js +6 -47
  75. package/incremental-tokenize.js +1 -1
  76. package/index.d.ts +39 -6
  77. package/index.js +30 -0
  78. package/languages/detect-index.d.ts +16 -0
  79. package/languages/detect-index.js +6 -0
  80. package/languages/loaders.d.ts +8 -0
  81. package/languages/loaders.js +370 -0
  82. package/package.json +50 -2
  83. package/preprocessor.js +20 -5
  84. package/search.js +2 -2
  85. package/stream-highlighter.js +198 -0
  86. package/stream.css +16 -0
  87. package/stream.d.ts +60 -0
  88. package/stream.js +283 -0
  89. package/style-registry.js +34 -3
  90. package/themes/_base-css.d.ts +1 -0
  91. package/themes/_base-css.js +1 -0
  92. package/typewriter-units.d.ts +3 -0
  93. package/typewriter-units.js +43 -0
  94. package/virtual-window.js +9 -4
package/README.md CHANGED
@@ -61,6 +61,50 @@ By default, overflowing horizontal content is contained by a scrollbar. Set `wra
61
61
 
62
62
  Don't combine `wrap` with `HighlightStream`'s `virtualize` mode or `HighlightVirtual` -- both assume one fixed-height line per row, which wrapping breaks.
63
63
 
64
+ ### Accessibility
65
+
66
+ A long line makes the code block scroll. Keyboard users can only scroll what they can focus, so each code block is a focusable region (`tabindex="0"`, `role="region"`). Use `label` to give the region a name. It defaults to `"Code"`. A focused region shows the browser's focus ring, drawn just inside its edge so a scrolling parent can't clip it.
67
+
68
+ ```svelte
69
+ <Highlight language={typescript} {code} label="Add function" />
70
+ ```
71
+
72
+ `label` works the same way on `HighlightAuto`, `HighlightAutoLazy`, `HighlightSvelte`, `LineNumbers`, `AnsiOutput`, `HighlightStream`, `HighlightVirtual`, and `Typewriter`. Inside a `CodeWindow`, the block takes the window's `title` (or its `label`) as its name.
73
+
74
+ ### Experimental: CSS Custom Highlight engine
75
+
76
+ Set `engine="css-highlights"` to paint tokens with the [CSS Custom Highlight API](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API) (`CSS.highlights`, `::highlight()`) instead of a `<span>` per token. The `<code>` then holds one plain text node. For a 1,768-line JavaScript file, `<code>` holds 2 DOM nodes instead of 9,478 (3,164 of them `<span>`s).
77
+
78
+ Pass `theme` (theme CSS or a `ThemePalette`) to generate the `::highlight()` rules. `Highlight` resolves each token's color and background the way the browser would for the `"dom"` markup. Compound rules (`.hljs-title.function_`), descendant rules (`.hljs-meta .hljs-keyword`), and the fallback from `title.function_` to `.hljs-title` all apply, so colors match the `"dom"` engine. You still need `HighlightStyle` for the base `.hljs` rules. Without `theme`, the text stays plain.
79
+
80
+ **Bold and italic are dropped.** `::highlight()` can't change `font-weight` or `font-style`, so a theme's bold keywords and italic comments render at normal weight and style. Underlines are dropped too.
81
+
82
+ ```svelte
83
+ <script>
84
+ import Highlight, { HighlightStyle } from "svelte-highlight";
85
+ import typescript from "svelte-highlight/languages/typescript";
86
+ import github from "svelte-highlight/styles/github";
87
+ </script>
88
+
89
+ <HighlightStyle theme={github}>
90
+ <Highlight language={typescript} {code} engine="css-highlights" theme={github} />
91
+ </HighlightStyle>
92
+ ```
93
+
94
+ - The default stays `engine="dom"`.
95
+ - SSR always renders the `"dom"` markup. The swap to plain text happens after mount, so hydration is unchanged.
96
+ - Where `CSS.highlights` is unavailable, `Highlight` keeps the `"dom"` markup. Check which engine is on screen with `resolvedEngine()` on a `bind:this` reference. It returns `"dom"` until the first CSS paint, and after a failed resolver load.
97
+ - Each instance registers its own highlight names, so many instances can share a page.
98
+ - The color resolver loads on first paint, as a separate chunk. Pages that only use `"dom"` don't download it. The `"dom"` markup stays until the resolver is ready, so the code never shows uncolored.
99
+ - A custom default slot renders its own markup, so the engine has no effect there.
100
+
101
+ **Limits.** The colors come from `theme` alone, resolved in JavaScript:
102
+
103
+ - Your app's own `.hljs-*` rules and `--shl-*` overrides don't reach the highlights.
104
+ - `@media` blocks in the theme CSS (such as `prefers-color-scheme`) are skipped. To switch themes, change the `theme` prop.
105
+ - Theme rules with selectors the resolver can't match (`:hover`, attributes, ids, sibling combinators) are skipped.
106
+ - There are no per-token elements to query or attach handlers to.
107
+
64
108
  ## Theming
65
109
 
66
110
  Every `highlight.js` theme is also compiled into a **`ThemePalette`**: a typed object of `--shl-*` CSS custom properties plus a shared structural stylesheet (`svelte-highlight/themes/base.css`) that maps `.hljs*` classes to those variables. This is the recommended way to theme new projects — themes are data, scoping is an inline `style` attribute (SSR-safe by construction), and any token is overridable with one CSS line or a Svelte style prop. See [SUPPORTED_THEMES.md](SUPPORTED_THEMES.md) for a list of compiled themes.
@@ -147,7 +191,7 @@ const custom = {
147
191
  };
148
192
  ```
149
193
 
150
- **`HighlightEditable`'s `"css-highlights"` engine accepts palettes too:**
194
+ **The `"css-highlights"` engine of `Highlight` and `HighlightEditable` accepts palettes too:**
151
195
 
152
196
  ```svelte
153
197
  <HighlightEditable engine="css-highlights" theme={atomOneDark} language={typescript} bind:code />
@@ -501,6 +545,7 @@ These apply to the outer container of every component (the `pre` element for `Hi
501
545
  | --copy-size | Width and height of the button | `2em` |
502
546
  | --copy-padding | Inner padding of the button | `0.5em` |
503
547
  | --copy-background | Background color of the button | `inherit` |
548
+ | --copy-hover-background | Background color on hover inside `CodeToolbar` | text color at 12% |
504
549
  | --copy-color | Foreground color of the button | `inherit` |
505
550
  | --copy-border-radius | Border radius of the button | `4px` |
506
551
  | --copy-border | Border of the button | `none` |
@@ -534,6 +579,7 @@ These apply when `langtag` is set to `true`.
534
579
  | --titlebar-color | Text color of the title bar | `rgba(255, 255, 255, 0.6)` |
535
580
  | --titlebar-font-family| Font family of the title bar | `system-ui, -apple-system, sans-serif`|
536
581
  | --titlebar-font-size | Font size of the title bar | `0.8125em` |
582
+ | --titlebar-line-height| Line height of the title bar | `normal` |
537
583
  | --dot-gap | Gap between the macOS traffic-light dots | `0.5em` |
538
584
  | --dot-size | Diameter of the macOS traffic-light dots | `0.75em` |
539
585
  | --dot-close | Color of the "close" traffic-light dot | `#ff5f56` |
@@ -558,6 +604,42 @@ These apply when `langtag` is set to `true`.
558
604
  | --tab-active-background | Background color of the active tab | the highlighted code's background |
559
605
  | --tab-focus-outline | Keyboard focus outline of a tab | `2px solid currentColor` |
560
606
 
607
+ ### `CodeToolbar` variables
608
+
609
+ | Variable | Description | Default value |
610
+ | :-------------------- | :--------------------------------------------------- | :-------------------------------------------------- |
611
+ | --toolbar-background | Tint painted over the theme background | `color-mix(in srgb, currentColor 5%, transparent)` |
612
+ | --toolbar-color | Text color of the toolbar content | the theme's text color |
613
+ | --toolbar-border | Bottom border of the toolbar | `1px solid` text color at 14% |
614
+ | --toolbar-padding | Padding of the toolbar | `0.25em 0.375em 0.25em 1em` |
615
+ | --toolbar-gap | Gap between the title, badge and controls | `0.75em` |
616
+ | --toolbar-height | Minimum height of the toolbar | `2.75em` |
617
+ | --toolbar-font-family | Font family of the toolbar | `system-ui, -apple-system, "Segoe UI", Roboto, sans-serif` |
618
+ | --toolbar-font-size | Font size of the toolbar | `0.8125em` |
619
+ | --toolbar-z-index | Stacking order of a sticky toolbar | `3` |
620
+ | --langtag-background | Background color of the language badge | text color at 10% |
621
+ | --langtag-color | Text color of the language badge | text color at 72% |
622
+ | --langtag-padding | Padding of the language badge | `0.375em 0.625em` |
623
+ | --langtag-border-radius | Corner radius of the language badge | `999px` |
624
+ | --langtag-font-size | Font size of the language badge | `0.875em` |
625
+
626
+ ### `ToolbarButton` variables
627
+
628
+ `WrapToggle`, and `CopyButton` inside `CodeToolbar`, use these too.
629
+
630
+ | Variable | Description | Default value |
631
+ | :---------------------------------- | :---------------------------------------- | :----------------- |
632
+ | --toolbar-button-size | Width and height of the button | `2em` |
633
+ | --toolbar-button-gap | Gap between the button's content | `0.4em` |
634
+ | --toolbar-button-padding | Padding of the button | `0.3em` |
635
+ | --toolbar-button-background | Background color of the button | `transparent` |
636
+ | --toolbar-button-color | Icon and text color of the button | text color at 72% |
637
+ | --toolbar-button-hover-background | Background color on hover | text color at 12% |
638
+ | --toolbar-button-pressed-background | Background color when pressed or active | text color at 18% |
639
+ | --toolbar-button-border-radius | Corner radius of the button | `6px` |
640
+ | --toolbar-button-border | Border of the button | `none` |
641
+ | --toolbar-button-font-size | Font size of the button | `inherit` |
642
+
561
643
  ## Svelte Syntax Highlighting
562
644
 
563
645
  Use the `HighlightSvelte` component for Svelte syntax highlighting. Its grammar understands Svelte 5 runes (`$state`, `$derived`, `$effect` and its suffixed forms, `$props.id`, `$inspect.trace`), store auto-subscription (`$store`, `$store()`, `$store.prop`), `lang="ts"`/`context="module"` script-block resolution, and directive shorthand (`on:`, `bind:`, `use:`, and friends) — genuinely ahead of generic HTML-plus-embedded-JS Svelte highlighting, which has no notion that runes exist.
@@ -591,7 +673,7 @@ See the [kitchen-sink live demo](https://svhe.onrender.com/preview-svelte) for a
591
673
  The `HighlightAuto` component uses the [highlightAuto API](https://highlightjs.readthedocs.io/en/latest/api.html#highlightauto) and attempts to guess what grammar to use based on the provided `code`. Its `on:highlight` event's `secondBest` field surfaces the runner-up candidate and its relevance, for showing detection confidence.
592
674
 
593
675
  > [!WARNING]
594
- > Mounting `HighlightAuto` statically imports all 279 shipped grammars, regardless of `languageNames`, so bundle size is unconditionally larger than a `Highlight` with a single named language. Specify a language if possible.
676
+ > Mounting `HighlightAuto` statically imports all 279 shipped grammars, regardless of `languageNames`, so bundle size is unconditionally larger than a `Highlight` with a single named language. Specify a language if possible. If you can't, and plain text before hydration is fine, use [`HighlightAutoLazy`](#lazy-auto-highlighting) instead. It loads only a few likely grammars.
595
677
 
596
678
  ```svelte
597
679
  <script>
@@ -627,6 +709,55 @@ You can restrict [language auto-detection](https://highlightjs.readthedocs.io/en
627
709
  <HighlightAuto {code} languageNames={["javascript", "typescript"]} />
628
710
  ```
629
711
 
712
+ ### Lazy auto-highlighting
713
+
714
+ `HighlightAutoLazy` detects the language without importing every grammar. It works in two steps:
715
+
716
+ 1. It scores `code` against a small generated fingerprint index (about 33 KB gzip) and picks the 5 likeliest grammars. This step loads no grammar.
717
+ 2. It imports only those grammars, plus any grammars they embed. Then the same relevance engine as `HighlightAuto` picks the winner from them and from every grammar already registered.
718
+
719
+ Each grammar is its own chunk, so a page fetches only the grammars its code needs.
720
+
721
+ ```svelte
722
+ <script>
723
+ import { HighlightAutoLazy } from "svelte-highlight";
724
+ import github from "svelte-highlight/styles/github";
725
+
726
+ const code = `@media (max-width: 600px) {\n body { padding: 0; }\n}`;
727
+ </script>
728
+
729
+ <svelte:head>
730
+ {@html github}
731
+ </svelte:head>
732
+
733
+ <HighlightAutoLazy {code} />
734
+ ```
735
+
736
+ It has the same props, slot props, and `on:highlight` detail as `HighlightAuto`, with these differences:
737
+
738
+ - **Plain text first.** On the server and on the first client render, it shows `code` as escaped plain text with no language. It highlights after mount, once the grammars load. If they are already registered, that happens at once.
739
+ - **`on:highlight` fires for results only.** It does not fire for the plain-text placeholder.
740
+ - **Latest `code` wins.** If `code` changes while grammars still load, the older result is dropped.
741
+ - **`languageNames` skips the fingerprint step.** It loads each named grammar on demand and detects among those only.
742
+ - **Different picks.** It picks from fewer grammars, so its answer can differ from `HighlightAuto`'s. On this repo's detection corpus it is right more often, but the fingerprint step misses some grammars with few keywords. To make sure a grammar competes, register it first (for example with `loadLanguage` and `registerAll`), or pass `languageNames`.
743
+
744
+ The two steps are also available without the component, from `svelte-highlight/auto-detect`:
745
+
746
+ ```js
747
+ import {
748
+ detectCandidates,
749
+ highlightAutoLazy,
750
+ } from "svelte-highlight/auto-detect";
751
+
752
+ detectCandidates(code); // ["stylus", "less", "css", "scss", "ada"]
753
+
754
+ const result = await highlightAutoLazy(code);
755
+ result.language; // "css"
756
+ result.value; // highlighted HTML
757
+ ```
758
+
759
+ Both accept an options object: `k` (number of candidates, default 5), `languageNames`, and `registry` (defaults to the shared registry). `highlightAutoIfLoaded(code, options)` does the same work synchronously and returns `undefined` if a grammar it needs is not registered yet.
760
+
630
761
  ## Line Numbers
631
762
 
632
763
  Use the `LineNumbers` component to render the highlighted code with line numbers.
@@ -917,6 +1048,12 @@ Use `--copy-*` style props to customize the button.
917
1048
  />
918
1049
  ```
919
1050
 
1051
+ Set `absolute={false}` to lay the button out in normal document flow instead of overlaying its container. Inside `CodeToolbar`, this is the default.
1052
+
1053
+ ```svelte
1054
+ <CopyButton {code} absolute={false} />
1055
+ ```
1056
+
920
1057
  ### With Line Numbers
921
1058
 
922
1059
  Compose `CopyButton` with `LineNumbers` by wrapping both in a relatively-positioned container.
@@ -1045,9 +1182,9 @@ Set `readonly` to keep highlighting, caret placement, and selection active while
1045
1182
 
1046
1183
  `engine="css-highlights"` paints tokens with the [CSS Custom Highlight API](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API) (`CSS.highlights`, `::highlight()`) instead of wrapping them in `<span>`s. The editable `<code>` stays plain text (one `<span>` per line, reused from the default engine's line structure, but with no per-token spans inside), so a repaint never replaces the DOM the caret is sitting in.
1047
1184
 
1048
- Requires Chrome 105+, Safari 17.2+, or Firefox 140+. Where `CSS.highlights` is unavailable, `HighlightEditable` falls back to `engine="dom"` silently; check what actually ran with `editor.resolvedEngine()`.
1185
+ Requires Chrome 105+, Safari 17.2+, or Firefox 140+. Where `CSS.highlights` is unavailable, `HighlightEditable` falls back to `engine="dom"` silently; check what is on screen with `editor.resolvedEngine()`. It returns `"dom"` until the first CSS paint, and while the resolver load has failed.
1049
1186
 
1050
- Pass `theme` (the same theme string you'd give `HighlightStyle`) to generate `::highlight()` rules from it. Only `color`/`background-color` convert, and only for single-class `.hljs-<scope>` rules — compound (`.hljs-title.class_`) and descendant-selector (`.hljs-meta .hljs-keyword`) scopes have no `::highlight()` equivalent and get **no color at all**, not just plain weight/style.
1187
+ Pass `theme` (theme CSS or a `ThemePalette`) to color the tokens. `HighlightEditable` resolves colors the same way `Highlight` does, so compound rules (`.hljs-title.function_`) and descendant rules (`.hljs-meta .hljs-keyword`) apply. Only colors and backgrounds carry over, and the same [limits](#experimental-css-custom-highlight-engine) apply. Each edit re-resolves only the lines it changed. As with `Highlight`, the resolver loads on the first paint, so `"dom"`-only pages don't bundle it. Until it loads, the editor shows `"dom"` spans.
1051
1188
 
1052
1189
  `theme` only covers token colors — you still need `HighlightStyle` (or an injected stylesheet) for the base `.hljs` layout rules (padding, overflow, background), exactly as with the default engine.
1053
1190
 
@@ -1065,6 +1202,28 @@ Pass `theme` (the same theme string you'd give `HighlightStyle`) to generate `::
1065
1202
  </HighlightStyle>
1066
1203
  ```
1067
1204
 
1205
+ ### Without Svelte
1206
+
1207
+ `createEditor` from `svelte-highlight/editable` runs the same editor on any element, with no framework. Use a `<code contenteditable>` inside a `<pre>`. It takes the same settings as the component and has the same methods, plus `update`, `syncCode` and `destroy`.
1208
+
1209
+ ```js
1210
+ import { createEditor } from "svelte-highlight/editable";
1211
+ import typescript from "svelte-highlight/languages/typescript";
1212
+
1213
+ const editor = createEditor(document.querySelector("pre code"), {
1214
+ language: typescript,
1215
+ code: "const add = (a, b) => a + b;",
1216
+ onChange: (code) => console.log(code),
1217
+ });
1218
+
1219
+ editor.update({ readonly: true });
1220
+ editor.destroy();
1221
+ ```
1222
+
1223
+ For the `"css-highlights"` engine, pass `theme` to `createEditor` or `update`. The editor adds its `::highlight()` rules to the page and removes them on `destroy`.
1224
+
1225
+ `instanceHighlightStyle(theme, editor.instanceId)` still works for an editor made without `theme`. Add its `<style>` tag to the page's `<head>`. It only converts single-class `.hljs-<scope>` rules, so compound scopes such as `title.function_` get no color.
1226
+
1068
1227
  ### Adding a gutter
1069
1228
 
1070
1229
  `HighlightEditable` has no slot and doesn't expose `highlighted`/`languageName`, so it can't be wrapped directly in `LineNumbers` the way a static `Highlight` block can. Mirror the same `code` in a second, read-only `Highlight` instance wrapped in `LineNumbers`, and position it alongside the editable block:
@@ -1364,7 +1523,7 @@ export default {
1364
1523
  At build time this becomes plain HTML:
1365
1524
 
1366
1525
  ```html
1367
- <pre class="hljs" data-language="javascript"><code class="hljs"
1526
+ <pre class="hljs" data-language="javascript"><code class="hljs" tabindex="0" role="region" aria-label="Code"
1368
1527
  ><span class="hljs-keyword">const</span> x = <span class="hljs-number">1</span>;</code
1369
1528
  ></pre>
1370
1529
  ```
@@ -1375,6 +1534,7 @@ The static transform runs only when all of these are true:
1375
1534
  - `code` is a string literal or a template literal with no `${...}` interpolation.
1376
1535
  - The element has no slot content, spread props, or directives (`bind:`, `on:`, etc.).
1377
1536
  - `langtag`, if set, is a bare flag or a static boolean literal (`langtag={true}`/`langtag={false}`) - not a variable or expression. Static output can't pull in `langtag.css` (that only happens when a runtime `LangTag` is in the bundle), so a truthy `langtag` renders the language badge as a plain inline-styled `<span>` instead, themed with the same `--langtag-*` custom properties `LangTag` reads - customization is limited to those variables, not `LangTag`'s slot content.
1537
+ - `label`, if set, is a string literal. Static output can't read a parent `CodeWindow`, so it uses `label` or `"Code"`.
1378
1538
 
1379
1539
  Dynamic `code` or `language`, `loadLanguage`, `HighlightAuto`, `HighlightSvelte`, and `HighlightEditable` keep the runtime component. No warning. That's intentional.
1380
1540
 
@@ -1703,6 +1863,100 @@ Put a `FileTabs` strip in the `titlebar` slot to switch between files without le
1703
1863
  </CodeWindow>
1704
1864
  ```
1705
1865
 
1866
+ ## Code Toolbar
1867
+
1868
+ `CodeToolbar` adds a bar above the code with a file name, a language badge and buttons. Put it first in `Highlight`'s default slot.
1869
+
1870
+ ```svelte
1871
+ <script>
1872
+ import Highlight, {
1873
+ CodeToolbar,
1874
+ CopyButton,
1875
+ LineNumbers,
1876
+ WrapToggle,
1877
+ } from "svelte-highlight";
1878
+ import typescript from "svelte-highlight/languages/typescript";
1879
+ import github from "svelte-highlight/styles/github";
1880
+
1881
+ export let code;
1882
+
1883
+ let wrap = false;
1884
+ </script>
1885
+
1886
+ <svelte:head>
1887
+ {@html github}
1888
+ </svelte:head>
1889
+
1890
+ <div class="code-block">
1891
+ <Highlight {code} language={typescript} {wrap} let:highlighted let:languageName>
1892
+ <CodeToolbar {languageName} title="app.ts" label="app.ts actions">
1893
+ <WrapToggle bind:wrap />
1894
+ <CopyButton {code} />
1895
+ </CodeToolbar>
1896
+ <LineNumbers {highlighted} wrapLines={wrap} style="max-height: 24rem" />
1897
+ </Highlight>
1898
+ </div>
1899
+
1900
+ <style>
1901
+ .code-block {
1902
+ border-radius: 8px;
1903
+ overflow: clip;
1904
+ }
1905
+ </style>
1906
+ ```
1907
+
1908
+ - **Theme colors:** the toolbar has the `hljs` class, so it takes its background and text color from your theme. A faint tint and a divider set it apart from the code. With no theme, it uses the system `Canvas` colors.
1909
+ - **Scoped themes:** if you scope a theme to a class, put that class on an element that wraps the toolbar, such as `.code-block` above. A global theme works as is.
1910
+ - **Scrolling:** put the `max-height` on `LineNumbers`, not on a wrapper. Then only the code scrolls, and the scrollbar starts below the toolbar. `overflow: clip` on the wrapper rounds the corners without making it scroll.
1911
+ - **Sticky:** if a wrapper or the page scrolls instead, the toolbar sticks to its top while the block is on screen. Set `sticky={false}` to turn it off.
1912
+ - **Buttons:** inside `CodeToolbar`, `CopyButton` sits in the bar, and `WrapToggle` and `CopyButton` share one icon-button style.
1913
+ - **Accessibility:** the root is a `role="toolbar"` element. Set `label` to give it a name. The buttons are ordinary tab stops, as in the lightweight [WAI-ARIA toolbar pattern](https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/).
1914
+
1915
+ ### Custom actions
1916
+
1917
+ Use `ToolbarButton` for your own actions. It matches the built-in buttons. Give it a `label` for the tooltip and screen readers, and an icon in its slot. Set `href` for a link, or `pressed` for a toggle.
1918
+
1919
+ ```svelte
1920
+ <script>
1921
+ import { ToolbarButton } from "svelte-highlight";
1922
+
1923
+ function download() {
1924
+ const url = URL.createObjectURL(new Blob([code], { type: "text/plain" }));
1925
+ Object.assign(document.createElement("a"), { href: url, download: "app.ts" }).click();
1926
+ URL.revokeObjectURL(url);
1927
+ }
1928
+ </script>
1929
+
1930
+ <CodeToolbar {languageName} title="app.ts">
1931
+ <ToolbarButton label="Download" on:click={download}>
1932
+ <svg aria-hidden="true"><!-- icon --></svg>
1933
+ </ToolbarButton>
1934
+ <ToolbarButton label="Open in playground" href={playgroundUrl} target="_blank" rel="noopener">
1935
+ <svg aria-hidden="true"><!-- icon --></svg>
1936
+ </ToolbarButton>
1937
+ <WrapToggle bind:wrap />
1938
+ <CopyButton {code} />
1939
+ </CodeToolbar>
1940
+ ```
1941
+
1942
+ Use the `start` slot for content after the badge, such as a status or a branch name.
1943
+
1944
+ ### Composing with CodeWindow
1945
+
1946
+ In a `CodeWindow`, the window title already names the file. Leave out the toolbar's `title`, so the name doesn't show twice:
1947
+
1948
+ ```svelte
1949
+ <CodeWindow variant="macos" title="app.ts">
1950
+ <Highlight {code} language={typescript} {wrap} let:highlighted let:languageName>
1951
+ <CodeToolbar {languageName}>
1952
+ <WrapToggle bind:wrap />
1953
+ <CopyButton {code} />
1954
+ </CodeToolbar>
1955
+ <LineNumbers {highlighted} wrapLines={wrap} />
1956
+ </Highlight>
1957
+ </CodeWindow>
1958
+ ```
1959
+
1706
1960
  ## Animation
1707
1961
 
1708
1962
  Use `Typewriter` inside `Highlight`'s default slot with the `highlighted` prop. It prints the code one character at a time, syntax highlighting included. A blinking caret marks the end of the typed text and hides when typing stops.
@@ -1777,7 +2031,9 @@ Fire `on:progress` for a progress bar or "X% typed" indicator -- it dispatches `
1777
2031
  </Highlight>
1778
2032
  ```
1779
2033
 
1780
- `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`.
2034
+ `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`). The caret stops blinking under `prefers-reduced-motion: reduce`. Customize the caret with `--caret-width`, `--caret-height`, `--caret-gap`, `--caret-color`, and `--caret-blink`.
2035
+
2036
+ Screen readers get the full text at once from a visually-hidden copy. The animated layer is `aria-hidden`, so they don't read a half-typed block.
1781
2037
 
1782
2038
 
1783
2039
  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.
@@ -1836,6 +2092,32 @@ Per-chunk work is O(tail), not O(stream length so far): finished output is seale
1836
2092
 
1837
2093
  `virtualize` renders only the lines within the scrolled viewport (plus `overscan`), the same windowing `HighlightVirtual` does for static documents -- a stream that runs to tens of thousands of lines still costs a couple dozen DOM nodes. It swaps the sealed-chunk session for `TokenizedDocument` (see [Large documents](#large-documents) below), so output always reflects the streaming (non-canonicalized) parse, even once `done` -- unlike the default mode, which upgrades to a canonical final render. `on:highlight` isn't dispatched in this mode, since materializing the full HTML on every repaint would defeat the point of windowing; `on:done`, the caret, and `autoScroll` all keep working. `on:windowchange` fires with `{ start, end, lineCount }` whenever the rendered window moves, so you can show something like "lines *N*-*M* of *T*" without counting DOM nodes yourself. Row math assumes one line per fixed-height row, so `virtualize` can't wrap lines -- it always renders with `white-space: pre`, overriding any `white-space` you pass through `$$restProps`. `bind:this`, then call `scrollToLine(line)` to scroll a given line into view -- works in both `virtualize` and default modes.
1838
2094
 
2095
+ ### Streaming without Svelte
2096
+
2097
+ `createStreamView` from `svelte-highlight/stream` runs the same rendering on any element, with no framework. Use a `<code>` inside a `<pre>`, and import `svelte-highlight/stream.css` for the caret. It takes the same settings as the component, minus `virtualize`, and renders the first frame at once.
2098
+
2099
+ ```js
2100
+ import "svelte-highlight/stream.css";
2101
+ import { createStreamView } from "svelte-highlight/stream";
2102
+ import typescript from "svelte-highlight/languages/typescript";
2103
+
2104
+ const view = createStreamView(document.querySelector("pre code"), {
2105
+ language: typescript,
2106
+ autoScroll: true,
2107
+ onDone: () => console.log(view.highlighted),
2108
+ });
2109
+
2110
+ let code = "";
2111
+ for await (const chunk of response) {
2112
+ code += chunk;
2113
+ view.update({ code });
2114
+ }
2115
+ view.update({ done: true });
2116
+ view.destroy();
2117
+ ```
2118
+
2119
+ `aria-busy` and the "finished" announcement are up to you here. Set `aria-busy` on the `<pre>` while streaming, and clear it in `onDone`.
2120
+
1839
2121
  ### Streaming Markdown with multiple fences
1840
2122
 
1841
2123
  `HighlightStream` highlights a single growing code buffer, but LLM chat output is Markdown: prose interleaved with several fenced code blocks, each in its own language. `svelte-highlight/fence`'s `createFenceSplitter` (see "[Rendering Markdown/MDX fences](#rendering-markdownmdx-fences)" above) turns that growing Markdown string into prose and fence segments, so you can drive one `HighlightStream` per fence as it streams in:
@@ -2099,6 +2381,222 @@ Browser Cmd+F can't see rows a virtualized view (`HighlightVirtual`, `HighlightS
2099
2381
 
2100
2382
  `highlightMatches(root, matches, { current, name })` paints `matches` into `root`, restricted to whatever rows are currently rendered there -- resolved per match's line via `[data-line]` (the row shape `HighlightVirtual`/`HighlightStream` render), then the `line`-th `.line` element (the shape `highlightFence`/fenced code renders), then the whole `<code>` split on `"\n"`; matches whose line resolves to nothing are skipped. It uses the CSS Custom Highlight API when available (two `Highlight`s: `name`, defaulting to `"shl-search"`, and `${name}-current` for the match at index `current`), or falls back to wrapping text in `<mark data-shl-search>` (plus `data-shl-search-current`) when it isn't. It paints once per call and returns `{ dispose() }` -- there's no diffing against a previous call, so a consumer disposes and re-runs it after the rendered window changes (`on:windowchange`) or the query changes (`onChange`), as in the example above. It's a no-op on the server. `import "svelte-highlight/search.css"` is optional and styles both highlight names via the `--search-match-background`/`--search-current-background` CSS variables; passing a custom `name` bypasses it, since the stylesheet only targets the default names.
2101
2383
 
2384
+ ## Diffs
2385
+
2386
+ `HighlightDiff` shows a syntax-highlighted diff of two texts. It highlights each side as a whole file, not hunk by hunk. So a string or comment that opens far above a change still highlights correctly inside it.
2387
+
2388
+ ```svelte
2389
+ <script>
2390
+ import { HighlightDiff } from "svelte-highlight";
2391
+ import typescript from "svelte-highlight/languages/typescript";
2392
+ import atomOneDark from "svelte-highlight/styles/atom-one-dark";
2393
+
2394
+ export let before;
2395
+ export let after;
2396
+ </script>
2397
+
2398
+ <svelte:head>
2399
+ {@html atomOneDark}
2400
+ </svelte:head>
2401
+
2402
+ <HighlightDiff {before} {after} language={typescript} style="height: 480px" />
2403
+ ```
2404
+
2405
+ Try every feature on the [diff preview page](https://svhe.onrender.com/preview-diff).
2406
+
2407
+ ### Views, folds, and word diffs
2408
+
2409
+ - `view` is `"unified"` (default) or `"split"`. It supports `bind:view`; the `v` key toggles it.
2410
+ - `context` (default `3`) sets how many unchanged lines stay around each change. Longer unchanged runs fold into a row you can click to expand.
2411
+ - `wordDiff` (default `true`) marks the changed words inside paired lines.
2412
+ - `ignoreWhitespace` treats lines that differ only in whitespace as unchanged.
2413
+ - `detectMoves` (default `true`) shows a block removed in one place and added in another as a move. Moved lines are purple, and their title says where they came from or went.
2414
+ - `wrap` wraps long lines. Without it, each side scrolls sideways on its own.
2415
+ - A minimap beside the scrollbar marks every change. Click it to jump. Turn it off with `minimap={false}`.
2416
+ - `palette="colorblind"` uses blue and orange instead of green and red.
2417
+
2418
+ The diff takes focus on click. Then `n`/`p` move to the next or previous change, `e`/`c` expand or collapse every fold, and `v` toggles the view.
2419
+
2420
+ Copying across rows gives one file's text, not both. In split view, it's the side where the selection started. In unified view, it's the new text, or the old text if you select only removed lines.
2421
+
2422
+ ### Virtualization
2423
+
2424
+ `virtualize` defaults to `"auto"`. Diffs up to 500 rows render every row, so browser find (Ctrl/Cmd+F), printing, and server rendering see the whole diff. Larger diffs render only the rows in view. `virtualize={true}` or `virtualize={false}` forces either mode. Rows can have different heights (wrapped lines, notes), and are measured as they render.
2425
+
2426
+ ### Streaming
2427
+
2428
+ Set `streaming` while `after` is still growing, for example while a model writes a new version of a file:
2429
+
2430
+ ```svelte
2431
+ <HighlightDiff {before} {after} streaming={!done} language={typescript} />
2432
+ ```
2433
+
2434
+ While streaming:
2435
+
2436
+ - The part of `before` that `after` hasn't reached yet shows as "not reached yet", not as deleted.
2437
+ - Rows behind the last unchanged run of 3 or more lines freeze. Later chunks don't move them, and each chunk only re-diffs what comes after them.
2438
+ - `follow` (default `true`) keeps the newest row in view until the reader scrolls away.
2439
+
2440
+ When `streaming` turns off, the diff finishes from the frozen rows. It doesn't start over, so nothing the reader saw reshuffles.
2441
+
2442
+ ### LLM edit formats
2443
+
2444
+ `parseEdits` reads the edit formats models write, and `applyEdits` applies them to a file:
2445
+
2446
+ ```js
2447
+ import { applyEdits, parseEdits } from "svelte-highlight/diff-edits";
2448
+
2449
+ const { format, edits } = parseEdits(modelOutput);
2450
+ const { text, results } = applyEdits(source, edits);
2451
+ // <HighlightDiff before={source} after={text} ... />
2452
+ ```
2453
+
2454
+ It reads:
2455
+
2456
+ - SEARCH/REPLACE blocks (`<<<<<<< SEARCH` … `=======` … `>>>>>>> REPLACE`), with an optional file path line before them.
2457
+ - Unified diffs. Line numbers are ignored, since models often get them wrong.
2458
+ - `str_replace` tool calls and `edits` arrays as JSON (`old_str`/`new_str` or `old_string`/`new_string`).
2459
+ - `apply_patch` envelopes (`*** Begin Patch`).
2460
+ - A single fenced code block, as a whole-file replacement.
2461
+
2462
+ `applyEdits` finds each edit's search text exactly first. Then it ignores trailing whitespace, then indentation (and re-indents the replacement to match the file), then it falls back to fuzzy line similarity. Each result reports `status`, `strategy`, `score`, and the matched lines. An edit that can't be found, or that overlaps an earlier edit, is skipped and reported as failed.
2463
+
2464
+ To show edits while the model is still writing them, use `streamEditPrefix`. It returns the part of the edited file that's settled so far, which only grows:
2465
+
2466
+ ```js
2467
+ import { streamEditPrefix } from "svelte-highlight/diff-edits";
2468
+
2469
+ const preview = streamEditPrefix(source, partialOutput, { done });
2470
+ // <HighlightDiff before={source} after={preview.after} streaming={!preview.done} ... />
2471
+ ```
2472
+
2473
+ ### Review
2474
+
2475
+ With `review`, each change gets Accept and Reject buttons. With the diff focused, `a`, `r`, and `u` accept, reject, or undo the current change. `on:review` fires on every decision with `{ decisions, text }`. `text` is `after` with the rejected changes reverted.
2476
+
2477
+ ```svelte
2478
+ <HighlightDiff
2479
+ bind:this={diff}
2480
+ {before}
2481
+ {after}
2482
+ language={typescript}
2483
+ review
2484
+ on:review={(e) => (result = e.detail.text)}
2485
+ />
2486
+ ```
2487
+
2488
+ `bind:this` gives you `decideAll("accepted" | "rejected")`, `getResult()`, and `getPatch({ oldPath, newPath })`. The patch is a unified diff that `git apply` accepts.
2489
+
2490
+ ### Git patches
2491
+
2492
+ To show a patch without its source files, parse it and pass one file at a time:
2493
+
2494
+ ```js
2495
+ import { parsePatch } from "svelte-highlight/diff-edits";
2496
+
2497
+ const files = parsePatch(gitDiffOutput);
2498
+ // <HighlightDiff patch={files[0]} language={...} />
2499
+ ```
2500
+
2501
+ `parsePatch` reads multi-file git output, including added, deleted, renamed, and binary files. Lines between hunks are unknown, so they show as folds that can't expand, with the hunk header. Line numbers stay real. Since only the hunks are known, highlighting can be less accurate than with full files.
2502
+
2503
+ ### Annotations
2504
+
2505
+ `annotations` puts notes below lines: `[{ side: "new", line: 12, body: "…", author, tone }]`. `side` is `"old"` or `"new"`, `line` is 1-based, and `tone` is `"info"`, `"warning"`, `"error"`, or `"suggestion"`. A note's row grows to fit it.
2506
+
2507
+ ### Building your own diff UI
2508
+
2509
+ `HighlightDiff` combines smaller parts that you can use on their own. They share one controller:
2510
+
2511
+ ```svelte
2512
+ <script>
2513
+ import {
2514
+ createDiffController,
2515
+ DiffMinimap,
2516
+ DiffStats,
2517
+ DiffView,
2518
+ } from "svelte-highlight";
2519
+ import typescript from "svelte-highlight/languages/typescript";
2520
+
2521
+ const diff = createDiffController({ language: typescript, view: "split" });
2522
+ $: diff.update(before, after);
2523
+ </script>
2524
+
2525
+ <DiffStats {diff} />
2526
+ <button on:click={() => diff.nextChange()}>Next change</button>
2527
+
2528
+ <div style="display: flex; height: 480px">
2529
+ <DiffView {diff} style="flex: 1">
2530
+ <div slot="note" let:note>{note.author}: {note.body}</div>
2531
+ <button slot="actions" let:change on:click={() => comment(change)}>Comment</button>
2532
+ </DiffView>
2533
+ <DiffMinimap {diff} />
2534
+ </div>
2535
+ ```
2536
+
2537
+ - `createDiffController(options)` holds the diff state: the diff, highlighting, folds, review decisions, and navigation. Use it as a Svelte store (`$diff`), or call it from anywhere. `update(before, after, { streaming })` and `setPatch(file)` set the input. `setOptions({ view, context, … })` changes options. `on("navigate" | "review" | …, listener)` subscribes to events.
2538
+ - `DiffView` renders the rows. Its slots replace fold rows (`fold`), note cards (`note`), and the controls on each change (`actions`).
2539
+ - `DiffMinimap` shows the change marks and the area a `DiffView` on the same controller shows. Click it to scroll there.
2540
+ - `DiffStats` shows the counts and, after you navigate, "change *N* of *M*".
2541
+
2542
+ Every part on a controller stays in sync. For example, a toolbar button that calls `diff.nextChange()` scrolls each `DiffView`.
2543
+
2544
+ ### Many files
2545
+
2546
+ `DiffFileList` shows a page of per-file diffs, like a large pull request. It mounts files near the viewport and unmounts far ones, and keeps each file's measured height so the page doesn't jump. A page of 827 files stays near 10,000 DOM nodes.
2547
+
2548
+ ```svelte
2549
+ <script>
2550
+ import { DiffFileList, parsePatch } from "svelte-highlight";
2551
+
2552
+ $: files = parsePatch(gitDiffOutput).map((file) => ({
2553
+ path: file.newPath,
2554
+ oldPath: file.oldPath,
2555
+ status: file.status,
2556
+ patch: file,
2557
+ }));
2558
+ </script>
2559
+
2560
+ <DiffFileList {files} />
2561
+ ```
2562
+
2563
+ - Each file is a parsed `patch` or a `before`/`after` pair.
2564
+ - It loads each file's language by extension the first time the file mounts. Pass `languageFor(path)` to choose another way, or set `language` on a file.
2565
+ - `windowing` is `"windowed"` (default), `"lazy"` (mount near the view, never unmount), or `"none"` (mount everything, for printing or browser find).
2566
+ - `maxHeight` (default `640`) caps each file's height before it scrolls on its own. `null` shows every file in full.
2567
+ - Click a header to collapse its file. Replace the header with the `header` slot.
2568
+ - `bind:this`, then `scrollToFile(index)` jumps to a file. The files around it mount first, so they have real heights before you scroll to them.
2569
+ - Set `root` if the list scrolls inside an element instead of the page.
2570
+
2571
+ When files above the view change height, the list keeps the first file in view still. It does this itself, since browsers' scroll anchoring doesn't catch these changes everywhere.
2572
+
2573
+ ### Headless diffs
2574
+
2575
+ `svelte-highlight/diff` has the diff itself, with no DOM:
2576
+
2577
+ ```js
2578
+ import { buildRows, diffTexts, toUnifiedPatch, wordDiff } from "svelte-highlight/diff";
2579
+
2580
+ const state = diffTexts(before, after, { ignoreWhitespace: false });
2581
+ state.blocks; // [{ type: "equal" | "change", a, aEnd, b, bEnd, id }]
2582
+ const rows = buildRows(state, { view: "split", context: 3 });
2583
+ const patch = toUnifiedPatch(state, { oldPath: "a/file.ts", newPath: "b/file.ts" });
2584
+ const { old, new: added } = wordDiff("const a = 1;", "const a = 2;");
2585
+ ```
2586
+
2587
+ - `diffTexts` and `diffLines` find shared prefixes and suffixes, then anchor on lines unique to both sides, then run Myers' algorithm between anchors.
2588
+ - `createDiffSession()` keeps state between calls, for streaming: `session.update(before, after, { streaming: true })`.
2589
+ - `applyReview(state, decisions)`, `detectMoves(state)`, and `diffStats(state)` work on the same state.
2590
+
2591
+ `svelte-highlight/diff-controller` exports `createDiffController`, and `svelte-highlight/diff-edits` exports the edit and patch parsers.
2592
+
2593
+ ### Limits
2594
+
2595
+ - With `ignoreWhitespace`, unchanged lines show their `after` text, and `toUnifiedPatch` writes `before`'s text for them. The patch then doesn't reproduce `after`'s whitespace.
2596
+ - A region with more than 2,000 edits shows as one replacement, to bound the work.
2597
+ - Moved blocks aren't detected while streaming.
2598
+ - `DiffView` only virtualizes inside its own scroll container. For a page of many diffs, use `DiffFileList`.
2599
+
2102
2600
  ## Terminal Output
2103
2601
 
2104
2602
  Use `AnsiOutput` to render terminal output that still contains ANSI [SGR](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters) escape codes. Colors, bold, dim, italic, and underline become styled HTML (including the colon sub-parameter forms modern tools emit, like `4:3` and `38:5:196`), along with OSC 8 hyperlinks, carriage-return overwrites, and reverse/strikethrough. The parser is separate from highlight.js, so reach for it with build logs, CLI output, and test runners.
@@ -2244,8 +2742,9 @@ The active tab's `--tab-active-color` and `--tab-active-background` are resolved
2244
2742
  | language | { name: `string`; register: `object` } | N/A (required) |
2245
2743
  | langtag | `boolean` | `false` |
2246
2744
  | wrap | `boolean` | `false` |
2745
+ | label | `string` | `"Code"` |
2247
2746
 
2248
- `$$restProps` are forwarded to the top-level `pre` element.
2747
+ `$$restProps` are forwarded to the top-level `pre` element. `label` names the focusable code region (see [Accessibility](#accessibility)).
2249
2748
 
2250
2749
  #### Dispatched Events
2251
2750
 
@@ -2303,8 +2802,9 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2303
2802
  | lineStates | `Record<number, "highlighted" \| "focus" \| "added" \| "removed">` | `{}` |
2304
2803
  | langtag | `boolean` | `false` |
2305
2804
  | languageName | `string` | `"plaintext"` |
2805
+ | label | `string` | `"Code with line numbers"` |
2306
2806
 
2307
- `$$restProps` are forwarded to the top-level `div` element.
2807
+ `$$restProps` are forwarded to the top-level `div` element. `label` names the focusable code region.
2308
2808
 
2309
2809
  ### `CopyButton`
2310
2810
 
@@ -2318,8 +2818,14 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2318
2818
  | timeout | `number` | `2000` |
2319
2819
  | text | `string` | `"Copy"` |
2320
2820
  | copiedText | `string` | `"Copied!"` |
2821
+ | errorText | `string` | `"Copy failed"` |
2822
+ | absolute | `boolean` | `true` (`false` inside `CodeToolbar`) |
2321
2823
 
2322
- `$$restProps` are forwarded to the top-level `button` element.
2824
+ `$$restProps` are forwarded to the top-level `button` element. A visually-hidden `role="status"` region after the button announces `copiedText` on success and `errorText` on failure.
2825
+
2826
+ ```svelte
2827
+ <CopyButton {code} copiedText="Copied to clipboard" errorText="Could not copy" />
2828
+ ```
2323
2829
 
2324
2830
  #### CSS Variables
2325
2831
 
@@ -2330,6 +2836,7 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2330
2836
  | --copy-size | Width and height of the button | `2em` |
2331
2837
  | --copy-padding | Inner padding of the button | `0.5em` |
2332
2838
  | --copy-background | Background color of the button | `inherit` |
2839
+ | --copy-hover-background | Background color on hover inside `CodeToolbar` | text color at 12% |
2333
2840
  | --copy-color | Foreground color of the button | `inherit` |
2334
2841
  | --copy-border-radius | Border radius of the button | `4px` |
2335
2842
  | --copy-border | Border of the button | `none` |
@@ -2358,8 +2865,15 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2358
2865
  | :------ | :--------------------------------- | :------------ |
2359
2866
  | variant | `"macos" \| "terminal" \| "plain"` | `"macos"` |
2360
2867
  | title | `string` | `""` |
2868
+ | label | `string` | `undefined` |
2361
2869
 
2362
- `$$restProps` are forwarded to the top-level `div` element.
2870
+ `$$restProps` are forwarded to the top-level `div` element. The code block inside the window takes `title`, or `label` when there is no title, as its region name.
2871
+
2872
+ ```svelte
2873
+ <CodeWindow variant="terminal" label="Install output">
2874
+ <AnsiOutput text={output} />
2875
+ </CodeWindow>
2876
+ ```
2363
2877
 
2364
2878
  #### Slots
2365
2879
 
@@ -2379,6 +2893,7 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2379
2893
  | --titlebar-color | Text color of the title bar | `rgba(255, 255, 255, 0.6)` |
2380
2894
  | --titlebar-font-family| Font family of the title bar | `system-ui, -apple-system, sans-serif`|
2381
2895
  | --titlebar-font-size | Font size of the title bar | `0.8125em` |
2896
+ | --titlebar-line-height| Line height of the title bar | `normal` |
2382
2897
  | --dot-gap | Gap between the macOS traffic-light dots | `0.5em` |
2383
2898
  | --dot-size | Diameter of the macOS traffic-light dots | `0.75em` |
2384
2899
  | --dot-close | Color of the "close" traffic-light dot | `#ff5f56` |
@@ -2388,6 +2903,86 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2388
2903
  | --prompt-font-weight | Font weight of the terminal prompt | `700` |
2389
2904
  | --prompt-color | Color of the terminal prompt | `inherit` |
2390
2905
 
2906
+ ### `CodeToolbar`
2907
+
2908
+ #### Props
2909
+
2910
+ | Name | Type | Default value |
2911
+ | :----------- | :-------- | :------------ |
2912
+ | languageName | `string` | `undefined` |
2913
+ | title | `string` | `""` |
2914
+ | sticky | `boolean` | `true` |
2915
+ | label | `string` | `undefined` |
2916
+
2917
+ `$$restProps` are forwarded to the top-level `div` element.
2918
+
2919
+ #### Slots
2920
+
2921
+ - **start**: rendered next to the language badge/title
2922
+ - default: rendered in the trailing/"end" region
2923
+
2924
+ #### CSS Variables
2925
+
2926
+ | Variable | Description | Default value |
2927
+ | :-------------------- | :--------------------------------------------------- | :-------------------------------------------------- |
2928
+ | --toolbar-background | Tint painted over the theme background | `color-mix(in srgb, currentColor 5%, transparent)` |
2929
+ | --toolbar-color | Text color of the toolbar content | the theme's text color |
2930
+ | --toolbar-border | Bottom border of the toolbar | `1px solid` text color at 14% |
2931
+ | --toolbar-padding | Padding of the toolbar | `0.25em 0.375em 0.25em 1em` |
2932
+ | --toolbar-gap | Gap between the title, badge and controls | `0.75em` |
2933
+ | --toolbar-height | Minimum height of the toolbar | `2.75em` |
2934
+ | --toolbar-font-family | Font family of the toolbar | `system-ui, -apple-system, "Segoe UI", Roboto, sans-serif` |
2935
+ | --toolbar-font-size | Font size of the toolbar | `0.8125em` |
2936
+ | --toolbar-z-index | Stacking order of a sticky toolbar | `3` |
2937
+ | --langtag-background | Background color of the language badge | text color at 10% |
2938
+ | --langtag-color | Text color of the language badge | text color at 72% |
2939
+ | --langtag-padding | Padding of the language badge | `0.375em 0.625em` |
2940
+ | --langtag-border-radius | Corner radius of the language badge | `999px` |
2941
+ | --langtag-font-size | Font size of the language badge | `0.875em` |
2942
+
2943
+ ### `WrapToggle`
2944
+
2945
+ #### Props
2946
+
2947
+ | Name | Type | Default value |
2948
+ | :---------- | :-------- | :------------- |
2949
+ | wrap | `boolean` | `false` |
2950
+ | text | `string` | `"Wrap"` |
2951
+
2952
+ `wrap` is bindable (`bind:wrap`). `$$restProps` are forwarded to the `ToolbarButton`.
2953
+
2954
+ #### Slots
2955
+
2956
+ - default: exposes `wrap`, falls back to a wrap icon (`text` is the `aria-label` and `title`)
2957
+
2958
+ #### CSS Variables
2959
+
2960
+ `WrapToggle` is a `ToolbarButton`. Style it with the `--toolbar-button-*` variables.
2961
+
2962
+ ### `ToolbarButton`
2963
+
2964
+ #### Props
2965
+
2966
+ | Name | Type | Default value |
2967
+ | :------ | :--------------------- | :------------- |
2968
+ | label | `string` | N/A (required) |
2969
+ | pressed | `boolean \| undefined` | `undefined` |
2970
+ | href | `string \| undefined` | `undefined` |
2971
+
2972
+ `label` is the `aria-label` and the `title` tooltip. Set `pressed` to make a toggle button. Set `href` to render a link instead of a button. `$$restProps` are forwarded to the `button` or `a` element, and `class` is merged with the button's own class.
2973
+
2974
+ #### Slots
2975
+
2976
+ - default: the icon or text
2977
+
2978
+ #### Events
2979
+
2980
+ - `on:click`
2981
+
2982
+ #### CSS Variables
2983
+
2984
+ See [`ToolbarButton` variables](#toolbarbutton-variables).
2985
+
2391
2986
  ### `AnsiOutput`
2392
2987
 
2393
2988
  #### Props
@@ -2397,8 +2992,9 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2397
2992
  | text | `string` | N/A (required) |
2398
2993
  | autoContrast | `boolean` | `true` |
2399
2994
  | wrap | `boolean` | `false` |
2995
+ | label | `string` | `"Terminal output"` |
2400
2996
 
2401
- `$$restProps` are forwarded to the top-level `pre` element.
2997
+ `$$restProps` are forwarded to the top-level `pre` element. `label` names the focusable output region.
2402
2998
 
2403
2999
  ### `HighlightSvelte`
2404
3000
 
@@ -2409,6 +3005,7 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2409
3005
  | code | `any` | N/A (required) |
2410
3006
  | langtag | `boolean` | `false` |
2411
3007
  | wrap | `boolean` | `false` |
3008
+ | label | `string` | `"Code"` |
2412
3009
 
2413
3010
  `$$restProps` are forwarded to the top-level `pre` element.
2414
3011
 
@@ -2442,6 +3039,7 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2442
3039
  | languageNames | `LanguageName[]` | `undefined` |
2443
3040
  | langtag | `boolean` | `false` |
2444
3041
  | wrap | `boolean` | `false` |
3042
+ | label | `string` | `"Code"` |
2445
3043
 
2446
3044
  `$$restProps` are forwarded to the top-level `pre` element.
2447
3045
 
@@ -2484,6 +3082,19 @@ import type { LanguageName } from "svelte-highlight";
2484
3082
  />
2485
3083
  ```
2486
3084
 
3085
+ ### `HighlightAutoLazy`
3086
+
3087
+ Same props, slot props, and `on:highlight` detail as [`HighlightAuto`](#highlightauto). See [Lazy auto-highlighting](#lazy-auto-highlighting) for how it differs.
3088
+
3089
+ | Name | Type | Default value |
3090
+ | :------------ | :--------------- | :------------- |
3091
+ | code | `any` | N/A (required) |
3092
+ | languageNames | `LanguageName[]` | `undefined` |
3093
+ | langtag | `boolean` | `false` |
3094
+ | wrap | `boolean` | `false` |
3095
+
3096
+ - **on:highlight**: fired once per detection result, after the grammars load. Not fired for the plain-text placeholder.
3097
+
2487
3098
  ### `HighlightEditable`
2488
3099
 
2489
3100
  #### Props
@@ -2495,8 +3106,13 @@ import type { LanguageName } from "svelte-highlight";
2495
3106
  | tabSize | `number` | `2` |
2496
3107
  | historyLimit | `number` | `200` |
2497
3108
  | readonly | `boolean` | `false` |
3109
+ | label | `string` | `"Code editor"` |
2498
3110
 
2499
- `$$restProps` are forwarded to the top-level `pre` element.
3111
+ `$$restProps` are forwarded to the top-level `pre` element. The editor is a `role="textbox"` with `aria-multiline`, and `label` is its accessible name. `readonly` also sets `aria-readonly`.
3112
+
3113
+ ```svelte
3114
+ <HighlightEditable language={typescript} bind:code label="Query editor" />
3115
+ ```
2500
3116
 
2501
3117
  `code` supports two-way binding (`bind:code`).
2502
3118
 
@@ -2534,8 +3150,9 @@ Use `bind:this`, then call `undo()`, `redo()`, `focus()`, `selectAll()`, `insert
2534
3150
  | overscan | `number` | `12` |
2535
3151
  | checkpointInterval | `number` | `100` |
2536
3152
  | doneText | `string` | `"Code finished streaming"` |
3153
+ | label | `string` | `"Code"` |
2537
3154
 
2538
- `$$restProps` are forwarded to the top-level `pre` element. `overscan` and `checkpointInterval` only apply when `virtualize` is set. `doneText` is announced by a visually-hidden live region once `done` becomes `true`; set it to `""` to disable the announcement.
3155
+ `$$restProps` are forwarded to the top-level `pre` element. `label` names the focusable code region. `overscan` and `checkpointInterval` only apply when `virtualize` is set. `doneText` is announced by a visually-hidden live region once `done` becomes `true`; set it to `""` to disable the announcement.
2539
3156
 
2540
3157
  #### Methods
2541
3158
 
@@ -2570,14 +3187,14 @@ Use `bind:this`, then call `scrollToLine(line)` -- works in both `virtualize` an
2570
3187
  | autoScroll | `boolean` | `true` |
2571
3188
  | doneText | `string` | `"Code finished streaming"` |
2572
3189
 
2573
- `$$restProps` are forwarded to the top-level `div` element. `resolveLanguage` results are cached per canonical language name for the component's lifetime. `doneText` is announced once, by the last fence only, once `done` becomes `true`; set it to `""` to disable the announcement.
3190
+ `$$restProps` are forwarded to the top-level `div` element. `resolveLanguage` results are cached per canonical language name for the component's lifetime. `doneText` is announced once, by the last fence only, once `done` becomes `true`; set it to `""` to disable the announcement. Each fence's code region is named for its language (`"js code"`), or `"Code"` when the fence has none.
2574
3191
 
2575
3192
  #### Slots
2576
3193
 
2577
3194
  | Name | Props | Fallback |
2578
3195
  | :--- | :-------------------- | :----------------------------------------------------------------- |
2579
3196
  | text | `segment` | `<div class="shl-md-text">{segment.text}</div>` |
2580
- | fence | `segment`, `language` | `<HighlightStream code={segment.code} {language} done={done \|\| !segment.open} caret={...} autoScroll={autoScroll} doneText={...} />` |
3197
+ | fence | `segment`, `language` | `<HighlightStream code={segment.code} {language} done={done \|\| !segment.open} caret={...} autoScroll={autoScroll} label={...} doneText={...} />` |
2581
3198
 
2582
3199
  #### Dispatched Events
2583
3200
 
@@ -2606,8 +3223,9 @@ Use `bind:this`, then call `scrollToLine(line)` -- works in both `virtualize` an
2606
3223
  | overscan | `number` | `12` |
2607
3224
  | checkpointInterval | `number` | `100` |
2608
3225
  | tokenizeAhead | `boolean` | `false` |
3226
+ | label | `string` | `"Code"` |
2609
3227
 
2610
- `$$restProps` are forwarded to the top-level `pre` element (the scroll container -- size it with `style`/`class`, but `white-space` is pinned to `pre` and can't be overridden this way).
3228
+ `label` names the focusable scroll region. `$$restProps` are forwarded to the top-level `pre` element (the scroll container -- size it with `style`/`class`, but `white-space` is pinned to `pre` and can't be overridden this way).
2611
3229
 
2612
3230
  #### Methods
2613
3231
 
@@ -2624,6 +3242,104 @@ Use `bind:this`, then call `scrollToLine(line, { align })`. It jumps without ani
2624
3242
 
2625
3243
  See [Large documents](#large-documents) above.
2626
3244
 
3245
+ ### `HighlightDiff`
3246
+
3247
+ #### Props
3248
+
3249
+ | Name | Type | Default value |
3250
+ | :--------------- | :------------------------------------------- | :------------- |
3251
+ | before | `string` | `""` |
3252
+ | after | `string` | `""` |
3253
+ | patch | `FilePatch \| null` (from `parsePatch`) | `null` |
3254
+ | language | { name: `string`; register: `object` } | N/A (required) |
3255
+ | view | `"unified" \| "split"` | `"unified"` |
3256
+ | context | `number` | `3` |
3257
+ | wordDiff | `boolean` | `true` |
3258
+ | ignoreWhitespace | `boolean` | `false` |
3259
+ | detectMoves | `boolean` | `true` |
3260
+ | streaming | `boolean` | `false` |
3261
+ | follow | `boolean` | `true` |
3262
+ | review | `boolean` | `false` |
3263
+ | wrap | `boolean` | `false` |
3264
+ | virtualize | `"auto" \| boolean` | `"auto"` |
3265
+ | annotations | `Annotation[]` | `[]` |
3266
+ | palette | `"default" \| "colorblind"` | `"default"` |
3267
+ | minimap | `boolean` | `true` |
3268
+ | overscan | `number` | `10` |
3269
+ | tabSize | `number` | `4` |
3270
+
3271
+ `patch` takes precedence over `before`/`after`. `view` supports `bind:view`. `class` and `style` go on the outer element; size the diff with them (it's `400px` tall by default). Other `$$restProps` are forwarded to the inner `DiffView`.
3272
+
3273
+ #### Methods
3274
+
3275
+ Use `bind:this`, then call `nextChange()`, `prevChange()`, `expandAll()`, `collapseAll()`, `decideAll("accepted" | "rejected")`, `getResult()`, or `getPatch({ oldPath, newPath })`. The `diff` property is the underlying controller.
3276
+
3277
+ #### Dispatched Events
3278
+
3279
+ - **on:stats**: fired when the counts change, with `{ additions, deletions, changes }`
3280
+ - **on:navigate**: fired on `nextChange`/`prevChange`, with `{ change, index, count }`
3281
+ - **on:review**: fired on every accept or reject, with `{ decisions, text }`
3282
+
3283
+ See [Diffs](#diffs) above.
3284
+
3285
+ ### `DiffView`
3286
+
3287
+ #### Props
3288
+
3289
+ | Name | Type | Default value |
3290
+ | :--------- | :--------------------------- | :------------- |
3291
+ | diff | `DiffController` | N/A (required) |
3292
+ | follow | `boolean` | `true` |
3293
+ | review | `boolean` | `false` |
3294
+ | wrap | `boolean` | `false` |
3295
+ | virtualize | `"auto" \| boolean` | `"auto"` |
3296
+ | palette | `"default" \| "colorblind"` | `"default"` |
3297
+ | overscan | `number` | `10` |
3298
+ | keyboard | `boolean` | `true` |
3299
+
3300
+ `$$restProps` are forwarded to the top-level `section` element.
3301
+
3302
+ #### Slots
3303
+
3304
+ - **fold**: replaces a fold row, with `{ fold, count, toggle }`
3305
+ - **note**: replaces an annotation card, with `{ note }`
3306
+ - **actions**: controls on the first row of each change, with `{ change, decision, decide }`. Filling it shows it even without `review`.
3307
+
3308
+ ### `DiffMinimap` and `DiffStats`
3309
+
3310
+ Both take one prop, `diff` (a `DiffController`). `$$restProps` are forwarded to the top-level element. `DiffMinimap` fills its parent's height, so give it one.
3311
+
3312
+ ### `DiffFileList`
3313
+
3314
+ #### Props
3315
+
3316
+ | Name | Type | Default value |
3317
+ | :--------------- | :------------------------------------------------ | :------------------------ |
3318
+ | files | `DiffFile[]` | `[]` |
3319
+ | view | `"unified" \| "split"` | `"unified"` |
3320
+ | context | `number` | `3` |
3321
+ | wordDiff | `boolean` | `true` |
3322
+ | ignoreWhitespace | `boolean` | `false` |
3323
+ | wrap | `boolean` | `false` |
3324
+ | review | `boolean` | `false` |
3325
+ | palette | `"default" \| "colorblind"` | `"default"` |
3326
+ | maxHeight | `number \| null` | `640` |
3327
+ | languageFor | `(path) => language \| Promise<language> \| undefined` | by file extension |
3328
+ | windowing | `"windowed" \| "lazy" \| "none"` | `"windowed"` |
3329
+ | rootMargin | `string` | `"1500px 0px"` |
3330
+ | root | `Element \| null` | `null` (the page scrolls) |
3331
+ | collapsible | `boolean` | `true` |
3332
+
3333
+ A `DiffFile` is `{ key?, path, oldPath?, status?, patch?, before?, after?, language? }`. `$$restProps` are forwarded to the top-level `div` element.
3334
+
3335
+ #### Slots
3336
+
3337
+ - **header**: replaces a file's header, with `{ file, index, stats, collapsed, toggle }`. `stats` comes from the patch, or from the file's diff once it has mounted.
3338
+
3339
+ #### Methods
3340
+
3341
+ Use `bind:this`, then call `scrollToFile(index, options)`. `options` are `scrollIntoView` options (default `{ block: "start" }`).
3342
+
2627
3343
  ### `FileTabs`
2628
3344
 
2629
3345
  #### Props
@@ -2658,8 +3374,9 @@ See [Large documents](#large-documents) above.
2658
3374
  | granularity | `"char" \| "word"` | `"char"` |
2659
3375
  | revealed | `number` | `0` |
2660
3376
  | total | `number` | `0` |
3377
+ | label | `string` | `"Code"` |
2661
3378
 
2662
- `$$restProps` are forwarded to the top-level `pre` element. `revealed`/`total` are read-only in practice (overwritten every frame) but exposed for `bind:revealed`/`bind:total`.
3379
+ `$$restProps` are forwarded to the top-level `pre` element. `label` names the focusable code region. `revealed`/`total` are read-only in practice (overwritten every frame) but exposed for `bind:revealed`/`bind:total`.
2663
3380
 
2664
3381
  #### Dispatched Events
2665
3382
 
@@ -2699,7 +3416,7 @@ See it as a complete page in [examples/cdn](examples/cdn).
2699
3416
 
2700
3417
  - **Stable, semver-governed:** `ScopeEvent`, `TEXT`/`OPEN`/`CLOSE`, `TokenRange`, `HighlightResult`, `LineToken`, `Renderer`, `renderHtml`, `toRanges`, `extendLines`, `tokenLines`, `escapeHtml`, `createHtmlRenderer`, `createRangeRenderer`, `createLineRenderer`, `Registry` and its methods, `createRegistry`, `registerAll`, `StreamSession`, `TokenizedDocument`, `createTokenizedDocument`, `TextSegment`, `FenceSegment`, `MarkdownSegment`, `FenceSplitter`, `createFenceSplitter`, `SearchMatch`, `SearchOptions`, `Search`, `createSearch`, `highlightMatches`, `UnknownLanguageError`, `TokenizerLoopError`. `Snapshot` is a serializable format that round-trips within one library version, but is **not** guaranteed stable across versions — a snapshot from an older release may be rejected on resume. The same caveat applies to `TokenizedDocument`: its method surface (`setCode`/`append`/`lineCount`/`lineRange`/`textRange`/`tokenizedThrough`/`checkpointCount`) is stable and semver-governed, but internally it resumes from `Snapshot`s the same way `StreamSession` does, so anything that tried to serialize and later resume a `TokenizedDocument`'s internal state directly would hit the same cross-version instability -- the public API doesn't expose that today.
2701
3418
  - **Generated data, versioned with the library:** `GrammarIR`/`GrammarState`. These come from the build pipeline and are consumed by `registerAll`; treat them as opaque payloads whose field-level structure may change in any minor release. Always load grammars from the same package version as the engine.
2702
- - **Experimental, may change in a minor release:** `createWorkerHighlighter`, `serveHighlighter`, `PostMessageTarget`, `WorkerHighlighter`, `WorkerSession`, `ServeHighlighterOptions` (`svelte-highlight/worker`). The wire protocol between the two halves is not part of the public contract — only the documented function behavior is.
3419
+ - **Experimental, may change in a minor release:** everything in `svelte-highlight/diff`, `svelte-highlight/diff-edits`, and `svelte-highlight/diff-controller`, and the `HighlightDiff`, `DiffView`, `DiffMinimap`, `DiffStats`, and `DiffFileList` components. They're new, and their API may change before they're stable. Also `createWorkerHighlighter`, `serveHighlighter`, `PostMessageTarget`, `WorkerHighlighter`, `WorkerSession`, `ServeHighlighterOptions` (`svelte-highlight/worker`). The wire protocol between the two halves is not part of the public contract — only the documented function behavior is.
2703
3420
 
2704
3421
  ### Headless highlighting, isolated registry
2705
3422