@adecore/editor 0.62.0 → 0.63.0-untangle.1

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 (95) hide show
  1. package/dist/attribution.js +0 -1
  2. package/dist/bidi.js +0 -1
  3. package/dist/column-selection.d.ts +0 -1
  4. package/dist/column-selection.js +1 -1
  5. package/dist/controller.d.ts +4 -2
  6. package/dist/controller.js +0 -5
  7. package/dist/engine.js +0 -3
  8. package/dist/fake.d.ts +3 -0
  9. package/dist/fake.js +29 -24
  10. package/dist/find.d.ts +3 -2
  11. package/dist/find.js +0 -2
  12. package/dist/geometry-stops.d.ts +1 -1
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +1 -1
  15. package/dist/keymap-table.d.ts +8 -1
  16. package/dist/keymap-table.js +0 -1
  17. package/dist/keymap.d.ts +2 -1
  18. package/dist/layout-changes.d.ts +2 -1
  19. package/dist/layout.d.ts +3 -57
  20. package/dist/layout.js +1 -6
  21. package/dist/line-geometry.d.ts +55 -0
  22. package/dist/line-geometry.js +1 -0
  23. package/dist/metrics.d.ts +1 -1
  24. package/dist/modifier-gesture.d.ts +2 -1
  25. package/dist/modifier-gesture.js +0 -1
  26. package/dist/native-input.d.ts +2 -1
  27. package/dist/outline.d.ts +3 -3
  28. package/dist/outline.js +0 -1
  29. package/dist/overview.d.ts +3 -2
  30. package/dist/paint.d.ts +5 -5
  31. package/dist/paint.js +3 -4
  32. package/dist/php-html.d.ts +0 -6
  33. package/dist/php-html.js +2 -2
  34. package/dist/pointer.d.ts +2 -1
  35. package/dist/scroll-animation.d.ts +0 -1
  36. package/dist/scroll-animation.js +1 -1
  37. package/dist/scroll.js +0 -1
  38. package/dist/search-client.d.ts +2 -2
  39. package/dist/shiki-document.js +1 -1
  40. package/dist/shiki-grammar.d.ts +7 -0
  41. package/dist/shiki-grammar.js +168 -0
  42. package/dist/shiki-worker.js +1 -1
  43. package/dist/shiki.d.ts +1 -7
  44. package/dist/shiki.js +1 -168
  45. package/dist/smart-keys.js +0 -1
  46. package/dist/testing.js +0 -2
  47. package/dist/todos.d.ts +2 -1
  48. package/dist/tokens.d.ts +2 -1
  49. package/dist/tokens.js +0 -1
  50. package/dist/touch.d.ts +2 -1
  51. package/dist/types.d.ts +5 -13
  52. package/dist/uniform-geometry.d.ts +1 -1
  53. package/dist/view.d.ts +12 -10
  54. package/dist/view.js +61 -38
  55. package/dist/zoom.d.ts +0 -2
  56. package/dist/zoom.js +2 -2
  57. package/package.json +8 -3
  58. package/src/attribution.ts +0 -1
  59. package/src/bidi.ts +0 -1
  60. package/src/column-selection.ts +1 -1
  61. package/src/controller.ts +3 -9
  62. package/src/engine.ts +0 -3
  63. package/src/fake.ts +38 -24
  64. package/src/find.ts +2 -4
  65. package/src/geometry-stops.ts +1 -1
  66. package/src/index.ts +2 -2
  67. package/src/keymap-table.ts +10 -3
  68. package/src/keymap.ts +2 -1
  69. package/src/layout-changes.ts +1 -1
  70. package/src/layout.ts +4 -81
  71. package/src/line-geometry.ts +69 -0
  72. package/src/metrics.ts +1 -1
  73. package/src/modifier-gesture.ts +1 -2
  74. package/src/native-input.ts +1 -1
  75. package/src/outline.ts +3 -5
  76. package/src/overview.ts +2 -2
  77. package/src/paint.ts +5 -11
  78. package/src/php-html.ts +2 -2
  79. package/src/pointer.ts +1 -4
  80. package/src/scroll-animation.ts +1 -1
  81. package/src/scroll.ts +0 -2
  82. package/src/search-client.ts +2 -2
  83. package/src/shiki-document.ts +1 -1
  84. package/src/shiki-grammar.ts +223 -0
  85. package/src/shiki-worker.ts +1 -1
  86. package/src/shiki.ts +1 -224
  87. package/src/smart-keys.ts +0 -1
  88. package/src/testing.ts +0 -2
  89. package/src/todos.ts +1 -1
  90. package/src/tokens.ts +1 -2
  91. package/src/touch.ts +1 -1
  92. package/src/types.ts +9 -22
  93. package/src/uniform-geometry.ts +1 -1
  94. package/src/view.ts +89 -56
  95. package/src/zoom.ts +2 -2
package/src/paint.ts CHANGED
@@ -7,13 +7,13 @@ import {
7
7
  type EditorLayout,
8
8
  type LayoutRect,
9
9
  type LayoutRow,
10
- type LineGeometry,
11
10
  scanLine,
12
11
  subRowBand,
13
12
  type SubRowBand,
14
13
  type VerticalWindow,
15
14
  type TextRow
16
15
  } from './layout.ts';
16
+ import { type LineGeometry } from './line-geometry.ts';
17
17
  import type { EditorChangeKind, EditorGutterIcon, LineToken } from './types.ts';
18
18
 
19
19
  const ITALIC = 1;
@@ -135,7 +135,7 @@ function fillRun(
135
135
  }
136
136
  }
137
137
 
138
- export function lineElement(
138
+ function lineElement(
139
139
  document: Document,
140
140
  geometry: LineGeometry,
141
141
  tokens: readonly LineToken[] | null,
@@ -493,7 +493,7 @@ export class RowPainter {
493
493
  }
494
494
  }
495
495
 
496
- export interface GutterPaint {
496
+ interface GutterPaint {
497
497
  lineNumber(line: number): string | null;
498
498
  activeLines: ReadonlySet<number>;
499
499
  /* How the lines the host marked differ from what it compares against. */
@@ -502,15 +502,11 @@ export interface GutterPaint {
502
502
  attribution: ReadonlyMap<number, AttributedLines>;
503
503
  /* The line highlights of the host, whose sign stands in the gutter. */
504
504
  highlights: ReadonlyMap<number, AttributedLines>;
505
- /* Lines a fold can start at, and whether each is collapsed. */
506
505
  foldable: ReadonlyMap<number, boolean>;
507
- /* What the fold control of a line is called, from its line and whether it is collapsed. */
508
506
  foldName(line: number, collapsed: boolean): string;
509
507
  /* A sentence read with the line, which then stands in for the drawn number and sign. */
510
508
  lineLabel(line: number): string | null;
511
- /* The line that carries the host's button, and what it is called. */
512
509
  action: { line: number; label: string } | null;
513
- /* The host's markers by line. */
514
510
  markers: ReadonlyMap<number, { id: string; label: string; icon?: EditorGutterIcon; pressed?: boolean }>;
515
511
  }
516
512
 
@@ -524,7 +520,6 @@ function gutterButton(document: Document, className: string, label: string): HTM
524
520
  return button;
525
521
  }
526
522
 
527
- /* The line numbers of the visible rows, and the fold control of the lines that have one. */
528
523
  export function paintGutter(container: HTMLElement, layout: EditorLayout, rows: readonly LayoutRow[], paint: GutterPaint): void {
529
524
  const document = container.ownerDocument;
530
525
  const fragment = document.createDocumentFragment();
@@ -656,7 +651,7 @@ export function paintGutter(container: HTMLElement, layout: EditorLayout, rows:
656
651
  container.replaceChildren(fragment);
657
652
  }
658
653
 
659
- export interface OverlayPaint {
654
+ interface OverlayPaint {
660
655
  currentLine: LayoutRect | null;
661
656
  selections: readonly LayoutRect[];
662
657
  focused: boolean;
@@ -796,7 +791,7 @@ const SVG = 'http://www.w3.org/2000/svg';
796
791
  * An arrow as the platform draws a tab or a soft wrap: a line across the middle of half a line's height,
797
792
  * ending in a head that points right with a bar behind it, in as much room as it has.
798
793
  */
799
- export function arrowSign(document: Document, width: number, lineHeight: number, className: string): SVGSVGElement {
794
+ function arrowSign(document: Document, width: number, lineHeight: number, className: string): SVGSVGElement {
800
795
  const svg = document.createElementNS(SVG, 'svg');
801
796
  svg.setAttribute('class', className);
802
797
  svg.setAttribute('width', String(Math.max(1, Math.round(width))));
@@ -817,7 +812,6 @@ export function arrowSign(document: Document, width: number, lineHeight: number,
817
812
  return svg as SVGSVGElement;
818
813
  }
819
814
 
820
- /* An arrow over each tab of a line. */
821
815
  function appendTabSigns(element: HTMLElement, geometry: LineGeometry, lineHeight: number, band: SubRowBand): void {
822
816
  if (geometry.uniform !== undefined) {
823
817
  return;
package/src/php-html.ts CHANGED
@@ -3,14 +3,14 @@ import type { Highlighter } from 'shiki';
3
3
  type LanguageRegistration = Extract<Parameters<Highlighter['loadLanguage']>[0], { readonly scopeName: string }>;
4
4
 
5
5
  /* Shiki's `php` is only the code inside the tags, which makes a plain `<?php` an operator and a constant. */
6
- export const PHP_DOCUMENT_ID = 'php-html';
6
+ const PHP_DOCUMENT_ID = 'php-html';
7
7
 
8
8
  /*
9
9
  * A PHP file as a document: HTML with PHP between its tags, the way `text.html.php` of the PHP
10
10
  * grammar family does it. Shiki bundles no such grammar, so it is written here on top of `html` and
11
11
  * `php`, which have to be loaded first. The tags carry the scope a theme draws a tag's brackets in.
12
12
  */
13
- export const PHP_DOCUMENT: LanguageRegistration = {
13
+ const PHP_DOCUMENT: LanguageRegistration = {
14
14
  name: PHP_DOCUMENT_ID,
15
15
  scopeName: 'text.html.php',
16
16
  embeddedLangs: ['html', 'php'],
package/src/pointer.ts CHANGED
@@ -2,7 +2,7 @@ import type { DocumentModel, Selection } from '@adecore/editor-core';
2
2
  import type { ContentPoint } from './column-selection.ts';
3
3
 
4
4
  /* A visual line as the layout knows it: a wrapped line is as many as it has rows and a collapsed fold is one. */
5
- export interface VisualLine {
5
+ interface VisualLine {
6
6
  start: number;
7
7
  end: number;
8
8
  next: number;
@@ -25,9 +25,7 @@ export interface PointerHost {
25
25
  columnMode(): boolean;
26
26
  /* The selection a point of the screen is on, for a press that may begin dragging it; null on anything else or when the text cannot be edited. */
27
27
  selectionAt(clientX: number, clientY: number): Selection | null;
28
- /* The place a drop would land, drawn as a caret; null takes it away. */
29
28
  setDropCaret(offset: number | null): void;
30
- /* Moves `[from, to)` to `offset`, or copies it there. */
31
29
  drop(from: number, to: number, offset: number, copy: boolean): void;
32
30
  /* Whether the key that turns a move into a copy is down. */
33
31
  copyHeld(event: PointerEvent): boolean;
@@ -62,7 +60,6 @@ interface Drag {
62
60
  carry?: Carry;
63
61
  /* With shift and alt a dragged box is added to the carets that are there, not put in their place. */
64
62
  keep: boolean;
65
- /* Whether a drag so far makes a box of columns. */
66
63
  box: boolean;
67
64
  /* Where the press landed in the content, which a scroll leaves in place. */
68
65
  anchorPoint: ContentPoint;
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  /* The longest the view takes to get anywhere. */
7
- export const SCROLL_DURATION_MS = 100;
7
+ const SCROLL_DURATION_MS = 100;
8
8
 
9
9
  /* How many lines away the view has to go before it takes any time, and how many before it takes all of it. */
10
10
  const FREE_LINES = 1;
package/src/scroll.ts CHANGED
@@ -17,7 +17,6 @@ export interface ScrollRequest {
17
17
  readonly target: { readonly x: number; readonly y: number };
18
18
  /* What is in view now: the text area, without the gutter. */
19
19
  readonly view: { readonly x: number; readonly y: number; readonly width: number; readonly height: number };
20
- /* How much there is to scroll over. */
21
20
  readonly content: { readonly width: number; readonly height: number };
22
21
  readonly lineHeight: number;
23
22
  readonly charWidth: number;
@@ -96,7 +95,6 @@ function horizontalPosition(request: ScrollRequest, kind: ScrollKind): number {
96
95
  return clamp(position, content.width - width);
97
96
  }
98
97
 
99
- /* The scroll position that shows the target the way `kind` asks. */
100
98
  export function scrollPosition(request: ScrollRequest, kind: ScrollKind): { x: number; y: number } {
101
99
  const { target, view } = request;
102
100
  const inView = target.x >= view.x && target.x < view.x + view.width && target.y >= view.y && target.y < view.y + view.height;
@@ -13,7 +13,7 @@ import {
13
13
  type EditorSearchResult,
14
14
  type EditorSearchSnapshot
15
15
  } from './search-protocol.ts';
16
- import type { EditorFindQuery } from './types.ts';
16
+ import type { EditorFindQuery, EditorSearchWorkerFactory } from './types.ts';
17
17
  import { createWorkerRequestClient, WorkerRequestError } from './worker-client.ts';
18
18
 
19
19
  export type EditorSearchErrorKind = 'timeout' | 'superseded' | 'unavailable' | 'syntax' | 'range' | 'snapshot' | 'error' | 'disposed';
@@ -29,7 +29,7 @@ export class EditorSearchError extends Error {
29
29
  }
30
30
 
31
31
  export interface EditorSearchClientOptions {
32
- readonly workerFactory: () => Pick<Worker, 'addEventListener' | 'removeEventListener' | 'postMessage' | 'terminate'>;
32
+ readonly workerFactory: EditorSearchWorkerFactory;
33
33
  /* Milliseconds, starting when the request is posted, including worker startup. Defaults to 1,500. */
34
34
  readonly deadline?: number;
35
35
  readonly schedule?: (callback: () => void, delay: number) => () => void;
@@ -1,5 +1,5 @@
1
1
  import type { GrammarState, Highlighter, ShikiTransformer, ThemedToken } from 'shiki';
2
- import { documentLanguageOf, loadGrammar } from './shiki.ts';
2
+ import { documentLanguageOf, loadGrammar } from './shiki-grammar.ts';
3
3
 
4
4
  export interface ShikiDocumentTokenOptions {
5
5
  readonly reset?: ReadonlySet<number>;
@@ -0,0 +1,223 @@
1
+ import type { GrammarState, Highlighter } from 'shiki';
2
+ import { documentLanguageOf, loadDocumentLanguage } from './php-html.ts';
3
+ import { scopeColorsOf, type ThemeRule } from './theme-scopes.ts';
4
+ import type { LineToken, LineTokenKind, LineTokenizer, ScopeColorSource, TokenizerSource } from './types.ts';
5
+
6
+ type LanguageId = Parameters<Highlighter['loadLanguage']>[0];
7
+ type ThemeId = Parameters<Highlighter['loadTheme']>[0];
8
+ type TokenOptions = Parameters<Highlighter['codeToTokensBase']>[1];
9
+
10
+ export { documentLanguageOf };
11
+
12
+ /* The standard token types of TextMate: 1 comment, 2 string, 3 regex. */
13
+ const KINDS: Record<number, LineTokenKind | undefined> = { 1: 'comment', 2: 'string', 3: 'regex' };
14
+
15
+ const PLAIN_TEXT = new Set(['', 'text', 'txt', 'plain', 'plaintext']);
16
+
17
+ /* Colors one line at a time and hands the grammar's state from one line to the next. A grammar Shiki rebuilt does not know the states of the old one. */
18
+ function lineTokenizer(highlighter: Highlighter, language: string, theme: string, embedded: EmbeddedIndex): LineTokenizer {
19
+ let grammar = highlighter.getLanguage(language);
20
+
21
+ return {
22
+ prepare: embedded.matcher === null ? undefined : (text) => loadEmbedded(highlighter, embedded, text),
23
+ stale() {
24
+ const current = highlighter.getLanguage(language);
25
+ const changed = current !== grammar;
26
+ grammar = current;
27
+
28
+ return changed;
29
+ },
30
+ tokenizeLine(text, state) {
31
+ const options = {
32
+ lang: language,
33
+ theme,
34
+ grammarState: (state ?? undefined) as GrammarState | undefined,
35
+ includeExplanation: 'tokenType'
36
+ } as TokenOptions;
37
+
38
+ const lines = highlighter.codeToTokensBase(text, options);
39
+
40
+ const tokens: LineToken[] = (lines[0] ?? []).map((token) => ({
41
+ length: token.content.length,
42
+ color: token.color ?? '',
43
+ fontStyle: token.fontStyle ?? 0,
44
+ kind: KINDS[token.type ?? 0]
45
+ }));
46
+
47
+ return { tokens, state: highlighter.getLastGrammarState(lines) };
48
+ },
49
+ sameState(a, b) {
50
+ if (a === b) {
51
+ return true;
52
+ }
53
+
54
+ const left = (a as GrammarState | null)?.getInternalStack(theme);
55
+ const right = (b as GrammarState | null)?.getInternalStack(theme);
56
+
57
+ return left !== undefined && right !== undefined && left.equals(right);
58
+ }
59
+ };
60
+ }
61
+
62
+ interface EmbeddedIndex {
63
+ readonly names: ReadonlyMap<string, string>;
64
+ readonly matcher: RegExp | null;
65
+ }
66
+
67
+ const languageLoads = new WeakMap<Highlighter, Map<string, Promise<void>>>();
68
+ const embeddedIndexes = new Map<string, Promise<EmbeddedIndex>>();
69
+
70
+ /* Concurrent documents await one load, so each learns the grammar was rebuilt. */
71
+ function loadOnce(highlighter: Highlighter, id: string): Promise<void> {
72
+ if (highlighter.getLoadedLanguages().includes(id)) {
73
+ return Promise.resolve();
74
+ }
75
+
76
+ let loads = languageLoads.get(highlighter);
77
+
78
+ if (loads === undefined) {
79
+ loads = new Map();
80
+ languageLoads.set(highlighter, loads);
81
+ }
82
+
83
+ const pending = loads.get(id);
84
+
85
+ if (pending !== undefined) {
86
+ return pending;
87
+ }
88
+
89
+ const load = (async () => {
90
+ await loadDocumentLanguage(highlighter, id);
91
+
92
+ if (!highlighter.getLoadedLanguages().includes(id)) {
93
+ await highlighter.loadLanguage(id as LanguageId);
94
+ }
95
+ })();
96
+
97
+ loads.set(id, load);
98
+
99
+ void load.catch(() => {
100
+ if (loads.get(id) === load) {
101
+ loads.delete(id);
102
+ }
103
+ });
104
+
105
+ return load;
106
+ }
107
+
108
+ function embedIndex(grammar: string): Promise<EmbeddedIndex> {
109
+ const cached = embeddedIndexes.get(grammar);
110
+
111
+ if (cached !== undefined) {
112
+ return cached;
113
+ }
114
+
115
+ const pending = (async (): Promise<EmbeddedIndex> => {
116
+ const { bundledLanguages, bundledLanguagesInfo } = await import('shiki');
117
+ const bundled = bundledLanguages[grammar as keyof typeof bundledLanguages];
118
+ const registrations = bundled === undefined ? [] : (await bundled()).default;
119
+ const lazy = registrations.find((registration) => registration.name === grammar)?.embeddedLangsLazy ?? [];
120
+ const names = new Map<string, string>();
121
+
122
+ for (const id of lazy) {
123
+ const aliases = bundledLanguagesInfo.find((info) => info.id === id)?.aliases ?? [];
124
+
125
+ for (const name of [id, ...aliases]) {
126
+ names.set(name.toLowerCase(), id);
127
+ }
128
+ }
129
+
130
+ if (names.size === 0) {
131
+ return { names, matcher: null };
132
+ }
133
+
134
+ let matcher: RegExp;
135
+
136
+ if (grammar === 'markdown' || grammar === 'mdx') {
137
+ matcher = /^\s*(?:`{3,}|~{3,})[ \t]*([\w#+.-]+)/gm;
138
+ } else if (grammar === 'vue' || grammar === 'svelte' || grammar === 'astro') {
139
+ matcher = /\blang\s*=\s*["']([\w#+.-]+)["']/gi;
140
+ } else {
141
+ const alternatives = [...names.keys()].map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
142
+ matcher = new RegExp(`(?<![\\w-])(${alternatives})(?![\\w-])`, 'gi');
143
+ }
144
+
145
+ return { names, matcher };
146
+ })();
147
+
148
+ embeddedIndexes.set(grammar, pending);
149
+ void pending.catch(() => embeddedIndexes.delete(grammar));
150
+
151
+ return pending;
152
+ }
153
+
154
+ async function loadEmbedded(highlighter: Highlighter, embedded: EmbeddedIndex, text: string): Promise<boolean> {
155
+ if (embedded.matcher === null) {
156
+ return false;
157
+ }
158
+
159
+ const loaded = new Set(highlighter.getLoadedLanguages());
160
+ const named = new Set<string>();
161
+
162
+ for (const match of text.matchAll(embedded.matcher)) {
163
+ const id = embedded.names.get(match[1]!.toLowerCase());
164
+
165
+ if (id !== undefined && !loaded.has(id)) {
166
+ named.add(id);
167
+ }
168
+ }
169
+
170
+ const results = await Promise.allSettled([...named].map((id) => loadOnce(highlighter, id)));
171
+
172
+ return results.some((result) => result.status === 'fulfilled');
173
+ }
174
+
175
+ /* Text names the optional embedded grammars that must load before the host hands out states. */
176
+ export async function loadGrammar(highlighter: Highlighter, grammar: string, text = ''): Promise<boolean> {
177
+ await loadOnce(highlighter, grammar);
178
+ await loadEmbedded(highlighter, await embedIndex(grammar), text);
179
+
180
+ return highlighter.getLoadedLanguages().includes(grammar);
181
+ }
182
+
183
+ /*
184
+ * Colors with the viewer's highlighter, so a grammar loads once for both. A language Shiki has no
185
+ * grammar for, or a theme it cannot load, is plain text.
186
+ */
187
+ export function shikiTokenizers(highlighter: () => Promise<Highlighter>): TokenizerSource {
188
+ return async (language, theme, text) => {
189
+ if (language === undefined || PLAIN_TEXT.has(language)) {
190
+ return null;
191
+ }
192
+
193
+ const grammar = documentLanguageOf(language);
194
+ const shiki = await highlighter();
195
+
196
+ try {
197
+ if (!shiki.getLoadedThemes().includes(theme)) {
198
+ await shiki.loadTheme(theme as ThemeId);
199
+ }
200
+
201
+ return (await loadGrammar(shiki, grammar, text)) ? lineTokenizer(shiki, grammar, theme, await embedIndex(grammar)) : null;
202
+ } catch {
203
+ return null;
204
+ }
205
+ };
206
+ }
207
+
208
+ /* The colors of a theme's own rules by scope, so what a language server classifies is drawn in the theme's colors. */
209
+ export function shikiScopeColors(highlighter: () => Promise<Highlighter>): ScopeColorSource {
210
+ return async (theme) => {
211
+ const shiki = await highlighter();
212
+
213
+ try {
214
+ if (!shiki.getLoadedThemes().includes(theme)) {
215
+ await shiki.loadTheme(theme as ThemeId);
216
+ }
217
+
218
+ return scopeColorsOf(shiki.getTheme(theme).settings as readonly ThemeRule[]);
219
+ } catch {
220
+ return null;
221
+ }
222
+ };
223
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Highlighter, ThemeRegistration, ThemedToken } from 'shiki';
2
2
  import { shikiDocumentTokens } from './shiki-document.ts';
3
- import { documentLanguageOf } from './shiki.ts';
3
+ import { documentLanguageOf } from './shiki-grammar.ts';
4
4
  import type { LineToken } from './types.ts';
5
5
 
6
6
  export interface DiffSyntaxDocument {
package/src/shiki.ts CHANGED
@@ -1,225 +1,2 @@
1
- import type { GrammarState, Highlighter } from 'shiki';
2
- import { documentLanguageOf, loadDocumentLanguage } from './php-html.ts';
3
- import { scopeColorsOf, type ThemeRule } from './theme-scopes.ts';
4
- import type { LineToken, LineTokenKind, LineTokenizer, ScopeColorSource, TokenizerSource } from './types.ts';
5
-
6
- type LanguageId = Parameters<Highlighter['loadLanguage']>[0];
7
- type ThemeId = Parameters<Highlighter['loadTheme']>[0];
8
- type TokenOptions = Parameters<Highlighter['codeToTokensBase']>[1];
9
-
10
- export { documentLanguageOf };
11
-
12
- /* The standard token types of TextMate: 1 comment, 2 string, 3 regex. */
13
- const KINDS: Record<number, LineTokenKind | undefined> = { 1: 'comment', 2: 'string', 3: 'regex' };
14
-
15
- const PLAIN_TEXT = new Set(['', 'text', 'txt', 'plain', 'plaintext']);
16
-
17
- /* Colors one line at a time and hands the grammar's state from one line to the next. A grammar Shiki rebuilt does not know the states of the old one. */
18
- function lineTokenizer(highlighter: Highlighter, language: string, theme: string, embedded: EmbeddedIndex): LineTokenizer {
19
- let grammar = highlighter.getLanguage(language);
20
-
21
- return {
22
- prepare: embedded.matcher === null ? undefined : (text) => loadEmbedded(highlighter, embedded, text),
23
- stale() {
24
- const current = highlighter.getLanguage(language);
25
- const changed = current !== grammar;
26
- grammar = current;
27
-
28
- return changed;
29
- },
30
- tokenizeLine(text, state) {
31
- const options = {
32
- lang: language,
33
- theme,
34
- grammarState: (state ?? undefined) as GrammarState | undefined,
35
- includeExplanation: 'tokenType'
36
- } as TokenOptions;
37
-
38
- const lines = highlighter.codeToTokensBase(text, options);
39
-
40
- const tokens: LineToken[] = (lines[0] ?? []).map((token) => ({
41
- length: token.content.length,
42
- color: token.color ?? '',
43
- fontStyle: token.fontStyle ?? 0,
44
- kind: KINDS[token.type ?? 0]
45
- }));
46
-
47
- return { tokens, state: highlighter.getLastGrammarState(lines) };
48
- },
49
- sameState(a, b) {
50
- if (a === b) {
51
- return true;
52
- }
53
-
54
- const left = (a as GrammarState | null)?.getInternalStack(theme);
55
- const right = (b as GrammarState | null)?.getInternalStack(theme);
56
-
57
- return left !== undefined && right !== undefined && left.equals(right);
58
- }
59
- };
60
- }
61
-
62
- interface EmbeddedIndex {
63
- readonly names: ReadonlyMap<string, string>;
64
- readonly matcher: RegExp | null;
65
- }
66
-
67
- const languageLoads = new WeakMap<Highlighter, Map<string, Promise<void>>>();
68
- const embeddedIndexes = new Map<string, Promise<EmbeddedIndex>>();
69
-
70
- /* Concurrent documents await one load, so each learns the grammar was rebuilt. */
71
- function loadOnce(highlighter: Highlighter, id: string): Promise<void> {
72
- if (highlighter.getLoadedLanguages().includes(id)) {
73
- return Promise.resolve();
74
- }
75
-
76
- let loads = languageLoads.get(highlighter);
77
-
78
- if (loads === undefined) {
79
- loads = new Map();
80
- languageLoads.set(highlighter, loads);
81
- }
82
-
83
- const pending = loads.get(id);
84
-
85
- if (pending !== undefined) {
86
- return pending;
87
- }
88
-
89
- const load = (async () => {
90
- await loadDocumentLanguage(highlighter, id);
91
-
92
- if (!highlighter.getLoadedLanguages().includes(id)) {
93
- await highlighter.loadLanguage(id as LanguageId);
94
- }
95
- })();
96
-
97
- loads.set(id, load);
98
-
99
- void load.catch(() => {
100
- if (loads.get(id) === load) {
101
- loads.delete(id);
102
- }
103
- });
104
-
105
- return load;
106
- }
107
-
108
- function embedIndex(grammar: string): Promise<EmbeddedIndex> {
109
- const cached = embeddedIndexes.get(grammar);
110
-
111
- if (cached !== undefined) {
112
- return cached;
113
- }
114
-
115
- const pending = (async (): Promise<EmbeddedIndex> => {
116
- const { bundledLanguages, bundledLanguagesInfo } = await import('shiki');
117
- const bundled = bundledLanguages[grammar as keyof typeof bundledLanguages];
118
- const registrations = bundled === undefined ? [] : (await bundled()).default;
119
- const lazy = registrations.find((registration) => registration.name === grammar)?.embeddedLangsLazy ?? [];
120
- const names = new Map<string, string>();
121
-
122
- for (const id of lazy) {
123
- const aliases = bundledLanguagesInfo.find((info) => info.id === id)?.aliases ?? [];
124
-
125
- for (const name of [id, ...aliases]) {
126
- names.set(name.toLowerCase(), id);
127
- }
128
- }
129
-
130
- if (names.size === 0) {
131
- return { names, matcher: null };
132
- }
133
-
134
- let matcher: RegExp;
135
-
136
- if (grammar === 'markdown' || grammar === 'mdx') {
137
- matcher = /^\s*(?:`{3,}|~{3,})[ \t]*([\w#+.-]+)/gm;
138
- } else if (grammar === 'vue' || grammar === 'svelte' || grammar === 'astro') {
139
- matcher = /\blang\s*=\s*["']([\w#+.-]+)["']/gi;
140
- } else {
141
- const alternatives = [...names.keys()].map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
142
- matcher = new RegExp(`(?<![\\w-])(${alternatives})(?![\\w-])`, 'gi');
143
- }
144
-
145
- return { names, matcher };
146
- })();
147
-
148
- embeddedIndexes.set(grammar, pending);
149
- void pending.catch(() => embeddedIndexes.delete(grammar));
150
-
151
- return pending;
152
- }
153
-
154
- async function loadEmbedded(highlighter: Highlighter, embedded: EmbeddedIndex, text: string): Promise<boolean> {
155
- if (embedded.matcher === null) {
156
- return false;
157
- }
158
-
159
- const loaded = new Set(highlighter.getLoadedLanguages());
160
- const named = new Set<string>();
161
-
162
- for (const match of text.matchAll(embedded.matcher)) {
163
- const id = embedded.names.get(match[1]!.toLowerCase());
164
-
165
- if (id !== undefined && !loaded.has(id)) {
166
- named.add(id);
167
- }
168
- }
169
-
170
- const results = await Promise.allSettled([...named].map((id) => loadOnce(highlighter, id)));
171
-
172
- return results.some((result) => result.status === 'fulfilled');
173
- }
174
-
175
- /* Text names the optional embedded grammars that must load before the host hands out states. */
176
- export async function loadGrammar(highlighter: Highlighter, grammar: string, text = ''): Promise<boolean> {
177
- await loadOnce(highlighter, grammar);
178
- await loadEmbedded(highlighter, await embedIndex(grammar), text);
179
-
180
- return highlighter.getLoadedLanguages().includes(grammar);
181
- }
182
-
183
- /*
184
- * Colors with the viewer's highlighter, so a grammar loads once for both. A language Shiki has no
185
- * grammar for, or a theme it cannot load, is plain text.
186
- */
187
- export function shikiTokenizers(highlighter: () => Promise<Highlighter>): TokenizerSource {
188
- return async (language, theme, text) => {
189
- if (language === undefined || PLAIN_TEXT.has(language)) {
190
- return null;
191
- }
192
-
193
- const grammar = documentLanguageOf(language);
194
- const shiki = await highlighter();
195
-
196
- try {
197
- if (!shiki.getLoadedThemes().includes(theme)) {
198
- await shiki.loadTheme(theme as ThemeId);
199
- }
200
-
201
- return (await loadGrammar(shiki, grammar, text)) ? lineTokenizer(shiki, grammar, theme, await embedIndex(grammar)) : null;
202
- } catch {
203
- return null;
204
- }
205
- };
206
- }
207
-
208
- /* The colors of a theme's own rules by scope, so what a language server classifies is drawn in the theme's colors. */
209
- export function shikiScopeColors(highlighter: () => Promise<Highlighter>): ScopeColorSource {
210
- return async (theme) => {
211
- const shiki = await highlighter();
212
-
213
- try {
214
- if (!shiki.getLoadedThemes().includes(theme)) {
215
- await shiki.loadTheme(theme as ThemeId);
216
- }
217
-
218
- return scopeColorsOf(shiki.getTheme(theme).settings as readonly ThemeRule[]);
219
- } catch {
220
- return null;
221
- }
222
- };
223
- }
224
-
1
+ export { documentLanguageOf, loadGrammar, shikiScopeColors, shikiTokenizers } from './shiki-grammar.ts';
225
2
  export { shikiDocumentHighlighter, shikiDocumentTokens, type ShikiDocumentTokenOptions } from './shiki-document.ts';
package/src/smart-keys.ts CHANGED
@@ -13,7 +13,6 @@ export const DEFAULT_SMART_KEYS: EditorSmartKeys = {
13
13
  camelHumps: false
14
14
  };
15
15
 
16
- /* The keys with what a host left out filled in from the defaults. */
17
16
  export function resolveSmartKeys(keys: Partial<EditorSmartKeys> | undefined): EditorSmartKeys {
18
17
  return { ...DEFAULT_SMART_KEYS, ...keys };
19
18
  }
package/src/testing.ts CHANGED
@@ -64,7 +64,6 @@ export interface KeyOptions {
64
64
  pointerType?: string;
65
65
  }
66
66
 
67
- /* Fires a keydown at the element and says whether the editor took the key. */
68
67
  export function press(window: Window, target: Element, key: string, options: KeyOptions = {}): boolean {
69
68
  const event = createEvent(window, 'keydown');
70
69
  Object.assign(event, { key, ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, isComposing: false, ...options });
@@ -73,7 +72,6 @@ export function press(window: Window, target: Element, key: string, options: Key
73
72
  return event.defaultPrevented;
74
73
  }
75
74
 
76
- /* Fires a keyup at the element, the other half of `press`. */
77
75
  export function release(window: Window, target: Element, key: string, options: KeyOptions = {}): void {
78
76
  const event = createEvent(window, 'keyup');
79
77
  Object.assign(event, { key, ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, isComposing: false, ...options });
package/src/todos.ts CHANGED
@@ -10,7 +10,7 @@ const TODO_LIMIT = 2_000_000;
10
10
  const CACHED_LINES = 600;
11
11
 
12
12
  /* The text is kept with the mark, since the list is only read again after a pause and the offsets may be stale until then. */
13
- export type TodoMark = TodoMatch & { readonly text: string };
13
+ type TodoMark = TodoMatch & { readonly text: string };
14
14
 
15
15
  /*
16
16
  * The TODO comments of a view: drawn in their own color over the grammar's on the lines being painted,