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
@@ -0,0 +1,90 @@
1
+ <script>
2
+ /**
3
+ * Accessible name and tooltip. Required for an icon-only button.
4
+ * @type {string}
5
+ */
6
+ export let label;
7
+
8
+ /**
9
+ * Set for a toggle button. Sets `aria-pressed` and the pressed style.
10
+ * @type {boolean | undefined}
11
+ */
12
+ export let pressed = undefined;
13
+
14
+ /**
15
+ * Renders a link instead of a button.
16
+ * @type {string | undefined}
17
+ */
18
+ export let href = undefined;
19
+
20
+ // A link can't be pressed, so only a button gets aria-pressed.
21
+ $: stateAttrs = href ? {} : { type: "button", "aria-pressed": pressed };
22
+ </script>
23
+
24
+ <svelte:element
25
+ this={href ? "a" : "button"}
26
+ {href}
27
+ aria-label={label}
28
+ {...stateAttrs}
29
+ title={label}
30
+ on:click
31
+ {...$$restProps}
32
+ class={["shl-toolbar-button", $$restProps.class].filter(Boolean).join(" ")}
33
+ ><slot /></svelte:element
34
+ >
35
+
36
+ <style>
37
+ .shl-toolbar-button {
38
+ display: inline-flex;
39
+ align-items: center;
40
+ justify-content: center;
41
+ gap: var(--toolbar-button-gap, 0.4em);
42
+ min-width: var(--toolbar-button-size, 2em);
43
+ height: var(--toolbar-button-size, 2em);
44
+ padding: var(--toolbar-button-padding, 0.3em);
45
+ background: var(--toolbar-button-background, transparent);
46
+ color: var(
47
+ --toolbar-button-color,
48
+ color-mix(in srgb, currentColor 72%, transparent)
49
+ );
50
+ border-radius: var(--toolbar-button-border-radius, 6px);
51
+ border: var(--toolbar-button-border, none);
52
+ font: inherit;
53
+ font-size: var(--toolbar-button-font-size, inherit);
54
+ line-height: 1;
55
+ text-decoration: none;
56
+ cursor: pointer;
57
+ transition:
58
+ background-color 120ms ease,
59
+ color 120ms ease;
60
+ }
61
+
62
+ .shl-toolbar-button:hover {
63
+ background: var(
64
+ --toolbar-button-hover-background,
65
+ color-mix(in srgb, currentColor 12%, transparent)
66
+ );
67
+ color: inherit;
68
+ }
69
+
70
+ .shl-toolbar-button[aria-pressed="true"],
71
+ .shl-toolbar-button:active {
72
+ background: var(
73
+ --toolbar-button-pressed-background,
74
+ color-mix(in srgb, currentColor 18%, transparent)
75
+ );
76
+ color: inherit;
77
+ }
78
+
79
+ .shl-toolbar-button:focus-visible {
80
+ color: inherit;
81
+ outline: 2px solid currentColor;
82
+ outline-offset: 1px;
83
+ }
84
+
85
+ @media (prefers-reduced-motion: reduce) {
86
+ .shl-toolbar-button {
87
+ transition: none;
88
+ }
89
+ }
90
+ </style>
@@ -0,0 +1,106 @@
1
+ import type { SvelteComponentTyped } from "svelte";
2
+ import type {
3
+ HTMLAnchorAttributes,
4
+ HTMLButtonAttributes,
5
+ } from "svelte/elements";
6
+
7
+ export type ToolbarButtonProps = Omit<HTMLButtonAttributes, "type"> &
8
+ Pick<HTMLAnchorAttributes, "target" | "rel" | "download"> & {
9
+ /**
10
+ * Accessible name (`aria-label`) and tooltip (`title`).
11
+ */
12
+ label: string;
13
+
14
+ /**
15
+ * Set it to make a toggle button. Sets `aria-pressed` and the
16
+ * pressed style. Leave it unset for a plain action.
17
+ * @default undefined
18
+ */
19
+ pressed?: boolean;
20
+
21
+ /**
22
+ * Renders an `<a>` with this `href` instead of a `<button>`.
23
+ * @default undefined
24
+ */
25
+ href?: string;
26
+
27
+ /**
28
+ * Width and height of the button.
29
+ * @default "2em"
30
+ */
31
+ "--toolbar-button-size"?: string;
32
+
33
+ /**
34
+ * Gap between the button's content.
35
+ * @default "0.4em"
36
+ */
37
+ "--toolbar-button-gap"?: string;
38
+
39
+ /**
40
+ * Button padding.
41
+ * @default "0.3em"
42
+ */
43
+ "--toolbar-button-padding"?: string;
44
+
45
+ /**
46
+ * Button background.
47
+ * @default "transparent"
48
+ */
49
+ "--toolbar-button-background"?: string;
50
+
51
+ /**
52
+ * Icon and text color.
53
+ * @default "color-mix(in srgb, currentColor 72%, transparent)"
54
+ */
55
+ "--toolbar-button-color"?: string;
56
+
57
+ /**
58
+ * Button background on hover.
59
+ * @default "color-mix(in srgb, currentColor 12%, transparent)"
60
+ */
61
+ "--toolbar-button-hover-background"?: string;
62
+
63
+ /**
64
+ * Button background when pressed or active.
65
+ * @default "color-mix(in srgb, currentColor 18%, transparent)"
66
+ */
67
+ "--toolbar-button-pressed-background"?: string;
68
+
69
+ /**
70
+ * Button border radius.
71
+ * @default "6px"
72
+ */
73
+ "--toolbar-button-border-radius"?: string;
74
+
75
+ /**
76
+ * Button border.
77
+ * @default "none"
78
+ */
79
+ "--toolbar-button-border"?: string;
80
+
81
+ /**
82
+ * Button font size.
83
+ * @default "inherit"
84
+ */
85
+ "--toolbar-button-font-size"?: string;
86
+ };
87
+
88
+ export type ToolbarButtonEvents = {
89
+ click: WindowEventMap["click"];
90
+ };
91
+
92
+ export type ToolbarButtonSlots = {
93
+ /** The icon or text inside the button. */
94
+ default: Record<string, never>;
95
+ };
96
+
97
+ /**
98
+ * An icon button styled to match `CodeToolbar`. Use it for custom
99
+ * actions such as a download or a link to a playground. `WrapToggle`
100
+ * is built on it.
101
+ */
102
+ export default class ToolbarButton extends SvelteComponentTyped<
103
+ ToolbarButtonProps,
104
+ ToolbarButtonEvents,
105
+ ToolbarButtonSlots
106
+ > {}
package/Typewriter.svelte CHANGED
@@ -8,15 +8,27 @@
8
8
  /** @type {boolean} */
9
9
  export let play = true;
10
10
 
11
- import { createEventDispatcher, onMount } from "svelte";
11
+ /**
12
+ * Accessible name of the scrollable code region. Inside a CodeWindow, the
13
+ * window's `title` or `label` is the default.
14
+ * @type {string | undefined}
15
+ */
16
+ export let label = undefined;
17
+
18
+ import { createEventDispatcher, getContext, onMount } from "svelte";
19
+ import { CODE_REGION, NO_REGION_LABEL } from "./code-region.js";
12
20
  import { linear } from "./typewriter-easing.js";
13
21
  import {
14
22
  buildUnitMarkup,
15
23
  computeWordBoundaries,
16
24
  createTypewriterSplitter,
17
25
  tokenizeTypewriter as tokenize,
26
+ unitText,
18
27
  } from "./typewriter-units.js";
19
28
 
29
+ /** @type {import("svelte/store").Readable<string | undefined>} */
30
+ const windowLabel = getContext(CODE_REGION) ?? NO_REGION_LABEL;
31
+
20
32
  /** @type {(t: number) => number} */
21
33
  export let easing = linear;
22
34
 
@@ -181,6 +193,8 @@
181
193
  }
182
194
 
183
195
  $: units = tokenize(highlighted);
196
+ // Assistive tech reads this full copy; the animated layer is aria-hidden.
197
+ $: text = unitText(units);
184
198
  $: splitter = createTypewriterSplitter(units, highlighted);
185
199
  $: total = units.reduce((sum, unit) => sum + unit.visible, 0);
186
200
  $: wordBoundaries =
@@ -220,17 +234,31 @@
220
234
  });
221
235
  </script>
222
236
 
223
- <pre {...$$restProps}><code class:hljs={true}
224
- ><span class="typewriter-content" bind:this={contentEl} hidden={!useUnitReveal}
225
- ></span
226
- >{#if !useUnitReveal}{@html parts.head}{#if showCaret}<span
227
- class="typewriter-caret"
228
- aria-hidden="true"
229
- ></span>{/if}<span class="typewriter-rest" aria-hidden="true"
230
- >{@html parts.tail}</span
231
- >{/if}</code></pre>
237
+ <!-- svelte-ignore a11y-no-noninteractive-tabindex -->
238
+ <pre {...$$restProps}><code
239
+ class:hljs={true}
240
+ tabindex="0"
241
+ role="region"
242
+ aria-label={label ?? $windowLabel ?? "Code"}
243
+ ><span class="typewriter-visually-hidden">{text}</span><span
244
+ aria-hidden="true"
245
+ ><span
246
+ class="typewriter-content"
247
+ bind:this={contentEl}
248
+ hidden={!useUnitReveal}
249
+ ></span>{#if !useUnitReveal}{@html parts.head}{#if showCaret}<span
250
+ class="typewriter-caret"></span>{/if}<span class="typewriter-rest"
251
+ >{@html parts.tail}</span
252
+ >{/if}</span
253
+ ></code
254
+ ></pre>
232
255
 
233
256
  <style>
257
+ /* Draw the ring inside, or a scrolling <pre> clips it in Safari. */
258
+ code:focus-visible {
259
+ outline-offset: -2px;
260
+ }
261
+
234
262
  .typewriter-rest {
235
263
  visibility: hidden;
236
264
  }
@@ -263,6 +291,27 @@
263
291
  animation: typewriter-blink var(--caret-blink, 1s) step-end infinite;
264
292
  }
265
293
 
294
+ .typewriter-visually-hidden {
295
+ position: absolute;
296
+ width: 1px;
297
+ height: 1px;
298
+ padding: 0;
299
+ margin: -1px;
300
+ overflow: hidden;
301
+ clip-path: inset(50%);
302
+ white-space: nowrap;
303
+ border: 0;
304
+ user-select: none;
305
+ }
306
+
307
+ /* The reveal itself is the consumer's call; a blinking caret is not. */
308
+ @media (prefers-reduced-motion: reduce) {
309
+ .typewriter-caret,
310
+ :global(.typewriter-unit.typewriter-caret)::before {
311
+ animation: none;
312
+ }
313
+ }
314
+
266
315
  @keyframes typewriter-blink {
267
316
  50% {
268
317
  opacity: 0;
@@ -27,6 +27,13 @@ export type TypewriterProps = HTMLAttributes<HTMLPreElement> & {
27
27
  /** Total visible characters; read-only, for `bind:total`. @default 0 */
28
28
  total?: number;
29
29
 
30
+ /**
31
+ * Accessible name of the scrollable code region. Inside a `CodeWindow`,
32
+ * the window's `title` or `label` is the default.
33
+ * @default "Code"
34
+ */
35
+ label?: string;
36
+
30
37
  /** Width of the blinking caret. @default "0.6em" */
31
38
  "--caret-width"?: string;
32
39
 
@@ -0,0 +1,34 @@
1
+ <script>
2
+ /** @type {boolean} */
3
+ export let wrap = false;
4
+
5
+ /** @type {string} */
6
+ export let text = "Wrap";
7
+
8
+ import ToolbarButton from "./ToolbarButton.svelte";
9
+ </script>
10
+
11
+ <ToolbarButton
12
+ label={text}
13
+ pressed={wrap}
14
+ on:click={() => (wrap = !wrap)}
15
+ {...$$restProps}
16
+ >
17
+ <slot {wrap}>
18
+ <svg
19
+ xmlns="http://www.w3.org/2000/svg"
20
+ viewBox="0 0 32 32"
21
+ width="16"
22
+ height="16"
23
+ fill="currentColor"
24
+ preserveAspectRatio="xMidYMid meet"
25
+ aria-hidden="true"
26
+ >
27
+ <path d="M4 6h24v2H4z"></path>
28
+ <path
29
+ d="M4 14h19.5a5.5 5.5 0 0 1 0 11h-4.672l2.586 2.586L20 29l-5-5 5-5 1.414 1.414L18.828 23H23.5a3.5 3.5 0 0 0 0-7H4z"
30
+ ></path>
31
+ <path d="M4 22h7v2H4z"></path>
32
+ </svg>
33
+ </slot>
34
+ </ToolbarButton>
@@ -0,0 +1,39 @@
1
+ import type { SvelteComponentTyped } from "svelte";
2
+ import type { ToolbarButtonProps } from "./ToolbarButton.svelte";
3
+
4
+ export type WrapToggleProps = Omit<
5
+ ToolbarButtonProps,
6
+ "label" | "pressed" | "href"
7
+ > & {
8
+ /**
9
+ * Whether wrapping is enabled. Bindable.
10
+ * @default false
11
+ */
12
+ wrap?: boolean;
13
+
14
+ /**
15
+ * `aria-label` and `title`. The default slot shows a wrap icon. The
16
+ * label stays the same when pressed; `aria-pressed` carries the state.
17
+ * @default "Wrap"
18
+ */
19
+ text?: string;
20
+
21
+ /* Style it with the `--toolbar-button-*` variables of `ToolbarButton`. */
22
+ };
23
+
24
+ export type WrapToggleEvents = {};
25
+
26
+ export type WrapToggleSlots = {
27
+ default: {
28
+ /**
29
+ * Current wrap state.
30
+ */
31
+ wrap: boolean;
32
+ };
33
+ };
34
+
35
+ export default class WrapToggle extends SvelteComponentTyped<
36
+ WrapToggleProps,
37
+ WrapToggleEvents,
38
+ WrapToggleSlots
39
+ > {}
package/action.js CHANGED
@@ -3,10 +3,14 @@ import { ensureRegistered, registry } from "./registry.js";
3
3
 
4
4
  const LANGUAGE_CLASS = /(?:^|\s)language-([\w#+-]+)(?:\s|$)/;
5
5
 
6
+ /** @typedef {import("./action.d.ts").HighlightActionParameters} HighlightActionParameters */
7
+
6
8
  /**
9
+ * Framework-free: returns `{ update, destroy }`, which Svelte accepts as an
10
+ * action. `action.d.ts` types it as a Svelte `Action` for `use:`.
7
11
  * @param {HTMLElement} node
8
- * @param {{ language?: import("./languages").LanguageType<string>; code?: string }} [parameters]
9
- * @returns {ReturnType<import("svelte/action").Action<HTMLElement, { language?: import("./languages").LanguageType<string>; code?: string }>>}
12
+ * @param {HighlightActionParameters} [parameters]
13
+ * @returns {{ update: (params?: HighlightActionParameters) => void; destroy: () => void }}
10
14
  */
11
15
  export function highlight(node, parameters = {}) {
12
16
  // Snapshot: after the first pass `textContent` is the highlighted output.
@@ -57,7 +61,7 @@ export function highlight(node, parameters = {}) {
57
61
  dispatch("highlighted", { html: value, language: language.name });
58
62
  }
59
63
 
60
- /** @param {{ language?: import("./languages").LanguageType<string>; code?: string }} params */
64
+ /** @param {HighlightActionParameters} params */
61
65
  function apply({ language, code } = {}) {
62
66
  generation += 1;
63
67
  const gen = generation;
package/ansi.d.ts CHANGED
@@ -3,9 +3,7 @@
3
3
  * a 256-color index (16-255), or a truecolor triple.
4
4
  */
5
5
  export type AnsiColor =
6
- | { name: string }
7
- | { index: number }
8
- | { rgb: [number, number, number] };
6
+ { name: string } | { index: number } | { rgb: [number, number, number] };
9
7
 
10
8
  /** Active styling while parsing. */
11
9
  export type AnsiStyle = {
@@ -0,0 +1,52 @@
1
+ import type { HighlightResult, Registry } from "./engine.d.ts";
2
+ import type { LanguageName } from "./languages";
3
+
4
+ /** How many fingerprint candidates `highlightAutoLazy` loads by default. */
5
+ export declare const DEFAULT_CANDIDATES: number;
6
+
7
+ export interface LazyAutoOptions {
8
+ /**
9
+ * How many fingerprint candidates to load. Ignored when
10
+ * `languageNames` is set.
11
+ * @default 5
12
+ */
13
+ k?: number;
14
+
15
+ /**
16
+ * Detect among these grammars only, and skip the fingerprint step.
17
+ * Use canonical names (`"javascript"`, not `"js"`).
18
+ */
19
+ languageNames?: (LanguageName | (string & {}))[];
20
+
21
+ /**
22
+ * Registry to load grammars into and detect with.
23
+ * @default the shared registry from `svelte-highlight/registry`
24
+ */
25
+ registry?: Registry;
26
+ }
27
+
28
+ /**
29
+ * Scores `code` against the fingerprint index and returns up to `k`
30
+ * likely grammar names, best first. Loads no grammars.
31
+ */
32
+ export declare function detectCandidates(code: any, k?: number): string[];
33
+
34
+ /**
35
+ * Loads the fingerprint candidates (and the grammars they embed),
36
+ * registers them, then runs `registry.highlightAuto` over the candidates
37
+ * plus every grammar already registered. A grammar that fails to load
38
+ * drops out.
39
+ */
40
+ export declare function highlightAutoLazy(
41
+ code: any,
42
+ options?: LazyAutoOptions,
43
+ ): Promise<HighlightResult>;
44
+
45
+ /**
46
+ * Same as `highlightAutoLazy`, but loads nothing. Returns `undefined`
47
+ * when a grammar it needs is not registered yet. Works during SSR.
48
+ */
49
+ export declare function highlightAutoIfLoaded(
50
+ code: any,
51
+ options?: LazyAutoOptions,
52
+ ): HighlightResult | undefined;
package/auto-detect.js ADDED
@@ -0,0 +1,208 @@
1
+ // Lazy language detection, in two steps:
2
+ //
3
+ // 1. `detectCandidates` scores code against a generated fingerprint index
4
+ // (languages/detect-index.js, built by scripts/build-detect-index.ts)
5
+ // and returns a few likely grammar names. It loads no grammars.
6
+ // 2. `highlightAutoLazy` imports only those grammars (plus the grammars
7
+ // they embed), registers them, and lets `Registry#highlightAuto` pick
8
+ // among them and every grammar already registered.
9
+ //
10
+ // So a page pays for the index and the grammars its code needs, not for
11
+ // every grammar that `languages/all.js` imports.
12
+ import { registerAll } from "./engine.js";
13
+ import { DETECT_INDEX, SUB_LANGUAGES } from "./languages/detect-index.js";
14
+ import { LOADERS } from "./languages/loaders.js";
15
+ import { LanguageLoadError } from "./load-language.js";
16
+ import { registry as sharedRegistry } from "./registry.js";
17
+
18
+ /** How many fingerprint candidates `highlightAutoLazy` loads by default. */
19
+ export const DEFAULT_CANDIDATES = 5;
20
+
21
+ // Fingerprints only need the start of the code. Same cap as the engine's
22
+ // detection sample.
23
+ const SAMPLE_LIMIT = 8000;
24
+ const WORD_RE = /\w+/g;
25
+ const WORD_ONLY_RE = /^\w+$/;
26
+
27
+ /**
28
+ * @typedef {{ name: string, caseInsensitive: boolean, total: number,
29
+ * words: [string, number][], literals: [string, number][] }} Fingerprint
30
+ */
31
+
32
+ /** @type {Fingerprint[] | undefined} */
33
+ let fingerprints;
34
+ /** @type {Map<string, number> | undefined} */
35
+ let indexOrder;
36
+
37
+ /** Parses the index once, on first use. */
38
+ function getFingerprints() {
39
+ fingerprints ??= DETECT_INDEX.map(([name, caseInsensitive, features]) => {
40
+ /** @type {Fingerprint} */
41
+ const fingerprint = {
42
+ name,
43
+ caseInsensitive: caseInsensitive === 1,
44
+ total: 0,
45
+ words: [],
46
+ literals: [],
47
+ };
48
+ for (const feature of features.split(" ")) {
49
+ const weight = Number.parseInt(feature[0] ?? "1", 36);
50
+ const value = feature.slice(1);
51
+ fingerprint.total += weight;
52
+ (WORD_ONLY_RE.test(value)
53
+ ? fingerprint.words
54
+ : fingerprint.literals
55
+ ).push([value, weight]);
56
+ }
57
+ return fingerprint;
58
+ });
59
+ return fingerprints;
60
+ }
61
+
62
+ /** Position in all.js order, so ties break the way HighlightAuto's do. */
63
+ function orderOf(/** @type {string} */ name) {
64
+ indexOrder ??= new Map(DETECT_INDEX.map(([entry], i) => [entry, i]));
65
+ return indexOrder.get(name) ?? Number.POSITIVE_INFINITY;
66
+ }
67
+
68
+ /**
69
+ * @param {string} code
70
+ * @returns {{ name: string, score: number }[]} Grammars that matched at
71
+ * least one feature, best first.
72
+ */
73
+ function rank(code) {
74
+ const sample =
75
+ code.length > SAMPLE_LIMIT ? code.slice(0, SAMPLE_LIMIT) : code;
76
+ const lower = sample.toLowerCase();
77
+ const words = new Set(sample.match(WORD_RE));
78
+ const lowerWords = new Set(lower.match(WORD_RE));
79
+
80
+ /** @type {{ name: string, score: number, fraction: number }[]} */
81
+ const scored = [];
82
+ for (const fingerprint of getFingerprints()) {
83
+ const text = fingerprint.caseInsensitive ? lower : sample;
84
+ const wordSet = fingerprint.caseInsensitive ? lowerWords : words;
85
+ let matched = 0;
86
+ for (const [value, weight] of fingerprint.words) {
87
+ if (wordSet.has(value)) matched += weight;
88
+ }
89
+ for (const [value, weight] of fingerprint.literals) {
90
+ if (text.includes(value)) matched += weight;
91
+ }
92
+ if (matched === 0) continue;
93
+ scored.push({
94
+ name: fingerprint.name,
95
+ // A grammar with a long fingerprint matches more by chance, so
96
+ // divide by the square root of its total weight.
97
+ score: matched / Math.sqrt(fingerprint.total),
98
+ fraction: matched / fingerprint.total,
99
+ });
100
+ }
101
+ // Higher score first. On a tie, the grammar whose own features matched
102
+ // more fully wins.
103
+ scored.sort((a, b) => b.score - a.score || b.fraction - a.fraction);
104
+ return scored;
105
+ }
106
+
107
+ /**
108
+ * @param {string} code
109
+ * @param {number} [k]
110
+ * @returns {string[]}
111
+ */
112
+ export function detectCandidates(code, k = DEFAULT_CANDIDATES) {
113
+ return rank(String(code ?? ""))
114
+ .slice(0, k)
115
+ .map(({ name }) => name);
116
+ }
117
+
118
+ /**
119
+ * Names to load: the candidates plus every grammar they embed.
120
+ * @param {string[]} names
121
+ */
122
+ function withSubLanguages(names) {
123
+ const all = new Set(names);
124
+ for (const name of all) {
125
+ for (const sub of SUB_LANGUAGES[name] ?? []) all.add(sub);
126
+ }
127
+ return [...all];
128
+ }
129
+
130
+ /**
131
+ * @typedef {import("./engine.d.ts").Registry} Registry
132
+ * @typedef {{ k?: number, languageNames?: string[], registry?: Registry }} LazyOptions
133
+ */
134
+
135
+ /**
136
+ * @param {string} source
137
+ * @param {LazyOptions} options
138
+ */
139
+ function plan(source, options) {
140
+ const {
141
+ k = DEFAULT_CANDIDATES,
142
+ languageNames,
143
+ registry = sharedRegistry,
144
+ } = options;
145
+ const candidates = languageNames ?? detectCandidates(source, k);
146
+ const missing = withSubLanguages(candidates).filter(
147
+ (name) => !registry.get(name),
148
+ );
149
+ return { candidates, missing, registry, languageNames };
150
+ }
151
+
152
+ /** @param {ReturnType<typeof plan>} p @param {string} source */
153
+ function run({ candidates, registry, languageNames }, source) {
154
+ if (languageNames) return registry.highlightAuto(source, languageNames);
155
+ const registered = registry.listLanguages();
156
+ const pool = [...new Set([...candidates, ...registered])].sort(
157
+ (a, b) => orderOf(a) - orderOf(b),
158
+ );
159
+ return registry.highlightAuto(source, pool);
160
+ }
161
+
162
+ /**
163
+ * Detects and highlights `code` without loading anything. Returns
164
+ * `undefined` when a grammar it would load is not registered yet.
165
+ * @param {any} code
166
+ * @param {LazyOptions} [options]
167
+ */
168
+ export function highlightAutoIfLoaded(code, options = {}) {
169
+ const source = String(code ?? "");
170
+ const p = plan(source, options);
171
+ return p.missing.length > 0 ? undefined : run(p, source);
172
+ }
173
+
174
+ /**
175
+ * Imports one grammar through the literal loader map. `loadLanguage` uses
176
+ * a template-literal `import()`, which Vite does not rewrite inside
177
+ * node_modules, so it can't serve the published package here.
178
+ *
179
+ * @param {string} name
180
+ * @returns {Promise<import("./languages").LanguageType<string>>}
181
+ */
182
+ async function loadGrammar(name) {
183
+ const load = Object.hasOwn(LOADERS, name) ? LOADERS[name] : undefined;
184
+ if (!load) throw new LanguageLoadError(name);
185
+ try {
186
+ return (await load()).default;
187
+ } catch (cause) {
188
+ throw new LanguageLoadError(name, { cause });
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Loads the candidate grammars, registers them, then detects and
194
+ * highlights `code`. A grammar that fails to load drops out of the pool.
195
+ * @param {any} code
196
+ * @param {LazyOptions} [options]
197
+ */
198
+ export async function highlightAutoLazy(code, options = {}) {
199
+ const source = String(code ?? "");
200
+ const p = plan(source, options);
201
+ const loaded = await Promise.allSettled(
202
+ p.missing.map((name) => loadGrammar(name)),
203
+ );
204
+ for (const result of loaded) {
205
+ if (result.status === "fulfilled") registerAll(p.registry, result.value);
206
+ }
207
+ return run(p, source);
208
+ }
@@ -0,0 +1,7 @@
1
+ import type { Readable } from "svelte/store";
2
+
3
+ /** Context key for the store that holds the CodeWindow label. */
4
+ export declare const CODE_REGION: unique symbol;
5
+
6
+ /** Store for code blocks outside a CodeWindow. It always holds `undefined`. */
7
+ export declare const NO_REGION_LABEL: Readable<string | undefined>;