svelte-highlight 7.21.0 → 7.22.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.
- package/CodeWindow.svelte +35 -11
- package/CodeWindow.svelte.d.ts +7 -1
- package/HighlightStream.svelte +22 -0
- package/HighlightStream.svelte.d.ts +4 -1
- package/LangTag.svelte +4 -0
- package/LineNumbers.svelte +1 -0
- package/MarkdownStream.svelte +202 -0
- package/MarkdownStream.svelte.d.ts +100 -0
- package/README.md +402 -6
- package/action.d.ts +16 -2
- package/action.js +92 -5
- package/engine.d.ts +29 -1
- package/engine.js +38 -3
- package/fence.d.ts +76 -4
- package/fence.js +274 -3
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/languages/agda.js +1 -1
- package/languages/aliases.d.ts +7 -0
- package/languages/aliases.js +4 -0
- package/languages/all.js +25 -1
- package/languages/alloy.d.ts +2 -0
- package/languages/alloy.js +2 -0
- package/languages/angular.js +1 -1
- package/languages/assemblyscript.js +1 -1
- package/languages/astro.js +1 -1
- package/languages/asymptote.d.ts +2 -0
- package/languages/asymptote.js +2 -0
- package/languages/baml.js +1 -1
- package/languages/bend.js +1 -1
- package/languages/bibtex.js +1 -1
- package/languages/bicep.js +1 -1
- package/languages/bitbake.js +1 -1
- package/languages/blade.js +1 -1
- package/languages/blockdiag.d.ts +2 -0
- package/languages/blockdiag.js +2 -0
- package/languages/blueprint.js +1 -1
- package/languages/bpftrace.js +1 -1
- package/languages/bqn.js +1 -1
- package/languages/bsv.d.ts +2 -0
- package/languages/bsv.js +2 -0
- package/languages/c.js +1 -1
- package/languages/c3.js +1 -1
- package/languages/caddy.js +1 -1
- package/languages/cairo.js +1 -1
- package/languages/casbin.d.ts +2 -0
- package/languages/casbin.js +2 -0
- package/languages/cedar.js +1 -1
- package/languages/cel.js +1 -1
- package/languages/choicescript.d.ts +2 -0
- package/languages/choicescript.js +2 -0
- package/languages/cisco.js +1 -1
- package/languages/civet.js +1 -1
- package/languages/clarity.js +1 -1
- package/languages/codeql.js +1 -1
- package/languages/cql.js +1 -1
- package/languages/crontab.js +1 -1
- package/languages/csharp.js +1 -1
- package/languages/cue.js +1 -1
- package/languages/cypher.js +1 -1
- package/languages/d2.js +1 -1
- package/languages/dafny.d.ts +2 -0
- package/languages/dafny.js +2 -0
- package/languages/dart.js +1 -1
- package/languages/datalog.js +1 -1
- package/languages/dax.js +1 -1
- package/languages/dbml.d.ts +2 -0
- package/languages/dbml.js +2 -0
- package/languages/dhall.js +1 -1
- package/languages/dialog.d.ts +2 -0
- package/languages/dialog.js +2 -0
- package/languages/djot.js +1 -1
- package/languages/dotenv.js +1 -1
- package/languages/dtrace.js +1 -1
- package/languages/earthfile.js +1 -1
- package/languages/ejs.js +1 -1
- package/languages/esql.js +1 -1
- package/languages/fennel.js +1 -1
- package/languages/fish.js +1 -1
- package/languages/flux.js +1 -1
- package/languages/fstar.d.ts +2 -0
- package/languages/fstar.js +2 -0
- package/languages/gdscript.js +1 -1
- package/languages/gdshader.js +1 -1
- package/languages/gleam.js +1 -1
- package/languages/gnuplot.d.ts +2 -0
- package/languages/gnuplot.js +2 -0
- package/languages/go.js +1 -1
- package/languages/groq.js +1 -1
- package/languages/haproxy.js +1 -1
- package/languages/harlowe.d.ts +2 -0
- package/languages/harlowe.js +2 -0
- package/languages/hcl.js +1 -1
- package/languages/heex.js +3 -1
- package/languages/helm.js +1 -1
- package/languages/hlsl.js +1 -1
- package/languages/hocon.js +1 -1
- package/languages/hurl.js +1 -1
- package/languages/idris.js +1 -1
- package/languages/imba.js +1 -1
- package/languages/index.d.ts +48 -0
- package/languages/index.js +24 -0
- package/languages/ink.js +1 -1
- package/languages/java.js +1 -1
- package/languages/javascript.js +1 -1
- package/languages/jinja.js +1 -1
- package/languages/jmespath.js +1 -1
- package/languages/jq.js +1 -1
- package/languages/json5.js +1 -1
- package/languages/jsonata.js +1 -1
- package/languages/jsonnet.js +1 -1
- package/languages/just.js +1 -1
- package/languages/kcl.js +1 -1
- package/languages/kconfig.js +1 -1
- package/languages/kdl.js +1 -1
- package/languages/koka.js +1 -1
- package/languages/kotlin.js +1 -1
- package/languages/kql.js +1 -1
- package/languages/lean.js +1 -1
- package/languages/likec4.d.ts +2 -0
- package/languages/likec4.js +2 -0
- package/languages/liquid.js +2 -1
- package/languages/logql.js +1 -1
- package/languages/lookml.js +1 -1
- package/languages/luau.js +1 -1
- package/languages/markdoc.js +1 -1
- package/languages/marko.js +1 -1
- package/languages/mdx.js +2 -1
- package/languages/mermaid.js +1 -1
- package/languages/modelfile.js +1 -1
- package/languages/mojo.js +1 -1
- package/languages/move.js +1 -1
- package/languages/nextflow.d.ts +2 -0
- package/languages/nextflow.js +2 -0
- package/languages/nickel.js +1 -1
- package/languages/nomnoml.d.ts +2 -0
- package/languages/nomnoml.js +2 -0
- package/languages/nushell.js +1 -1
- package/languages/odin.js +1 -1
- package/languages/openfga.d.ts +2 -0
- package/languages/openfga.js +2 -0
- package/languages/org.js +1 -1
- package/languages/pikchr.d.ts +2 -0
- package/languages/pikchr.js +2 -0
- package/languages/pkl.js +1 -1
- package/languages/plsql.js +1 -1
- package/languages/polar.js +1 -1
- package/languages/powerquery.js +1 -1
- package/languages/promql.js +1 -1
- package/languages/prql.js +1 -1
- package/languages/purescript.js +1 -1
- package/languages/python.js +1 -1
- package/languages/racket.js +1 -1
- package/languages/raku.js +1 -1
- package/languages/regex.js +1 -1
- package/languages/roc.js +1 -1
- package/languages/ron.js +1 -1
- package/languages/rust.js +1 -1
- package/languages/semver.d.ts +2 -0
- package/languages/semver.js +2 -0
- package/languages/shaderlab.js +1 -1
- package/languages/slint.js +1 -1
- package/languages/smithy.js +1 -1
- package/languages/snort.js +1 -1
- package/languages/solidity.js +1 -1
- package/languages/spade.d.ts +2 -0
- package/languages/spade.js +2 -0
- package/languages/sparql.js +1 -1
- package/languages/spicedb.d.ts +2 -0
- package/languages/spicedb.js +2 -0
- package/languages/splunk.js +1 -1
- package/languages/structurizr.js +1 -1
- package/languages/surrealql.js +1 -1
- package/languages/svelte.js +1 -1
- package/languages/swift.js +1 -1
- package/languages/systemd.js +1 -1
- package/languages/tlaplus.d.ts +2 -0
- package/languages/tlaplus.js +2 -0
- package/languages/toml.js +1 -1
- package/languages/traceql.js +1 -1
- package/languages/tsq.js +1 -1
- package/languages/tsql.js +1 -1
- package/languages/typescript.js +1 -1
- package/languages/typespec.js +1 -1
- package/languages/url.d.ts +2 -0
- package/languages/url.js +2 -0
- package/languages/v.js +1 -1
- package/languages/vcl.js +1 -1
- package/languages/verse.js +1 -1
- package/languages/veryl.d.ts +2 -0
- package/languages/veryl.js +2 -0
- package/languages/vrl.js +1 -1
- package/languages/vue.js +1 -1
- package/languages/vyper.js +1 -1
- package/languages/wdl.d.ts +2 -0
- package/languages/wdl.js +2 -0
- package/languages/wgsl.js +1 -1
- package/languages/wit.js +1 -1
- package/languages/yara.js +1 -1
- package/languages/zig.js +1 -1
- package/package.json +30 -2
- package/search.css +16 -0
- package/search.d.ts +92 -0
- package/search.js +518 -0
- package/styles/blacklight-dark.css +1 -1
- package/styles/blacklight-dark.js +1 -1
- package/styles/cyanotype-light.css +1 -1
- package/styles/cyanotype-light.js +1 -1
- package/styles/dusk-dark.css +1 -1
- package/styles/dusk-dark.js +1 -1
- package/styles/peat-dark.css +1 -1
- package/styles/peat-dark.js +1 -1
- package/styles/thermal-dark.css +1 -1
- package/styles/thermal-dark.js +1 -1
- package/styles/wet-plate-dark.css +1 -1
- package/styles/wet-plate-dark.js +1 -1
- package/themes/blacklight-dark.css +1 -1
- package/themes/blacklight-dark.js +2 -2
- package/themes/cyanotype-light.css +1 -1
- package/themes/cyanotype-light.js +2 -2
- package/themes/dusk-dark.css +1 -1
- package/themes/dusk-dark.js +2 -2
- package/themes/peat-dark.css +1 -1
- package/themes/peat-dark.js +2 -2
- package/themes/thermal-dark.css +1 -1
- package/themes/thermal-dark.js +2 -2
- package/themes/wet-plate-dark.css +1 -1
- package/themes/wet-plate-dark.js +2 -2
- package/transformers.d.ts +44 -0
- package/transformers.js +154 -0
- package/worker.d.ts +45 -0
- package/worker.js +379 -0
package/README.md
CHANGED
|
@@ -115,7 +115,7 @@ This renders SSR-identical output — no `<svelte:head>`, no `<style>` tag, just
|
|
|
115
115
|
**Dual light/dark via [`light-dark()`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/light-dark):**
|
|
116
116
|
|
|
117
117
|
```svelte
|
|
118
|
-
<HighlightStyle light={
|
|
118
|
+
<HighlightStyle light={cyanotypeLight} dark={cyanotypeDark} mode="auto">
|
|
119
119
|
<Highlight language={typescript} {code} />
|
|
120
120
|
</HighlightStyle>
|
|
121
121
|
```
|
|
@@ -292,7 +292,7 @@ bun scripts/import-textmate-theme.ts ./night-owl-color-theme.json ./night-owl.pa
|
|
|
292
292
|
|
|
293
293
|
## Styling
|
|
294
294
|
|
|
295
|
-
Import styles from `svelte-highlight/styles`. See [SUPPORTED_STYLES.md](SUPPORTED_STYLES.md) for a list of supported styles. For new projects, prefer [Theming](#theming) above — this is the original, string-based theming path, kept fully supported for backward compatibility. Legacy styles are stable and will not be removed. One concrete reason to pick this path over `ThemePalette`: `base.css` assumes the default `hljs-` class prefix, so projects using a custom `classPrefix` should stay here.
|
|
295
|
+
Import styles from `svelte-highlight/styles`. See [SUPPORTED_STYLES.md](SUPPORTED_STYLES.md) for a list of supported styles. For new projects, prefer [Theming](#theming) above — this is the original, string-based theming path, kept fully supported for backward compatibility. Legacy styles are stable and will not be removed. One concrete reason to pick this path over `ThemePalette`: `base.css` assumes the default `hljs-` class prefix, so projects using a custom `classPrefix` should stay here. 45 of the styles (90 dark/light files) are original pairs authored by svelte-highlight rather than ported from highlight.js, marked as custom in the gallery and in `SUPPORTED_STYLES.md`.
|
|
296
296
|
|
|
297
297
|
There are two ways to apply `highlight.js` styles.
|
|
298
298
|
|
|
@@ -1418,7 +1418,18 @@ const html = await highlightFence({
|
|
|
1418
1418
|
});
|
|
1419
1419
|
```
|
|
1420
1420
|
|
|
1421
|
-
`lang`
|
|
1421
|
+
`lang` accepts either the grammar's canonical file name or a known alias (e.g. `"ts"`, `"sh"`) -- `highlightFence` resolves it internally via `resolveLanguageName`, and rejects with `LanguageLoadError` when neither resolves. `meta` is the Expressive Code/Shiki-style vocabulary standardized on by tools like Astro, Starlight, and rehype-pretty-code: a bare `{1,3-5}` or `mark={1,3-5}` marks lines, `ins={...}`/`del={...}` mark insertions/deletions, `title="..."` sets a title, and `showLineNumbers` is a bare flag. The output wraps each line in `<span class="line" data-line-state="mark|ins|del">` (only when a state applies) inside a `<pre class="hljs" data-language="...">`, so a `mark`/`ins`/`del`-aware stylesheet can target `[data-line-state]` the same way it would target Expressive Code or Shiki output.
|
|
1422
|
+
|
|
1423
|
+
Call `resolveLanguageName` directly when you need the canonical name ahead of `highlightFence` -- e.g. to pick a display label, or to call `loadLanguage`/`<Highlight>` yourself instead:
|
|
1424
|
+
|
|
1425
|
+
```js
|
|
1426
|
+
import { resolveLanguageName } from "svelte-highlight/fence";
|
|
1427
|
+
|
|
1428
|
+
resolveLanguageName("ts"); // "typescript"
|
|
1429
|
+
resolveLanguageName("nope"); // undefined
|
|
1430
|
+
```
|
|
1431
|
+
|
|
1432
|
+
It trims, lowercases, and reads only the first word, so passing a whole info string (`resolveLanguageName("ts title=\"app.ts\"")`) works too. The alias table it reads from is also importable directly, as `svelte-highlight/languages/aliases` (`LANGUAGE_ALIASES: Readonly<Record<string, string>>`), for consumers that want the raw alias -> canonical mapping without going through `resolveLanguageName`.
|
|
1422
1433
|
|
|
1423
1434
|
**mdsvex.** Wire `highlightFence` into `highlight.highlighter`, whose signature is `(code, lang, meta) => string | Promise<string>`:
|
|
1424
1435
|
|
|
@@ -1489,6 +1500,8 @@ function rehypeHighlightFence() {
|
|
|
1489
1500
|
|
|
1490
1501
|
Use the `highlight` action to highlight existing `<pre><code>` markup in place. This is useful for progressively enhancing server-rendered content (e.g. markdown) without swapping in a component.
|
|
1491
1502
|
|
|
1503
|
+
Place `use:highlight` on the `<code>` element inside a `<pre>`, matching the theme CSS's `.hljs code` selector -- elsewhere (directly on `<pre>`, or a non-`<pre><code>` element) it still highlights but may not be visually targeted by the active theme.
|
|
1504
|
+
|
|
1492
1505
|
The action accepts the same `language` prop as the components. When `code` is omitted, the element's existing `textContent` is highlighted. Updating `code` re-highlights the element.
|
|
1493
1506
|
|
|
1494
1507
|
```svelte
|
|
@@ -1515,11 +1528,31 @@ Omit `code` to highlight the element's existing contents:
|
|
|
1515
1528
|
></pre>
|
|
1516
1529
|
```
|
|
1517
1530
|
|
|
1531
|
+
`language` is also optional: when omitted, the action reads a `language-xxx` class off its own node (the Prism/highlight.js Markdown convention) and resolves it via `loadLanguage`, so server-rendered Markdown output needs no per-block `language` prop. With no matching class, it warns in dev and dispatches `error`.
|
|
1532
|
+
|
|
1533
|
+
```svelte
|
|
1534
|
+
<pre><code class="language-typescript" use:highlight>const add = (a, b) => a + b;</code></pre>
|
|
1535
|
+
```
|
|
1536
|
+
|
|
1537
|
+
### Dispatched Events
|
|
1538
|
+
|
|
1539
|
+
The action dispatches `highlighted` (`detail: { html, language }`) on success and `error` (`detail: { error }`) on failure, on the node it's placed on.
|
|
1540
|
+
|
|
1541
|
+
```svelte
|
|
1542
|
+
<pre><code
|
|
1543
|
+
use:highlight={{ language: typescript, code }}
|
|
1544
|
+
on:highlighted={(e) => console.log(e.detail.html, e.detail.language)}
|
|
1545
|
+
on:error={(e) => console.error(e.detail.error)}
|
|
1546
|
+
></code></pre>
|
|
1547
|
+
```
|
|
1548
|
+
|
|
1549
|
+
`highlighted` is also a composition hook for a sibling `LineNumbers`: `on:highlighted={(e) => (highlighted = e.detail.html)}` feeding `<LineNumbers {highlighted} languageName={typescript.name} />`.
|
|
1550
|
+
|
|
1518
1551
|
## Code Window
|
|
1519
1552
|
|
|
1520
1553
|
Wrap a code block in `CodeWindow` to frame it with window chrome. It's purely cosmetic; the default slot renders your content unchanged.
|
|
1521
1554
|
|
|
1522
|
-
Use the `variant` prop to choose the chrome style: `"macos"` (default) renders traffic-light dots, `"terminal"` renders a prompt, and `"plain"` renders just the title bar. The optional `title` is shown in the title bar.
|
|
1555
|
+
Use the `variant` prop to choose the chrome style: `"macos"` (default) renders traffic-light dots, `"terminal"` renders a prompt, and `"plain"` renders just the title bar. The optional `title` is shown in the title bar, and is also exposed as a native tooltip via the HTML `title` attribute so a truncated title is readable on hover or focus.
|
|
1523
1556
|
|
|
1524
1557
|
```svelte
|
|
1525
1558
|
<script>
|
|
@@ -1565,6 +1598,8 @@ added 1 package in 1.2s`;
|
|
|
1565
1598
|
|
|
1566
1599
|
### Theming the chrome
|
|
1567
1600
|
|
|
1601
|
+
The title bar is a three-column flex row (leading chrome, title, a mirrored trailing spacer), so the title stays centered in the space actually left over without overlapping the dots or prompt even at narrow widths -- this doesn't apply to `plain`, which has no leading chrome to mirror.
|
|
1602
|
+
|
|
1568
1603
|
Every part of the chrome is driven by CSS variables (see [`CodeWindow` variables](#codewindow-variables)). Pass them as style props to restyle the window without `:global` overrides. For example, give the default square window rounded corners with `--window-radius`:
|
|
1569
1604
|
|
|
1570
1605
|
```svelte
|
|
@@ -1640,6 +1675,34 @@ Or layer a `CopyButton` over it by wrapping both in a relatively-positioned cont
|
|
|
1640
1675
|
</div>
|
|
1641
1676
|
```
|
|
1642
1677
|
|
|
1678
|
+
Put a `FileTabs` strip in the `titlebar` slot to switch between files without leaving the title bar:
|
|
1679
|
+
|
|
1680
|
+
```svelte
|
|
1681
|
+
<script>
|
|
1682
|
+
import Highlight, { CodeWindow, FileTabs } from "svelte-highlight";
|
|
1683
|
+
import javascript from "svelte-highlight/languages/javascript";
|
|
1684
|
+
import typescript from "svelte-highlight/languages/typescript";
|
|
1685
|
+
import github from "svelte-highlight/styles/github";
|
|
1686
|
+
|
|
1687
|
+
const sources = {
|
|
1688
|
+
"App.svelte": { language: typescript, code: "const answer = 42;" },
|
|
1689
|
+
"index.js": { language: javascript, code: "export default answer;" },
|
|
1690
|
+
};
|
|
1691
|
+
|
|
1692
|
+
const files = Object.keys(sources);
|
|
1693
|
+
let active = files[0];
|
|
1694
|
+
</script>
|
|
1695
|
+
|
|
1696
|
+
<svelte:head>
|
|
1697
|
+
{@html github}
|
|
1698
|
+
</svelte:head>
|
|
1699
|
+
|
|
1700
|
+
<CodeWindow variant="macos">
|
|
1701
|
+
<FileTabs {files} bind:active slot="titlebar" />
|
|
1702
|
+
<Highlight language={sources[active].language} code={sources[active].code} />
|
|
1703
|
+
</CodeWindow>
|
|
1704
|
+
```
|
|
1705
|
+
|
|
1643
1706
|
## Animation
|
|
1644
1707
|
|
|
1645
1708
|
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.
|
|
@@ -1771,7 +1834,131 @@ Per-chunk work is O(tail), not O(stream length so far): finished output is seale
|
|
|
1771
1834
|
<HighlightStream language={typescript} {code} {done} virtualize style="height: 20em;" />
|
|
1772
1835
|
```
|
|
1773
1836
|
|
|
1774
|
-
`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`.
|
|
1837
|
+
`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
|
+
|
|
1839
|
+
### Streaming Markdown with multiple fences
|
|
1840
|
+
|
|
1841
|
+
`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:
|
|
1842
|
+
|
|
1843
|
+
```svelte
|
|
1844
|
+
<script>
|
|
1845
|
+
import { HighlightStream, loadLanguage } from "svelte-highlight";
|
|
1846
|
+
import { createFenceSplitter } from "svelte-highlight/fence";
|
|
1847
|
+
import github from "svelte-highlight/styles/github";
|
|
1848
|
+
|
|
1849
|
+
const splitter = createFenceSplitter();
|
|
1850
|
+
let segments = splitter.segments();
|
|
1851
|
+
let done = false;
|
|
1852
|
+
|
|
1853
|
+
// Wire this up to your streaming source (fetch, WebSocket, SSE, ...).
|
|
1854
|
+
async function stream() {
|
|
1855
|
+
for (const chunk of chunks) {
|
|
1856
|
+
splitter.append(chunk);
|
|
1857
|
+
segments = splitter.segments();
|
|
1858
|
+
await new Promise((r) => setTimeout(r, 30));
|
|
1859
|
+
}
|
|
1860
|
+
done = true;
|
|
1861
|
+
}
|
|
1862
|
+
</script>
|
|
1863
|
+
|
|
1864
|
+
<svelte:head>
|
|
1865
|
+
{@html github}
|
|
1866
|
+
</svelte:head>
|
|
1867
|
+
|
|
1868
|
+
{#each segments as segment (segment.id)}
|
|
1869
|
+
{#if segment.kind === "text"}
|
|
1870
|
+
<p style="white-space: pre-wrap">{segment.text}</p>
|
|
1871
|
+
{:else}
|
|
1872
|
+
{#await loadLanguage(segment.lang ?? "plaintext") then grammar}
|
|
1873
|
+
<HighlightStream language={grammar} code={segment.code} done={!segment.open} />
|
|
1874
|
+
{/await}
|
|
1875
|
+
{/if}
|
|
1876
|
+
{/each}
|
|
1877
|
+
```
|
|
1878
|
+
|
|
1879
|
+
Every segment's `id` is stable across both `append` (growing the buffer) and a full `set` (a regenerated buffer, keyed by common prefix) for everything before the first change, so the keyed `{#each}` never re-mounts a fence's `HighlightStream` just because more text arrived elsewhere in the document -- only the segment that actually changed gets a new instance.
|
|
1880
|
+
|
|
1881
|
+
### `MarkdownStream`
|
|
1882
|
+
|
|
1883
|
+
`MarkdownStream` wraps the pattern above: pass it a growing Markdown `text` buffer and it drives one `HighlightStream` per fence for you, keyed by the splitter's stable ids. Prose renders as plain text by default -- it's not a Markdown renderer, just a router for fenced code.
|
|
1884
|
+
|
|
1885
|
+
```svelte
|
|
1886
|
+
<script>
|
|
1887
|
+
import { MarkdownStream } from "svelte-highlight";
|
|
1888
|
+
import github from "svelte-highlight/styles/github";
|
|
1889
|
+
|
|
1890
|
+
let text = "";
|
|
1891
|
+
let done = false;
|
|
1892
|
+
|
|
1893
|
+
// Wire this up to your streaming source (fetch, WebSocket, SSE, ...).
|
|
1894
|
+
async function stream() {
|
|
1895
|
+
for (const chunk of chunks) {
|
|
1896
|
+
text += chunk;
|
|
1897
|
+
await new Promise((r) => setTimeout(r, 30));
|
|
1898
|
+
}
|
|
1899
|
+
done = true;
|
|
1900
|
+
}
|
|
1901
|
+
</script>
|
|
1902
|
+
|
|
1903
|
+
<svelte:head>
|
|
1904
|
+
{@html github}
|
|
1905
|
+
</svelte:head>
|
|
1906
|
+
|
|
1907
|
+
<MarkdownStream {text} {done} />
|
|
1908
|
+
```
|
|
1909
|
+
|
|
1910
|
+
`done` is forwarded to every fence's `HighlightStream` as `done || !segment.open`, so a trailing fence still open when the overall stream ends is treated as closed. The caret only ever renders on the last open fence, and `doneText`'s completion announcement fires once, from the last fence, rather than once per fence.
|
|
1911
|
+
|
|
1912
|
+
Override the `text` slot to render real Markdown prose (headings, lists, inline code) with a library of your choice, leaving fences to `MarkdownStream`:
|
|
1913
|
+
|
|
1914
|
+
```svelte
|
|
1915
|
+
<script>
|
|
1916
|
+
import { MarkdownStream } from "svelte-highlight";
|
|
1917
|
+
import { renderInlineMarkdown } from "./your-markdown-renderer.js";
|
|
1918
|
+
</script>
|
|
1919
|
+
|
|
1920
|
+
<MarkdownStream {text} {done}>
|
|
1921
|
+
<div slot="text" let:segment>{@html renderInlineMarkdown(segment.text)}</div>
|
|
1922
|
+
</MarkdownStream>
|
|
1923
|
+
```
|
|
1924
|
+
|
|
1925
|
+
By default, `resolveLanguage` dynamically imports one grammar per language seen via `loadLanguage`, falling back to plaintext while loading and for an unrecognized fence language. Pass your own `resolveLanguage` to restrict resolution to a fixed set of languages -- for example, everything else falls back to plaintext instead of fetching an arbitrary grammar chunk:
|
|
1926
|
+
|
|
1927
|
+
```svelte
|
|
1928
|
+
<script>
|
|
1929
|
+
import { MarkdownStream, loadLanguage } from "svelte-highlight";
|
|
1930
|
+
|
|
1931
|
+
const ALLOWED = new Set(["typescript", "javascript", "bash", "json"]);
|
|
1932
|
+
|
|
1933
|
+
function resolveLanguage(lang) {
|
|
1934
|
+
return lang && ALLOWED.has(lang) ? loadLanguage(lang) : undefined;
|
|
1935
|
+
}
|
|
1936
|
+
</script>
|
|
1937
|
+
|
|
1938
|
+
<MarkdownStream {text} {done} {resolveLanguage} />
|
|
1939
|
+
```
|
|
1940
|
+
|
|
1941
|
+
That still dynamically imports each allowed language's grammar on first use. For an app that wants no dynamic chunks at all -- everything bundled up front, same tradeoff as [Loading a language by name](#loading-a-language-by-name) -- map the allowlist to statically imported grammars instead:
|
|
1942
|
+
|
|
1943
|
+
```svelte
|
|
1944
|
+
<script>
|
|
1945
|
+
import { MarkdownStream } from "svelte-highlight";
|
|
1946
|
+
import bash from "svelte-highlight/languages/bash";
|
|
1947
|
+
import javascript from "svelte-highlight/languages/javascript";
|
|
1948
|
+
import json from "svelte-highlight/languages/json";
|
|
1949
|
+
import typescript from "svelte-highlight/languages/typescript";
|
|
1950
|
+
|
|
1951
|
+
const GRAMMARS = { typescript, javascript, bash, json };
|
|
1952
|
+
|
|
1953
|
+
function resolveLanguage(lang) {
|
|
1954
|
+
return lang ? GRAMMARS[lang] : undefined;
|
|
1955
|
+
}
|
|
1956
|
+
</script>
|
|
1957
|
+
|
|
1958
|
+
<MarkdownStream {text} {done} {resolveLanguage} />
|
|
1959
|
+
```
|
|
1960
|
+
|
|
1961
|
+
See [Code-splitting](#code-splitting) for the tradeoffs between a static import (bundled up front, no request-time latency) and `loadLanguage` (smaller initial bundle, one chunk fetched per language actually seen).
|
|
1775
1962
|
|
|
1776
1963
|
## Large documents
|
|
1777
1964
|
|
|
@@ -1857,6 +2044,59 @@ For documents in the low thousands to tens of thousands of lines (roughly 2,000-
|
|
|
1857
2044
|
|
|
1858
2045
|
Each line is its own block-level `<div>`, not a row in a `<table>`/`<tr>` (the way `LineNumbers` renders) -- `content-visibility` doesn't apply to table-internal display types, so off-screen table rows never get the skip. Off-screen `<div>` lines do: the browser skips layout/paint/style for them, using `contain-intrinsic-size` as a placeholder size until they scroll near the viewport. Unlike `HighlightVirtual`, this is a progressive enhancement, not a hard requirement -- browsers without `content-visibility` support just render every line normally, and you get native text selection, find-in-page, and line wrapping for free (drop the `white-space: pre` on each line's `<div>` to allow it).
|
|
1859
2046
|
|
|
2047
|
+
## Find in document
|
|
2048
|
+
|
|
2049
|
+
Browser Cmd+F can't see rows a virtualized view (`HighlightVirtual`, `HighlightStream`'s `virtualize` mode) hasn't mounted, and neither of them ships a search box -- `svelte-highlight/search` is a headless find-in-document engine plus a DOM-painting helper, so any consumer can build one. No `<input>` component is exported; that's application UI, not a library primitive.
|
|
2050
|
+
|
|
2051
|
+
`createSearch(source)` accepts a plain `string` (split on `"\n"`), a `string[]` of lines, or a `TokenizedDocument` (duck-typed -- only `lineCount`/`lineRange` are used, never checked via `instanceof`), such as the one backing a `HighlightStream` in `virtualize` mode. Against a `TokenizedDocument`, repeated `query()` calls with unchanged text/options only rescan lines appended since the last call, instead of rescanning the whole document every time:
|
|
2052
|
+
|
|
2053
|
+
```svelte
|
|
2054
|
+
<script>
|
|
2055
|
+
import { HighlightVirtual } from "svelte-highlight";
|
|
2056
|
+
import typescript from "svelte-highlight/languages/typescript";
|
|
2057
|
+
import { createSearch, highlightMatches } from "svelte-highlight/search";
|
|
2058
|
+
import "svelte-highlight/search.css";
|
|
2059
|
+
|
|
2060
|
+
export let code;
|
|
2061
|
+
const search = createSearch(code);
|
|
2062
|
+
|
|
2063
|
+
/** @type {HighlightVirtual} */
|
|
2064
|
+
let ref;
|
|
2065
|
+
/** @type {HTMLElement} */
|
|
2066
|
+
let root;
|
|
2067
|
+
let dispose = () => {};
|
|
2068
|
+
|
|
2069
|
+
function repaint() {
|
|
2070
|
+
dispose();
|
|
2071
|
+
dispose = highlightMatches(root, search.matches(), {
|
|
2072
|
+
current: search.current()?.index,
|
|
2073
|
+
}).dispose;
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
const unsubscribe = search.onChange(repaint);
|
|
2077
|
+
|
|
2078
|
+
function onInput(event) {
|
|
2079
|
+
search.query(event.currentTarget.value, { wholeWord: true });
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
function next() {
|
|
2083
|
+
const match = search.next();
|
|
2084
|
+
if (match) ref.scrollToLine(match.line);
|
|
2085
|
+
}
|
|
2086
|
+
</script>
|
|
2087
|
+
|
|
2088
|
+
<input on:input={onInput} />
|
|
2089
|
+
<button on:click={next}>Next ({search.count()})</button>
|
|
2090
|
+
|
|
2091
|
+
<div bind:this={root}>
|
|
2092
|
+
<HighlightVirtual bind:this={ref} language={typescript} {code} on:windowchange={repaint} />
|
|
2093
|
+
</div>
|
|
2094
|
+
```
|
|
2095
|
+
|
|
2096
|
+
`query(text, options)` runs a search; `options.caseSensitive` and `options.wholeWord` (wraps the pattern in `\b...\b`) both default to `false`. `options.regex` treats `text` as a regular expression source instead of literal text -- capped at 256 characters and compiled in a `try`/`catch`, so an over-long or invalid pattern yields zero matches and sets `error()` rather than throwing. Empty `text` clears matches without an error. `matches()` returns every `{ line, start, end }` match in document order (never spanning a line); `count()` is its length. `current()`/`next()`/`prev()` return the selected match plus its `index` into `matches()`, wrapping around the ends; all return `undefined` before any query or with zero matches. `setSource(source)` swaps the document and re-runs an already-active query as a full rescan. `onChange(callback)` fires after every mutating call and returns an unsubscribe function.
|
|
2097
|
+
|
|
2098
|
+
`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.
|
|
2099
|
+
|
|
1860
2100
|
## Terminal Output
|
|
1861
2101
|
|
|
1862
2102
|
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, 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.
|
|
@@ -2063,10 +2303,26 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
|
|
|
2063
2303
|
|
|
2064
2304
|
`$$restProps` are forwarded to the top-level `button` element.
|
|
2065
2305
|
|
|
2306
|
+
#### CSS Variables
|
|
2307
|
+
|
|
2308
|
+
| Variable | Description | Default value |
|
|
2309
|
+
| :-------------------- | :----------------------------------- | :------------ |
|
|
2310
|
+
| --copy-top | Top offset of the button | `0.5em` |
|
|
2311
|
+
| --copy-right | Right offset of the button | `0.5em` |
|
|
2312
|
+
| --copy-size | Width and height of the button | `2em` |
|
|
2313
|
+
| --copy-padding | Inner padding of the button | `0.5em` |
|
|
2314
|
+
| --copy-background | Background color of the button | `inherit` |
|
|
2315
|
+
| --copy-color | Foreground color of the button | `inherit` |
|
|
2316
|
+
| --copy-border-radius | Border radius of the button | `4px` |
|
|
2317
|
+
| --copy-border | Border of the button | `none` |
|
|
2318
|
+
| --copy-z-index | Stacking order of the button | `2` |
|
|
2319
|
+
|
|
2066
2320
|
#### Dispatched Events
|
|
2067
2321
|
|
|
2068
2322
|
- **on:copy**: fired after a successful copy, with `{ code }` -- the `transform`-applied string, not the original `code` prop
|
|
2069
2323
|
- **on:error**: fired if the copy behavior throws, with `{ error }`
|
|
2324
|
+
- **on:mouseenter**: forwarded `MouseEvent`, useful for prefetching an async copy on hover
|
|
2325
|
+
- **on:mouseleave**: forwarded `MouseEvent`
|
|
2070
2326
|
|
|
2071
2327
|
```svelte
|
|
2072
2328
|
<CopyButton
|
|
@@ -2087,6 +2343,33 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
|
|
|
2087
2343
|
|
|
2088
2344
|
`$$restProps` are forwarded to the top-level `div` element.
|
|
2089
2345
|
|
|
2346
|
+
#### Slots
|
|
2347
|
+
|
|
2348
|
+
- **titlebar**: optional content rendered in the mirrored trailing region of the title bar (empty by default, which keeps the title centered)
|
|
2349
|
+
|
|
2350
|
+
#### CSS Variables
|
|
2351
|
+
|
|
2352
|
+
| Variable | Description | Default value |
|
|
2353
|
+
| :-------------------- | :---------------------------------------- | :---------------------------------- |
|
|
2354
|
+
| --window-background | Background color of the window body | `#1e1e1e` |
|
|
2355
|
+
| --window-border | Border of the window | `1px solid rgba(255, 255, 255, 0.1)`|
|
|
2356
|
+
| --window-radius | Corner radius of the window | `0` |
|
|
2357
|
+
| --titlebar-gap | Gap between items in the title bar | `0.5em` |
|
|
2358
|
+
| --titlebar-padding | Padding of the title bar | `0.65em 1em` |
|
|
2359
|
+
| --titlebar-background | Background color of the title bar | `#2d2d2d` |
|
|
2360
|
+
| --titlebar-border | Bottom border of the title bar | `1px solid rgba(255, 255, 255, 0.1)`|
|
|
2361
|
+
| --titlebar-color | Text color of the title bar | `rgba(255, 255, 255, 0.6)` |
|
|
2362
|
+
| --titlebar-font-family| Font family of the title bar | `system-ui, -apple-system, sans-serif`|
|
|
2363
|
+
| --titlebar-font-size | Font size of the title bar | `0.8125em` |
|
|
2364
|
+
| --dot-gap | Gap between the macOS traffic-light dots | `0.5em` |
|
|
2365
|
+
| --dot-size | Diameter of the macOS traffic-light dots | `0.75em` |
|
|
2366
|
+
| --dot-close | Color of the "close" traffic-light dot | `#ff5f56` |
|
|
2367
|
+
| --dot-minimize | Color of the "minimize" traffic-light dot| `#ffbd2e` |
|
|
2368
|
+
| --dot-maximize | Color of the "maximize" traffic-light dot| `#27c93f` |
|
|
2369
|
+
| --prompt-font-family | Font family of the terminal prompt | `ui-monospace, monospace` |
|
|
2370
|
+
| --prompt-font-weight | Font weight of the terminal prompt | `700` |
|
|
2371
|
+
| --prompt-color | Color of the terminal prompt | `inherit` |
|
|
2372
|
+
|
|
2090
2373
|
### `AnsiOutput`
|
|
2091
2374
|
|
|
2092
2375
|
#### Props
|
|
@@ -2236,6 +2519,10 @@ Use `bind:this`, then call `undo()`, `redo()`, `focus()`, `selectAll()`, `insert
|
|
|
2236
2519
|
|
|
2237
2520
|
`$$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.
|
|
2238
2521
|
|
|
2522
|
+
#### Methods
|
|
2523
|
+
|
|
2524
|
+
Use `bind:this`, then call `scrollToLine(line)` -- works in both `virtualize` and default modes.
|
|
2525
|
+
|
|
2239
2526
|
#### Dispatched Events
|
|
2240
2527
|
|
|
2241
2528
|
- **on:highlight**: fired after each highlight pass, with `{ highlighted }` -- not dispatched when `virtualize` is set
|
|
@@ -2252,6 +2539,44 @@ Use `bind:this`, then call `undo()`, `redo()`, `focus()`, `selectAll()`, `insert
|
|
|
2252
2539
|
/>
|
|
2253
2540
|
```
|
|
2254
2541
|
|
|
2542
|
+
### `MarkdownStream`
|
|
2543
|
+
|
|
2544
|
+
#### Props
|
|
2545
|
+
|
|
2546
|
+
| Name | Type | Default value |
|
|
2547
|
+
| :-------------- | :------------------------------------------------------------------------ | :----------------------------------- |
|
|
2548
|
+
| text | `string` | `""` |
|
|
2549
|
+
| done | `boolean` | `false` |
|
|
2550
|
+
| resolveLanguage | `(lang: string \| undefined, segment: FenceSegment) => LanguageType \| Promise<LanguageType> \| undefined` | resolves via `loadLanguage`, falling back to plaintext |
|
|
2551
|
+
| caret | `boolean` | `true` |
|
|
2552
|
+
| autoScroll | `boolean` | `true` |
|
|
2553
|
+
| doneText | `string` | `"Code finished streaming"` |
|
|
2554
|
+
|
|
2555
|
+
`$$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.
|
|
2556
|
+
|
|
2557
|
+
#### Slots
|
|
2558
|
+
|
|
2559
|
+
| Name | Props | Fallback |
|
|
2560
|
+
| :--- | :-------------------- | :----------------------------------------------------------------- |
|
|
2561
|
+
| text | `segment` | `<div class="shl-md-text">{segment.text}</div>` |
|
|
2562
|
+
| fence | `segment`, `language` | `<HighlightStream code={segment.code} {language} done={done \|\| !segment.open} caret={...} autoScroll={autoScroll} doneText={...} />` |
|
|
2563
|
+
|
|
2564
|
+
#### Dispatched Events
|
|
2565
|
+
|
|
2566
|
+
- **on:fence**: fired once, the first time a fence segment appears, with `{ id, lang }`
|
|
2567
|
+
- **on:done**: fired once when `done` becomes `true`
|
|
2568
|
+
|
|
2569
|
+
#### CSS Variables
|
|
2570
|
+
|
|
2571
|
+
| Variable | Description | Default value |
|
|
2572
|
+
| :----------------------- | :------------------------------------ | :------------- |
|
|
2573
|
+
| --md-gap | Gap between prose and fence segments | `1em` |
|
|
2574
|
+
| --md-text-white-space | `white-space` of the default prose block | `pre-wrap` |
|
|
2575
|
+
|
|
2576
|
+
```svelte
|
|
2577
|
+
<MarkdownStream {text} {done} on:fence={(e) => console.log(e.detail.lang)} />
|
|
2578
|
+
```
|
|
2579
|
+
|
|
2255
2580
|
### `HighlightVirtual`
|
|
2256
2581
|
|
|
2257
2582
|
#### Props
|
|
@@ -2331,10 +2656,30 @@ See [Large documents](#large-documents) above.
|
|
|
2331
2656
|
|
|
2332
2657
|
The highlighting engine's output is a flat scope-event stream (`ScopeEvent[]`): a sequence of `TEXT`/`OPEN`/`CLOSE` events that `renderHtml`, `toRanges`, and `tokenLines` each render differently. Every `<Highlight>`-family component exposes this stream (as `events`, in the default slot and the `highlight` event detail — see [Component API](#component-api) above), and `svelte-highlight/engine` + `svelte-highlight/registry` expose it directly, so highlighting can be consumed headlessly: server routes, build pipelines, tests, or any non-component context. `svelte-highlight/engine` has zero Svelte dependency and works in any JS runtime.
|
|
2333
2658
|
|
|
2659
|
+
### Zero-bundler usage from a CDN
|
|
2660
|
+
|
|
2661
|
+
`svelte-highlight/engine` has no `import` statements of its own, so it — and any generated language grammar — can be loaded straight from a CDN like [esm.sh](https://esm.sh), with no bundler, build step, or Svelte in the loop:
|
|
2662
|
+
|
|
2663
|
+
```html
|
|
2664
|
+
<script type="module">
|
|
2665
|
+
import { createRegistry, registerAll, renderHtml } from "https://esm.sh/svelte-highlight/engine";
|
|
2666
|
+
import typescript from "https://esm.sh/svelte-highlight/languages/typescript";
|
|
2667
|
+
|
|
2668
|
+
const registry = createRegistry();
|
|
2669
|
+
registerAll(registry, typescript);
|
|
2670
|
+
|
|
2671
|
+
const { events } = registry.tokenize("const greeting: string = 'hi';", "typescript");
|
|
2672
|
+
document.querySelector("pre").innerHTML = renderHtml(events);
|
|
2673
|
+
</script>
|
|
2674
|
+
```
|
|
2675
|
+
|
|
2676
|
+
See it as a complete page in [examples/cdn](examples/cdn).
|
|
2677
|
+
|
|
2334
2678
|
### Stability tiers
|
|
2335
2679
|
|
|
2336
|
-
- **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`. `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`/`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.
|
|
2680
|
+
- **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`/`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.
|
|
2337
2681
|
- **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.
|
|
2682
|
+
- **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.
|
|
2338
2683
|
|
|
2339
2684
|
### Headless highlighting, isolated registry
|
|
2340
2685
|
|
|
@@ -2379,6 +2724,45 @@ const snapshot = session.snapshot(); // JSON-serializable checkpoint
|
|
|
2379
2724
|
const { value } = session.finish();
|
|
2380
2725
|
```
|
|
2381
2726
|
|
|
2727
|
+
### Highlighting in a Web Worker
|
|
2728
|
+
|
|
2729
|
+
`svelte-highlight/worker` is a headless pair — a worker-side handler and a main-thread client — for running the engine off the main thread. Both halves have zero Svelte dependency.
|
|
2730
|
+
|
|
2731
|
+
```js
|
|
2732
|
+
// highlight.worker.js
|
|
2733
|
+
import { serveHighlighter } from "svelte-highlight/worker";
|
|
2734
|
+
serveHighlighter();
|
|
2735
|
+
```
|
|
2736
|
+
|
|
2737
|
+
```js
|
|
2738
|
+
import { createWorkerHighlighter } from "svelte-highlight/worker";
|
|
2739
|
+
|
|
2740
|
+
const highlighter = createWorkerHighlighter(
|
|
2741
|
+
typeof Worker !== "undefined"
|
|
2742
|
+
? new Worker(new URL("./highlight.worker.js", import.meta.url), { type: "module" })
|
|
2743
|
+
: undefined,
|
|
2744
|
+
);
|
|
2745
|
+
```
|
|
2746
|
+
|
|
2747
|
+
An omitted (or falsy) `worker` runs the identical API in-process against `svelte-highlight/registry`'s shared singleton instead — the SSR/tests fallback, and why the construction above is a single ternary: the same code works whether or not `Worker` exists in the current environment.
|
|
2748
|
+
|
|
2749
|
+
```js
|
|
2750
|
+
const { value } = await highlighter.highlight(code, "typescript");
|
|
2751
|
+
const lines = await highlighter.tokenLines(code, "typescript");
|
|
2752
|
+
```
|
|
2753
|
+
|
|
2754
|
+
Streaming works the same way as `registry.createSession`, just async:
|
|
2755
|
+
|
|
2756
|
+
```js
|
|
2757
|
+
const session = highlighter.createSession("typescript");
|
|
2758
|
+
await session.append(chunk); // repeat as chunks arrive
|
|
2759
|
+
await session.replace(from, to, text); // patch an earlier range without restarting
|
|
2760
|
+
const snapshot = await session.snapshot(); // JSON-serializable checkpoint
|
|
2761
|
+
const { value } = await session.finish();
|
|
2762
|
+
```
|
|
2763
|
+
|
|
2764
|
+
Grammars load lazily inside the worker, per language, the first time each is seen. `HighlightStream` can't yet consume a remote, worker-backed session — its incremental rendering assumes a same-thread `StreamSession` — so streaming highlight results back into a component still requires posting the resolved HTML/events yourself. `terminate()` tears down the underlying `Worker` (a no-op in local mode).
|
|
2765
|
+
|
|
2382
2766
|
### Reaching the stream from a component — no HTML re-parsing
|
|
2383
2767
|
|
|
2384
2768
|
```svelte
|
|
@@ -2414,6 +2798,17 @@ const myRenderer = {
|
|
|
2414
2798
|
};
|
|
2415
2799
|
```
|
|
2416
2800
|
|
|
2801
|
+
### Errors
|
|
2802
|
+
|
|
2803
|
+
- **`UnknownLanguageError`** (`{ language }`): thrown by `tokenize`, `highlight`, `tokenizeRanges`, and `createSession` when `language` isn't registered.
|
|
2804
|
+
- **`TokenizerLoopError`** (`{ grammarName, iterations }`): thrown once a parse exceeds 500,000 tokenizer iterations, guarding against a grammar bug that never advances position.
|
|
2805
|
+
|
|
2806
|
+
Both are exported from `svelte-highlight/engine` and are distinct from `LanguageLoadError` (exported from `svelte-highlight` and `svelte-highlight/load-language`), which fires from a grammar module's *dynamic import* failure, not a registry lookup.
|
|
2807
|
+
|
|
2808
|
+
### `illegal` is enforced only during auto-detection
|
|
2809
|
+
|
|
2810
|
+
A grammar's `illegal` pattern only aborts `tokenizeAuto`/`highlightAuto`: a candidate whose text matches its own `illegal` pattern loses relevance scoring and is dropped from consideration. An explicit `tokenize`/`highlight`/`createSession` call never checks it, unlike hljs's own `ignoreIllegals: false` default, which throws on the same condition. This is deliberate: streamed or LLM-generated code is routinely "illegal" mid-stream — an unclosed string, a dangling `#` — and an explicit-language highlighter that could throw partway through a stream would be unusable for that case. For hljs-style strict validation, run `highlightAuto(code, [language])` instead.
|
|
2811
|
+
|
|
2417
2812
|
## [Supported Languages](SUPPORTED_LANGUAGES.md)
|
|
2418
2813
|
|
|
2419
2814
|
## [Supported Styles](SUPPORTED_STYLES.md)
|
|
@@ -2428,6 +2823,7 @@ By default, example set-ups use Svelte 5. The exception is `examples/vite@svelte
|
|
|
2428
2823
|
- [examples/vite](examples/vite)
|
|
2429
2824
|
- [examples/vite@svelte-4](examples/vite@svelte-4)
|
|
2430
2825
|
- [examples/webpack](examples/webpack)
|
|
2826
|
+
- [examples/worker](examples/worker)
|
|
2431
2827
|
|
|
2432
2828
|
## [Changelog](CHANGELOG.md)
|
|
2433
2829
|
|
package/action.d.ts
CHANGED
|
@@ -3,9 +3,13 @@ import type { LanguageType } from "./languages";
|
|
|
3
3
|
|
|
4
4
|
export type HighlightActionParameters = {
|
|
5
5
|
/**
|
|
6
|
-
* Language used to highlight the element's contents.
|
|
6
|
+
* Language used to highlight the element's contents. When omitted, the
|
|
7
|
+
* action reads a `language-xxx` class off the node itself (the
|
|
8
|
+
* Prism/highlight.js Markdown convention) and resolves it via
|
|
9
|
+
* `loadLanguage`. No `language` prop and no matching class dispatches
|
|
10
|
+
* `error` and leaves the content untouched.
|
|
7
11
|
*/
|
|
8
|
-
language
|
|
12
|
+
language?: LanguageType<string>;
|
|
9
13
|
|
|
10
14
|
/**
|
|
11
15
|
* Code to highlight. When omitted, the element's
|
|
@@ -16,5 +20,15 @@ export type HighlightActionParameters = {
|
|
|
16
20
|
|
|
17
21
|
/**
|
|
18
22
|
* Highlight element contents in place with highlight.js.
|
|
23
|
+
*
|
|
24
|
+
* Should be placed on the `<code>` element inside a `<pre>`, matching the
|
|
25
|
+
* theme CSS's `.hljs code` selector -- elsewhere (directly on `<pre>`, or a
|
|
26
|
+
* non-`<pre><code>` element) it still highlights but may not be visually
|
|
27
|
+
* targeted by the active theme.
|
|
28
|
+
*
|
|
29
|
+
* Dispatches two events on the node:
|
|
30
|
+
* - `highlighted`: `detail: { html: string; language: string }`, after a
|
|
31
|
+
* successful highlight.
|
|
32
|
+
* - `error`: `detail: { error: unknown }`, after a failed highlight.
|
|
19
33
|
*/
|
|
20
34
|
export declare const highlight: Action<HTMLElement, HighlightActionParameters>;
|