@dou-ui/code 0.1.0-alpha.3 → 0.1.0-alpha.30

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 (42) hide show
  1. package/dist/assets/default-BWWFJmzn.js.map +1 -0
  2. package/dist/code-diff.js.map +1 -1
  3. package/dist/code-diff.vue_vue_type_script_setup_true_lang.js +756 -63
  4. package/dist/code-diff.vue_vue_type_script_setup_true_lang.js.map +1 -1
  5. package/dist/code-editor.js.map +1 -1
  6. package/dist/code-editor.vue_vue_type_script_setup_true_lang.js +784 -474
  7. package/dist/code-editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
  8. package/dist/extension.js +6 -1
  9. package/dist/extension.js.map +1 -1
  10. package/dist/index.js +3 -2
  11. package/dist/index.js.map +1 -1
  12. package/dist/language/highlighter.js +1 -1
  13. package/dist/language/highlighter.js.map +1 -1
  14. package/dist/language/language.js +24 -2
  15. package/dist/language/language.js.map +1 -1
  16. package/dist/language/remote-tokens.js +131 -0
  17. package/dist/language/remote-tokens.js.map +1 -0
  18. package/dist/language/worker-client.js +308 -33
  19. package/dist/language/worker-client.js.map +1 -1
  20. package/dist/language/worker-protocol.js.map +1 -1
  21. package/dist/shiki/index.js +54 -3
  22. package/dist/shiki/index.js.map +1 -1
  23. package/dist/style.css +1 -1
  24. package/dist/types/code-diff.vue.d.ts +18 -21
  25. package/dist/types/code-editor.vue.d.ts +3 -1
  26. package/dist/types/extension.d.ts +57 -5
  27. package/dist/types/index.d.ts +97 -21
  28. package/dist/types/language/language.d.ts +27 -0
  29. package/dist/types/language/remote-tokens.d.ts +38 -0
  30. package/dist/types/language/worker-client.d.ts +85 -15
  31. package/dist/types/language/worker-protocol.d.ts +53 -2
  32. package/dist/types/shiki/index.d.ts +36 -1
  33. package/dist/types/types.d.ts +166 -10
  34. package/dist/types/view/measure.d.ts +6 -0
  35. package/dist/types/worker/index.d.ts +27 -12
  36. package/dist/view/measure.js +23 -5
  37. package/dist/view/measure.js.map +1 -1
  38. package/dist/worker/default.js +1 -1
  39. package/dist/worker/index.js +280 -53
  40. package/dist/worker/index.js.map +1 -1
  41. package/package.json +3 -3
  42. package/dist/assets/default-BZBMZKf_.js.map +0 -1
package/dist/extension.js CHANGED
@@ -5,12 +5,17 @@ function defineCodeExtension(extension) {
5
5
  return extension;
6
6
  }
7
7
  var CODE_EDITOR_KEY = Symbol("DouCodeEditor");
8
+ /**
9
+ * Internal: told each widget height an editor measures, by `extension/id`;
10
+ * DouCodeDiff leaves a blank of the same height across from it.
11
+ */
12
+ var WIDGET_HEIGHT_KEY = Symbol("DouCodeWidgetHeight");
8
13
  /** The editor a panel or gutter component is drawn in. */
9
14
  function useCodeEditor() {
10
15
  const context = inject(CODE_EDITOR_KEY, null);
11
16
  if (!context) throw new Error("[@dou-ui/code] useCodeEditor() must be called inside <DouCodeEditor>");
12
17
  return context;
13
18
  }
14
- export { CODE_EDITOR_KEY, defineCodeExtension, useCodeEditor };
19
+ export { CODE_EDITOR_KEY, WIDGET_HEIGHT_KEY, defineCodeExtension, useCodeEditor };
15
20
 
16
21
  //# sourceMappingURL=extension.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"extension.js","names":[],"sources":["../src/extension.ts"],"sourcesContent":["import type { CodeMessages } from './locale'\nimport { type Component, type InjectionKey, type VNodeChild, inject } from 'vue'\nimport type { CodeKeymap } from './core/keymap'\nimport type { CodeSelection } from './core/selection'\nimport type { CodeText } from './core/text'\nimport type { CodeState, CodeTransaction, CodeTransactionResult } from './core/transaction'\nimport type { CodeEditorExpose } from './types'\n\n/** How bad a diagnostic is, worst first. */\nexport type CodeDiagnosticSeverity = 'error' | 'warning' | 'info' | 'hint'\n\n/** A fix offered with a diagnostic. */\nexport interface CodeDiagnosticAction {\n label: string\n /** Makes the fix, usually with `context.transact`. */\n run: (context: CodeExtensionContext, diagnostic: CodeDiagnostic) => void\n}\n\n/**\n * A problem found in the text, from `from` to `to` (offsets in the text,\n * the same as a language service's ranges). An empty range marks the\n * character after it.\n */\nexport interface CodeDiagnostic {\n from: number\n to: number\n severity: CodeDiagnosticSeverity\n message: string\n /** Who found it, shown after the message, e.g. the name of a linter. */\n source?: string\n /** Fixes, shown under the message and with `Mod` + `.`. */\n actions?: CodeDiagnosticAction[]\n}\n\n/**\n * How a part of the text is drawn. Marks and line classes only change how\n * the text looks (colors, backgrounds, underlines, borders), never its\n * size, so the cursor still lands where the characters are; an inline\n * widget takes its own room in the line.\n */\nexport type CodeDecoration =\n /**\n * Classes on the characters from `from` to `to`. `style` sets inline\n * styles on them as well, e.g. a CSS variable holding a person's color;\n * where marks overlap, the later one's styles win.\n */\n | {\n type: 'mark'\n from: number\n to: number\n class: string\n title?: string\n style?: Readonly<Record<string, string>>\n }\n /** A class on a whole line (`line` from 1), e.g. a tinted background. */\n | { type: 'line'; line: number; class: string }\n /**\n * Something drawn inside a line, before the character at `pos`, such as\n * a color swatch or a parameter's name. It isn't text: the cursor steps\n * over it and copying leaves it out. `width` in px saves measuring it;\n * without it the widget is measured once drawn, and the width is kept by\n * `id`.\n */\n | { type: 'inline'; pos: number; render: () => VNodeChild; width?: number; id?: string }\n\n/**\n * A component drawn between lines, across the editor, e.g. a review\n * comment. The lines below move down to make room, and it moves with the\n * text as lines are added or removed above it.\n */\nexport interface CodeWidget {\n /** Tells widgets apart, unique among one extension's; its measured height is kept by it. */\n id: string\n /**\n * Where it is: below the line of text position `pos`, or below line\n * `line` (from 1); above with `position: 'above'`. Give one of them.\n */\n pos?: number\n line?: number\n /** Defaults to `below`. */\n position?: 'above' | 'below'\n render: () => VNodeChild\n /** Its height in px before it has been drawn and measured; defaults to one line. */\n height?: number\n /** What it is, read out when the cursor moves onto its line, e.g. \"戴兜的评论\". */\n label?: string\n}\n\n/** Something drawn in a column beside the line numbers, on line `line` (from 1). */\nexport interface CodeGutterMarker {\n line: number\n /** Drawn in the middle of the column. */\n icon?: Component\n /** Short text, when there is no icon. */\n text?: string\n class?: string\n /** Shown on hover and read out. */\n title?: string\n}\n\n/** A column of the gutter, left of the line numbers. */\nexport interface CodeGutter {\n name: string\n /** In px. Defaults to 16. */\n width?: number\n /** The markers on the lines in view; reactive state read here updates them. */\n markers: (context: CodeExtensionContext) => CodeGutterMarker[]\n /** A press on the column, on line `line`, e.g. to set a breakpoint. */\n onPress?: (line: number, event: PointerEvent, context: CodeExtensionContext) => void\n}\n\n/** An undo history that takes the place of the editor's own, e.g. one shared with others. */\nexport interface CodeHistoryHandler {\n /** `false` when there is nothing to undo. */\n undo: () => boolean\n redo: () => boolean\n /** Read in templates and computed values: keep them reactive. */\n canUndo: () => boolean\n canRedo: () => boolean\n /** The next change starts a new undo step, e.g. when the editor loses focus. */\n close?: () => void\n}\n\n/** A bar above or below the text, inside the editor's frame. */\nexport interface CodePanel {\n /** Tells panels apart, unique among one extension's. */\n name: string\n /** Defaults to `bottom`. */\n position?: 'top' | 'bottom'\n render: () => VNodeChild\n}\n\n/** What a completion is, shown as its icon. */\nexport type CodeCompletionKind =\n | 'keyword'\n | 'function'\n | 'method'\n | 'variable'\n | 'property'\n | 'constant'\n | 'class'\n | 'type'\n | 'module'\n | 'snippet'\n | 'text'\n\n/** One entry of the completion list. */\nexport interface CodeCompletion {\n /** Shown, and matched against what was typed. */\n label: string\n kind?: CodeCompletionKind\n /** Short, after the label, e.g. a type. */\n detail?: string\n /** Longer, below the list while this entry is picked: text, or a function returning VNodes. */\n info?: string | (() => VNodeChild)\n /** What goes into the text, if not the label. */\n insert?: string\n /** Inserted as a snippet instead: `${1:name}` places to fill in, Tab to the next, `$0` where it ends. */\n snippet?: string\n /** Moves the entry up (positive) or down among equally good matches. */\n boost?: number\n}\n\n/** What a completion source is asked with. */\nexport interface CodeCompletionRequest {\n /** The cursor. */\n pos: number\n /** The word right before the cursor, by the language's word characters; empty when there is none. */\n word: { from: number; to: number; text: string }\n /** Asked for from the keyboard (`Ctrl` + `Space`, `Alt` + `Esc`) rather than by typing. */\n explicit: boolean\n /** Aborted when the answer is no longer wanted, so a slow source can stop. */\n signal: AbortSignal\n}\n\n/** What a hover or signature source is asked with. */\nexport interface CodePositionRequest {\n /** The position asked about: under the pointer, or the cursor. */\n pos: number\n /** Aborted when the answer is no longer wanted, so a slow source can stop. */\n signal: AbortSignal\n}\n\n/** What a completion source answers: entries to put in place of `from`–cursor. */\nexport interface CodeCompletionResult {\n from: number\n options: CodeCompletion[]\n}\n\n/** Text shown on hover, or with the cursor on it from the keyboard. */\nexport interface CodeHoverResult {\n /** What it is about, `from`–`to`; defaults to the word under the pointer. */\n from?: number\n to?: number\n /** Plain text, or a render function for anything else. */\n content: string | (() => VNodeChild)\n}\n\n/** The parameters of the call the cursor is in. */\nexport interface CodeSignatureResult {\n /** The whole signature, e.g. `slice(start, end)`. */\n label: string\n /** Each parameter as `[from, to]` in `label`. */\n params: Array<[number, number]>\n /** Which parameter the cursor is at, from 0. */\n active: number\n /** Shown under the signature: text, or a function returning VNodes. */\n info?: string | (() => VNodeChild)\n}\n\nexport interface CodeExtension {\n name: string\n /** Higher runs first: its keys and hooks come before others. Defaults to 100. */\n priority?: number\n /** Keys tried before the built-in ones, and after the `keymap` prop. */\n keymap?: (context: CodeExtensionContext) => CodeKeymap\n /**\n * How parts of the text look, read while drawing: reactive state read\n * here updates them. Asked for the lines in view (`context.visible`),\n * which is all that needs them.\n */\n decorations?: (context: CodeExtensionContext) => CodeDecoration[]\n /** Columns beside the line numbers. */\n gutters?: CodeGutter[]\n /**\n * Components between lines. Unlike decorations, these are asked for the\n * whole text, since their heights place every line after them; keep\n * them few (comments, not one per line).\n */\n widgets?: (context: CodeExtensionContext) => CodeWidget[]\n /**\n * Lines left out of view: line numbers (from 1, not text positions), from\n * line `from` to line `to`, both left out,\n * e.g. the unchanged lines of a diff. Unlike a fold, nothing marks the\n * spot; put a widget there for that. Asked for the whole text; reactive\n * state read here updates them. Moving up and down steps over them.\n */\n hide?: (context: CodeExtensionContext) => Array<{ from: number; to: number }>\n /** Bars above or below the text; reactive state read here updates them. */\n panels?: (context: CodeExtensionContext) => CodePanel[]\n /**\n * Finds problems in the text. Run when the editor mounts and again a\n * moment after the text stops changing; an answer that arrives after\n * the text changed again is dropped, and the next run follows it.\n * Meanwhile the problems found move with the text.\n */\n lint?: (\n context: CodeExtensionContext,\n ) => CodeDiagnostic[] | null | undefined | Promise<CodeDiagnostic[] | null | undefined>\n /**\n * Offers completions while typing (after a word character or one of\n * `completionTriggers`) and on `Ctrl` + `Space` or `Alt` + `Esc`. Answers from every\n * extension are put in one list; a Promise is waited for, and dropped\n * when the text has moved on.\n */\n completion?: (\n request: CodeCompletionRequest,\n context: CodeExtensionContext,\n ) => CodeCompletionResult | null | undefined | Promise<CodeCompletionResult | null | undefined>\n /** Characters that ask for completions when typed, such as `.`. */\n completionTriggers?: string[]\n /**\n * Text about a position, shown on hover and with `Mod` + `I`. A Promise\n * is waited for; `signal` aborts when the pointer moves on.\n */\n hover?: (\n request: CodePositionRequest,\n context: CodeExtensionContext,\n ) => CodeHoverResult | null | undefined | Promise<CodeHoverResult | null | undefined>\n /**\n * The parameters of the call around the cursor, shown while typing its\n * arguments. A Promise is waited for, and dropped when the cursor has\n * moved on.\n */\n signature?: (\n request: CodePositionRequest,\n context: CodeExtensionContext,\n ) => CodeSignatureResult | null | undefined | Promise<CodeSignatureResult | null | undefined>\n /**\n * Sees every change before it is applied, in priority order, and may add\n * to it (positions are in the text before the change). Undo, redo, new\n * `v-model` values and other people's changes (`action: 'remote'`) don't\n * come through here.\n */\n transaction?: (tr: CodeTransaction, context: CodeExtensionContext) => void\n /**\n * Runs after every step the editor took, with the text and selection\n * already updated: typing, commands, undo and redo, new `v-model`\n * values and other people's changes. `result.meta.action` tells them\n * apart.\n */\n update?: (result: CodeTransactionResult, context: CodeExtensionContext) => void\n /**\n * Replaces the editor's undo history; the first extension that has one\n * wins. Called once per list of extensions: return the same handler\n * each time.\n */\n history?: (context: CodeExtensionContext) => CodeHistoryHandler\n /**\n * Buttons added to the toolbar shown over the selection on touch screens,\n * after cut, copy, paste and select all. Read again as the selection\n * changes.\n */\n menu?: (context: CodeExtensionContext) => CodeMenuItem[]\n /** Runs once the editor is mounted. Return a function to run when it unmounts. */\n setup?: (context: CodeExtensionContext) => void | (() => void)\n}\n\n/** A button of the touch toolbar, from an extension's `menu`. */\nexport interface CodeMenuItem {\n label: string\n run: (context: CodeExtensionContext) => void\n}\n\n/** What an extension sees of the editor: its instance, plus a little more. */\nexport interface CodeExtensionContext extends CodeEditorExpose {\n /** The text and selection now; reading them in `decorations` or `panels` follows every change. */\n readonly state: CodeState\n readonly doc: CodeText\n readonly selection: CodeSelection\n /** The lines in view: line numbers (from 1, not text positions), both ends in view. */\n readonly visible: { readonly from: number; readonly to: number }\n /** The problems found now, by all linters and the `diagnostics` prop, in text order. */\n readonly diagnostics: readonly CodeDiagnostic[]\n /** Whether the editor has focus; reading it in reactive code follows it. */\n readonly focused: boolean\n /** The editor's texts, in DouUI's locale or as given by the `messages` prop. */\n readonly messages: CodeMessages\n /** Reads a message out to screen readers. */\n announce: (message: string) => void\n /**\n * Runs the linter of the extension named `name` again now (every linter\n * without a name), for problems that arrive by themselves, such as ones a\n * server pushes.\n */\n relint: (name?: string) => void\n}\n\n/** Types an extension; returns it as it is. */\nexport function defineCodeExtension(extension: CodeExtension): CodeExtension {\n return extension\n}\n\nexport const CODE_EDITOR_KEY: InjectionKey<CodeExtensionContext> = Symbol('DouCodeEditor')\n\n/** The editor a panel or gutter component is drawn in. */\nexport function useCodeEditor(): CodeExtensionContext {\n const context = inject(CODE_EDITOR_KEY, null)\n if (!context)\n throw new Error('[@dou-ui/code] useCodeEditor() must be called inside <DouCodeEditor>')\n return context\n}\n"],"mappings":";;;AAmVA,SAAgB,oBAAoB,WAAyC;CAC3E,OAAO;AACT;AAEA,IAAa,kBAAsD,OAAO,eAAe;;AAGzF,SAAgB,gBAAsC;CACpD,MAAM,UAAU,OAAO,iBAAiB,IAAI;CAC5C,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,sEAAsE;CACxF,OAAO;AACT"}
1
+ {"version":3,"file":"extension.js","names":[],"sources":["../src/extension.ts"],"sourcesContent":["import type { CodeMessages } from './locale'\nimport { type Component, type InjectionKey, type VNodeChild, inject } from 'vue'\nimport type { CodeKeymap } from './core/keymap'\nimport type { CodeSelection } from './core/selection'\nimport type { CodeText } from './core/text'\nimport type { CodeState, CodeTransaction, CodeTransactionResult } from './core/transaction'\nimport type { CodeEditorExpose } from './types'\n\n/** How bad a diagnostic is, worst first. */\nexport type CodeDiagnosticSeverity = 'error' | 'warning' | 'info' | 'hint'\n\n/** A fix offered with a diagnostic. */\nexport interface CodeDiagnosticAction {\n label: string\n /** Makes the fix, usually with `context.transact`. */\n run: (context: CodeExtensionContext, diagnostic: CodeDiagnostic) => void\n}\n\n/**\n * A problem found in the text, from `from` to `to` (offsets in the text,\n * the same as a language service's ranges). An empty range marks the\n * character after it.\n */\nexport interface CodeDiagnostic {\n from: number\n to: number\n severity: CodeDiagnosticSeverity\n message: string\n /** Who found it, shown after the message, e.g. the name of a linter. */\n source?: string\n /** Fixes, shown under the message and with `Mod` + `.`. */\n actions?: CodeDiagnosticAction[]\n}\n\n/**\n * How a part of the text is drawn. Marks and line classes only change how\n * the text looks (colors, backgrounds, underlines, borders), never its\n * size, so the cursor still lands where the characters are; an inline\n * widget takes its own room in the line.\n */\nexport type CodeDecoration =\n /**\n * Classes on the characters from `from` to `to`. `style` sets inline\n * styles on them as well, e.g. a CSS variable holding a person's color;\n * where marks overlap, the later one's styles win.\n */\n | {\n type: 'mark'\n from: number\n to: number\n class: string\n title?: string\n style?: Readonly<Record<string, string>>\n }\n /** A class on a whole line (`line` from 1), e.g. a tinted background. */\n | { type: 'line'; line: number; class: string }\n /**\n * Something drawn inside a line, before the character at `pos`, such as\n * a color swatch or a parameter's name. It isn't text: the cursor steps\n * over it and copying leaves it out. `width` in px saves measuring it;\n * without it the widget is measured once drawn, and the width is kept by\n * `id`.\n */\n | { type: 'inline'; pos: number; render: () => VNodeChild; width?: number; id?: string }\n\n/**\n * A component drawn between lines, across the editor, e.g. a review\n * comment. The lines below move down to make room, and it moves with the\n * text as lines are added or removed above it.\n */\nexport interface CodeWidget {\n /** Tells widgets apart, unique among one extension's; its measured height is kept by it. */\n id: string\n /**\n * Where it is: below the line of text position `pos`, or below line\n * `line` (from 1); above with `position: 'above'`. Give one of them.\n */\n pos?: number\n line?: number\n /** Defaults to `below`. */\n position?: 'above' | 'below'\n render: () => VNodeChild\n /** Its height in px before it has been drawn and measured; defaults to one line. */\n height?: number\n /** What it is, read out when the cursor moves onto its line, e.g. \"戴兜的评论\". */\n label?: string\n /**\n * Draws across the gutter too, taking the full width of the editor's view.\n * Off by default, so widgets start beside the gutter, aligned with the text.\n */\n fullWidth?: boolean\n}\n\n/** Something drawn in a column beside the line numbers, on line `line` (from 1). */\nexport interface CodeGutterMarker {\n line: number\n /** Drawn in the middle of the column. */\n icon?: Component\n /** Short text, when there is no icon. */\n text?: string\n class?: string\n /**\n * Shown on hover. Required when the column has `onPress`: the marker is\n * then a button, and this is its name.\n */\n title?: string\n /**\n * When the marker shows: `always`, or `hover`, out of sight until its\n * line is hovered, holds the cursor, or the marker has the focus, e.g. a\n * \"comment\" mark offered on every line. Defaults to `always`.\n */\n visible?: 'always' | 'hover'\n}\n\n/**\n * The marker a column shows on every line without one of its own, out of\n * sight until the line is hovered (as `visible: 'hover'`), e.g. \"add a\n * breakpoint\" offered on every line.\n */\nexport interface CodeGutterHoverMarker extends Pick<CodeGutterMarker, 'icon' | 'text' | 'class'> {\n /**\n * Its name, as a marker's `title`; a function names the marker of each\n * line, e.g. \"Add a breakpoint on line 3\". It is called for every line in\n * view, often: keep it quick.\n */\n title?: string | ((line: number) => string)\n}\n\n/** A column of the gutter, left of the line numbers. */\nexport interface CodeGutter {\n name: string\n /** In px. Defaults to 16 (or 18 when `overlay` is set). */\n width?: number\n /**\n * Draws markers floating over the gutter's right edge without reserving a\n * dedicated column width (0px layout footprint). Best paired with\n * `hoverMarker` or `visible: 'hover'` for row actions such as adding review\n * comments. Empty rows take no pointer events.\n */\n overlay?: boolean\n /** The markers on the lines in view; reactive state read here updates them. */\n markers?: (context: CodeExtensionContext) => CodeGutterMarker[]\n /** A marker on every other line, shown on hover. */\n hoverMarker?: CodeGutterHoverMarker\n /**\n * Where `onPress` answers: `any` cell of the column (the default), e.g. to\n * set a breakpoint on an empty line, or only its `markers`.\n */\n pressOn?: 'any' | 'markers'\n /**\n * A press on the column, on line `line`, e.g. to set a breakpoint. A\n * marker in such a column is a button: the one on the cursor's line is\n * reached with Escape then Shift+Tab, and Enter or Space presses it. A\n * finger or pen presses when it lifts in place; a tap on a marker still\n * out of sight first moves the cursor to its line, which shows it.\n */\n onPress?: (\n line: number,\n event: PointerEvent | KeyboardEvent,\n context: CodeExtensionContext,\n ) => void\n}\n\n/** An undo history that takes the place of the editor's own, e.g. one shared with others. */\nexport interface CodeHistoryHandler {\n /** `false` when there is nothing to undo. */\n undo: () => boolean\n redo: () => boolean\n /** Read in templates and computed values: keep them reactive. */\n canUndo: () => boolean\n canRedo: () => boolean\n /** The next change starts a new undo step, e.g. when the editor loses focus. */\n close?: () => void\n}\n\n/** A bar above or below the text, inside the editor's frame. */\nexport interface CodePanel {\n /** Tells panels apart, unique among one extension's. */\n name: string\n /** Defaults to `bottom`. */\n position?: 'top' | 'bottom'\n render: () => VNodeChild\n}\n\n/** What a completion is, shown as its icon. */\nexport type CodeCompletionKind =\n | 'keyword'\n | 'function'\n | 'method'\n | 'variable'\n | 'property'\n | 'constant'\n | 'class'\n | 'type'\n | 'module'\n | 'snippet'\n | 'text'\n\n/** One entry of the completion list. */\nexport interface CodeCompletion {\n /** Shown, and matched against what was typed. */\n label: string\n kind?: CodeCompletionKind\n /** Short, after the label, e.g. a type. */\n detail?: string\n /** Longer, below the list while this entry is picked: text, or a function returning VNodes. */\n info?: string | (() => VNodeChild)\n /** What goes into the text, if not the label. */\n insert?: string\n /** Inserted as a snippet instead: `${1:name}` places to fill in, Tab to the next, `$0` where it ends. */\n snippet?: string\n /** Moves the entry up (positive) or down among equally good matches. */\n boost?: number\n}\n\n/** What a completion source is asked with. */\nexport interface CodeCompletionRequest {\n /** The cursor. */\n pos: number\n /** The word right before the cursor, by the language's word characters; empty when there is none. */\n word: { from: number; to: number; text: string }\n /** Asked for from the keyboard (`Ctrl` + `Space`, `Alt` + `Esc`) rather than by typing. */\n explicit: boolean\n /** Aborted when the answer is no longer wanted, so a slow source can stop. */\n signal: AbortSignal\n}\n\n/** What a hover or signature source is asked with. */\nexport interface CodePositionRequest {\n /** The position asked about: under the pointer, or the cursor. */\n pos: number\n /** Aborted when the answer is no longer wanted, so a slow source can stop. */\n signal: AbortSignal\n}\n\n/** What a completion source answers: entries to put in place of `from`–cursor. */\nexport interface CodeCompletionResult {\n from: number\n options: CodeCompletion[]\n}\n\n/** Text shown on hover, or with the cursor on it from the keyboard. */\nexport interface CodeHoverResult {\n /** What it is about, `from`–`to`; defaults to the word under the pointer. */\n from?: number\n to?: number\n /** Plain text, or a render function for anything else. */\n content: string | (() => VNodeChild)\n}\n\n/** The parameters of the call the cursor is in. */\nexport interface CodeSignatureResult {\n /** The whole signature, e.g. `slice(start, end)`. */\n label: string\n /** Each parameter as `[from, to]` in `label`. */\n params: Array<[number, number]>\n /** Which parameter the cursor is at, from 0. */\n active: number\n /** Shown under the signature: text, or a function returning VNodes. */\n info?: string | (() => VNodeChild)\n}\n\nexport interface CodeExtension {\n name: string\n /** Higher runs first: its keys and hooks come before others. Defaults to 100. */\n priority?: number\n /** Keys tried before the built-in ones, and after the `keymap` prop. */\n keymap?: (context: CodeExtensionContext) => CodeKeymap\n /**\n * How parts of the text look, read while drawing: reactive state read\n * here updates them. Asked for the lines in view (`context.visible`),\n * which is all that needs them.\n */\n decorations?: (context: CodeExtensionContext) => CodeDecoration[]\n /** Columns beside the line numbers. */\n gutters?: CodeGutter[]\n /**\n * Components between lines. Unlike decorations, these are asked for the\n * whole text, since their heights place every line after them; keep\n * them few (comments, not one per line).\n */\n widgets?: (context: CodeExtensionContext) => CodeWidget[]\n /**\n * Lines left out of view: line numbers (from 1, not text positions), from\n * line `from` to line `to`, both left out,\n * e.g. the unchanged lines of a diff. Unlike a fold, nothing marks the\n * spot; put a widget there for that. Asked for the whole text; reactive\n * state read here updates them. Moving up and down steps over them.\n */\n hide?: (context: CodeExtensionContext) => Array<{ from: number; to: number }>\n /** Bars above or below the text; reactive state read here updates them. */\n panels?: (context: CodeExtensionContext) => CodePanel[]\n /**\n * Finds problems in the text. Run when the editor mounts and again a\n * moment after the text stops changing; an answer that arrives after\n * the text changed again is dropped, and the next run follows it.\n * Meanwhile the problems found move with the text.\n */\n lint?: (\n context: CodeExtensionContext,\n ) => CodeDiagnostic[] | null | undefined | Promise<CodeDiagnostic[] | null | undefined>\n /**\n * Offers completions while typing (after a word character or one of\n * `completionTriggers`) and on `Ctrl` + `Space` or `Alt` + `Esc`. Answers from every\n * extension are put in one list; a Promise is waited for, and dropped\n * when the text has moved on.\n */\n completion?: (\n request: CodeCompletionRequest,\n context: CodeExtensionContext,\n ) => CodeCompletionResult | null | undefined | Promise<CodeCompletionResult | null | undefined>\n /** Characters that ask for completions when typed, such as `.`. */\n completionTriggers?: string[]\n /**\n * Text about a position, shown on hover and with `Mod` + `I`. A Promise\n * is waited for; `signal` aborts when the pointer moves on.\n */\n hover?: (\n request: CodePositionRequest,\n context: CodeExtensionContext,\n ) => CodeHoverResult | null | undefined | Promise<CodeHoverResult | null | undefined>\n /**\n * The parameters of the call around the cursor, shown while typing its\n * arguments. A Promise is waited for, and dropped when the cursor has\n * moved on.\n */\n signature?: (\n request: CodePositionRequest,\n context: CodeExtensionContext,\n ) => CodeSignatureResult | null | undefined | Promise<CodeSignatureResult | null | undefined>\n /**\n * Sees every change before it is applied, in priority order, and may add\n * to it (positions are in the text before the change). Undo, redo, new\n * `v-model` values and other people's changes (`action: 'remote'`) don't\n * come through here.\n */\n transaction?: (tr: CodeTransaction, context: CodeExtensionContext) => void\n /**\n * Runs after every step the editor took, with the text and selection\n * already updated: typing, commands, undo and redo, new `v-model`\n * values and other people's changes. `result.meta.action` tells them\n * apart.\n */\n update?: (result: CodeTransactionResult, context: CodeExtensionContext) => void\n /**\n * Replaces the editor's undo history; the first extension that has one\n * wins. Called once per list of extensions: return the same handler\n * each time.\n */\n history?: (context: CodeExtensionContext) => CodeHistoryHandler\n /**\n * Buttons added to the toolbar shown over the selection on touch screens,\n * after cut, copy, paste and select all. Read again as the selection\n * changes.\n */\n menu?: (context: CodeExtensionContext) => CodeMenuItem[]\n /** Runs once the editor is mounted. Return a function to run when it unmounts. */\n setup?: (context: CodeExtensionContext) => void | (() => void)\n}\n\n/** A button of the touch toolbar, from an extension's `menu`. */\nexport interface CodeMenuItem {\n label: string\n run: (context: CodeExtensionContext) => void\n}\n\n/** What an extension sees of the editor: its instance, plus a little more. */\nexport interface CodeExtensionContext extends CodeEditorExpose {\n /** The text and selection now; reading them in `decorations` or `panels` follows every change. */\n readonly state: CodeState\n readonly doc: CodeText\n readonly selection: CodeSelection\n /** The lines in view: line numbers (from 1, not text positions), both ends in view. */\n readonly visible: { readonly from: number; readonly to: number }\n /** The problems found now, by all linters and the `diagnostics` prop, in text order. */\n readonly diagnostics: readonly CodeDiagnostic[]\n /** Whether the editor has focus; reading it in reactive code follows it. */\n readonly focused: boolean\n /** The editor's texts, in DouUI's locale or as given by the `messages` prop. */\n readonly messages: CodeMessages\n /** Reads a message out to screen readers. */\n announce: (message: string) => void\n /**\n * Runs the linter of the extension named `name` again now (every linter\n * without a name), for problems that arrive by themselves, such as ones a\n * server pushes.\n */\n relint: (name?: string) => void\n}\n\n/** Types an extension; returns it as it is. */\nexport function defineCodeExtension(extension: CodeExtension): CodeExtension {\n return extension\n}\n\nexport const CODE_EDITOR_KEY: InjectionKey<CodeExtensionContext> = Symbol('DouCodeEditor')\n\n/**\n * Internal: told each widget height an editor measures, by `extension/id`;\n * DouCodeDiff leaves a blank of the same height across from it.\n */\nexport const WIDGET_HEIGHT_KEY: InjectionKey<((key: string, height: number) => void) | null> =\n Symbol('DouCodeWidgetHeight')\n\n/** The editor a panel or gutter component is drawn in. */\nexport function useCodeEditor(): CodeExtensionContext {\n const context = inject(CODE_EDITOR_KEY, null)\n if (!context)\n throw new Error('[@dou-ui/code] useCodeEditor() must be called inside <DouCodeEditor>')\n return context\n}\n"],"mappings":";;;AAuYA,SAAgB,oBAAoB,WAAyC;CAC3E,OAAO;AACT;AAEA,IAAa,kBAAsD,OAAO,eAAe;;;;;AAMzF,IAAa,oBACX,OAAO,qBAAqB;;AAG9B,SAAgB,gBAAsC;CACpD,MAAM,UAAU,OAAO,iBAAiB,IAAI;CAC5C,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,sEAAsE;CACxF,OAAO;AACT"}
package/dist/index.js CHANGED
@@ -7,8 +7,9 @@ import { CodeText, splitLines } from "./core/text.js";
7
7
  import { CodeTransaction } from "./core/transaction.js";
8
8
  import { matchAfter, queryRegExp, replacementFor, searchText } from "./core/search.js";
9
9
  import { CodeStream } from "./language/stream.js";
10
- import { copyPlain, defineCodeLanguage, languageFor, lineParts, samePlain, tokenTypes, tokenizeLine } from "./language/language.js";
10
+ import { copyPlain, defineCodeLanguage, languageFor, lineParts, remoteCodeLanguage, samePlain, tokenTypes, tokenizeLine } from "./language/language.js";
11
11
  import { CodeHighlighter } from "./language/highlighter.js";
12
+ import { createCodeWorkerPool } from "./language/worker-client.js";
12
13
  import { codeLocales } from "./locale.js";
13
14
  import { defaultCodeKeys } from "./code-keys.js";
14
15
  import code_keys_default from "./code-keys2.js";
@@ -33,6 +34,6 @@ var DouCodeEditor = withInstall(code_editor_default);
33
34
  var DouCodeKeys = withInstall(code_keys_default);
34
35
  var DouCodeInput = withInstall(code_input_default);
35
36
  var DouCodeDiff = withInstall(code_diff_default);
36
- export { ChangeSet, CodeHighlighter, CodeStream, CodeText, CodeTransaction, DouCodeDiff, DouCodeEditor, DouCodeEditor as default, DouCodeInput, DouCodeKeys, commands_exports as codeCommands, codeLocales, copyPlain, createCodeHighlighter, createCss, createHtml, createJavaScript, createMarkdown, css, defaultCodeKeys, defaultKeymap, defineCodeExtension, defineCodeLanguage, diffText, findPartner, highlightToHtml, html, isEmptyRange, javascript, json, jsx, languageFor, lineParts, mainRange, mapSelection, markdown, matchAfter, matchBracket, normalizeSelection, python, queryRegExp, rangeFrom, rangeTo, replacementFor, samePlain, sameSelection, scss, searchText, selectionOf, shell, splitLines, sql, tokenTypes, tokenizeLine, tsx, typescript, useCodeEditor, vue, yaml };
37
+ export { ChangeSet, CodeHighlighter, CodeStream, CodeText, CodeTransaction, DouCodeDiff, DouCodeEditor, DouCodeEditor as default, DouCodeInput, DouCodeKeys, commands_exports as codeCommands, codeLocales, copyPlain, createCodeHighlighter, createCodeWorkerPool, createCss, createHtml, createJavaScript, createMarkdown, css, defaultCodeKeys, defaultKeymap, defineCodeExtension, defineCodeLanguage, diffText, findPartner, highlightToHtml, html, isEmptyRange, javascript, json, jsx, languageFor, lineParts, mainRange, mapSelection, markdown, matchAfter, matchBracket, normalizeSelection, python, queryRegExp, rangeFrom, rangeTo, remoteCodeLanguage, replacementFor, samePlain, sameSelection, scss, searchText, selectionOf, shell, splitLines, sql, tokenTypes, tokenizeLine, tsx, typescript, useCodeEditor, vue, yaml };
37
38
 
38
39
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["CodeEditor","CodeKeys","CodeInput","CodeDiff"],"sources":["../src/index.ts"],"sourcesContent":["import { withInstall } from 'dou-ui'\nimport CodeEditor from './code-editor.vue'\nimport CodeDiff from './code-diff.vue'\nimport CodeInput from './code-input.vue'\nimport CodeKeys from './code-keys.vue'\n\nexport const DouCodeEditor = withInstall(CodeEditor)\nexport const DouCodeKeys = withInstall(CodeKeys)\nexport const DouCodeInput = withInstall(CodeInput)\nexport const DouCodeDiff = withInstall(CodeDiff)\nexport { diffText } from './core/diff'\nexport type { CodeDiffHunk, CodeDiffOptions, CodeDiffPart } from './core/diff'\nexport { defaultCodeKeys } from './code-keys'\nexport { defineCodeExtension, useCodeEditor } from './extension'\nexport type {\n CodeDecoration,\n CodeDiagnostic,\n CodeDiagnosticAction,\n CodeDiagnosticSeverity,\n CodeExtension,\n CodeExtensionContext,\n CodeGutter,\n CodeGutterMarker,\n CodeHistoryHandler,\n CodeCompletion,\n CodeCompletionKind,\n CodeCompletionRequest,\n CodePositionRequest,\n CodeCompletionResult,\n CodeHoverResult,\n CodeMenuItem,\n CodePanel,\n CodeSignatureResult,\n CodeWidget,\n} from './extension'\nexport default DouCodeEditor\n\nexport type {\n CodeDiffEmits,\n CodeDiffProps,\n CodeEditorEmits,\n CodeEditorExpose,\n CodeEditorProps,\n CodeInputEmits,\n CodeInputProps,\n CodeKey,\n CodeKeysProps,\n} from './types'\nexport { CodeText, splitLines } from './core/text'\nexport type { CodeLine } from './core/text'\nexport { ChangeSet } from './core/changes'\nexport type { CodeChange, CodeChangeSpec, MapAssoc } from './core/changes'\nexport {\n isEmptyRange,\n mainRange,\n mapSelection,\n normalizeSelection,\n rangeFrom,\n rangeTo,\n sameSelection,\n selectionOf,\n} from './core/selection'\nexport type { CodeRange, CodeSelection } from './core/selection'\nexport { CodeTransaction } from './core/transaction'\nexport type {\n CodeAction,\n CodeState,\n CodeTransactionMeta,\n CodeTransactionResult,\n} from './core/transaction'\nexport * as codeCommands from './core/commands'\nexport type { CodeCommand, CodeCommandTarget } from './core/commands'\nexport { defaultKeymap } from './core/keymap'\nexport { findPartner, matchBracket } from './core/brackets'\nexport type { BracketMatch } from './core/brackets'\nexport { CodeStream } from './language/stream'\nexport {\n copyPlain,\n defineCodeLanguage,\n languageFor,\n lineParts,\n samePlain,\n tokenizeLine,\n tokenTypes,\n} from './language/language'\nexport type {\n CodeLanguage,\n CodeLanguageSpec,\n CodeLineTokens,\n CodeTokenType,\n} from './language/language'\nexport { CodeHighlighter } from './language/highlighter'\nexport { createCodeHighlighter, highlightToHtml } from './language/to-html'\nexport { createJavaScript, javascript, jsx, tsx, typescript } from './languages/javascript'\nexport type { JavaScriptOptions, JavaScriptState } from './languages/javascript'\nexport { createCss, css, scss } from './languages/css'\nexport type { CssState } from './languages/css'\nexport { json } from './languages/json'\nexport type { JsonState } from './languages/json'\nexport { createHtml, html, vue } from './languages/html'\nexport type { HtmlState } from './languages/html'\nexport { createMarkdown, markdown } from './languages/markdown'\nexport type { MarkdownOptions, MarkdownState } from './languages/markdown'\nexport { python } from './languages/python'\nexport type { PythonState } from './languages/python'\nexport { shell } from './languages/shell'\nexport type { ShellState } from './languages/shell'\nexport { sql } from './languages/sql'\nexport type { SqlState } from './languages/sql'\nexport { yaml } from './languages/yaml'\nexport type { YamlState } from './languages/yaml'\nexport type { CodeKeyBinding, CodeKeymap } from './core/keymap'\nexport type { CodeAssistControl, CodeDiagnosticControl, CodeSearchControl } from './core/commands'\nexport { matchAfter, queryRegExp, replacementFor, searchText } from './core/search'\nexport type { CodeMatch, CodeSearchQuery, CodeSearchResult } from './core/search'\nexport { codeLocales } from './locale'\nexport type { CodeMessages } from './locale'\n\ndeclare module 'vue' {\n export interface GlobalComponents {\n DouCodeEditor: typeof DouCodeEditor\n DouCodeKeys: typeof DouCodeKeys\n DouCodeInput: typeof DouCodeInput\n DouCodeDiff: typeof DouCodeDiff\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAa,gBAAgB,YAAYA,mBAAU;AACnD,IAAa,cAAc,YAAYC,iBAAQ;AAC/C,IAAa,eAAe,YAAYC,kBAAS;AACjD,IAAa,cAAc,YAAYC,iBAAQ"}
1
+ {"version":3,"file":"index.js","names":["CodeEditor","CodeKeys","CodeInput","CodeDiff"],"sources":["../src/index.ts"],"sourcesContent":["import { withInstall } from 'dou-ui'\nimport CodeEditor from './code-editor.vue'\nimport CodeDiff from './code-diff.vue'\nimport CodeInput from './code-input.vue'\nimport CodeKeys from './code-keys.vue'\n\nexport const DouCodeEditor = withInstall(CodeEditor)\nexport const DouCodeKeys = withInstall(CodeKeys)\nexport const DouCodeInput = withInstall(CodeInput)\nexport const DouCodeDiff = withInstall(CodeDiff)\nexport { diffText } from './core/diff'\nexport type { CodeDiffHunk, CodeDiffOptions, CodeDiffPart } from './core/diff'\nexport { defaultCodeKeys } from './code-keys'\nexport { defineCodeExtension, useCodeEditor } from './extension'\nexport type {\n CodeDecoration,\n CodeDiagnostic,\n CodeDiagnosticAction,\n CodeDiagnosticSeverity,\n CodeExtension,\n CodeExtensionContext,\n CodeGutter,\n CodeGutterHoverMarker,\n CodeGutterMarker,\n CodeHistoryHandler,\n CodeCompletion,\n CodeCompletionKind,\n CodeCompletionRequest,\n CodePositionRequest,\n CodeCompletionResult,\n CodeHoverResult,\n CodeMenuItem,\n CodePanel,\n CodeSignatureResult,\n CodeWidget,\n} from './extension'\nexport default DouCodeEditor\n\nexport type {\n CodeDiffEmits,\n CodeDiffExpose,\n CodeDiffGutter,\n CodeDiffGutterMarker,\n CodeDiffHoverMarker,\n CodeDiffProps,\n CodeDiffSide,\n CodeDiffSlots,\n CodeDiffWidget,\n CodeEditorEmits,\n CodeEditorExpose,\n CodeEditorProps,\n CodeInputEmits,\n CodeInputProps,\n CodeKey,\n CodeKeysProps,\n} from './types'\nexport { CodeText, splitLines } from './core/text'\nexport type { CodeLine } from './core/text'\nexport { ChangeSet } from './core/changes'\nexport type { CodeChange, CodeChangeSpec, MapAssoc } from './core/changes'\nexport {\n isEmptyRange,\n mainRange,\n mapSelection,\n normalizeSelection,\n rangeFrom,\n rangeTo,\n sameSelection,\n selectionOf,\n} from './core/selection'\nexport type { CodeRange, CodeSelection } from './core/selection'\nexport { CodeTransaction } from './core/transaction'\nexport type {\n CodeAction,\n CodeState,\n CodeTransactionMeta,\n CodeTransactionResult,\n} from './core/transaction'\nexport * as codeCommands from './core/commands'\nexport type { CodeCommand, CodeCommandTarget } from './core/commands'\nexport { defaultKeymap } from './core/keymap'\nexport { findPartner, matchBracket } from './core/brackets'\nexport type { BracketMatch } from './core/brackets'\nexport { CodeStream } from './language/stream'\nexport {\n copyPlain,\n defineCodeLanguage,\n languageFor,\n lineParts,\n remoteCodeLanguage,\n samePlain,\n tokenizeLine,\n tokenTypes,\n} from './language/language'\nexport type {\n CodeLanguage,\n CodeLanguageSpec,\n CodeLineTokens,\n CodeTokenType,\n RemoteCodeLanguageOptions,\n} from './language/language'\nexport { createCodeWorkerPool } from './language/worker-client'\nexport type {\n CodeWorkerOption,\n CodeWorkerPool,\n CodeWorkerPoolOptions,\n} from './language/worker-client'\nexport { CodeHighlighter } from './language/highlighter'\nexport { createCodeHighlighter, highlightToHtml } from './language/to-html'\nexport { createJavaScript, javascript, jsx, tsx, typescript } from './languages/javascript'\nexport type { JavaScriptOptions, JavaScriptState } from './languages/javascript'\nexport { createCss, css, scss } from './languages/css'\nexport type { CssState } from './languages/css'\nexport { json } from './languages/json'\nexport type { JsonState } from './languages/json'\nexport { createHtml, html, vue } from './languages/html'\nexport type { HtmlState } from './languages/html'\nexport { createMarkdown, markdown } from './languages/markdown'\nexport type { MarkdownOptions, MarkdownState } from './languages/markdown'\nexport { python } from './languages/python'\nexport type { PythonState } from './languages/python'\nexport { shell } from './languages/shell'\nexport type { ShellState } from './languages/shell'\nexport { sql } from './languages/sql'\nexport type { SqlState } from './languages/sql'\nexport { yaml } from './languages/yaml'\nexport type { YamlState } from './languages/yaml'\nexport type { CodeKeyBinding, CodeKeymap } from './core/keymap'\nexport type { CodeAssistControl, CodeDiagnosticControl, CodeSearchControl } from './core/commands'\nexport { matchAfter, queryRegExp, replacementFor, searchText } from './core/search'\nexport type { CodeMatch, CodeSearchQuery, CodeSearchResult } from './core/search'\nexport { codeLocales } from './locale'\nexport type { CodeMessages } from './locale'\n\ndeclare module 'vue' {\n export interface GlobalComponents {\n DouCodeEditor: typeof DouCodeEditor\n DouCodeKeys: typeof DouCodeKeys\n DouCodeInput: typeof DouCodeInput\n DouCodeDiff: typeof DouCodeDiff\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAa,gBAAgB,YAAYA,mBAAU;AACnD,IAAa,cAAc,YAAYC,iBAAQ;AAC/C,IAAa,eAAe,YAAYC,kBAAS;AACjD,IAAa,cAAc,YAAYC,iBAAQ"}
@@ -287,7 +287,7 @@ var CodeHighlighter = class {
287
287
  const start = this.read;
288
288
  while (this.read < end) {
289
289
  this.step(false);
290
- if ((this.read & 15) === 0 && performance.now() >= deadline) break;
290
+ if ((this.read & 3) === 0 && performance.now() >= deadline) break;
291
291
  }
292
292
  return this.read > start;
293
293
  }
@@ -1 +1 @@
1
- {"version":3,"file":"highlighter.js","names":[],"sources":["../../src/language/highlighter.ts"],"sourcesContent":["import type { ChangeSet } from '../core/changes'\nimport type { CodeText } from '../core/text'\nimport { type CodeLanguage, type CodeLineTokens, tokenizeLine } from './language'\n\n/** Lines between the start states kept: a line read again costs at most this many. */\nconst INTERVAL = 32\n/** Lines whose tokens are kept; the rest are read again from a kept state when drawn. */\nconst CACHE = 4000\n\nexport interface CodeHighlighterOptions {\n tabSize?: number\n /** Lines between kept start states. */\n interval?: number\n /** Lines whose tokens are kept. */\n cache?: number\n}\n\n/**\n * Keeps the tokens of a text up to date as it changes.\n *\n * Reading goes down from the top. It keeps the state at the start of\n * every 32nd line read, and the tokens of the lines drawn lately; a line\n * whose tokens are gone is read again from the kept state above it. So a\n * text of a million lines, all read, holds some thirty thousand states\n * and a few thousand lines' tokens.\n *\n * After an edit, lines before it keep everything; reading resumes at the\n * edited line and stops as soon as a line after the edit starts in the\n * same state as before, because from there on nothing can differ. Typing\n * inside a function rereads one line; opening a comment rereads up to\n * where it closes.\n *\n * Lines are read only when asked for (the ones in view and those before\n * them); the rest wait for idle time, or come from a worker through\n * `adopt`, so opening a long file costs nothing up front.\n */\nexport class CodeHighlighter<S = unknown> {\n readonly tabSize: number\n private readonly interval: number\n private readonly cacheSize: number\n\n /** Kept start states: `lines[k]` starts in `states[k]`; the first is line 0. */\n private lines: number[] = [0]\n private states: S[]\n /** Lines above this index are read; `tip` is the state line `read` starts in. */\n private read = 0\n private tip: S\n\n /**\n * What was read past an edit, moved to where those lines are now. Once\n * reading reaches one of these lines in the same state, everything up to\n * `oldEnd` (which starts in `oldTip`) is read again for free.\n */\n private oldLines: number[] = []\n private oldStates: S[] = []\n private oldAt = 0\n private oldEnd = -1\n private oldTip: S | undefined\n\n /** Where reading again from a kept state last got to, so going down line by line doesn't start over each time. */\n private walk: { line: number; state: S } | null = null\n\n /** Tokens by line index, oldest first. */\n private cache = new Map<number, CodeLineTokens>()\n\n constructor(\n readonly language: CodeLanguage<S>,\n private doc: CodeText,\n options: number | CodeHighlighterOptions = {},\n ) {\n const opts = typeof options === 'number' ? { tabSize: options } : options\n this.tabSize = opts.tabSize ?? 2\n this.interval = Math.max(1, opts.interval ?? INTERVAL)\n this.cacheSize = Math.max(1, opts.cache ?? CACHE)\n this.tip = language.startState()\n this.states = [this.tip]\n }\n\n /** How many lines from the top are read. */\n get frontier(): number {\n return this.read\n }\n\n /** The text being read. */\n get text(): CodeText {\n return this.doc\n }\n\n /** Takes in a new text, made from the old one by `changes`. Without them, starts over. */\n update(doc: CodeText, changes?: ChangeSet): void {\n const old = this.doc\n this.doc = doc\n if (!changes || changes.empty) {\n if (!changes) this.reset()\n return\n }\n const list = changes.changes\n const first = list[0]!\n const last = list[list.length - 1]!\n // Line indices touched in the old text, and where they end in the new one.\n const a = old.lineAt(first.from).number - 1\n const b = old.lineAt(last.to).number - 1\n const end = doc.lineAt(changes.mapPos(last.to, 1)).number - 1\n const delta = end - b\n\n for (const key of this.cache.keys()) if (key >= a) this.cache.delete(key)\n if (this.walk && this.walk.line > a) this.walk = null\n\n const movedLines: number[] = []\n const movedStates: S[] = []\n let endLine = -1\n let endTip: S | undefined\n const move = (line: number, state: S) => {\n if (line > b) {\n movedLines.push(line + delta)\n movedStates.push(state)\n }\n }\n\n if (a < this.read) {\n // What was read after the edit becomes old, to compare the new reading with.\n if (b + 1 < this.read) {\n // The line right after the edit, so typing on one line stops at the next.\n const at = this.lines[this.keptAt(b + 1)]!\n if (at !== b + 1) move(b + 1, this.stateIn(old, b + 1))\n }\n for (let k = 0; k < this.lines.length; k++) move(this.lines[k]!, this.states[k]!)\n // What was still to be taken back past `read` doesn't follow on from the new\n // reading, so it goes; reading through the edit ends at the old `read`.\n if (this.read > b) {\n endLine = this.read + delta\n endTip = this.tip\n }\n // Reading starts again at the last kept state at or above the edit.\n const keep = this.keptAt(a) + 1\n this.lines.length = keep\n this.states.length = keep\n this.read = this.lines[keep - 1]!\n this.tip = this.states[keep - 1]!\n } else if (this.oldEnd >= 0) {\n // Only what is still to be taken back can be touched.\n const lines = this.oldLines\n if (this.oldAt < lines.length && lines[this.oldAt]! <= a && a < this.oldEnd) {\n // An edit among those lines: the ones above it can still be taken back, up to the last one.\n for (let k = this.oldAt; k < lines.length && lines[k]! <= a; k++) {\n movedLines.push(lines[k]!)\n movedStates.push(this.oldStates[k]!)\n }\n } else {\n for (let k = this.oldAt; k < lines.length; k++) move(lines[k]!, this.oldStates[k]!)\n if (this.oldEnd > b) {\n endLine = this.oldEnd + delta\n endTip = this.oldTip\n } else if (this.oldEnd <= a) {\n endLine = this.oldEnd\n endTip = this.oldTip\n }\n }\n } else return\n\n // Without its last line, the last state taken back ends it.\n if (endLine < 0 && movedLines.length) {\n endLine = movedLines.pop()!\n endTip = movedStates.pop()\n }\n this.oldLines = movedLines\n this.oldStates = movedStates\n this.oldAt = 0\n this.oldEnd = endLine > this.read && endLine <= doc.lines ? endLine : -1\n this.oldTip = this.oldEnd >= 0 ? endTip : undefined\n if (this.oldEnd < 0) this.dropOld()\n }\n\n private reset() {\n this.tip = this.language.startState()\n this.lines = [0]\n this.states = [this.tip]\n this.read = 0\n this.cache.clear()\n this.walk = null\n this.dropOld()\n }\n\n private dropOld() {\n this.oldLines = []\n this.oldStates = []\n this.oldAt = 0\n this.oldEnd = -1\n this.oldTip = undefined\n }\n\n /** The index of the last kept state at or above line `i`. */\n private keptAt(i: number): number {\n let lo = 0\n let hi = this.lines.length - 1\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if (this.lines[mid]! <= i) lo = mid\n else hi = mid - 1\n }\n return lo\n }\n\n /** Where to start reading line `i` again from: a kept state, or where the last such reading got to. */\n private from(i: number): { line: number; state: S } {\n const k = this.keptAt(i)\n const walk = this.walk\n if (walk && walk.line <= i && walk.line >= this.lines[k]!)\n return { line: walk.line, state: this.language.copyState(walk.state) }\n return { line: this.lines[k]!, state: this.language.copyState(this.states[k]!) }\n }\n\n /** The state line `i` starts in, read from the kept state above it in `doc`. */\n private stateIn(doc: CodeText, i: number): S {\n if (doc !== this.doc) {\n const k = this.keptAt(i)\n const state = this.language.copyState(this.states[k]!)\n for (let j = this.lines[k]!; j < i; j++)\n tokenizeLine(this.language, doc.lineText(j + 1), state, this.tabSize)\n return state\n }\n const start = this.from(i)\n const state = start.state\n for (let j = start.line; j < i; j++)\n tokenizeLine(this.language, doc.lineText(j + 1), state, this.tabSize)\n this.walk = { line: i, state }\n return state\n }\n\n private remember(i: number, tokens: CodeLineTokens) {\n this.cache.delete(i)\n this.cache.set(i, tokens)\n if (this.cache.size > this.cacheSize) this.cache.delete(this.cache.keys().next().value!)\n }\n\n /** Reads the next unread line, keeping its tokens with `keep`. */\n private step(keep: boolean) {\n const i = this.read\n const state = this.language.copyState(this.tip)\n const tokens = tokenizeLine(this.language, this.doc.lineText(i + 1), state, this.tabSize)\n if (keep) this.remember(i, tokens)\n const next = i + 1\n if (this.oldEnd >= 0) {\n const lines = this.oldLines\n while (this.oldAt < lines.length && lines[this.oldAt]! < next) this.oldAt++\n const same =\n next === this.oldEnd\n ? this.language.sameState(state, this.oldTip!)\n : lines[this.oldAt] === next &&\n this.language.sameState(state, this.oldStates[this.oldAt]!)\n if (same) {\n // Same state as before the edit: everything up to `oldEnd` stands.\n if (next - this.lines[this.lines.length - 1]! >= this.interval) {\n this.lines.push(next)\n this.states.push(state)\n }\n for (let k = this.oldAt; k < lines.length; k++) {\n if (lines[k]! <= next) continue\n this.lines.push(lines[k]!)\n this.states.push(this.oldStates[k]!)\n }\n this.read = this.oldEnd\n this.tip = this.oldTip!\n this.dropOld()\n return\n }\n if (next >= this.oldEnd) this.dropOld()\n }\n if (next - this.lines[this.lines.length - 1]! >= this.interval) {\n this.lines.push(next)\n this.states.push(state)\n }\n this.read = next\n this.tip = state\n }\n\n /**\n * The tokens of line `n` (from 1), reading up to it if it takes no more\n * than `limit` lines; `null` when it would take more, so the caller\n * draws plain text and lets idle time catch up.\n */\n line(n: number, limit = Infinity): CodeLineTokens | null {\n const i = n - 1\n if (i < 0 || i >= this.doc.lines) return null\n const cached = this.cache.get(i)\n if (cached) return cached\n if (i < this.read) {\n // Read again from the kept state above it.\n const start = this.from(i)\n const state = start.state\n let tokens: CodeLineTokens = []\n for (let j = start.line; j <= i; j++) {\n tokens = tokenizeLine(this.language, this.doc.lineText(j + 1), state, this.tabSize)\n this.remember(j, tokens)\n }\n this.walk = { line: i + 1, state }\n return tokens\n }\n if (i - this.read > limit) return null\n // the lines just above it are likely drawn too\n const near = i - Math.min(this.cacheSize >> 1, 256)\n while (this.read <= i) this.step(this.read >= near)\n return this.cache.get(i) ?? null\n }\n\n /** The state at the start of line `n`, reading up to it. */\n stateAt(n: number): S {\n const i = Math.min(Math.max(n - 1, 0), this.doc.lines - 1)\n if (i === this.read) return this.tip\n if (i < this.read) return this.stateIn(this.doc, i)\n while (this.read < i) this.step(false)\n return this.tip\n }\n\n /** The language active at the start of line `n`: an inner one inside a nesting language. */\n languageAt(n: number): CodeLanguage {\n let language: CodeLanguage = this.language\n let state: unknown = this.stateAt(n)\n // A nested language may itself nest, e.g. Markdown → HTML → script.\n for (let depth = 0; depth < 4; depth++) {\n const inner = language.languageAt(state)\n if (!inner) break\n const innerState = (state as { inner?: { state: unknown } }).inner?.state\n language = inner\n state = innerState\n }\n return language\n }\n\n /** Reads ahead until `deadline` (a `performance.now()` time) or line `until`; returns whether it read any. */\n work(deadline: number, until = this.doc.lines): boolean {\n const end = Math.min(until, this.doc.lines)\n const start = this.read\n while (this.read < end) {\n this.step(false)\n // the clock is read every few lines: it costs more than a short line\n if ((this.read & 15) === 0 && performance.now() >= deadline) break\n }\n return this.read > start\n }\n\n /** Whether every line up to `n` is read. */\n ready(n: number): boolean {\n return this.read >= Math.min(n, this.doc.lines)\n }\n\n /**\n * The kept start states from line `from` (an index) on, as\n * `[line, state]` pairs, ending with the line reading is at.\n */\n checkpoints(from = 0): Array<[line: number, state: S]> {\n const out: Array<[number, S]> = []\n for (let k = this.keptAt(from); k < this.lines.length; k++)\n if (this.lines[k]! >= from) out.push([this.lines[k]!, this.states[k]!])\n if (this.read > (out.length ? out[out.length - 1]![0] : -1)) out.push([this.read, this.tip])\n return out\n }\n\n /**\n * Takes in start states read elsewhere (a worker reading the same text):\n * `[line, state]` pairs in order, the last one where that reading is.\n * Those past what is read here are kept as read.\n */\n adopt(points: ReadonlyArray<readonly [line: number, state: S]>): void {\n if (!points.length) return\n const [endLine, endState] = points[points.length - 1]!\n if (endLine <= this.read || endLine > this.doc.lines) return\n // Only states after a kept one here, so each line keeps one reading.\n const after = this.read\n // The state at `read` is known here; ones before it must match it.\n let k = 0\n while (k < points.length && points[k]![0] <= after) k++\n const kept = this.lines[this.lines.length - 1]!\n let last = kept\n for (; k < points.length - 1; k++) {\n const [line, state] = points[k]!\n if (line - last < this.interval) continue\n this.lines.push(line)\n this.states.push(state)\n last = line\n }\n for (const key of this.cache.keys()) if (key >= after) this.cache.delete(key)\n this.read = endLine\n this.tip = endState\n this.dropOld()\n }\n}\n"],"mappings":";;;AAKA,IAAM,WAAW;;AAEjB,IAAM,QAAQ;;;;;;;;;;;;;;;;;;;;AA6Bd,IAAa,kBAAb,MAA0C;CA8B7B;CACD;CA9BV;CACA;CACA;;CAGA,QAA0B,CAAC,CAAC;CAC5B;;CAEA,OAAe;CACf;;;;;;CAOA,WAA6B,CAAC;CAC9B,YAAyB,CAAC;CAC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KAAK,QAAQ,IAAI,SAAS,IAAI,IAAI,SAAS,EAAE,CAAE,KAAK,KAAK,IAAI,KAAK,CAAC,KAAK,MAAM,KAAK,GAAG,CAAC;EAC3F,OAAO;CACT;;;;;;CAOA,MAAM,QAAgE;EACpE,IAAI,CAAC,OAAO,QAAQ;EACpB,MAAM,CAAC,SAAS,YAAY,OAAO,OAAO,SAAS;EACnD,IAAI,WAAW,KAAK,QAAQ,UAAU,KAAK,IAAI,OAAO;EAEtD,MAAM,QAAQ,KAAK;EAEnB,IAAI,IAAI;EACR,OAAO,IAAI,OAAO,UAAU,OAAO,EAAE,CAAE,MAAM,OAAO;EAEpD,IAAI,OADS,KAAK,MAAM,KAAK,MAAM,SAAS;EAE5C,OAAO,IAAI,OAAO,SAAS,GAAG,KAAK;GACjC,MAAM,CAAC,MAAM,SAAS,OAAO;GAC7B,IAAI,OAAO,OAAO,KAAK,UAAU;GACjC,KAAK,MAAM,KAAK,IAAI;GACpB,KAAK,OAAO,KAAK,KAAK;GACtB,OAAO;EACT;EACA,KAAK,MAAM,OAAO,KAAK,MAAM,KAAK,GAAG,IAAI,OAAO,OAAO,KAAK,MAAM,OAAO,GAAG;EAC5E,KAAK,OAAO;EACZ,KAAK,MAAM;EACX,KAAK,QAAQ;CACf;AACF"}
1
+ {"version":3,"file":"highlighter.js","names":[],"sources":["../../src/language/highlighter.ts"],"sourcesContent":["import type { ChangeSet } from '../core/changes'\nimport type { CodeText } from '../core/text'\nimport { type CodeLanguage, type CodeLineTokens, tokenizeLine } from './language'\n\n/** Lines between the start states kept: a line read again costs at most this many. */\nconst INTERVAL = 32\n/** Lines whose tokens are kept; the rest are read again from a kept state when drawn. */\nconst CACHE = 4000\n\nexport interface CodeHighlighterOptions {\n tabSize?: number\n /** Lines between kept start states. */\n interval?: number\n /** Lines whose tokens are kept. */\n cache?: number\n}\n\n/**\n * Keeps the tokens of a text up to date as it changes.\n *\n * Reading goes down from the top. It keeps the state at the start of\n * every 32nd line read, and the tokens of the lines drawn lately; a line\n * whose tokens are gone is read again from the kept state above it. So a\n * text of a million lines, all read, holds some thirty thousand states\n * and a few thousand lines' tokens.\n *\n * After an edit, lines before it keep everything; reading resumes at the\n * edited line and stops as soon as a line after the edit starts in the\n * same state as before, because from there on nothing can differ. Typing\n * inside a function rereads one line; opening a comment rereads up to\n * where it closes.\n *\n * Lines are read only when asked for (the ones in view and those before\n * them); the rest wait for idle time, or come from a worker through\n * `adopt`, so opening a long file costs nothing up front.\n */\nexport class CodeHighlighter<S = unknown> {\n readonly tabSize: number\n private readonly interval: number\n private readonly cacheSize: number\n\n /** Kept start states: `lines[k]` starts in `states[k]`; the first is line 0. */\n private lines: number[] = [0]\n private states: S[]\n /** Lines above this index are read; `tip` is the state line `read` starts in. */\n private read = 0\n private tip: S\n\n /**\n * What was read past an edit, moved to where those lines are now. Once\n * reading reaches one of these lines in the same state, everything up to\n * `oldEnd` (which starts in `oldTip`) is read again for free.\n */\n private oldLines: number[] = []\n private oldStates: S[] = []\n private oldAt = 0\n private oldEnd = -1\n private oldTip: S | undefined\n\n /** Where reading again from a kept state last got to, so going down line by line doesn't start over each time. */\n private walk: { line: number; state: S } | null = null\n\n /** Tokens by line index, oldest first. */\n private cache = new Map<number, CodeLineTokens>()\n\n constructor(\n readonly language: CodeLanguage<S>,\n private doc: CodeText,\n options: number | CodeHighlighterOptions = {},\n ) {\n const opts = typeof options === 'number' ? { tabSize: options } : options\n this.tabSize = opts.tabSize ?? 2\n this.interval = Math.max(1, opts.interval ?? INTERVAL)\n this.cacheSize = Math.max(1, opts.cache ?? CACHE)\n this.tip = language.startState()\n this.states = [this.tip]\n }\n\n /** How many lines from the top are read. */\n get frontier(): number {\n return this.read\n }\n\n /** The text being read. */\n get text(): CodeText {\n return this.doc\n }\n\n /** Takes in a new text, made from the old one by `changes`. Without them, starts over. */\n update(doc: CodeText, changes?: ChangeSet): void {\n const old = this.doc\n this.doc = doc\n if (!changes || changes.empty) {\n if (!changes) this.reset()\n return\n }\n const list = changes.changes\n const first = list[0]!\n const last = list[list.length - 1]!\n // Line indices touched in the old text, and where they end in the new one.\n const a = old.lineAt(first.from).number - 1\n const b = old.lineAt(last.to).number - 1\n const end = doc.lineAt(changes.mapPos(last.to, 1)).number - 1\n const delta = end - b\n\n for (const key of this.cache.keys()) if (key >= a) this.cache.delete(key)\n if (this.walk && this.walk.line > a) this.walk = null\n\n const movedLines: number[] = []\n const movedStates: S[] = []\n let endLine = -1\n let endTip: S | undefined\n const move = (line: number, state: S) => {\n if (line > b) {\n movedLines.push(line + delta)\n movedStates.push(state)\n }\n }\n\n if (a < this.read) {\n // What was read after the edit becomes old, to compare the new reading with.\n if (b + 1 < this.read) {\n // The line right after the edit, so typing on one line stops at the next.\n const at = this.lines[this.keptAt(b + 1)]!\n if (at !== b + 1) move(b + 1, this.stateIn(old, b + 1))\n }\n for (let k = 0; k < this.lines.length; k++) move(this.lines[k]!, this.states[k]!)\n // What was still to be taken back past `read` doesn't follow on from the new\n // reading, so it goes; reading through the edit ends at the old `read`.\n if (this.read > b) {\n endLine = this.read + delta\n endTip = this.tip\n }\n // Reading starts again at the last kept state at or above the edit.\n const keep = this.keptAt(a) + 1\n this.lines.length = keep\n this.states.length = keep\n this.read = this.lines[keep - 1]!\n this.tip = this.states[keep - 1]!\n } else if (this.oldEnd >= 0) {\n // Only what is still to be taken back can be touched.\n const lines = this.oldLines\n if (this.oldAt < lines.length && lines[this.oldAt]! <= a && a < this.oldEnd) {\n // An edit among those lines: the ones above it can still be taken back, up to the last one.\n for (let k = this.oldAt; k < lines.length && lines[k]! <= a; k++) {\n movedLines.push(lines[k]!)\n movedStates.push(this.oldStates[k]!)\n }\n } else {\n for (let k = this.oldAt; k < lines.length; k++) move(lines[k]!, this.oldStates[k]!)\n if (this.oldEnd > b) {\n endLine = this.oldEnd + delta\n endTip = this.oldTip\n } else if (this.oldEnd <= a) {\n endLine = this.oldEnd\n endTip = this.oldTip\n }\n }\n } else return\n\n // Without its last line, the last state taken back ends it.\n if (endLine < 0 && movedLines.length) {\n endLine = movedLines.pop()!\n endTip = movedStates.pop()\n }\n this.oldLines = movedLines\n this.oldStates = movedStates\n this.oldAt = 0\n this.oldEnd = endLine > this.read && endLine <= doc.lines ? endLine : -1\n this.oldTip = this.oldEnd >= 0 ? endTip : undefined\n if (this.oldEnd < 0) this.dropOld()\n }\n\n private reset() {\n this.tip = this.language.startState()\n this.lines = [0]\n this.states = [this.tip]\n this.read = 0\n this.cache.clear()\n this.walk = null\n this.dropOld()\n }\n\n private dropOld() {\n this.oldLines = []\n this.oldStates = []\n this.oldAt = 0\n this.oldEnd = -1\n this.oldTip = undefined\n }\n\n /** The index of the last kept state at or above line `i`. */\n private keptAt(i: number): number {\n let lo = 0\n let hi = this.lines.length - 1\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if (this.lines[mid]! <= i) lo = mid\n else hi = mid - 1\n }\n return lo\n }\n\n /** Where to start reading line `i` again from: a kept state, or where the last such reading got to. */\n private from(i: number): { line: number; state: S } {\n const k = this.keptAt(i)\n const walk = this.walk\n if (walk && walk.line <= i && walk.line >= this.lines[k]!)\n return { line: walk.line, state: this.language.copyState(walk.state) }\n return { line: this.lines[k]!, state: this.language.copyState(this.states[k]!) }\n }\n\n /** The state line `i` starts in, read from the kept state above it in `doc`. */\n private stateIn(doc: CodeText, i: number): S {\n if (doc !== this.doc) {\n const k = this.keptAt(i)\n const state = this.language.copyState(this.states[k]!)\n for (let j = this.lines[k]!; j < i; j++)\n tokenizeLine(this.language, doc.lineText(j + 1), state, this.tabSize)\n return state\n }\n const start = this.from(i)\n const state = start.state\n for (let j = start.line; j < i; j++)\n tokenizeLine(this.language, doc.lineText(j + 1), state, this.tabSize)\n this.walk = { line: i, state }\n return state\n }\n\n private remember(i: number, tokens: CodeLineTokens) {\n this.cache.delete(i)\n this.cache.set(i, tokens)\n if (this.cache.size > this.cacheSize) this.cache.delete(this.cache.keys().next().value!)\n }\n\n /** Reads the next unread line, keeping its tokens with `keep`. */\n private step(keep: boolean) {\n const i = this.read\n const state = this.language.copyState(this.tip)\n const tokens = tokenizeLine(this.language, this.doc.lineText(i + 1), state, this.tabSize)\n if (keep) this.remember(i, tokens)\n const next = i + 1\n if (this.oldEnd >= 0) {\n const lines = this.oldLines\n while (this.oldAt < lines.length && lines[this.oldAt]! < next) this.oldAt++\n const same =\n next === this.oldEnd\n ? this.language.sameState(state, this.oldTip!)\n : lines[this.oldAt] === next &&\n this.language.sameState(state, this.oldStates[this.oldAt]!)\n if (same) {\n // Same state as before the edit: everything up to `oldEnd` stands.\n if (next - this.lines[this.lines.length - 1]! >= this.interval) {\n this.lines.push(next)\n this.states.push(state)\n }\n for (let k = this.oldAt; k < lines.length; k++) {\n if (lines[k]! <= next) continue\n this.lines.push(lines[k]!)\n this.states.push(this.oldStates[k]!)\n }\n this.read = this.oldEnd\n this.tip = this.oldTip!\n this.dropOld()\n return\n }\n if (next >= this.oldEnd) this.dropOld()\n }\n if (next - this.lines[this.lines.length - 1]! >= this.interval) {\n this.lines.push(next)\n this.states.push(state)\n }\n this.read = next\n this.tip = state\n }\n\n /**\n * The tokens of line `n` (from 1), reading up to it if it takes no more\n * than `limit` lines; `null` when it would take more, so the caller\n * draws plain text and lets idle time catch up.\n */\n line(n: number, limit = Infinity): CodeLineTokens | null {\n const i = n - 1\n if (i < 0 || i >= this.doc.lines) return null\n const cached = this.cache.get(i)\n if (cached) return cached\n if (i < this.read) {\n // Read again from the kept state above it.\n const start = this.from(i)\n const state = start.state\n let tokens: CodeLineTokens = []\n for (let j = start.line; j <= i; j++) {\n tokens = tokenizeLine(this.language, this.doc.lineText(j + 1), state, this.tabSize)\n this.remember(j, tokens)\n }\n this.walk = { line: i + 1, state }\n return tokens\n }\n if (i - this.read > limit) return null\n // the lines just above it are likely drawn too\n const near = i - Math.min(this.cacheSize >> 1, 256)\n while (this.read <= i) this.step(this.read >= near)\n return this.cache.get(i) ?? null\n }\n\n /** The state at the start of line `n`, reading up to it. */\n stateAt(n: number): S {\n const i = Math.min(Math.max(n - 1, 0), this.doc.lines - 1)\n if (i === this.read) return this.tip\n if (i < this.read) return this.stateIn(this.doc, i)\n while (this.read < i) this.step(false)\n return this.tip\n }\n\n /** The language active at the start of line `n`: an inner one inside a nesting language. */\n languageAt(n: number): CodeLanguage {\n let language: CodeLanguage = this.language\n let state: unknown = this.stateAt(n)\n // A nested language may itself nest, e.g. Markdown → HTML → script.\n for (let depth = 0; depth < 4; depth++) {\n const inner = language.languageAt(state)\n if (!inner) break\n const innerState = (state as { inner?: { state: unknown } }).inner?.state\n language = inner\n state = innerState\n }\n return language\n }\n\n /** Reads ahead until `deadline` (a `performance.now()` time) or line `until`; returns whether it read any. */\n work(deadline: number, until = this.doc.lines): boolean {\n const end = Math.min(until, this.doc.lines)\n const start = this.read\n while (this.read < end) {\n this.step(false)\n // the clock is read every few lines: it costs more than a short line\n if ((this.read & 3) === 0 && performance.now() >= deadline) break\n }\n return this.read > start\n }\n\n /** Whether every line up to `n` is read. */\n ready(n: number): boolean {\n return this.read >= Math.min(n, this.doc.lines)\n }\n\n /**\n * The kept start states from line `from` (an index) on, as\n * `[line, state]` pairs, ending with the line reading is at.\n */\n checkpoints(from = 0): Array<[line: number, state: S]> {\n const out: Array<[number, S]> = []\n for (let k = this.keptAt(from); k < this.lines.length; k++)\n if (this.lines[k]! >= from) out.push([this.lines[k]!, this.states[k]!])\n if (this.read > (out.length ? out[out.length - 1]![0] : -1)) out.push([this.read, this.tip])\n return out\n }\n\n /**\n * Takes in start states read elsewhere (a worker reading the same text):\n * `[line, state]` pairs in order, the last one where that reading is.\n * Those past what is read here are kept as read.\n */\n adopt(points: ReadonlyArray<readonly [line: number, state: S]>): void {\n if (!points.length) return\n const [endLine, endState] = points[points.length - 1]!\n if (endLine <= this.read || endLine > this.doc.lines) return\n // Only states after a kept one here, so each line keeps one reading.\n const after = this.read\n // The state at `read` is known here; ones before it must match it.\n let k = 0\n while (k < points.length && points[k]![0] <= after) k++\n const kept = this.lines[this.lines.length - 1]!\n let last = kept\n for (; k < points.length - 1; k++) {\n const [line, state] = points[k]!\n if (line - last < this.interval) continue\n this.lines.push(line)\n this.states.push(state)\n last = line\n }\n for (const key of this.cache.keys()) if (key >= after) this.cache.delete(key)\n this.read = endLine\n this.tip = endState\n this.dropOld()\n }\n}\n"],"mappings":";;;AAKA,IAAM,WAAW;;AAEjB,IAAM,QAAQ;;;;;;;;;;;;;;;;;;;;AA6Bd,IAAa,kBAAb,MAA0C;CA8B7B;CACD;CA9BV;CACA;CACA;;CAGA,QAA0B,CAAC,CAAC;CAC5B;;CAEA,OAAe;CACf;;;;;;CAOA,WAA6B,CAAC;CAC9B,YAAyB,CAAC;CAC1B,QAAgB;CAChB,SAAiB;CACjB;;CAGA,OAAkD;;CAGlD,wBAAgB,IAAI,IAA4B;CAEhD,YACE,UACA,KACA,UAA2C,CAAC,GAC5C;EAHS,KAAA,WAAA;EACD,KAAA,MAAA;EAGR,MAAM,OAAO,OAAO,YAAY,WAAW,EAAE,SAAS,QAAQ,IAAI;EAClE,KAAK,UAAU,KAAK,WAAW;EAC/B,KAAK,WAAW,KAAK,IAAI,GAAG,KAAK,YAAY,QAAQ;EACrD,KAAK,YAAY,KAAK,IAAI,GAAG,KAAK,SAAS,KAAK;EAChD,KAAK,MAAM,SAAS,WAAW;EAC/B,KAAK,SAAS,CAAC,KAAK,GAAG;CACzB;;CAGA,IAAI,WAAmB;EACrB,OAAO,KAAK;CACd;;CAGA,IAAI,OAAiB;EACnB,OAAO,KAAK;CACd;;CAGA,OAAO,KAAe,SAA2B;EAC/C,MAAM,MAAM,KAAK;EACjB,KAAK,MAAM;EACX,IAAI,CAAC,WAAW,QAAQ,OAAO;GAC7B,IAAI,CAAC,SAAS,KAAK,MAAM;GACzB;EACF;EACA,MAAM,OAAO,QAAQ;EACrB,MAAM,QAAQ,KAAK;EACnB,MAAM,OAAO,KAAK,KAAK,SAAS;EAEhC,MAAM,IAAI,IAAI,OAAO,MAAM,IAAI,CAAC,CAAC,SAA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@ function defineCodeLanguage(spec) {
85
85
  autoClose: spec.autoClose ?? openers + "'\"",
86
86
  indentAfter: spec.indentAfter,
87
87
  languageAt: spec.languageAt ?? (() => null),
88
- nested: spec.nested ?? []
88
+ nested: spec.nested ?? [],
89
+ workerMode: spec.workerMode
90
+ });
91
+ }
92
+ /**
93
+ * Describes a language highlighted entirely inside a Web Worker (such as a
94
+ * Shiki grammar loaded in the worker), without loading its tokenizer or WASM
95
+ * on the main thread. Editing features (comments, bracket pairing, auto-close,
96
+ * indentation) still work on the page; without a worker it renders plain text.
97
+ */
98
+ function remoteCodeLanguage(options) {
99
+ return defineCodeLanguage({
100
+ name: options.name,
101
+ aliases: options.aliases,
102
+ comment: options.comment,
103
+ brackets: options.brackets,
104
+ autoClose: options.autoClose,
105
+ indentAfter: options.indentAfter,
106
+ workerMode: "tokens",
107
+ token(stream) {
108
+ stream.skipToEnd();
109
+ return null;
110
+ }
89
111
  });
90
112
  }
91
113
  /** The language among `languages` named `name` or one of its aliases, ignoring case. */
@@ -133,6 +155,6 @@ function lineParts(text, tokens) {
133
155
  if (from < text.length) out.push([text.slice(from), null]);
134
156
  return out;
135
157
  }
136
- export { copyPlain, defineCodeLanguage, languageFor, lineParts, samePlain, tokenTypes, tokenizeLine };
158
+ export { copyPlain, defineCodeLanguage, languageFor, lineParts, remoteCodeLanguage, samePlain, tokenTypes, tokenizeLine };
137
159
 
138
160
  //# sourceMappingURL=language.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"language.js","names":[],"sources":["../../src/language/language.ts"],"sourcesContent":["import { markRaw } from 'vue'\nimport { CodeStream } from './stream'\n\n/**\n * What a token is. The editor draws each kind with its\n * `--dou-color-syntax-*` color, so a theme recolors code without\n * highlighting it again.\n */\nexport type CodeTokenType =\n | 'keyword'\n | 'string'\n | 'number'\n | 'comment'\n | 'function'\n | 'type'\n | 'variable'\n | 'property'\n | 'operator'\n | 'punctuation'\n | 'tag'\n | 'attribute'\n | 'meta'\n | 'invalid'\n | 'heading'\n | 'strong'\n | 'emphasis'\n | 'link'\n\n/** Every token kind, in a fixed order; tokens are stored by their index here. */\nexport const tokenTypes: readonly CodeTokenType[] = [\n 'keyword',\n 'string',\n 'number',\n 'comment',\n 'function',\n 'type',\n 'variable',\n 'property',\n 'operator',\n 'punctuation',\n 'tag',\n 'attribute',\n 'meta',\n 'invalid',\n 'heading',\n 'strong',\n 'emphasis',\n 'link',\n]\n/** Lines longer than this are not read. */\nconst MAX_LINE = 10_000\nconst typeIndex = new Map(tokenTypes.map((type, i) => [type, i]))\n\nexport interface CodeLanguageSpec<S> {\n /** The name, also matched by `languageFor('…')` and code block `lang`. */\n name: string\n /** Other names, such as file extensions: `['js', 'mjs']`. */\n aliases?: string[]\n /** The state at the start of the text. Plain data: objects, arrays, strings, numbers. */\n startState?: () => S\n /**\n * Reads one token from the stream (at least one character) and returns\n * its kind, or `null` for plain text. May change `state`, which carries\n * over to the next token and the next line.\n */\n token: (stream: CodeStream, state: S) => CodeTokenType | null\n /** Called for an empty line, for states that end at a line's end. */\n blankLine?: (state: S) => void\n /** Copies a state. By default a deep copy of its plain objects and arrays. */\n copyState?: (state: S) => S\n /** Whether two states are the same. By default compares their plain data. */\n sameState?: (a: S, b: S) => boolean\n /** How the language writes comments, for toggling them. */\n comment?: { line?: string; block?: [open: string, close: string] }\n /** Bracket pairs, for matching and indenting. Default `'()[]{}'`. */\n brackets?: string\n /** Characters, as one string, that get their closing partner typed with them. Default the brackets' openers and `'\"`. */\n autoClose?: string\n /** A line before the cursor that matches this gets one more indent on Enter, besides an open bracket. */\n indentAfter?: RegExp\n /** The language that is active in a state, for languages that hold others (a `<script>` in HTML). */\n languageAt?: (state: S) => CodeLanguage | null\n /**\n * The languages this one may hold, for languages with `languageAt`. A\n * worker sends states with the languages in them by name; these are the\n * ones the names are looked up in.\n */\n nested?: readonly CodeLanguage[]\n}\n\n/** A language: how to read its tokens, and a few facts for editing it. */\nexport interface CodeLanguage<S = any> {\n readonly name: string\n readonly aliases: readonly string[]\n startState(): S\n token(stream: CodeStream, state: S): CodeTokenType | null\n blankLine?(state: S): void\n copyState(state: S): S\n sameState(a: S, b: S): boolean\n readonly comment: { line?: string; block?: [string, string] }\n readonly brackets: string\n readonly autoClose: string\n readonly indentAfter?: RegExp\n languageAt(state: S): CodeLanguage | null\n readonly nested: readonly CodeLanguage[]\n}\n\nconst isPlain = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' &&\n value !== null &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)\n\n/** Copies arrays and plain objects; everything else (languages among them) is shared. */\nexport function copyPlain<T>(value: T): T {\n if (Array.isArray(value)) return value.map(copyPlain) as T\n if (isPlain(value)) {\n const out: Record<string, unknown> = {}\n for (const key in value) out[key] = copyPlain(value[key])\n return out as T\n }\n return value\n}\n\n/** Compares arrays and plain objects by their content; everything else by identity. */\nexport function samePlain(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) if (!samePlain(a[i], b[i])) return false\n return true\n }\n if (isPlain(a) && isPlain(b)) {\n const keys = Object.keys(a)\n if (keys.length !== Object.keys(b).length) return false\n for (const key of keys) if (!samePlain(a[key], b[key])) return false\n return true\n }\n return false\n}\n\n/**\n * Defines a language from a tokenizer that reads one line at a time.\n *\n * ```ts\n * const ini = defineCodeLanguage({\n * name: 'ini',\n * token(stream) {\n * if (stream.sol() && stream.match(/^\\s*[;#].*$/)) return 'comment'\n * if (stream.sol() && stream.match(/^\\s*\\[[^\\]]*\\]/)) return 'keyword'\n * if (stream.match(/^[\\w.-]+(?=\\s*=)/)) return 'property'\n * stream.next()\n * return null\n * },\n * })\n * ```\n */\nexport function defineCodeLanguage<S = Record<string, never>>(\n spec: CodeLanguageSpec<S>,\n): CodeLanguage<S> {\n const brackets = spec.brackets ?? '()[]{}'\n let openers = ''\n for (let i = 0; i < brackets.length; i += 2) openers += brackets[i]\n return markRaw({\n name: spec.name,\n aliases: spec.aliases ?? [],\n startState: spec.startState ?? (() => ({}) as S),\n token: spec.token,\n blankLine: spec.blankLine,\n copyState: spec.copyState ?? copyPlain,\n sameState: spec.sameState ?? samePlain,\n comment: spec.comment ?? {},\n brackets,\n autoClose: spec.autoClose ?? openers + '\\'\"',\n indentAfter: spec.indentAfter,\n languageAt: spec.languageAt ?? (() => null),\n nested: spec.nested ?? [],\n })\n}\n\n/** The language among `languages` named `name` or one of its aliases, ignoring case. */\nexport function languageFor(\n languages: readonly CodeLanguage[],\n name: string | undefined,\n): CodeLanguage | null {\n if (!name) return null\n const key = name.trim().toLowerCase()\n return (\n languages.find(\n (language) => language.name.toLowerCase() === key || language.aliases.includes(key),\n ) ?? null\n )\n}\n\n/**\n * One line's tokens, as pairs of numbers: where each token ends and its\n * kind's index in `tokenTypes` (`-1` for plain text). Each token starts\n * where the one before ended.\n */\nexport type CodeLineTokens = readonly number[]\n\n/** Reads one line from `state` (which it changes into the state after the line). */\nexport function tokenizeLine<S>(\n language: CodeLanguage<S>,\n text: string,\n state: S,\n tabSize = 2,\n): CodeLineTokens {\n if (!text) {\n language.blankLine?.(state)\n return []\n }\n // Very long lines (minified code) are drawn plain; reading them would stall typing.\n if (text.length > MAX_LINE) return []\n const out: number[] = []\n const stream = new CodeStream(text, tabSize)\n let guard = 0\n while (!stream.eol()) {\n stream.start = stream.pos\n const type = language.token(stream, state)\n // A tokenizer that reads nothing would loop forever; take one character as plain text.\n if (stream.pos <= stream.start) {\n stream.pos = stream.start + 1\n push(out, stream.pos, -1)\n } else push(out, stream.pos, type ? (typeIndex.get(type) ?? -1) : -1)\n if (++guard > 100_000) break\n }\n return out\n}\n\nfunction push(out: number[], to: number, type: number) {\n // A token of the same kind as the one before joins it.\n if (out.length && out[out.length - 1] === type) out[out.length - 2] = to\n else out.push(to, type)\n}\n\n/** A line's tokens as `[text, kind]` pairs, kind `null` for plain text. */\nexport function lineParts(\n text: string,\n tokens: CodeLineTokens | null | undefined,\n): Array<[text: string, type: CodeTokenType | null]> {\n if (!tokens?.length) return [[text, null]]\n const out: Array<[string, CodeTokenType | null]> = []\n let from = 0\n for (let i = 0; i < tokens.length; i += 2) {\n const to = tokens[i]!\n const type = tokens[i + 1]!\n if (to > from) out.push([text.slice(from, to), type < 0 ? null : tokenTypes[type]!])\n from = to\n }\n if (from < text.length) out.push([text.slice(from), null])\n return out\n}\n"],"mappings":";;;;AA6BA,IAAa,aAAuC;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAEA,IAAM,WAAW;AACjB,IAAM,YAAY,IAAI,IAAI,WAAW,KAAK,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AAwDhE,IAAM,WAAW,UACf,OAAO,UAAU,YACjB,UAAU,SACT,OAAO,eAAe,KAAK,MAAM,OAAO,aAAa,OAAO,eAAe,KAAK,MAAM;;AAGzF,SAAgB,UAAa,OAAa;CACxC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,SAAS;CACpD,IAAI,QAAQ,KAAK,GAAG;EAClB,MAAM,MAA+B,CAAC;EACtC,KAAK,MAAM,OAAO,OAAO,IAAI,OAAO,UAAU,MAAM,IAAI;EACxD,OAAO;CACT;CACA,OAAO;AACT;;AAGA,SAAgB,UAAU,GAAY,GAAqB;CACzD,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,MAAM,QAAQ,CAAC,GAAG;EACpB,IAAI,CAAC,MAAM,QAAQ,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,OAAO;EACvD,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,IAAI,CAAC,UAAU,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO;EACtE,OAAO;CACT;CACA,IAAI,QAAQ,CAAC,KAAK,QAAQ,CAAC,GAAG;EAC5B,MAAM,OAAO,OAAO,KAAK,CAAC;EAC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,MAAM,QAAQ,KAAK;EAEzC,IAAI,OAAO,OAAO,OAAO,OAAO;GAC9B,OAAO,MAAM,OAAO,QAAQ;GAC5B,KAAK,KAAK,OAAO,KAAK,EAAE;EAC1B,OAAO,KAAK,KAAK,OAAO,KAAK,OAAQ,UAAU,IAAI,IAAI,KAAK,KAAM,EAAE;EACpE,IAAI,EAAE,QAAQ,KAAS;CACzB;CACA,OAAO;AACT;AAEA,SAAS,KAAK,KAAe,IAAY,MAAc;CAErD,IAAI,IAAI,UAAU,IAAI,IAAI,SAAS,OAAO,MAAM,IAAI,IAAI,SAAS,KAAK;MACjE,IAAI,KAAK,IAAI,IAAI;AACxB;;AAGA,SAAgB,UACd,MACA,QACmD;CACnD,IAAI,CAAC,QAAQ,QAAQ,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC;CACzC,MAAM,MAA6C,CAAC;CACpD,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,GAAG;EACzC,MAAM,KAAK,OAAO;EAClB,MAAM,OAAO,OAAO,IAAI;EACxB,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,KAAK,MAAM,MAAM,EAAE,GAAG,OAAO,IAAI,OAAO,WAAW,KAAM,CAAC;EACnF,OAAO;CACT;CACA,IAAI,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,MAAM,IAAI,GAAG,IAAI,CAAC;CACzD,OAAO;AACT"}
1
+ {"version":3,"file":"language.js","names":[],"sources":["../../src/language/language.ts"],"sourcesContent":["import { markRaw } from 'vue'\nimport { CodeStream } from './stream'\n\n/**\n * What a token is. The editor draws each kind with its\n * `--dou-color-syntax-*` color, so a theme recolors code without\n * highlighting it again.\n */\nexport type CodeTokenType =\n | 'keyword'\n | 'string'\n | 'number'\n | 'comment'\n | 'function'\n | 'type'\n | 'variable'\n | 'property'\n | 'operator'\n | 'punctuation'\n | 'tag'\n | 'attribute'\n | 'meta'\n | 'invalid'\n | 'heading'\n | 'strong'\n | 'emphasis'\n | 'link'\n\n/** Every token kind, in a fixed order; tokens are stored by their index here. */\nexport const tokenTypes: readonly CodeTokenType[] = [\n 'keyword',\n 'string',\n 'number',\n 'comment',\n 'function',\n 'type',\n 'variable',\n 'property',\n 'operator',\n 'punctuation',\n 'tag',\n 'attribute',\n 'meta',\n 'invalid',\n 'heading',\n 'strong',\n 'emphasis',\n 'link',\n]\n/** Lines longer than this are not read. */\nconst MAX_LINE = 10_000\nconst typeIndex = new Map(tokenTypes.map((type, i) => [type, i]))\n\nexport interface CodeLanguageSpec<S> {\n /** The name, also matched by `languageFor('…')` and code block `lang`. */\n name: string\n /** Other names, such as file extensions: `['js', 'mjs']`. */\n aliases?: string[]\n /** The state at the start of the text. Plain data: objects, arrays, strings, numbers. */\n startState?: () => S\n /**\n * Reads one token from the stream (at least one character) and returns\n * its kind, or `null` for plain text. May change `state`, which carries\n * over to the next token and the next line.\n */\n token: (stream: CodeStream, state: S) => CodeTokenType | null\n /** Called for an empty line, for states that end at a line's end. */\n blankLine?: (state: S) => void\n /** Copies a state. By default a deep copy of its plain objects and arrays. */\n copyState?: (state: S) => S\n /** Whether two states are the same. By default compares their plain data. */\n sameState?: (a: S, b: S) => boolean\n /** How the language writes comments, for toggling them. */\n comment?: { line?: string; block?: [open: string, close: string] }\n /** Bracket pairs, for matching and indenting. Default `'()[]{}'`. */\n brackets?: string\n /** Characters, as one string, that get their closing partner typed with them. Default the brackets' openers and `'\"`. */\n autoClose?: string\n /** A line before the cursor that matches this gets one more indent on Enter, besides an open bracket. */\n indentAfter?: RegExp\n /** The language that is active in a state, for languages that hold others (a `<script>` in HTML). */\n languageAt?: (state: S) => CodeLanguage | null\n /**\n * The languages this one may hold, for languages with `languageAt`. A\n * worker sends states with the languages in them by name; these are the\n * ones the names are looked up in.\n */\n nested?: readonly CodeLanguage[]\n /**\n * How a highlighting worker transfers results for this language:\n * - `'states'` (default): sends serialized state checkpoints so the page tokenizes visible lines.\n * - `'tokens'`: keeps non-serializable states (such as Shiki's `StateStack`) in the worker and sends flat line token arrays directly.\n */\n workerMode?: 'states' | 'tokens'\n}\n\n/** A language: how to read its tokens, and a few facts for editing it. */\nexport interface CodeLanguage<S = any> {\n readonly name: string\n readonly aliases: readonly string[]\n startState(): S\n token(stream: CodeStream, state: S): CodeTokenType | null\n blankLine?(state: S): void\n copyState(state: S): S\n sameState(a: S, b: S): boolean\n readonly comment: { line?: string; block?: [string, string] }\n readonly brackets: string\n readonly autoClose: string\n readonly indentAfter?: RegExp\n languageAt(state: S): CodeLanguage | null\n readonly nested: readonly CodeLanguage[]\n readonly workerMode?: 'states' | 'tokens'\n}\n\nconst isPlain = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' &&\n value !== null &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)\n\n/** Copies arrays and plain objects; everything else (languages among them) is shared. */\nexport function copyPlain<T>(value: T): T {\n if (Array.isArray(value)) return value.map(copyPlain) as T\n if (isPlain(value)) {\n const out: Record<string, unknown> = {}\n for (const key in value) out[key] = copyPlain(value[key])\n return out as T\n }\n return value\n}\n\n/** Compares arrays and plain objects by their content; everything else by identity. */\nexport function samePlain(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) if (!samePlain(a[i], b[i])) return false\n return true\n }\n if (isPlain(a) && isPlain(b)) {\n const keys = Object.keys(a)\n if (keys.length !== Object.keys(b).length) return false\n for (const key of keys) if (!samePlain(a[key], b[key])) return false\n return true\n }\n return false\n}\n\n/**\n * Defines a language from a tokenizer that reads one line at a time.\n *\n * ```ts\n * const ini = defineCodeLanguage({\n * name: 'ini',\n * token(stream) {\n * if (stream.sol() && stream.match(/^\\s*[;#].*$/)) return 'comment'\n * if (stream.sol() && stream.match(/^\\s*\\[[^\\]]*\\]/)) return 'keyword'\n * if (stream.match(/^[\\w.-]+(?=\\s*=)/)) return 'property'\n * stream.next()\n * return null\n * },\n * })\n * ```\n */\nexport function defineCodeLanguage<S = Record<string, never>>(\n spec: CodeLanguageSpec<S>,\n): CodeLanguage<S> {\n const brackets = spec.brackets ?? '()[]{}'\n let openers = ''\n for (let i = 0; i < brackets.length; i += 2) openers += brackets[i]\n return markRaw({\n name: spec.name,\n aliases: spec.aliases ?? [],\n startState: spec.startState ?? (() => ({}) as S),\n token: spec.token,\n blankLine: spec.blankLine,\n copyState: spec.copyState ?? copyPlain,\n sameState: spec.sameState ?? samePlain,\n comment: spec.comment ?? {},\n brackets,\n autoClose: spec.autoClose ?? openers + '\\'\"',\n indentAfter: spec.indentAfter,\n languageAt: spec.languageAt ?? (() => null),\n nested: spec.nested ?? [],\n workerMode: spec.workerMode,\n })\n}\n\nexport interface RemoteCodeLanguageOptions {\n /** The language name resolved inside the highlighting worker (e.g. `'rust'`, `'go'`, `'proto'`). */\n name: string\n aliases?: string[]\n /** How the language writes comments, for toggling them. */\n comment?: { line?: string; block?: [open: string, close: string] }\n brackets?: string\n autoClose?: string\n indentAfter?: RegExp\n}\n\n/**\n * Describes a language highlighted entirely inside a Web Worker (such as a\n * Shiki grammar loaded in the worker), without loading its tokenizer or WASM\n * on the main thread. Editing features (comments, bracket pairing, auto-close,\n * indentation) still work on the page; without a worker it renders plain text.\n */\nexport function remoteCodeLanguage(options: RemoteCodeLanguageOptions): CodeLanguage {\n return defineCodeLanguage({\n name: options.name,\n aliases: options.aliases,\n comment: options.comment,\n brackets: options.brackets,\n autoClose: options.autoClose,\n indentAfter: options.indentAfter,\n workerMode: 'tokens',\n token(stream) {\n stream.skipToEnd()\n return null\n },\n })\n}\n\n/** The language among `languages` named `name` or one of its aliases, ignoring case. */\nexport function languageFor(\n languages: readonly CodeLanguage[],\n name: string | undefined,\n): CodeLanguage | null {\n if (!name) return null\n const key = name.trim().toLowerCase()\n return (\n languages.find(\n (language) => language.name.toLowerCase() === key || language.aliases.includes(key),\n ) ?? null\n )\n}\n\n/**\n * One line's tokens, as pairs of numbers: where each token ends and its\n * kind's index in `tokenTypes` (`-1` for plain text). Each token starts\n * where the one before ended.\n */\nexport type CodeLineTokens = readonly number[]\n\n/** Reads one line from `state` (which it changes into the state after the line). */\nexport function tokenizeLine<S>(\n language: CodeLanguage<S>,\n text: string,\n state: S,\n tabSize = 2,\n): CodeLineTokens {\n if (!text) {\n language.blankLine?.(state)\n return []\n }\n // Very long lines (minified code) are drawn plain; reading them would stall typing.\n if (text.length > MAX_LINE) return []\n const out: number[] = []\n const stream = new CodeStream(text, tabSize)\n let guard = 0\n while (!stream.eol()) {\n stream.start = stream.pos\n const type = language.token(stream, state)\n // A tokenizer that reads nothing would loop forever; take one character as plain text.\n if (stream.pos <= stream.start) {\n stream.pos = stream.start + 1\n push(out, stream.pos, -1)\n } else push(out, stream.pos, type ? (typeIndex.get(type) ?? -1) : -1)\n if (++guard > 100_000) break\n }\n return out\n}\n\nfunction push(out: number[], to: number, type: number) {\n // A token of the same kind as the one before joins it.\n if (out.length && out[out.length - 1] === type) out[out.length - 2] = to\n else out.push(to, type)\n}\n\n/** A line's tokens as `[text, kind]` pairs, kind `null` for plain text. */\nexport function lineParts(\n text: string,\n tokens: CodeLineTokens | null | undefined,\n): Array<[text: string, type: CodeTokenType | null]> {\n if (!tokens?.length) return [[text, null]]\n const out: Array<[string, CodeTokenType | null]> = []\n let from = 0\n for (let i = 0; i < tokens.length; i += 2) {\n const to = tokens[i]!\n const type = tokens[i + 1]!\n if (to > from) out.push([text.slice(from, to), type < 0 ? null : tokenTypes[type]!])\n from = to\n }\n if (from < text.length) out.push([text.slice(from), null])\n return out\n}\n"],"mappings":";;;;AA6BA,IAAa,aAAuC;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAEA,IAAM,WAAW;AACjB,IAAM,YAAY,IAAI,IAAI,WAAW,KAAK,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AA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,EAAE,QAAQ,KAAS;CACzB;CACA,OAAO;AACT;AAEA,SAAS,KAAK,KAAe,IAAY,MAAc;CAErD,IAAI,IAAI,UAAU,IAAI,IAAI,SAAS,OAAO,MAAM,IAAI,IAAI,SAAS,KAAK;MACjE,IAAI,KAAK,IAAI,IAAI;AACxB;;AAGA,SAAgB,UACd,MACA,QACmD;CACnD,IAAI,CAAC,QAAQ,QAAQ,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC;CACzC,MAAM,MAA6C,CAAC;CACpD,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,GAAG;EACzC,MAAM,KAAK,OAAO;EAClB,MAAM,OAAO,OAAO,IAAI;EACxB,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,KAAK,MAAM,MAAM,EAAE,GAAG,OAAO,IAAI,OAAO,WAAW,KAAM,CAAC;EACnF,OAAO;CACT;CACA,IAAI,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,MAAM,IAAI,GAAG,IAAI,CAAC;CACzD,OAAO;AACT"}
@@ -0,0 +1,131 @@
1
+ // src/language/remote-tokens.ts
2
+ /** Maximum number of line token arrays cached on the page in remote-token mode. */
3
+ var CACHE = 4e3;
4
+ /** Compresses sorted 1-based line numbers into contiguous inclusive `[from, to]` intervals. */
5
+ function compressLineRanges(numbers) {
6
+ const ranges = [];
7
+ for (let i = 0; i < numbers.length; i++) {
8
+ const n = numbers[i];
9
+ const prev = ranges[ranges.length - 1];
10
+ if (prev && n <= prev[1] + 1) {
11
+ if (n > prev[1]) prev[1] = n;
12
+ } else ranges.push([n, n]);
13
+ }
14
+ return ranges;
15
+ }
16
+ /**
17
+ * Caches flat per-line tokens returned by a highlighting worker in `tokens`
18
+ * mode (e.g. Shiki grammars whose state lives only inside the worker).
19
+ *
20
+ * Lines before an edit stay fresh across document versions; lines after an edit
21
+ * shift by the line delta so the viewport keeps its colors without flickering
22
+ * while the worker recomputes the new version.
23
+ */
24
+ var RemoteTokenStore = class {
25
+ maxSize;
26
+ /** 1-based line number → flat tokens, oldest first for LRU eviction. */
27
+ tokens = /* @__PURE__ */ new Map();
28
+ /** 1-based line number → version at which the cached tokens were produced. */
29
+ versions = /* @__PURE__ */ new Map();
30
+ currentVersion = 0;
31
+ workerFrontier = 0;
32
+ constructor(maxSize = CACHE) {
33
+ this.maxSize = Math.max(1, maxSize);
34
+ }
35
+ get version() {
36
+ return this.currentVersion;
37
+ }
38
+ get frontier() {
39
+ return this.workerFrontier;
40
+ }
41
+ /** Cached tokens for 1-based line `n`, or `null` if never received yet. */
42
+ line(n) {
43
+ return this.tokens.get(n) ?? null;
44
+ }
45
+ /** Whether every line in 1-based inclusive `[from, to]` has tokens for the current version. */
46
+ readyRange(from, to) {
47
+ for (let n = from; n <= to; n++) if (this.versions.get(n) !== this.currentVersion) return false;
48
+ return true;
49
+ }
50
+ /** Whether every 1-based line number in `numbers` has tokens for the current version. */
51
+ readyNumbers(numbers) {
52
+ for (let i = 0; i < numbers.length; i++) if (this.versions.get(numbers[i]) !== this.currentVersion) return false;
53
+ return true;
54
+ }
55
+ /** Stores flat line tokens starting at 1-based line `from` from the worker. */
56
+ adopt(from, lines, frontier) {
57
+ this.workerFrontier = Math.max(this.workerFrontier, frontier);
58
+ const cap = Math.max(this.maxSize, lines.length);
59
+ for (let i = 0; i < lines.length; i++) {
60
+ const n = from + i;
61
+ this.tokens.delete(n);
62
+ this.tokens.set(n, lines[i]);
63
+ this.versions.set(n, this.currentVersion);
64
+ if (this.tokens.size > cap) {
65
+ const oldest = this.tokens.keys().next().value;
66
+ this.tokens.delete(oldest);
67
+ this.versions.delete(oldest);
68
+ }
69
+ }
70
+ }
71
+ /** Stores flat line tokens for multiple disjoint visible ranges returned by the worker. */
72
+ adoptRanges(ranges, frontier) {
73
+ this.workerFrontier = Math.max(this.workerFrontier, frontier);
74
+ let batchSize = 0;
75
+ for (const [, lines] of ranges) batchSize += lines.length;
76
+ const cap = Math.max(this.maxSize, batchSize);
77
+ for (const [from, lines] of ranges) for (let i = 0; i < lines.length; i++) {
78
+ const n = from + i;
79
+ this.tokens.delete(n);
80
+ this.tokens.set(n, lines[i]);
81
+ this.versions.set(n, this.currentVersion);
82
+ if (this.tokens.size > cap) {
83
+ const oldest = this.tokens.keys().next().value;
84
+ this.tokens.delete(oldest);
85
+ this.versions.delete(oldest);
86
+ }
87
+ }
88
+ }
89
+ /** Shifts cached lines across an edit so unchanged regions avoid flicker while stale lines re-fetch. */
90
+ update(oldDoc, nextDoc, changes) {
91
+ if (!changes) {
92
+ this.clear();
93
+ return;
94
+ }
95
+ if (changes.empty) return;
96
+ this.currentVersion++;
97
+ const list = changes.changes;
98
+ const first = list[0];
99
+ const last = list[list.length - 1];
100
+ const a = oldDoc.lineAt(first.from).number;
101
+ const b = oldDoc.lineAt(last.to).number;
102
+ const delta = nextDoc.lineAt(changes.mapPos(last.to, 1)).number - b;
103
+ const nextTokens = /* @__PURE__ */ new Map();
104
+ const nextVersions = /* @__PURE__ */ new Map();
105
+ for (const [line, value] of this.tokens) {
106
+ const ver = this.versions.get(line) ?? -1;
107
+ if (line < a) {
108
+ nextTokens.set(line, value);
109
+ nextVersions.set(line, ver === this.currentVersion - 1 ? this.currentVersion : ver);
110
+ } else if (line > b) {
111
+ const shifted = line + delta;
112
+ if (shifted >= 1 && shifted <= nextDoc.lines) {
113
+ nextTokens.set(shifted, value);
114
+ nextVersions.set(shifted, ver);
115
+ }
116
+ }
117
+ }
118
+ this.tokens = nextTokens;
119
+ this.versions = nextVersions;
120
+ this.workerFrontier = Math.min(this.workerFrontier, a - 1);
121
+ }
122
+ clear() {
123
+ this.currentVersion++;
124
+ this.workerFrontier = 0;
125
+ this.tokens.clear();
126
+ this.versions.clear();
127
+ }
128
+ };
129
+ export { RemoteTokenStore, compressLineRanges };
130
+
131
+ //# sourceMappingURL=remote-tokens.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-tokens.js","names":[],"sources":["../../src/language/remote-tokens.ts"],"sourcesContent":["import type { ChangeSet } from '../core/changes'\nimport type { CodeText } from '../core/text'\nimport type { CodeLineTokens } from './language'\n\n/** Maximum number of line token arrays cached on the page in remote-token mode. */\nconst CACHE = 4000\n\n/** Compresses sorted 1-based line numbers into contiguous inclusive `[from, to]` intervals. */\nexport function compressLineRanges(numbers: readonly number[]): Array<[from: number, to: number]> {\n const ranges: Array<[number, number]> = []\n for (let i = 0; i < numbers.length; i++) {\n const n = numbers[i]!\n const prev = ranges[ranges.length - 1]\n if (prev && n <= prev[1] + 1) {\n if (n > prev[1]) prev[1] = n\n } else {\n ranges.push([n, n])\n }\n }\n return ranges\n}\n\n/**\n * Caches flat per-line tokens returned by a highlighting worker in `tokens`\n * mode (e.g. Shiki grammars whose state lives only inside the worker).\n *\n * Lines before an edit stay fresh across document versions; lines after an edit\n * shift by the line delta so the viewport keeps its colors without flickering\n * while the worker recomputes the new version.\n */\nexport class RemoteTokenStore {\n private readonly maxSize: number\n /** 1-based line number → flat tokens, oldest first for LRU eviction. */\n private tokens = new Map<number, CodeLineTokens>()\n /** 1-based line number → version at which the cached tokens were produced. */\n private versions = new Map<number, number>()\n private currentVersion = 0\n private workerFrontier = 0\n\n constructor(maxSize = CACHE) {\n this.maxSize = Math.max(1, maxSize)\n }\n\n get version(): number {\n return this.currentVersion\n }\n\n get frontier(): number {\n return this.workerFrontier\n }\n\n /** Cached tokens for 1-based line `n`, or `null` if never received yet. */\n line(n: number): CodeLineTokens | null {\n return this.tokens.get(n) ?? null\n }\n\n /** Whether every line in 1-based inclusive `[from, to]` has tokens for the current version. */\n readyRange(from: number, to: number): boolean {\n for (let n = from; n <= to; n++) {\n if (this.versions.get(n) !== this.currentVersion) return false\n }\n return true\n }\n\n /** Whether every 1-based line number in `numbers` has tokens for the current version. */\n readyNumbers(numbers: readonly number[]): boolean {\n for (let i = 0; i < numbers.length; i++) {\n if (this.versions.get(numbers[i]!) !== this.currentVersion) return false\n }\n return true\n }\n\n /** Stores flat line tokens starting at 1-based line `from` from the worker. */\n adopt(from: number, lines: readonly CodeLineTokens[], frontier: number): void {\n this.workerFrontier = Math.max(this.workerFrontier, frontier)\n const cap = Math.max(this.maxSize, lines.length)\n for (let i = 0; i < lines.length; i++) {\n const n = from + i\n this.tokens.delete(n)\n this.tokens.set(n, lines[i]!)\n this.versions.set(n, this.currentVersion)\n if (this.tokens.size > cap) {\n const oldest = this.tokens.keys().next().value!\n this.tokens.delete(oldest)\n this.versions.delete(oldest)\n }\n }\n }\n\n /** Stores flat line tokens for multiple disjoint visible ranges returned by the worker. */\n adoptRanges(\n ranges: ReadonlyArray<readonly [from: number, lines: readonly CodeLineTokens[]]>,\n frontier: number,\n ): void {\n this.workerFrontier = Math.max(this.workerFrontier, frontier)\n let batchSize = 0\n for (const [, lines] of ranges) batchSize += lines.length\n const cap = Math.max(this.maxSize, batchSize)\n for (const [from, lines] of ranges) {\n for (let i = 0; i < lines.length; i++) {\n const n = from + i\n this.tokens.delete(n)\n this.tokens.set(n, lines[i]!)\n this.versions.set(n, this.currentVersion)\n if (this.tokens.size > cap) {\n const oldest = this.tokens.keys().next().value!\n this.tokens.delete(oldest)\n this.versions.delete(oldest)\n }\n }\n }\n }\n\n /** Shifts cached lines across an edit so unchanged regions avoid flicker while stale lines re-fetch. */\n update(oldDoc: CodeText, nextDoc: CodeText, changes?: ChangeSet): void {\n if (!changes) {\n this.clear()\n return\n }\n if (changes.empty) return\n this.currentVersion++\n const list = changes.changes\n const first = list[0]!\n const last = list[list.length - 1]!\n // 1-based inclusive line numbers touched in `oldDoc`.\n const a = oldDoc.lineAt(first.from).number\n const b = oldDoc.lineAt(last.to).number\n const end = nextDoc.lineAt(changes.mapPos(last.to, 1)).number\n const delta = end - b\n\n const nextTokens = new Map<number, CodeLineTokens>()\n const nextVersions = new Map<number, number>()\n for (const [line, value] of this.tokens) {\n const ver = this.versions.get(line) ?? -1\n if (line < a) {\n // Lines above the edit cannot change syntax state: keep them fresh.\n nextTokens.set(line, value)\n nextVersions.set(line, ver === this.currentVersion - 1 ? this.currentVersion : ver)\n } else if (line > b) {\n const shifted = line + delta\n if (shifted >= 1 && shifted <= nextDoc.lines) {\n nextTokens.set(shifted, value)\n // Keep previous version so `readyRange` requests updated tokens from the worker,\n // while rendering keeps temporary colors without flashing plain text.\n nextVersions.set(shifted, ver)\n }\n }\n }\n this.tokens = nextTokens\n this.versions = nextVersions\n this.workerFrontier = Math.min(this.workerFrontier, a - 1)\n }\n\n clear(): void {\n this.currentVersion++\n this.workerFrontier = 0\n this.tokens.clear()\n this.versions.clear()\n }\n}\n"],"mappings":";;AAKA,IAAM,QAAQ;;AAGd,SAAgB,mBAAmB,SAA+D;CAChG,MAAM,SAAkC,CAAC;CACzC,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;EACvC,MAAM,IAAI,QAAQ;EAClB,MAAM,OAAO,OAAO,OAAO,SAAS;EACpC,IAAI,QAAQ,KAAK,KAAK,KAAK,GACrB;OAAA,IAAI,KAAK,IAAI,KAAK,KAAK;EAAA,OAE3B,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC;CAEtB;CACA,OAAO;AACT;;;;;;;;;AAUA,IAAa,mBAAb,MAA8B;CAC5B;;CAEA,yBAAiB,IAAI,IAA4B;;CAEjD,2BAAmB,IAAI,IAAoB;CAC3C,iBAAyB;CACzB,iBAAyB;CAEzB,YAAY,UAAU,OAAO;EAC3B,KAAK,UAAU,KAAK,IAAI,GAAG,OAAO;CACpC;CAEA,IAAI,UAAkB;EACpB,OAAO,KAAK;CACd;CAEA,IAAI,WAAmB;EACrB,OAAO,KAAK;CACd;;CAGA,KAAK,GAAkC;EACrC,OAAO,KAAK,OAAO,IAAI,CAAC,KAAK;CAC/B;;CAGA,WAAW,MAAc,IAAqB;EAC5C,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,KAC1B,IAAI,KAAK,SAAS,IAAI,CAAC,MAAM,KAAK,gBAAgB,OAAO;EAE3D,OAAO;CACT;;C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