@aardarch/aardink-web 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -97,6 +97,67 @@ await registerLanguage({
97
97
  });
98
98
  ```
99
99
 
100
+ A language can also take VS Code's `language-configuration.json`, as the object or its text, for
101
+ closing pairs, surrounding a selection and indentation on Enter:
102
+
103
+ ```ts
104
+ await registerLanguage({ id: 'toy', grammar, configuration: await (await fetch('/toy.configuration.json')).text() });
105
+ ```
106
+
107
+ The providers go beyond completions: `provideHover`, `provideDiagnostics`, `provideDocumentSymbols`,
108
+ `provideDocumentColors`, and, with the `inlayHints` and `codeLens` options on, `provideInlayHints`
109
+ and `provideCodeLenses` with `runCodeLensCommand` for a lens's click:
110
+
111
+ ```ts
112
+ await registerLanguage(definition, {
113
+ provideInlayHints: (text, range) => [{ position: { lineNumber: 3, column: 9 }, label: ': Int' }],
114
+ provideCodeLenses: (text) => [
115
+ { range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }, command: { id: 'app.run', title: 'Run' } },
116
+ ],
117
+ runCodeLensCommand: (id, args) => run(id, args),
118
+ });
119
+ const editor = await createEditor(container, save, { language: 'toy', inlayHints: true, codeLens: true });
120
+ ```
121
+
122
+ Hover, completion documentation and signature help are Markdown, shown in a card and, for the
123
+ selected completion, in a pane beside the list. A link there, or Ctrl/Cmd+click on a URL in the
124
+ text, opens `http` and `https` in a new tab; listen to decide for yourself, and check the target
125
+ first, since text from a language server can hold a `javascript:` link:
126
+
127
+ ```ts
128
+ const links = editor.onOpenLink((target) => {
129
+ if (target.startsWith('https://')) window.open(target, '_blank', 'noopener');
130
+ });
131
+ ```
132
+
133
+ Ghost text, as an assistant offers it, comes from a provider of its own, for any language. Tab
134
+ accepts, Alt+] and Alt+[ go through what is on offer, and Escape hides it; a phone runs
135
+ `editor.action.inlineSuggest.commit` and `.hide` from buttons through `trigger`:
136
+
137
+ ```ts
138
+ import { registerInlineCompletionsProvider } from '@aardarch/aardink-web';
139
+
140
+ await registerInlineCompletionsProvider('kotlin', {
141
+ provideInlineCompletions: async (text, line, column) => ({ items: [{ insertText: await suggest(text, line, column) }] }),
142
+ });
143
+ ```
144
+
145
+ A language server reached over a WebSocket follows every editor of a language, adding what it
146
+ knows to what the language has; with `semanticHighlighting: true` its semantic tokens colour the
147
+ text too:
148
+
149
+ ```ts
150
+ import { connectLanguageServer } from '@aardarch/aardink-web';
151
+
152
+ const server = await connectLanguageServer('wss://example.com/lsp', 'kotlin');
153
+ // ...
154
+ server.dispose(); // closes each document and shuts the server down
155
+ ```
156
+
157
+ The socket carries one JSON-RPC message per frame, so a server that speaks over stdin and stdout
158
+ needs a bridge in front of it. Nothing reconnects by itself, and a server never changes what typing
159
+ does: Enter, closing pairs and surrounding stay the language's.
160
+
100
161
  The editor answers to your keys and actions as Monaco's does, and tells you what changed:
101
162
 
102
163
  ```ts
@@ -109,7 +170,7 @@ editor.revealLineInCenter(42);
109
170
  ```
110
171
 
111
172
  The editor fills its container, so give the container a size. `createEditor` is async because
112
- the first call loads the WebAssembly module (about 13 MB, 4.7 MB gzipped); every editor on the
173
+ the first call loads the WebAssembly module (about 14 MB, 5 MB gzipped); every editor on the
113
174
  page shares that one module. If that load fails, the call rejects and the next call loads again
114
175
  (though Chrome keeps a failed module download until the page is reloaded). See
115
176
  [`index.d.ts`](./index.d.ts) for the full API, and the
@@ -152,10 +213,15 @@ Read these before adopting the package; the
152
213
  [integration guide](https://github.com/aardarch/aardink/blob/main/docs/WEB_INTEGRATION.md) has
153
214
  the measurements and the device checklist.
154
215
 
155
- - **A disposed editor is not fully released** (about 275 KB each) until Aardink moves to Compose
216
+ - **A disposed editor is not fully released** (about 320 KB each) until Aardink moves to Compose
156
217
  Multiplatform 1.13. Reuse one editor with `setValue` and `updateOptions` rather than mounting
157
218
  one per view.
158
219
  - A theme rule's `background` is ignored; its `foreground` and `fontStyle` apply.
220
+ - A language from `registerLanguage`, and the built-in language it `extends`, answer before a
221
+ language server: with `extends: 'json'`, JSON's formatter and outline come ahead of the server's.
222
+ - The page has no save, so a language server never hears `willSave` or `didSave`.
223
+ - Of the keys that type a character with Alt held, only Alt+] and Alt+[ reach the editor:
224
+ `addCommand('Alt+K', ...)` never runs. Use a key with Ctrl or Cmd.
159
225
 
160
226
  ## Licence
161
227
 
package/index.d.ts CHANGED
@@ -60,6 +60,19 @@ export interface AardinkOptions {
60
60
  breadcrumbs?: boolean;
61
61
  /** The font's ligatures; on by default. */
62
62
  fontLigatures?: boolean;
63
+ /** Colours what a language server's semantic tokens say over the syntax's. Off by default. */
64
+ semanticHighlighting?: boolean;
65
+ /**
66
+ * Shows what `provideInlayHints` or a language server says, among the characters of the lines
67
+ * around the view. Off by default. Takes Monaco's `{ enabled }` too; with `'onUnlessPressed'` and
68
+ * `'offUnlessPressed'` no key is watched, so they mean on and off.
69
+ */
70
+ inlayHints?: boolean | { enabled?: boolean | 'on' | 'off' | 'onUnlessPressed' | 'offUnlessPressed' };
71
+ /**
72
+ * Shows what `provideCodeLenses` or a language server says, in a row above its lines. Off by
73
+ * default, where Monaco's is on.
74
+ */
75
+ codeLens?: boolean;
63
76
  }
64
77
 
65
78
  /**
@@ -233,7 +246,8 @@ export interface AardinkEditor {
233
246
  * `editor.action.changeAll`, `editor.action.insertCursorAtEndOfEachLineSelected`,
234
247
  * `editor.action.addCommentLine`, `editor.action.removeCommentLine`, `editor.action.blockComment`,
235
248
  * `editor.action.insertLineAfter` and `Before`, `expandLineSelection`,
236
- * `editor.action.showColorPicker`, and
249
+ * `editor.action.showColorPicker`, `editor.action.inlineSuggest.commit`, `.showNext`,
250
+ * `.showPrevious` and `.hide`, and
237
251
  * `editor.action.insertSnippet` with `{ snippet }`. `source` is accepted for Monaco's shape.
238
252
  * Returns whether it ran.
239
253
  */
@@ -278,6 +292,14 @@ export interface AardinkEditor {
278
292
  getScrollHeight(): number;
279
293
  /** Called as the text scrolls. Returns an unsubscribe function. */
280
294
  onDidScrollChange(listener: (event: { scrollTop: number; scrollLeft: number; scrollHeight: number }) => void): () => void;
295
+ /**
296
+ * Called with the target of every link opened in the editor, by Ctrl/Cmd+click on a URL in the
297
+ * text or a click in a hover, signature help or completion card, whatever its scheme. A target
298
+ * can come from a language server, so check it before following it: it may be `javascript:`. With
299
+ * no listener, `http` and `https` links open in a new tab with `noopener`, and anything else does
300
+ * nothing. Returns a disposable.
301
+ */
302
+ onOpenLink(listener: (target: string) => void): { dispose(): void };
281
303
  /** Measures the container again now; the editor follows its container's size by itself. */
282
304
  layout(): void;
283
305
  /**
@@ -373,10 +395,17 @@ export interface AardinkLanguageDefinition {
373
395
  id: string;
374
396
  /**
375
397
  * A subset of Monaco's Monarch: states in `tokenizer` (`root` first), rules of
376
- * `[regex, action, next?]`, `cases` with `@array`/`@default`/`@eos`, capture groups (each
377
- * with a token name, `{ token, next }` or `cases` of its own), `include`, `@rematch`,
378
- * `defaultToken`, `ignoreCase`, `tokenPostfix`. RegExp literals are fine. Lookbehind is not
379
- * supported, and is refused.
398
+ * `[regex, action, next?]`, `cases`, capture groups (each with a token name, `{ token, next }`
399
+ * or `cases` of its own), `include`, `@rematch`, `switchTo`, `goBack`, `@brackets` with a
400
+ * top-level `brackets`, `defaultToken`, `ignoreCase`, `tokenPostfix`, and `@name` in a regex
401
+ * for the top-level string `name`, as a group of its own. A guard is
402
+ * `@default`, `@eos`, or a subject of `$#` or `$S0`, `$S1`... then `@array`, `~regex`, `==text`
403
+ * or `!@`, `!~`, `!=`, as in `$#==$S2`; `next` and `switchTo` take `$#` and `$Sn` too. `log` is
404
+ * accepted and ignored. RegExp literals are fine. Lookbehind and `$` in a token name are
405
+ * refused, as is `goBack` in a capture group's action. `nextEmbedded` hands the text to the
406
+ * grammar of the language registered with that id, before or after this one, and
407
+ * `nextEmbedded: '@pop'` takes it back; with no such language, the text stays on this grammar.
408
+ * A built-in language has no grammar, so it cannot be embedded.
380
409
  */
381
410
  grammar: object;
382
411
  /** A built-in or registered language whose completions, diagnostics, hover and folding this one takes too, e.g. `'xml'`. */
@@ -400,6 +429,66 @@ export interface AardinkLanguageDefinition {
400
429
  * checks, closing tags and formatting when it extends none). Your providers still come first.
401
430
  */
402
431
  schema?: AardinkXmlSchema;
432
+ /**
433
+ * What the language says about typing, as VS Code's `language-configuration.json`: the object,
434
+ * or the file's text, which may have comments and trailing commas. Regular expressions are
435
+ * refused with a lookbehind. Its `comments` replace the definition's.
436
+ */
437
+ configuration?: AardinkLanguageConfiguration | string;
438
+ }
439
+
440
+ /** A regular expression in a language configuration: VS Code's two forms, or a RegExp literal. */
441
+ export type AardinkConfigurationRegExp = string | RegExp | { pattern: string; flags?: string };
442
+
443
+ /** An opening and a closing text, such as `['(', ')']`. */
444
+ export type AardinkCharacterPair = [string, string] | { open: string; close: string };
445
+
446
+ /**
447
+ * `registerLanguage`'s `configuration`. Every field is optional. As in VS Code, without
448
+ * `autoClosingPairs` the brackets close themselves, and without `surroundingPairs` those pairs
449
+ * surround. `wordPattern`, `autoCloseBefore` and `folding.offSide` are not read.
450
+ */
451
+ export interface AardinkLanguageConfiguration {
452
+ /** What Ctrl/Cmd+/ comments with. */
453
+ comments?: { lineComment?: string | { comment: string }; blockComment?: [string, string] };
454
+ /** Pairs the language nests: Enter indents after an opening one. Matching and colouring brackets stay `()[]{}`. */
455
+ brackets?: AardinkCharacterPair[];
456
+ /**
457
+ * Closed when the opening text is typed. `notIn` (`'string'`, `'comment'`) is worked out from the
458
+ * caret's own line, so a block comment opened on an earlier line is not seen.
459
+ */
460
+ autoClosingPairs?: (AardinkCharacterPair | { open: string; close: string; notIn?: string[] })[];
461
+ /** Wrap a selection when the opening text, one character, is typed over it. */
462
+ surroundingPairs?: AardinkCharacterPair[];
463
+ /** What Enter does, the first rule that matches. */
464
+ onEnterRules?: AardinkOnEnterRule[];
465
+ /** What Enter does when no rule and no bracket decides. */
466
+ indentationRules?: {
467
+ increaseIndentPattern?: AardinkConfigurationRegExp;
468
+ decreaseIndentPattern?: AardinkConfigurationRegExp;
469
+ indentNextLinePattern?: AardinkConfigurationRegExp;
470
+ unIndentedLinePattern?: AardinkConfigurationRegExp;
471
+ };
472
+ /** Lines that open and close a fold region. */
473
+ folding?: { markers?: { start: AardinkConfigurationRegExp; end: AardinkConfigurationRegExp } };
474
+ }
475
+
476
+ /** One of `onEnterRules`: every regular expression given must match. */
477
+ export interface AardinkOnEnterRule {
478
+ /** Against the text before the caret. */
479
+ beforeText?: AardinkConfigurationRegExp;
480
+ /** Against the text after the caret. */
481
+ afterText?: AardinkConfigurationRegExp;
482
+ /** Against the line above the one Enter was pressed on. */
483
+ previousLineText?: AardinkConfigurationRegExp;
484
+ action: {
485
+ /** `indentOutdent` leaves the closer at the opener's indentation and adds no line in between. */
486
+ indent: 'none' | 'indent' | 'outdent' | 'indentOutdent';
487
+ /** What the new line starts with after its indentation. Not used with `indentOutdent`. */
488
+ appendText?: string;
489
+ /** Characters taken off the end of the indentation. */
490
+ removeText?: number;
491
+ };
403
492
  }
404
493
 
405
494
  /** An XML vocabulary, for `registerLanguage`'s `schema`. */
@@ -466,8 +555,7 @@ export interface AardinkModelDeltaDecoration {
466
555
  /**
467
556
  * Monaco's `IModelDecorationOptions`, as far as the editor draws them. Where Monaco takes a CSS
468
557
  * class (`className`, `inlineClassName`, `linesDecorationsClassName`), give a colour instead: CSS
469
- * hex, `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`. Nothing here changes the text's layout, so
470
- * Monaco's `before` and `after` are not read.
558
+ * hex, `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`.
471
559
  */
472
560
  export interface AardinkDecorationOptions {
473
561
  /** Behind the characters; behind whole lines with `isWholeLine`. */
@@ -478,6 +566,15 @@ export interface AardinkDecorationOptions {
478
566
  underlineColor?: string;
479
567
  /** A bar at the gutter's text edge on each line, as Monaco's `linesDecorationsClassName` places one. */
480
568
  gutterColor?: string;
569
+ /** The colour of the range's characters, in place of Monaco's `inlineClassName`, and of `before` and `after`. */
570
+ inlineColor?: string;
571
+ /**
572
+ * Text in front of the range, as Monaco's `before`. It is not in the document, moves with the range,
573
+ * and is drawn in `inlineColor`, or faintly without it. `content` is all that is read, on one row.
574
+ */
575
+ before?: { content: string };
576
+ /** Text behind the range, as Monaco's `after`, by the same rules as `before`. */
577
+ after?: { content: string };
481
578
  isWholeLine?: boolean;
482
579
  hoverMessage?: string | { value: string } | Array<string | { value: string }>;
483
580
  overviewRuler?: { color: string; position?: number };
@@ -518,11 +615,11 @@ export interface AardinkCompletionItem {
518
615
  | 'method' | 'constructor' | 'field' | 'variable' | 'class' | 'struct' | 'interface' | 'enum' | 'enumMember' | 'keyword'
519
616
  | 'text' | 'file' | 'folder' | 'reference' | 'constant' | 'event' | 'operator' | 'typeParameter' | 'unit' | 'user' | 'issue'
520
617
  | number;
521
- /** A short line about the item, such as a type or a signature, shown beside the label. */
618
+ /** A short line about the item, such as a type or a signature, shown beside the label and above its `documentation`. */
522
619
  detail?: string;
523
620
  /** Characters that, typed while this item is selected, accept it and are then typed after it. Not for snippets. */
524
621
  commitCharacters?: string[];
525
- /** Shown beside the label; Monaco's `{ value }` is shown as plain text. */
622
+ /** Markdown, either way. Shown beside the label as one line of plain text, and whole beside the list for the selected item. */
526
623
  documentation?: string | { value: string };
527
624
  /**
528
625
  * What the text typed so far is matched against, as in Monaco: its characters in order, ignoring
@@ -555,7 +652,7 @@ export interface AardinkCompletionList {
555
652
 
556
653
  export interface AardinkHover {
557
654
  title?: string;
558
- /** Plain text. */
655
+ /** Markdown. Raw HTML shows as written. A link goes to `onOpenLink`, or to a new tab for `http` and `https`. */
559
656
  contents: string;
560
657
  /** Shown as code below `contents`. */
561
658
  example?: string;
@@ -594,6 +691,42 @@ export interface AardinkLanguageProviders {
594
691
  * picked in the editor's picker is written back as CSS hex (`#rrggbb`, `#rrggbbaa`).
595
692
  */
596
693
  provideDocumentColors?(text: string): AardinkColorInformation[] | null | Promise<AardinkColorInformation[] | null>;
694
+ /**
695
+ * Labels shown among the characters of `range`, as Monaco's `provideInlayHints`, with the
696
+ * `inlayHints` option on. `range` holds whole lines around the view: it is asked after a pause in
697
+ * typing, in scrolling past what it last asked about, or after a fold opens or closes. A long closed
698
+ * fold on screen makes that a few calls at once, one for the lines on either side of it. With
699
+ * `extends`, the base language's are added, less any at a position this has one at. With a language
700
+ * server these are shown after a second if it has not answered by then.
701
+ */
702
+ provideInlayHints?(text: string, range: AardinkRange): AardinkInlayHint[] | null | Promise<AardinkInlayHint[] | null>;
703
+ /**
704
+ * What is shown in a row above the line each `range` starts on, as Monaco's `provideCodeLenses`,
705
+ * with the `codeLens` option on. It is about the whole text, and asked after a pause in typing;
706
+ * between answers each lens moves with its text. Lenses on one line share a row. An array, with no
707
+ * `{ lenses }` around it, and each lens with its `command`: there is no `resolveCodeLens`. With
708
+ * `extends`, the base language's are added, less any with this one's position and title. With a
709
+ * language server these are shown after a second if it has not answered by then.
710
+ */
711
+ provideCodeLenses?(text: string): AardinkCodeLens[] | null | Promise<AardinkCodeLens[] | null>;
712
+ /**
713
+ * A lens from `provideCodeLenses` was clicked or tapped: its command's `id`, and its `arguments`,
714
+ * `[]` when it has none. As they passed through JSON, they hold only what JSON can. There is no
715
+ * command registry behind this: a lens does what this does with its `id`.
716
+ */
717
+ runCodeLensCommand?(id: string, args: unknown[]): void | Promise<void>;
718
+ }
719
+
720
+ /** Monaco's `CodeLens`, with the command it must have here: a title in a row above the line `range` starts on. */
721
+ export interface AardinkCodeLens {
722
+ range: AardinkRange;
723
+ command: { id: string; title: string; arguments?: unknown[] };
724
+ }
725
+
726
+ /** Monaco's `InlayHint`, as far as the editor draws it: a label at a position, in front of the character there. */
727
+ export interface AardinkInlayHint {
728
+ position: AardinkPosition;
729
+ label: string;
597
730
  }
598
731
 
599
732
  /** Monaco's `IColorInformation`: where a colour is written, and the colour, each channel from 0 to 1. */
@@ -621,6 +754,83 @@ export interface AardinkThemeData {
621
754
  /** Adds a theme for `createEditor`'s `theme` option: Monaco's `defineTheme` data, or a VS Code theme's JSON. */
622
755
  export function registerTheme(name: string, theme: AardinkThemeData | object): Promise<void>;
623
756
 
757
+ /**
758
+ * Connects to the language server at a WebSocket URL, which carries one JSON-RPC message per frame,
759
+ * and has it follow every editor of `languageId`: those open now, those created later, and those
760
+ * switched to it with `updateOptions`. Each is a document of its own to the server, under a
761
+ * generated `file:///aardink/` URI.
762
+ *
763
+ * What the server knows joins what the language has. The providers of a language from
764
+ * `registerLanguage` answer first and the server fills in; a built-in language's answers come after
765
+ * the server's. Either way Enter, closing pairs and surrounding a selection stay the language's,
766
+ * even where it does nothing, and an editor with no language service, such as plain text, types as
767
+ * it does without a server. Completions, diagnostics, code actions, references, links and colours
768
+ * come from both, and what a server pushes shows after a pause in typing.
769
+ *
770
+ * Resolves once the connection has been asked for, not once it is up. A server that cannot be
771
+ * reached, or that drops later, is said on the console and the editors go on with their language's
772
+ * own service. Nothing reconnects by itself: call this again for that. A rename reaching other
773
+ * files, and `workspace/applyEdit`, are refused. `dispose()` closes each document and shuts the
774
+ * server down.
775
+ */
776
+ export function connectLanguageServer(url: string | URL, languageId: string): Promise<{ dispose(): void }>;
777
+
778
+ /** What `provideInlineCompletions` offers: Monaco's `InlineCompletions`, or just its `items`. */
779
+ export interface AardinkInlineCompletions {
780
+ items: AardinkInlineCompletion[];
781
+ }
782
+
783
+ /**
784
+ * Monaco's `InlineCompletion`, as far as the editor shows it. `insertText` is a string: a
785
+ * `{ snippet }` is left out, as ghost text cannot fill in its stops.
786
+ *
787
+ * `range` is what it replaces, and must hold the caret. What `insertText` repeats of it is not shown
788
+ * again: over `)`, the text `x) {` shows `x` before the bracket and ` {` after it, which is how ghost
789
+ * text keeps from doubling what follows the caret. So it has to hold all of `range`, in order, or it
790
+ * does not show, as in Monaco. An empty `range` is a plain insertion.
791
+ *
792
+ * Without `range`, it replaces the word at the caret and the rest of the line, as in Monaco. Where
793
+ * Monaco then shows nothing for text that does not hold them, this tries the rest of the line alone,
794
+ * and then puts the text in at the caret, so a provider that only knows what comes next can leave
795
+ * `range` out. Text the document has already, from the caret on or from the word's start to the caret
796
+ * or past it, shows nothing.
797
+ */
798
+ export interface AardinkInlineCompletion {
799
+ insertText: string;
800
+ range?: AardinkRange;
801
+ }
802
+
803
+ /** Monaco's `InlineCompletionsProvider`, as far as the editor asks one anything. */
804
+ export interface AardinkInlineCompletionsProvider {
805
+ /**
806
+ * What might come next at a 1-based `line` and `column`, best first: the first shows, and Alt+] and
807
+ * Alt+[ go through the others. Asked once typing pauses, not for each key, and at once after one
808
+ * is accepted, or by `editor.action.inlineSuggest.showNext` with none showing. While one shows,
809
+ * typing what it says asks nothing. An answer for text that has moved on is dropped; there is no
810
+ * cancellation token, so the work behind it is not told to stop.
811
+ */
812
+ provideInlineCompletions(
813
+ text: string,
814
+ line: number,
815
+ column: number,
816
+ ): AardinkInlineCompletions | AardinkInlineCompletion[] | null | Promise<AardinkInlineCompletions | AardinkInlineCompletion[] | null>;
817
+ }
818
+
819
+ /**
820
+ * Has `provider` offer ghost text in every editor of `languageId`, open now or to come, as Monaco's
821
+ * `languages.registerInlineCompletionsProvider`. Several for one language are all asked, and their
822
+ * answers follow each other, oldest first. Tab accepts, as one undo step; Alt+] and Alt+[ go through
823
+ * what is on offer; Escape dismisses, until the next edit asks again. A phone has neither key, so run
824
+ * `editor.action.inlineSuggest.commit` and `.hide` from buttons: `getAction` says whether anything
825
+ * shows. Nothing shows in a read-only editor, with a selection or several carets, while filling in a
826
+ * snippet, while an input method composes, or under an open completion list, which takes Tab.
827
+ * `dispose()` ends it.
828
+ */
829
+ export function registerInlineCompletionsProvider(
830
+ languageId: string,
831
+ provider: AardinkInlineCompletionsProvider,
832
+ ): Promise<{ dispose(): void }>;
833
+
624
834
  /** Monaco's name for `registerTheme`. */
625
835
  export const defineTheme: typeof registerTheme;
626
836
 
package/index.js CHANGED
@@ -17,7 +17,7 @@
17
17
  // Adapts the Kotlin module's integer-handle exports (aardinkCreate, aardinkGetValue, ...) into
18
18
  // the Monaco-shaped object described in index.d.ts.
19
19
 
20
- export const version = '0.8.0';
20
+ export const version = '0.9.0';
21
21
 
22
22
  /** Monaco's flags for a completion's `insertText`. */
23
23
  export const CompletionItemInsertTextRule = Object.freeze({ None: 0, KeepWhitespace: 1, InsertAsSnippet: 4 });
@@ -139,9 +139,31 @@ function monarchToJson(value) {
139
139
  return value;
140
140
  }
141
141
 
142
+ /** A language configuration's RegExp literals, for JSON.stringify: VS Code's `{ pattern, flags }`. */
143
+ function regexAsPattern(key, value) {
144
+ return value instanceof RegExp ? { pattern: value.source, flags: value.flags } : value;
145
+ }
146
+
142
147
  /** The decorations owner deltaDecorations sets; each collection has its own. */
143
148
  const DELTA_OWNER = 'delta';
144
149
 
150
+ /**
151
+ * What the Kotlin side asks by name, and the host's function that answers it, read at each call. A
152
+ * new provider is one line here; a name not here has no provider, and gets null.
153
+ */
154
+ const PROVIDERS = new Map([
155
+ ['completions', (providers) => providers.provideCompletionItems],
156
+ ['hover', (providers) => providers.provideHover],
157
+ ['diagnostics', (providers) => providers.provideDiagnostics &&
158
+ ((text) => Promise.resolve(providers.provideDiagnostics(text)).then((list) => (list == null ? null : list.map(toKotlinDiagnostic))))],
159
+ ['documentSymbols', (providers) => providers.provideDocumentSymbols],
160
+ ['documentColors', (providers) => providers.provideDocumentColors],
161
+ ['inlayHints', (providers) => providers.provideInlayHints],
162
+ ['codeLenses', (providers) => providers.provideCodeLenses],
163
+ // A click is about a command, so no text comes with it.
164
+ ['runCodeLensCommand', (providers) => providers.runCodeLensCommand && ((_text, id, args) => providers.runCodeLensCommand(id, args))],
165
+ ]);
166
+
145
167
  /** A provider's answer (a value or a Promise of one) as the Promise of JSON the Kotlin side awaits. */
146
168
  function answer(provider, ...args) {
147
169
  if (!provider) return Promise.resolve(null);
@@ -166,24 +188,39 @@ export async function registerLanguage(definition, providers = {}) {
166
188
  extensions: definition.extensions,
167
189
  inheritCompletions: definition.inheritCompletions,
168
190
  schema: definition.schema,
191
+ configuration: JSON.parse(JSON.stringify(definition.configuration ?? null, regexAsPattern)),
169
192
  // On the providers, as on Monaco's completion provider; the Kotlin side reads it with the definition.
170
193
  triggerCharacters: providers.triggerCharacters,
171
194
  grammar,
172
195
  }),
173
- (text, line, column) => answer(providers.provideCompletionItems, text, line, column),
174
- (text, line, column) => answer(providers.provideHover, text, line, column),
175
- (text) =>
176
- answer(
177
- providers.provideDiagnostics &&
178
- ((t) => Promise.resolve(providers.provideDiagnostics(t)).then((list) => (list == null ? null : list.map(toKotlinDiagnostic)))),
179
- text,
180
- ),
181
- (text) => answer(providers.provideDocumentSymbols, text),
182
- (text) => answer(providers.provideDocumentColors, text),
196
+ (method, text, argsJson) => answer(PROVIDERS.get(method)?.(providers), text, ...JSON.parse(argsJson)),
183
197
  );
184
198
  if (error) throw new Error(`Aardink: ${error}`);
185
199
  }
186
200
 
201
+ /**
202
+ * Has the language server at a WebSocket URL follow every editor of a language. See index.d.ts: it
203
+ * resolves once asked, not once connected, and a server that cannot be reached costs no editor.
204
+ */
205
+ export async function connectLanguageServer(url, languageId) {
206
+ const k = await load();
207
+ const id = k.aardinkConnectLanguageServer(String(url), languageId);
208
+ return { dispose: () => k.aardinkDisconnectLanguageServer(id) };
209
+ }
210
+
211
+ /**
212
+ * Has `provider.provideInlineCompletions` offer ghost text in every editor of a language, as Monaco's
213
+ * registerInlineCompletionsProvider. See index.d.ts.
214
+ */
215
+ export async function registerInlineCompletionsProvider(languageId, provider) {
216
+ const k = await load();
217
+ const id = k.aardinkRegisterInlineCompletionsProvider(
218
+ languageId,
219
+ (text, line, column) => answer((...args) => provider.provideInlineCompletions(...args), text, line, column),
220
+ );
221
+ return { dispose: () => k.aardinkDisposeInlineCompletionsProvider(id) };
222
+ }
223
+
187
224
  /** Monaco's defineTheme data ({ base, inherit, rules, colors }) as VS Code theme JSON; VS Code JSON as it is. */
188
225
  function toVsCodeTheme(theme) {
189
226
  if (!theme.rules) return theme;
@@ -236,9 +273,16 @@ function toKotlinOptions(options) {
236
273
  if (options.overviewRuler !== undefined) out.overviewRuler = !!options.overviewRuler;
237
274
  if (options.occurrencesHighlight !== undefined) out.occurrencesHighlight = options.occurrencesHighlight !== false && options.occurrencesHighlight !== 'off';
238
275
  if (options.fontLigatures !== undefined) out.fontLigatures = options.fontLigatures !== false && options.fontLigatures !== 'off';
239
- for (const key of ['linkedEditing', 'colorDecorators', 'breadcrumbs']) {
276
+ for (const key of ['linkedEditing', 'colorDecorators', 'breadcrumbs', 'semanticHighlighting', 'codeLens']) {
240
277
  if (options[key] !== undefined) out[key] = !!options[key];
241
278
  }
279
+ if (options.inlayHints !== undefined) {
280
+ // Monaco's { enabled: 'on' | 'off' | 'onUnlessPressed' | 'offUnlessPressed' }; a key held down is not
281
+ // read, so those two are their first word. A plain boolean works too.
282
+ const value = options.inlayHints;
283
+ const enabled = typeof value === 'object' && value !== null ? value.enabled ?? 'on' : value;
284
+ out.inlayHints = !!enabled && enabled !== 'off' && enabled !== 'offUnlessPressed';
285
+ }
242
286
  for (const key of ['minimap', 'stickyScroll', 'bracketPairColorization']) {
243
287
  const value = options[key];
244
288
  if (value !== undefined) out[key] = typeof value === 'object' && value !== null ? value.enabled !== false : !!value;
@@ -297,6 +341,11 @@ export async function createEditor(container, onChange, options = {}) {
297
341
  for (const listener of scrollListeners) listener(event);
298
342
  });
299
343
 
344
+ // Unlike the listeners above, the Kotlin side hears of these only while there is one: with none it
345
+ // opens http and https links itself. It does that in the click, which a popup blocker wants.
346
+ const linkListeners = new Set();
347
+ const openLink = (target) => linkListeners.forEach((listener) => listener(target));
348
+
300
349
  // Decorations: those set through deltaDecorations, with their ids, and each collection's own.
301
350
  let deltaDecorations = [];
302
351
  let nextDecorationId = 1;
@@ -390,6 +439,16 @@ export async function createEditor(container, onChange, options = {}) {
390
439
  scrollListeners.add(listener);
391
440
  return () => scrollListeners.delete(listener);
392
441
  },
442
+ onOpenLink(listener) {
443
+ if (linkListeners.size === 0) k.aardinkOnOpenLink(id, openLink);
444
+ linkListeners.add(listener);
445
+ return {
446
+ dispose() {
447
+ linkListeners.delete(listener);
448
+ if (linkListeners.size === 0 && !disposed) k.aardinkOnOpenLink(id, null);
449
+ },
450
+ };
451
+ },
393
452
  layout: () => k.aardinkLayout(id),
394
453
  onDidChangeDiagnostics(listener) {
395
454
  diagnosticsListeners.add(listener);
@@ -471,6 +530,7 @@ export async function createEditor(container, onChange, options = {}) {
471
530
  focusListeners.clear();
472
531
  blurListeners.clear();
473
532
  scrollListeners.clear();
533
+ linkListeners.clear();
474
534
  k.aardinkDispose(id);
475
535
  },
476
536
  };
@@ -214,6 +214,7 @@ const js_code = {
214
214
  'org.w3c.dom.events.target_$external_prop_getter' : (_this) => _this.target,
215
215
  'org.w3c.dom.events.cancelable_$external_prop_getter' : (_this) => _this.cancelable,
216
216
  'org.w3c.dom.events.timeStamp_$external_prop_getter' : (_this) => _this.timeStamp,
217
+ 'org.w3c.dom.events.stopPropagation_$external_fun' : (_this, ) => _this.stopPropagation(),
217
218
  'org.w3c.dom.events.preventDefault_$external_fun' : (_this, ) => _this.preventDefault(),
218
219
  'org.w3c.dom.events.Event_$external_class_instanceof' : (x) => x instanceof Event,
219
220
  'org.w3c.dom.events.Event_$external_class_get' : () => Event,
@@ -240,8 +241,9 @@ const js_code = {
240
241
  'org.w3c.dom.events.FocusEvent_$external_class_instanceof' : (x) => x instanceof FocusEvent,
241
242
  'org.w3c.dom.events.FocusEvent_$external_class_get' : () => FocusEvent,
242
243
  'org.w3c.dom.events.addEventListener_$external_fun' : (_this, p0, p1, p2) => _this.addEventListener(p0, p1, p2),
243
- 'org.w3c.dom.events.addEventListener_$external_fun_1' : (_this, p0, p1) => _this.addEventListener(p0, p1),
244
+ 'org.w3c.dom.events.addEventListener_$external_fun_1' : (_this, p0, p1, p2) => _this.addEventListener(p0, p1, p2),
244
245
  'org.w3c.dom.events.addEventListener_$external_fun_2' : (_this, p0, p1) => _this.addEventListener(p0, p1),
246
+ 'org.w3c.dom.events.addEventListener_$external_fun_3' : (_this, p0, p1) => _this.addEventListener(p0, p1),
245
247
  'org.w3c.dom.events.removeEventListener_$external_fun' : (_this, p0, p1) => _this.removeEventListener(p0, p1),
246
248
  'org.w3c.dom.events.removeEventListener_$external_fun_1' : (_this, p0, p1) => _this.removeEventListener(p0, p1),
247
249
  'org.w3c.dom.events.clientX_$external_prop_getter' : (_this) => _this.clientX,
@@ -272,6 +274,7 @@ const js_code = {
272
274
  'org.w3c.dom.getComputedStyle_$external_fun' : (_this, p0, p1, isDefault0) => _this.getComputedStyle(p0, isDefault0 ? undefined : p1, ),
273
275
  'org.w3c.dom.matches_$external_prop_getter' : (_this) => _this.matches,
274
276
  'org.w3c.dom.addListener_$external_fun' : (_this, p0) => _this.addListener(p0),
277
+ 'org.w3c.dom.removeListener_$external_fun' : (_this, p0) => _this.removeListener(p0),
275
278
  'org.w3c.dom.MediaQueryList_$external_class_instanceof' : (x) => x instanceof MediaQueryList,
276
279
  'org.w3c.dom.MediaQueryList_$external_class_get' : () => MediaQueryList,
277
280
  'org.w3c.dom.protocol_$external_prop_getter' : (_this) => _this.protocol,
@@ -329,11 +332,15 @@ const js_code = {
329
332
  'org.w3c.dom.userAgent_$external_prop_getter' : (_this) => _this.userAgent,
330
333
  'org.w3c.dom.language_$external_prop_getter' : (_this) => _this.language,
331
334
  'org.w3c.dom.caches_$external_prop_getter' : (_this) => _this.caches,
335
+ 'org.w3c.dom.setTimeout_$external_fun' : (_this, p0, p1, p2, isDefault0, isDefault1) => _this.setTimeout(p0, isDefault0 ? undefined : p1, ...p2, ),
332
336
  'org.w3c.dom.fetch_$external_fun' : (_this, p0, p1, isDefault0) => _this.fetch(p0, isDefault0 ? undefined : p1, ),
333
337
  'org.w3c.dom.top_$external_prop_getter' : (_this) => _this.top,
334
338
  'org.w3c.dom.left_$external_prop_getter' : (_this) => _this.left,
335
339
  'org.w3c.dom.remove_$external_fun' : (_this, ) => _this.remove(),
336
340
  'org.w3c.dom.Companion_$external_object_getInstance' : () => ({}),
341
+ 'org.w3c.dom.data_$external_prop_getter' : (_this) => _this.data,
342
+ 'org.w3c.dom.MessageEvent_$external_class_instanceof' : (x) => x instanceof MessageEvent,
343
+ 'org.w3c.dom.MessageEvent_$external_class_get' : () => MessageEvent,
337
344
  'org.w3c.dom.value_$external_prop_getter' : (_this) => _this.value,
338
345
  'org.w3c.dom.value_$external_prop_setter' : (_this, v) => _this.value = v,
339
346
  'org.w3c.dom.add_$external_fun_1' : (_this, p0) => _this.add(p0),
@@ -348,6 +355,14 @@ const js_code = {
348
355
  'org.w3c.dom.HTMLOptionElement_$external_class_get' : () => HTMLOptionElement,
349
356
  'org.w3c.dom.HTMLButtonElement_$external_class_instanceof' : (x) => x instanceof HTMLButtonElement,
350
357
  'org.w3c.dom.HTMLButtonElement_$external_class_get' : () => HTMLButtonElement,
358
+ 'org.w3c.dom.WebSocket_$external_fun' : (p0, p1, isDefault0) => new WebSocket(p0, isDefault0 ? undefined : p1, ),
359
+ 'org.w3c.dom.readyState_$external_prop_getter' : (_this) => _this.readyState,
360
+ 'org.w3c.dom.onopen_$external_prop_setter' : (_this, v) => _this.onopen = v,
361
+ 'org.w3c.dom.onerror_$external_prop_setter' : (_this, v) => _this.onerror = v,
362
+ 'org.w3c.dom.onclose_$external_prop_setter' : (_this, v) => _this.onclose = v,
363
+ 'org.w3c.dom.onmessage_$external_prop_setter' : (_this, v) => _this.onmessage = v,
364
+ 'org.w3c.dom.close_$external_fun' : (_this, p0, p1, isDefault0, isDefault1) => _this.close(isDefault0 ? undefined : p0, isDefault1 ? undefined : p1, ),
365
+ 'org.w3c.dom.send_$external_fun' : (_this, p0) => _this.send(p0),
351
366
  'org.w3c.dom.pointerevents.pointerId_$external_prop_getter' : (_this) => _this.pointerId,
352
367
  'org.w3c.dom.pointerevents.pressure_$external_prop_getter' : (_this) => _this.pressure,
353
368
  'org.w3c.dom.pointerevents.PointerEvent_$external_class_instanceof' : (x) => x instanceof PointerEvent,
@@ -423,6 +438,7 @@ const js_code = {
423
438
  'androidx.compose.ui.events.withSignalAndPassive' : (signal, passive) => ({signal: signal, passive: passive}),
424
439
  'androidx.compose.ui.events.AbortController_$external_fun' : () => new AbortController(),
425
440
  'androidx.compose.ui.events.signal_$external_prop_getter' : (_this) => _this.signal,
441
+ 'androidx.compose.ui.events.abort_$external_fun' : (_this, ) => _this.abort(),
426
442
  'androidx.compose.ui.internal.focusExt' : (element, _preventScroll) => element.focus({ preventScroll: _preventScroll }),
427
443
  'androidx.compose.ui.node.WeakRef_$external_fun' : (p0) => new WeakRef(p0),
428
444
  'androidx.compose.ui.node.deref_$external_fun' : (_this, ) => _this.deref(),
@@ -587,12 +603,32 @@ const js_code = {
587
603
  observer.disconnect();
588
604
  };
589
605
  },
606
+ 'com.aardarch.aardink.web.openNewTab' : (url) => {
607
+ try {
608
+ window.open(url, '_blank', 'noopener');
609
+ } catch (e) {
610
+ console.warn('Aardink: could not open ' + url, e);
611
+ }
612
+ },
590
613
  'com.aardarch.aardink.web.dispatchResize' : () => window.dispatchEvent(new Event('resize')),
591
614
  'com.aardarch.aardink.web.callStop' : (stop) => stop(),
615
+ 'com.aardarch.aardink.web.releaseWebGlContexts' : (element) => {
616
+ const roots = [element];
617
+ while (roots.length > 0) {
618
+ const root = roots.pop();
619
+ for (const node of root.querySelectorAll('*')) {
620
+ if (node.shadowRoot) roots.push(node.shadowRoot);
621
+ if (node.tagName !== 'CANVAS') continue;
622
+ const gl = node.getContext('webgl2') || node.getContext('webgl');
623
+ const lose = gl && gl.getExtension('WEBGL_lose_context');
624
+ if (lose && !gl.isContextLost()) lose.loseContext();
625
+ }
626
+ }
627
+ },
592
628
  'com.aardarch.aardink.sampleweb.__callJsClosure_((String)->Unit)' : (f, p0) => f(p0),
593
629
  'com.aardarch.aardink.sampleweb.__callJsClosure_((Int,Int)->Unit)' : (f, p0, p1) => f(p0, p1),
630
+ 'com.aardarch.aardink.sampleweb.__callJsClosure_((String,String,String)->Js)' : (f, p0, p1, p2) => f(p0, p1, p2),
594
631
  'com.aardarch.aardink.sampleweb.__callJsClosure_((String,Int,Int)->Js)' : (f, p0, p1, p2) => f(p0, p1, p2),
595
- 'com.aardarch.aardink.sampleweb.__callJsClosure_((String)->Js)' : (f, p0) => f(p0),
596
632
  'com.aardarch.aardink.sampleweb.__callJsClosure_((String,Int,String,String)->Unit)' : (f, p0, p1, p2, p3) => f(p0, p1, p2, p3),
597
633
  'com.aardarch.aardink.sampleweb.__callJsClosure_((Boolean)->Unit)' : (f, p0) => f(p0),
598
634
  'com.aardarch.aardink.sampleweb.usedJsHeapBytes' : () => (performance.memory ? performance.memory.usedJSHeapSize : -1)
@@ -94,6 +94,7 @@ export const {
94
94
  aardinkSetScrollTop,
95
95
  aardinkGetScrollHeight,
96
96
  aardinkOnScrollChange,
97
+ aardinkOnOpenLink,
97
98
  aardinkLayout,
98
99
  aardinkSetDecorations,
99
100
  aardinkGetDecorationRanges,
@@ -101,6 +102,10 @@ export const {
101
102
  aardinkGetSymbolPathAt,
102
103
  aardinkRevalidate,
103
104
  aardinkRegisterLanguage,
105
+ aardinkConnectLanguageServer,
106
+ aardinkDisconnectLanguageServer,
107
+ aardinkRegisterInlineCompletionsProvider,
108
+ aardinkDisposeInlineCompletionsProvider,
104
109
  aardinkRegisterTheme,
105
110
  aardinkOnContentChange,
106
111
  aardinkOnSelectionChange,
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aardarch/aardink-web",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "The Aardink code editor for the browser: Compose Multiplatform on WebAssembly behind a Monaco-shaped API.",
5
5
  "keywords": [
6
6
  "code-editor",