svelte-highlight 7.23.2 → 7.25.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 (157) 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/abap.d.ts +2 -0
  79. package/languages/abap.js +2 -0
  80. package/languages/aliases.js +1 -1
  81. package/languages/all.js +18 -1
  82. package/languages/angular.js +1 -1
  83. package/languages/antlr.d.ts +2 -0
  84. package/languages/antlr.js +2 -0
  85. package/languages/apex.d.ts +2 -0
  86. package/languages/apex.js +2 -0
  87. package/languages/bash.js +1 -1
  88. package/languages/cobol.d.ts +2 -0
  89. package/languages/cobol.js +2 -0
  90. package/languages/coq.js +1 -1
  91. package/languages/cpp.js +1 -1
  92. package/languages/csharp.js +1 -1
  93. package/languages/css.js +1 -1
  94. package/languages/cython.d.ts +2 -0
  95. package/languages/cython.js +2 -0
  96. package/languages/dart.js +1 -1
  97. package/languages/detect-index.d.ts +16 -0
  98. package/languages/detect-index.js +6 -0
  99. package/languages/fluent.d.ts +2 -0
  100. package/languages/fluent.js +2 -0
  101. package/languages/freemarker.d.ts +2 -0
  102. package/languages/freemarker.js +3 -0
  103. package/languages/handlebars.js +1 -1
  104. package/languages/httpfile.d.ts +2 -0
  105. package/languages/httpfile.js +3 -0
  106. package/languages/index.d.ts +34 -0
  107. package/languages/index.js +17 -0
  108. package/languages/jinja.js +1 -1
  109. package/languages/json.js +1 -1
  110. package/languages/kotlin.js +1 -1
  111. package/languages/lex.d.ts +2 -0
  112. package/languages/lex.js +3 -0
  113. package/languages/lisp.js +1 -1
  114. package/languages/loaders.d.ts +8 -0
  115. package/languages/loaders.js +387 -0
  116. package/languages/mathematica.js +1 -1
  117. package/languages/meson.d.ts +2 -0
  118. package/languages/meson.js +2 -0
  119. package/languages/metal.d.ts +2 -0
  120. package/languages/metal.js +2 -0
  121. package/languages/mlir.d.ts +2 -0
  122. package/languages/mlir.js +2 -0
  123. package/languages/mojo.js +1 -1
  124. package/languages/nextflow.js +1 -1
  125. package/languages/objectivec.js +1 -1
  126. package/languages/pgsql.js +1 -1
  127. package/languages/php.js +1 -1
  128. package/languages/po.d.ts +2 -0
  129. package/languages/po.js +2 -0
  130. package/languages/riscv.d.ts +2 -0
  131. package/languages/riscv.js +2 -0
  132. package/languages/robotframework.d.ts +2 -0
  133. package/languages/robotframework.js +2 -0
  134. package/languages/roc.js +1 -1
  135. package/languages/solidity.js +1 -1
  136. package/languages/sshconfig.d.ts +2 -0
  137. package/languages/sshconfig.js +2 -0
  138. package/languages/svelte.js +1 -1
  139. package/languages/uiua.js +1 -1
  140. package/languages/verilog.js +1 -1
  141. package/languages/vim.js +1 -1
  142. package/languages/yacc.d.ts +2 -0
  143. package/languages/yacc.js +3 -0
  144. package/languages/zig.js +1 -1
  145. package/package.json +50 -2
  146. package/preprocessor.js +20 -5
  147. package/search.js +2 -2
  148. package/stream-highlighter.js +198 -0
  149. package/stream.css +16 -0
  150. package/stream.d.ts +60 -0
  151. package/stream.js +283 -0
  152. package/style-registry.js +34 -3
  153. package/themes/_base-css.d.ts +1 -0
  154. package/themes/_base-css.js +1 -0
  155. package/typewriter-units.d.ts +3 -0
  156. package/typewriter-units.js +43 -0
  157. package/virtual-window.js +9 -4
@@ -0,0 +1,76 @@
1
+ import type { SvelteComponentTyped } from "svelte";
2
+ import type { HTMLAttributes } from "svelte/elements";
3
+ import type { Row } from "./diff";
4
+ import type { Annotation, DiffController } from "./diff-controller";
5
+
6
+ export type DiffViewProps = HTMLAttributes<HTMLElement> & {
7
+ /** A controller from `createDiffController`. */
8
+ diff: DiffController;
9
+
10
+ /**
11
+ * While streaming, keep the newest row in view until the reader scrolls.
12
+ * @default true
13
+ */
14
+ follow?: boolean;
15
+
16
+ /**
17
+ * Show accept/reject buttons on each change. Filling the `actions` slot
18
+ * shows it without this.
19
+ * @default false
20
+ */
21
+ review?: boolean;
22
+
23
+ /**
24
+ * Wrap long lines instead of scrolling each side sideways. Rows are
25
+ * measured, so wrapped rows keep virtualization.
26
+ * @default false
27
+ */
28
+ wrap?: boolean;
29
+
30
+ /** @default "default" */
31
+ palette?: "default" | "colorblind";
32
+
33
+ /**
34
+ * Extra rows rendered above and below the viewport.
35
+ * @default 10
36
+ */
37
+ overscan?: number;
38
+
39
+ /**
40
+ * Handle n/p (next/previous change), e/c (expand/collapse), v (view),
41
+ * and a/r/u (accept/reject/undo, with `review`) while focused.
42
+ * @default true
43
+ */
44
+ keyboard?: boolean;
45
+
46
+ /**
47
+ * Render only the rows in view. `"auto"` virtualizes past 500 rows, so
48
+ * small diffs keep browser find (Ctrl/Cmd+F), printing, and server
49
+ * rendering of every row.
50
+ * @default "auto"
51
+ */
52
+ virtualize?: "auto" | boolean;
53
+ };
54
+
55
+ export type DiffViewSlots = {
56
+ /** Replaces a fold row. */
57
+ fold: {
58
+ fold: NonNullable<Row["fold"]>;
59
+ count: number | undefined;
60
+ toggle: () => void;
61
+ };
62
+ /** Replaces an annotation card. The row grows to fit it. */
63
+ note: { note: Annotation };
64
+ /** Controls shown on the first row of each change. */
65
+ actions: {
66
+ change: number;
67
+ decision: "accepted" | "rejected" | undefined;
68
+ decide: (decision: "accepted" | "rejected" | undefined) => void;
69
+ };
70
+ };
71
+
72
+ export default class DiffView extends SvelteComponentTyped<
73
+ DiffViewProps,
74
+ Record<string, never>,
75
+ DiffViewSlots
76
+ > {}
package/FileTabs.svelte CHANGED
@@ -20,7 +20,7 @@
20
20
  let root;
21
21
 
22
22
  /** @type {HTMLButtonElement[]} */
23
- let tabs = [];
23
+ const tabs = [];
24
24
 
25
25
  // Used to pick a neighbor when the active file disappears from `files`.
26
26
  let lastValidIndex = -1;
@@ -133,10 +133,7 @@
133
133
  class:active={file === active}
134
134
  aria-controls="{baseId}-panel"
135
135
  tabindex={file === active ? 0 : -1}
136
- {...{
137
- // Spread sidesteps Biome `useValidAriaValues` on templated booleans.
138
- "aria-selected": file === active,
139
- }}
136
+ aria-selected={file === active}
140
137
  on:click={() => selectTab(file)}
141
138
  on:keydown={(event) => handleKeydown(event, index)}
142
139
  >
package/Highlight.svelte CHANGED
@@ -1,3 +1,32 @@
1
+ <script context="module">
2
+ let instanceCount = 0;
3
+ function nextInstanceId() {
4
+ return ++instanceCount;
5
+ }
6
+
7
+ /**
8
+ * The resolver loads on first paint, so `"dom"`-only pages don't bundle
9
+ * it. One load serves every instance.
10
+ * @type {Promise<typeof import("./highlight-cascade.js")> | undefined}
11
+ */
12
+ let cascadeLoad;
13
+
14
+ /** @type {typeof import("./highlight-cascade.js") | undefined} */
15
+ let cascadeModule;
16
+
17
+ function loadCascade() {
18
+ // A static specifier, so bundlers split the module into its own chunk.
19
+ cascadeLoad ??= import("./highlight-cascade.js").then(
20
+ (module) => (cascadeModule = module),
21
+ (error) => {
22
+ cascadeLoad = undefined;
23
+ throw error;
24
+ },
25
+ );
26
+ return cascadeLoad;
27
+ }
28
+ </script>
29
+
1
30
  <script>
2
31
  /** @type {import("./languages").LanguageType<string>} */
3
32
  export let language;
@@ -11,7 +40,30 @@
11
40
  /** @type {boolean} */
12
41
  export let wrap = false;
13
42
 
14
- import { afterUpdate, createEventDispatcher } from "svelte";
43
+ /**
44
+ * Rendering engine. `"css-highlights"` paints tokens via the CSS Custom
45
+ * Highlight API over plain text instead of a `<span>` per token, falling
46
+ * back to `"dom"` where unsupported. SSR renders `"dom"` markup; the swap
47
+ * happens after mount. No effect with a custom default slot.
48
+ * @type {"dom" | "css-highlights"}
49
+ */
50
+ export let engine = "dom";
51
+
52
+ /**
53
+ * Theme CSS or `ThemePalette` for `::highlight()` rules (`"css-highlights"`
54
+ * only). Each token gets the color and background the `"dom"` engine's
55
+ * markup would get. Bold and italic are dropped. Without a theme, the
56
+ * text stays plain.
57
+ * @type {string | import("./theme.d.ts").ThemePalette | undefined}
58
+ */
59
+ export let theme = undefined;
60
+
61
+ import { afterUpdate, createEventDispatcher, onMount } from "svelte";
62
+ import {
63
+ createScopeHighlights,
64
+ paintTokenRanges,
65
+ resolveEngine,
66
+ } from "./css-highlights.js";
15
67
  import LangTag from "./LangTag.svelte";
16
68
  import { ensureRegistered, registry } from "./registry.js";
17
69
 
@@ -21,6 +73,10 @@
21
73
  */
22
74
  const dispatch = createEventDispatcher();
23
75
 
76
+ // Distinct from HighlightEditable's numeric ids, so names never clash.
77
+ const highlightPrefix = `hljs-highlight-${nextInstanceId()}`;
78
+ const cssHighlights = createScopeHighlights(highlightPrefix);
79
+
24
80
  /** @type {string} */
25
81
  let highlighted = "";
26
82
 
@@ -30,13 +86,106 @@
30
86
  /** @type {import("./engine.d.ts").ScopeEvent[] | undefined} */
31
87
  let lastDispatchedEvents;
32
88
 
89
+ /** @type {HTMLElement | undefined} */
90
+ let codeElement;
91
+
92
+ let mounted = false;
93
+
94
+ /** The resolver, once loaded. */
95
+ let cascadeApi = cascadeModule;
96
+
97
+ /**
98
+ * What the current ranges were painted from, if any.
99
+ * @type {{ runs: unknown; code: HTMLElement; text: Node | null } | undefined}
100
+ */
101
+ let painted;
102
+
103
+ $: resolvedEngineValue = resolveEngine(engine);
104
+ // Wait for mount, so hydration sees the same markup as SSR.
105
+ $: wantsPainting = mounted && resolvedEngineValue === "css-highlights";
106
+ $: if (wantsPainting && !cascadeApi) {
107
+ loadCascade().then(
108
+ (module) => {
109
+ // Unmounted meanwhile: paint nothing. Otherwise the reactive
110
+ // statements below paint the latest props.
111
+ if (mounted) cascadeApi = module;
112
+ },
113
+ () => {
114
+ // Keep the "dom" markup.
115
+ },
116
+ );
117
+ }
118
+ // When painting, LangTag gets an empty `highlighted` and renders `code` as
119
+ // plain text. Until the resolver loads, keep the "dom" markup, so the code
120
+ // never shows as plain text without colors.
121
+ $: painting = wantsPainting && cascadeApi !== undefined;
122
+ $: cascade =
123
+ painting && cascadeApi && theme !== undefined
124
+ ? cascadeApi.createThemeCascade(theme, outsideColor)
125
+ : undefined;
126
+ // One range per run of text, named by its resolved color and background.
127
+ $: runs =
128
+ cascade && cascadeApi
129
+ ? cascadeApi.cascadeRanges(events, cascade)
130
+ : undefined;
131
+ $: cssHighlightStyle =
132
+ runs && cascadeApi
133
+ ? cascadeApi.cascadeHighlightStyle(runs.styles, highlightPrefix)
134
+ : "";
135
+
136
+ /** The color the `<pre>` inherits, for themes that use `currentColor`. */
137
+ function outsideColor() {
138
+ const outside = codeElement?.closest("pre")?.parentElement;
139
+ return outside ? getComputedStyle(outside).color : null;
140
+ }
141
+
142
+ function paint() {
143
+ if (!painting || !codeElement || !runs) {
144
+ if (painted) {
145
+ cssHighlights.clear();
146
+ painted = undefined;
147
+ }
148
+ return;
149
+ }
150
+ const text = codeElement.firstChild;
151
+ if (
152
+ painted?.runs === runs &&
153
+ painted.code === codeElement &&
154
+ painted.text === text
155
+ ) {
156
+ return;
157
+ }
158
+ cssHighlights.clear();
159
+ paintTokenRanges(cssHighlights, codeElement, runs.ranges);
160
+ painted = { runs, code: codeElement, text };
161
+ }
162
+
33
163
  afterUpdate(() => {
34
164
  if (events !== lastDispatchedEvents) {
35
165
  lastDispatchedEvents = events;
36
166
  dispatch("highlight", { highlighted, events });
37
167
  }
168
+ paint();
38
169
  });
39
170
 
171
+ onMount(() => {
172
+ mounted = true;
173
+ return () => {
174
+ mounted = false;
175
+ cssHighlights.clear();
176
+ };
177
+ });
178
+
179
+ /**
180
+ * The engine on screen. `"css-highlights"` once it paints. `"dom"`
181
+ * before mount, where `CSS.highlights` is missing, until the color
182
+ * resolver loads, for good if that load fails, and with a custom
183
+ * default slot.
184
+ */
185
+ export function resolvedEngine() {
186
+ return painting && codeElement ? "css-highlights" : "dom";
187
+ }
188
+
40
189
  $: {
41
190
  ensureRegistered(language);
42
191
  const source = String(code ?? "");
@@ -46,13 +195,20 @@
46
195
  }
47
196
  </script>
48
197
 
198
+ <svelte:head
199
+ >{#if cssHighlightStyle}
200
+ {@html cssHighlightStyle}
201
+ {/if}</svelte:head
202
+ >
203
+
49
204
  <slot {highlighted} {langtag} {wrap} languageName={language.name} {events}>
50
205
  <LangTag
51
206
  {...$$restProps}
52
207
  languageName={language.name}
53
208
  {langtag}
54
209
  {wrap}
55
- {highlighted}
210
+ highlighted={painting ? "" : highlighted}
56
211
  {code}
212
+ bind:codeElement
57
213
  />
58
214
  </slot>
@@ -2,6 +2,7 @@ import type { SvelteComponentTyped } from "svelte";
2
2
  import type { HTMLAttributes } from "svelte/elements";
3
3
  import type { ScopeEvent } from "./engine.d.ts";
4
4
  import type { LanguageType } from "./languages";
5
+ import type { ThemePalette } from "./theme.d.ts";
5
6
 
6
7
  export type LangtagProps = {
7
8
  /**
@@ -40,8 +41,19 @@ export type LangtagProps = {
40
41
  wrap?: boolean;
41
42
  };
42
43
 
44
+ export type CodeRegionProps = {
45
+ /**
46
+ * Accessible name of the scrollable code region. The region is
47
+ * keyboard-focusable so keyboard users can scroll it. Inside a
48
+ * `CodeWindow`, the window's `title` or `label` is the default.
49
+ * @default "Code"
50
+ */
51
+ label?: string;
52
+ };
53
+
43
54
  export type HighlightProps = HTMLAttributes<HTMLPreElement> &
44
- LangtagProps & {
55
+ LangtagProps &
56
+ CodeRegionProps & {
45
57
  /**
46
58
  * Code to highlight. The container also reads `--overflow-x`,
47
59
  * `--overflow-y`, `--border-radius`, `--width`, and `--max-width`.
@@ -54,6 +66,34 @@ export type HighlightProps = HTMLAttributes<HTMLPreElement> &
54
66
  * import typescript from "svelte-highlight/languages/typescript";
55
67
  */
56
68
  language: LanguageType<string>;
69
+
70
+ /**
71
+ * Rendering engine. `"css-highlights"` paints tokens with the CSS
72
+ * Custom Highlight API (`CSS.highlights`) over plain text, instead of
73
+ * a `<span>` per token. Falls back to `"dom"` where `CSS.highlights`
74
+ * is missing; check with `resolvedEngine()`.
75
+ *
76
+ * SSR always renders the `"dom"` markup. The swap to plain text
77
+ * happens after mount. Has no effect with a custom default slot.
78
+ *
79
+ * Colors only: `::highlight()` ignores `font-weight` and
80
+ * `font-style`, so bold and italic are dropped. Underlines are
81
+ * dropped too.
82
+ * @default "dom"
83
+ */
84
+ engine?: "dom" | "css-highlights";
85
+
86
+ /**
87
+ * Theme for the `"css-highlights"` engine's `::highlight()` rules:
88
+ * theme CSS from `svelte-highlight/styles/*`, or a `ThemePalette`
89
+ * from `svelte-highlight/themes/*`. Each token gets the `color` and
90
+ * `background-color` that the theme gives its `<span>` in the `"dom"`
91
+ * engine. Without a theme, the text stays plain. Ignored by the
92
+ * `"dom"` engine.
93
+ * @example
94
+ * import github from "svelte-highlight/styles/github";
95
+ */
96
+ theme?: string | ThemePalette;
57
97
  };
58
98
 
59
99
  export type HighlightEvents = {
@@ -81,4 +121,12 @@ export default class Highlight extends SvelteComponentTyped<
81
121
  HighlightProps,
82
122
  HighlightEvents,
83
123
  HighlightSlots
84
- > {}
124
+ > {
125
+ /**
126
+ * The engine on screen. `"css-highlights"` once it paints. `"dom"`
127
+ * before mount, where `CSS.highlights` is missing, until the color
128
+ * resolver loads, for good if that load fails, and with a custom
129
+ * default slot.
130
+ */
131
+ resolvedEngine(): "dom" | "css-highlights";
132
+ }
@@ -1,11 +1,12 @@
1
1
  import type { SvelteComponentTyped } from "svelte";
2
2
  import type { HTMLAttributes } from "svelte/elements";
3
3
  import type { ScopeEvent } from "./engine.d.ts";
4
- import type { LangtagProps } from "./Highlight.svelte";
4
+ import type { CodeRegionProps, LangtagProps } from "./Highlight.svelte";
5
5
  import type { LanguageName } from "./languages";
6
6
 
7
7
  export type HighlightAutoProps = HTMLAttributes<HTMLPreElement> &
8
- LangtagProps & {
8
+ LangtagProps &
9
+ CodeRegionProps & {
9
10
  /** Code to highlight. */
10
11
  code: any;
11
12
 
@@ -0,0 +1,112 @@
1
+ <script>
2
+ import LangTag from "./LangTag.svelte";
3
+
4
+ /** @type {any} */
5
+ export let code;
6
+
7
+ /** @type {(import("./languages").LanguageName | (string & {}))[] | undefined} */
8
+ export let languageNames = undefined;
9
+
10
+ /** @type {boolean} */
11
+ export let langtag = false;
12
+
13
+ /** @type {boolean} */
14
+ export let wrap = false;
15
+
16
+ import { afterUpdate, createEventDispatcher, onMount } from "svelte";
17
+ import { highlightAutoIfLoaded, highlightAutoLazy } from "./auto-detect.js";
18
+ import { escapeHtml, TEXT } from "./engine.js";
19
+
20
+ /**
21
+ * @typedef {{ highlighted: string; language: string; events: import("./engine.d.ts").ScopeEvent[]; secondBest?: { language: string | undefined; relevance: number } }} HighlightEventDetail
22
+ * @type {import("svelte").EventDispatcher<{ highlight: HighlightEventDetail}>}
23
+ */
24
+ const dispatch = createEventDispatcher();
25
+
26
+ /** @type {string} */
27
+ let highlighted = "";
28
+
29
+ /** @type {string} */
30
+ let language = "";
31
+
32
+ /** @type {import("./engine.d.ts").ScopeEvent[]} */
33
+ let events = [];
34
+
35
+ /** @type {{ language: string | undefined; relevance: number } | undefined} */
36
+ let secondBest;
37
+
38
+ // True once `events` holds a detection result, not the plain-text
39
+ // placeholder. Only results dispatch `highlight`.
40
+ let detected = false;
41
+
42
+ /** @type {import("./engine.d.ts").ScopeEvent[] | undefined} */
43
+ let lastDispatchedEvents;
44
+
45
+ afterUpdate(() => {
46
+ if (detected && events !== lastDispatchedEvents) {
47
+ lastDispatchedEvents = events;
48
+ dispatch("highlight", { highlighted, language, events, secondBest });
49
+ }
50
+ });
51
+
52
+ /** @param {string} source */
53
+ function showPlainText(source) {
54
+ highlighted = escapeHtml(source);
55
+ language = "";
56
+ events = [{ t: TEXT, v: source }];
57
+ secondBest = undefined;
58
+ detected = false;
59
+ }
60
+
61
+ /** @param {import("./engine.d.ts").HighlightResult} result */
62
+ function showResult(result) {
63
+ highlighted = result.value;
64
+ language = result.language ?? "";
65
+ events = result.events;
66
+ secondBest = result.secondBest;
67
+ detected = true;
68
+ }
69
+
70
+ // Bumped on every run, so a slow load for older `code` can't overwrite
71
+ // the result for newer `code`.
72
+ let run = 0;
73
+
74
+ /**
75
+ * @param {string} source
76
+ * @param {string[] | undefined} names
77
+ */
78
+ async function detect(source, names) {
79
+ const id = ++run;
80
+ const options = { languageNames: names };
81
+ const ready = highlightAutoIfLoaded(source, options);
82
+ if (ready) {
83
+ showResult(ready);
84
+ return;
85
+ }
86
+ showPlainText(source);
87
+ const result = await highlightAutoLazy(source, options);
88
+ if (id === run) showResult(result);
89
+ }
90
+
91
+ // Server and first client render both show plain text, so hydration
92
+ // matches. Detection starts after mount.
93
+ let mounted = false;
94
+ onMount(() => {
95
+ mounted = true;
96
+ });
97
+
98
+ $: source = String(code ?? "");
99
+ $: if (!mounted) showPlainText(source);
100
+ $: if (mounted) detect(source, languageNames);
101
+ </script>
102
+
103
+ <slot {highlighted} {langtag} {wrap} languageName={language} {events}>
104
+ <LangTag
105
+ {...$$restProps}
106
+ languageName={language}
107
+ {langtag}
108
+ {wrap}
109
+ {highlighted}
110
+ {code}
111
+ />
112
+ </slot>
@@ -0,0 +1,66 @@
1
+ import type { SvelteComponentTyped } from "svelte";
2
+ import type { HTMLAttributes } from "svelte/elements";
3
+ import type { ScopeEvent } from "./engine.d.ts";
4
+ import type { CodeRegionProps, LangtagProps } from "./Highlight.svelte";
5
+ import type { LanguageName } from "./languages";
6
+
7
+ export type HighlightAutoLazyProps = HTMLAttributes<HTMLPreElement> &
8
+ LangtagProps &
9
+ CodeRegionProps & {
10
+ /** Code to highlight. */
11
+ code: any;
12
+
13
+ /**
14
+ * Detect among these grammars only. Skips the fingerprint step and
15
+ * loads each named grammar on demand. Use canonical names.
16
+ * @example ["javascript", "typescript"]
17
+ */
18
+ languageNames?: (LanguageName | (string & {}))[];
19
+ };
20
+
21
+ export type HighlightAutoLazyEvents = {
22
+ /**
23
+ * Fires when a detection result renders. Does not fire for the
24
+ * plain-text placeholder shown during SSR and while grammars load.
25
+ */
26
+ highlight: CustomEvent<{
27
+ /** The highlighted HTML. */
28
+ highlighted: string;
29
+
30
+ /** The detected language name, e.g. `"css"`. */
31
+ language: string;
32
+
33
+ /** Scope events behind `highlighted` (see `svelte-highlight/engine`). */
34
+ events: ScopeEvent[];
35
+
36
+ /**
37
+ * Runner-up candidate and its relevance score; `undefined` when no other
38
+ * candidate scored above zero.
39
+ */
40
+ secondBest?: { language: string | undefined; relevance: number };
41
+ }>;
42
+ };
43
+
44
+ export type HighlightAutoLazySlots = {
45
+ default: {
46
+ /** The highlighted HTML. */
47
+ highlighted: string;
48
+
49
+ /** Scope events behind `highlighted` (see `svelte-highlight/engine`). */
50
+ events: ScopeEvent[];
51
+ };
52
+ };
53
+
54
+ /**
55
+ * Like `HighlightAuto`, but does not import every grammar. It scores the
56
+ * code against a small fingerprint index, loads only a few likely
57
+ * grammars, and lets the relevance engine pick among them and every
58
+ * grammar already registered.
59
+ *
60
+ * Renders plain text during SSR and until the grammars load.
61
+ */
62
+ export default class HighlightAutoLazy extends SvelteComponentTyped<
63
+ HighlightAutoLazyProps,
64
+ HighlightAutoLazyEvents,
65
+ HighlightAutoLazySlots
66
+ > {}