@nibling/editor 0.0.0-stage → 0.0.2

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 (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +53 -2
  3. package/dist/commands/autoclose.d.ts +13 -0
  4. package/dist/commands/autoclose.js +78 -0
  5. package/dist/commands/commands.d.ts +104 -0
  6. package/dist/commands/commands.js +442 -0
  7. package/dist/commands/comments.d.ts +3 -0
  8. package/dist/commands/comments.js +9 -0
  9. package/dist/commands/fold.d.ts +18 -0
  10. package/dist/commands/fold.js +75 -0
  11. package/dist/commands/keymap.d.ts +40 -0
  12. package/dist/commands/keymap.js +118 -0
  13. package/dist/complete/autocomplete.d.ts +35 -0
  14. package/dist/complete/autocomplete.js +386 -0
  15. package/dist/complete/source.d.ts +72 -0
  16. package/dist/complete/source.js +52 -0
  17. package/dist/complete/words.d.ts +53 -0
  18. package/dist/complete/words.js +203 -0
  19. package/dist/element.d.ts +119 -0
  20. package/dist/element.js +1011 -0
  21. package/dist/expand/expansions.d.ts +68 -0
  22. package/dist/expand/expansions.js +143 -0
  23. package/dist/expand/projection.d.ts +73 -0
  24. package/dist/expand/projection.js +189 -0
  25. package/dist/expand/resolver.d.ts +42 -0
  26. package/dist/expand/resolver.js +585 -0
  27. package/dist/expand/slice-tokens.d.ts +25 -0
  28. package/dist/expand/slice-tokens.js +79 -0
  29. package/dist/extension.d.ts +58 -0
  30. package/dist/extension.js +1 -0
  31. package/dist/find/find.d.ts +12 -0
  32. package/dist/find/find.js +469 -0
  33. package/dist/find/search.d.ts +81 -0
  34. package/dist/find/search.js +308 -0
  35. package/dist/headless.d.ts +16 -0
  36. package/dist/headless.js +19 -0
  37. package/dist/index.d.ts +6 -0
  38. package/dist/index.js +6 -0
  39. package/dist/inline-expansion.d.ts +89 -0
  40. package/dist/inline-expansion.js +324 -0
  41. package/dist/input/edit-context.d.ts +23 -0
  42. package/dist/input/edit-context.js +102 -0
  43. package/dist/input/surface.d.ts +101 -0
  44. package/dist/input/surface.js +84 -0
  45. package/dist/input/textarea.d.ts +26 -0
  46. package/dist/input/textarea.js +125 -0
  47. package/dist/sheet.d.ts +6 -0
  48. package/dist/sheet.js +12 -0
  49. package/dist/state/core.d.ts +73 -0
  50. package/dist/state/core.js +86 -0
  51. package/dist/state/fold-ranges.d.ts +41 -0
  52. package/dist/state/fold-ranges.js +167 -0
  53. package/dist/state/folds.d.ts +45 -0
  54. package/dist/state/folds.js +240 -0
  55. package/dist/state/history.d.ts +25 -0
  56. package/dist/state/history.js +127 -0
  57. package/dist/state/indent.d.ts +33 -0
  58. package/dist/state/indent.js +121 -0
  59. package/dist/state/selection.d.ts +45 -0
  60. package/dist/state/selection.js +106 -0
  61. package/dist/state/whitespace.d.ts +16 -0
  62. package/dist/state/whitespace.js +54 -0
  63. package/dist/text/changeset.d.ts +56 -0
  64. package/dist/text/changeset.js +321 -0
  65. package/dist/text/text.d.ts +30 -0
  66. package/dist/text/text.js +321 -0
  67. package/dist/tokens/bridge.d.ts +107 -0
  68. package/dist/tokens/bridge.js +461 -0
  69. package/dist/tokens/engine.d.ts +39 -0
  70. package/dist/tokens/engine.js +360 -0
  71. package/dist/tokens/protocol.d.ts +113 -0
  72. package/dist/tokens/protocol.js +38 -0
  73. package/dist/tokens/textmate/ascii-regex.d.ts +5 -0
  74. package/dist/tokens/textmate/ascii-regex.js +156 -0
  75. package/dist/tokens/textmate/index.d.ts +7 -0
  76. package/dist/tokens/textmate/index.js +19 -0
  77. package/dist/tokens/textmate/linker.d.ts +67 -0
  78. package/dist/tokens/textmate/linker.js +238 -0
  79. package/dist/tokens/textmate/scopes.d.ts +14 -0
  80. package/dist/tokens/textmate/scopes.js +54 -0
  81. package/dist/tokens/textmate/theme.d.ts +54 -0
  82. package/dist/tokens/textmate/theme.js +138 -0
  83. package/dist/tokens/textmate/tokenizer.d.ts +29 -0
  84. package/dist/tokens/textmate/tokenizer.js +684 -0
  85. package/dist/tokens/textmate.d.ts +49 -0
  86. package/dist/tokens/textmate.js +4 -0
  87. package/dist/view/decorations.d.ts +183 -0
  88. package/dist/view/decorations.js +51 -0
  89. package/dist/view/guides.d.ts +58 -0
  90. package/dist/view/guides.js +174 -0
  91. package/dist/view/heightmap.d.ts +97 -0
  92. package/dist/view/heightmap.js +229 -0
  93. package/dist/view/line-dom.d.ts +54 -0
  94. package/dist/view/line-dom.js +168 -0
  95. package/dist/view/measure.d.ts +37 -0
  96. package/dist/view/measure.js +136 -0
  97. package/dist/view/overlays.d.ts +32 -0
  98. package/dist/view/overlays.js +135 -0
  99. package/dist/view/rail.d.ts +27 -0
  100. package/dist/view/rail.js +232 -0
  101. package/dist/view/remote.d.ts +24 -0
  102. package/dist/view/remote.js +143 -0
  103. package/dist/view/scope-focus.d.ts +27 -0
  104. package/dist/view/scope-focus.js +255 -0
  105. package/dist/view/view.d.ts +114 -0
  106. package/dist/view/view.js +1231 -0
  107. package/dist/vite.d.ts +12 -0
  108. package/dist/vite.js +66 -0
  109. package/dist/worker.d.ts +1 -0
  110. package/dist/worker.js +64 -0
  111. package/grammars/astro.mjs +2 -0
  112. package/grammars/chunks/r-90cb351dba.mjs +1 -0
  113. package/grammars/chunks/r-b92a500aab.mjs +1 -0
  114. package/grammars/chunks/r-ced5311992.mjs +1 -0
  115. package/grammars/chunks/r-ebae91d4ec.mjs +1 -0
  116. package/grammars/chunks/s-1821e66170.mjs +1 -0
  117. package/grammars/css.mjs +1 -0
  118. package/grammars/diff.mjs +1 -0
  119. package/grammars/docker.mjs +1 -0
  120. package/grammars/dotenv.mjs +1 -0
  121. package/grammars/graphql.mjs +1 -0
  122. package/grammars/html.mjs +2 -0
  123. package/grammars/ini.mjs +1 -0
  124. package/grammars/javascript.mjs +5 -0
  125. package/grammars/json.mjs +1 -0
  126. package/grammars/json5.mjs +1 -0
  127. package/grammars/jsonc.mjs +1 -0
  128. package/grammars/less.mjs +1 -0
  129. package/grammars/manifest.json +58 -0
  130. package/grammars/markdown.mjs +1 -0
  131. package/grammars/mdx.mjs +1 -0
  132. package/grammars/pug.mjs +1 -0
  133. package/grammars/scss.mjs +1 -0
  134. package/grammars/shellscript.mjs +1 -0
  135. package/grammars/sql.mjs +1 -0
  136. package/grammars/stylus.mjs +1 -0
  137. package/grammars/svelte.mjs +1 -0
  138. package/grammars/toml.mjs +1 -0
  139. package/grammars/tsx.mjs +5 -0
  140. package/grammars/typescript.mjs +2 -0
  141. package/grammars/vue.mjs +1 -0
  142. package/grammars/yaml.mjs +1 -0
  143. package/package.json +71 -3
  144. package/themes/dark-plus.json +1 -0
  145. package/themes/light-plus.json +1 -0
  146. package/themes/monokai.json +1 -0
@@ -0,0 +1,118 @@
1
+ import * as commands from "./commands.js";
2
+ /** Keys pressed during composition never reach the keymap: `isComposing` folds to a key name
3
+ * that no binding can ever register (it is not a valid `KeyboardEvent.key` value). */
4
+ export function normalizeKey(e, apple) {
5
+ if (e.isComposing)
6
+ return '';
7
+ const parts = [];
8
+ const mod = apple ? e.metaKey : e.ctrlKey;
9
+ const ctrl = apple ? e.ctrlKey : false;
10
+ if (mod)
11
+ parts.push('Mod');
12
+ if (ctrl)
13
+ parts.push('Ctrl');
14
+ if (e.altKey)
15
+ parts.push('Alt');
16
+ if (e.shiftKey)
17
+ parts.push('Shift');
18
+ parts.push(e.key);
19
+ return parts.join('-');
20
+ }
21
+ /**
22
+ * Layers of bindings. Higher priority layers are consulted first; within a layer, later
23
+ * registrations win. `candidates` yields in that order; the caller runs each until one returns a
24
+ * spec. Keys pressed during composition never reach the keymap.
25
+ */
26
+ export class Keymap {
27
+ #layers = new Map();
28
+ #seq = 0;
29
+ add(bindings, priority = 0, signal) {
30
+ const seq = this.#seq++;
31
+ const added = [];
32
+ for (const b of bindings) {
33
+ const entry = { priority, seq, run: b.run };
34
+ const list = this.#layers.get(b.key);
35
+ if (list)
36
+ list.push(entry);
37
+ else
38
+ this.#layers.set(b.key, [entry]);
39
+ added.push({ key: b.key, entry });
40
+ }
41
+ if (signal) {
42
+ const remove = () => {
43
+ for (const { key, entry } of added) {
44
+ const list = this.#layers.get(key);
45
+ if (!list)
46
+ continue;
47
+ const i = list.indexOf(entry);
48
+ if (i >= 0)
49
+ list.splice(i, 1);
50
+ }
51
+ };
52
+ if (signal.aborted)
53
+ remove();
54
+ else
55
+ signal.addEventListener('abort', remove, { once: true });
56
+ }
57
+ }
58
+ candidates(key) {
59
+ const list = this.#layers.get(key);
60
+ if (!list || list.length === 0)
61
+ return [];
62
+ return list
63
+ .slice()
64
+ .sort((a, b) => b.priority - a.priority || b.seq - a.seq)
65
+ .map((e) => e.run);
66
+ }
67
+ }
68
+ /** The first-slice bindings. Undo/redo are added by the element because they close over History. */
69
+ export const defaultKeymap = [
70
+ { key: 'ArrowLeft', run: commands.moveGrapheme(-1, false) },
71
+ { key: 'Shift-ArrowLeft', run: commands.moveGrapheme(-1, true) },
72
+ { key: 'ArrowRight', run: commands.moveGrapheme(1, false) },
73
+ { key: 'Shift-ArrowRight', run: commands.moveGrapheme(1, true) },
74
+ { key: 'ArrowUp', run: commands.moveVertical(-1, false) },
75
+ { key: 'Shift-ArrowUp', run: commands.moveVertical(-1, true) },
76
+ { key: 'ArrowDown', run: commands.moveVertical(1, false) },
77
+ { key: 'Shift-ArrowDown', run: commands.moveVertical(1, true) },
78
+ { key: 'PageUp', run: commands.moveVertical(-1, false, true) },
79
+ { key: 'Shift-PageUp', run: commands.moveVertical(-1, true, true) },
80
+ { key: 'PageDown', run: commands.moveVertical(1, false, true) },
81
+ { key: 'Shift-PageDown', run: commands.moveVertical(1, true, true) },
82
+ { key: 'Home', run: commands.moveLineBoundary('start', false) },
83
+ { key: 'Shift-Home', run: commands.moveLineBoundary('start', true) },
84
+ { key: 'End', run: commands.moveLineBoundary('end', false) },
85
+ { key: 'Shift-End', run: commands.moveLineBoundary('end', true) },
86
+ { key: 'Backspace', run: commands.deleteBackward },
87
+ { key: 'Delete', run: commands.deleteForward },
88
+ { key: 'Enter', run: commands.insertNewline },
89
+ { key: 'Mod-a', run: commands.selectAll },
90
+ { key: 'Escape', run: commands.collapseSelection },
91
+ { key: 'Mod-Shift-k', run: commands.deleteLine },
92
+ { key: 'Mod-Shift-K', run: commands.deleteLine },
93
+ { key: 'Mod-Alt-ArrowUp', run: commands.addCursorVertical(-1) },
94
+ { key: 'Mod-Alt-ArrowDown', run: commands.addCursorVertical(1) },
95
+ { key: 'Mod-d', run: commands.selectNextOccurrence },
96
+ { key: 'Mod-Shift-l', run: commands.selectAllOccurrences },
97
+ { key: 'Mod-Shift-L', run: commands.selectAllOccurrences },
98
+ ];
99
+ /**
100
+ * Word and line bindings differ by platform. Every one of them is bound, because an unbound key
101
+ * falls through to the platform, which acts on the primary cursor only and then collapses the
102
+ * rest of the selection.
103
+ */
104
+ export function platformKeymap(apple) {
105
+ const word = apple ? 'Alt' : 'Mod';
106
+ const bindings = [
107
+ { key: `${word}-ArrowLeft`, run: commands.moveWord(-1, false) },
108
+ { key: `${word}-Shift-ArrowLeft`, run: commands.moveWord(-1, true) },
109
+ { key: `${word}-ArrowRight`, run: commands.moveWord(1, false) },
110
+ { key: `${word}-Shift-ArrowRight`, run: commands.moveWord(1, true) },
111
+ { key: `${word}-Backspace`, run: commands.deleteWord(-1) },
112
+ { key: `${word}-Delete`, run: commands.deleteWord(1) },
113
+ ];
114
+ if (apple) {
115
+ bindings.push({ key: 'Mod-ArrowLeft', run: commands.moveLineBoundary('start', false) }, { key: 'Mod-Shift-ArrowLeft', run: commands.moveLineBoundary('start', true) }, { key: 'Mod-ArrowRight', run: commands.moveLineBoundary('end', false) }, { key: 'Mod-Shift-ArrowRight', run: commands.moveLineBoundary('end', true) }, { key: 'Mod-Backspace', run: commands.deleteToLineBoundary('start') }, { key: 'Mod-Delete', run: commands.deleteToLineBoundary('end') });
116
+ }
117
+ return bindings;
118
+ }
@@ -0,0 +1,35 @@
1
+ import type { Extension } from '../extension.ts';
2
+ import { type CompletionSource } from './source.ts';
3
+ /**
4
+ * Popup knobs (docs/design/theming.md): nibling's tokens first, then colors mixed from the
5
+ * editor's own background and foreground, so it reads as part of the editor under any theme.
6
+ */
7
+ export declare const completeCss = "\n:host{\n --nib-editor-completion-bg:var(--nib-color-surface,color-mix(in srgb,var(--nib-fg,#d4d4d4) 6%,var(--nib-bg,#1e1e1e)));\n --nib-editor-completion-fg:var(--nib-color-text,var(--nib-fg,#d4d4d4));\n --nib-editor-completion-border:var(--nib-color-border,color-mix(in srgb,var(--nib-fg,#d4d4d4) 18%,var(--nib-bg,#1e1e1e)));\n --nib-editor-completion-selected:var(--nib-color-selected,var(--nib-selection,#264f78));\n --nib-editor-completion-match:var(--nib-color-accent,currentColor);\n --nib-editor-completion-detail:var(--nib-color-text-muted,color-mix(in srgb,var(--nib-fg,#d4d4d4) 55%,var(--nib-bg,#1e1e1e)));\n}\n.nib-complete{position:fixed;inset:auto;margin:0;padding:2px 0;box-sizing:border-box;z-index:10;\n min-width:16ch;max-width:min(60ch,calc(100vw - 16px));max-height:calc(10 * var(--nib-lh,18px) + 6px);overflow:auto;\n background:var(--nib-editor-completion-bg);color:var(--nib-editor-completion-fg);\n border:1px solid var(--nib-editor-completion-border);border-radius:4px;box-shadow:0 4px 16px rgb(0 0 0 / 0.25);\n font:var(--nib-font,13px/18px ui-monospace,Menlo,Consolas,monospace);overscroll-behavior:contain}\n.nib-complete:not(:popover-open):not(.nib-open){display:none}\n.nib-complete-option{display:flex;gap:2ch;padding:0 6px;white-space:pre;cursor:default}\n.nib-complete-option[aria-selected=\"true\"]{background:var(--nib-editor-completion-selected)}\n.nib-complete-option b{font-weight:inherit;color:var(--nib-editor-completion-match)}\n.nib-complete-label{flex:1 0 auto}\n.nib-complete-detail{color:var(--nib-editor-completion-detail);overflow:hidden;text-overflow:ellipsis}\n";
8
+ export interface AutocompleteOptions {
9
+ /** The registered sources, read at each request. */
10
+ readonly sources: () => readonly CompletionSource[];
11
+ /** Characters of word before the caret that open the popup while typing. */
12
+ readonly minPrefix?: number;
13
+ /** Typing pause, in ms, before sources are asked. */
14
+ readonly delay?: number;
15
+ }
16
+ /**
17
+ * The completion popup: anchored at the start of the word before the caret, fed by every
18
+ * registered CompletionSource. Typing a word opens it after `minPrefix` characters and a short
19
+ * pause. While it shows, a high-priority keymap takes ArrowUp/Down, PageUp/Down, Enter and Tab
20
+ * (accept) and Escape (close); closed, those keys are untouched. It closes on blur, when the caret
21
+ * leaves the word, on any edit that isn't typing or deleting in it, and when nothing matches.
22
+ * Composition closes it and never updates it, and keys pressed while composing never reach the
23
+ * keymap. Ctrl-Space asks explicitly.
24
+ *
25
+ * Accessibility: the popup is a listbox of options. In textarea mode the textarea gets
26
+ * aria-activedescendant and aria-controls pointing into it. In EditContext mode the focused
27
+ * element is the host, which cannot reference ids inside its own shadow root, so the listbox is
28
+ * shown but not wired.
29
+ */
30
+ export declare function autocomplete(options: AutocompleteOptions): Extension;
31
+ /**
32
+ * Document words as a fallback CompletionSource. The index starts building, in slices between
33
+ * tasks, the first time completion is asked for, and follows every edit after that.
34
+ */
35
+ export declare function wordCompletions(): Extension;
@@ -0,0 +1,386 @@
1
+ import { isCursor } from "../state/selection.js";
2
+ import { acceptOption, rankOptions } from "./source.js";
3
+ import { WordIndex, wordBefore, wordSource } from "./words.js";
4
+ /**
5
+ * Popup knobs (docs/design/theming.md): nibling's tokens first, then colors mixed from the
6
+ * editor's own background and foreground, so it reads as part of the editor under any theme.
7
+ */
8
+ export const completeCss = `
9
+ :host{
10
+ --nib-editor-completion-bg:var(--nib-color-surface,color-mix(in srgb,var(--nib-fg,#d4d4d4) 6%,var(--nib-bg,#1e1e1e)));
11
+ --nib-editor-completion-fg:var(--nib-color-text,var(--nib-fg,#d4d4d4));
12
+ --nib-editor-completion-border:var(--nib-color-border,color-mix(in srgb,var(--nib-fg,#d4d4d4) 18%,var(--nib-bg,#1e1e1e)));
13
+ --nib-editor-completion-selected:var(--nib-color-selected,var(--nib-selection,#264f78));
14
+ --nib-editor-completion-match:var(--nib-color-accent,currentColor);
15
+ --nib-editor-completion-detail:var(--nib-color-text-muted,color-mix(in srgb,var(--nib-fg,#d4d4d4) 55%,var(--nib-bg,#1e1e1e)));
16
+ }
17
+ .nib-complete{position:fixed;inset:auto;margin:0;padding:2px 0;box-sizing:border-box;z-index:10;
18
+ min-width:16ch;max-width:min(60ch,calc(100vw - 16px));max-height:calc(10 * var(--nib-lh,18px) + 6px);overflow:auto;
19
+ background:var(--nib-editor-completion-bg);color:var(--nib-editor-completion-fg);
20
+ border:1px solid var(--nib-editor-completion-border);border-radius:4px;box-shadow:0 4px 16px rgb(0 0 0 / 0.25);
21
+ font:var(--nib-font,13px/18px ui-monospace,Menlo,Consolas,monospace);overscroll-behavior:contain}
22
+ .nib-complete:not(:popover-open):not(.nib-open){display:none}
23
+ .nib-complete-option{display:flex;gap:2ch;padding:0 6px;white-space:pre;cursor:default}
24
+ .nib-complete-option[aria-selected="true"]{background:var(--nib-editor-completion-selected)}
25
+ .nib-complete-option b{font-weight:inherit;color:var(--nib-editor-completion-match)}
26
+ .nib-complete-label{flex:1 0 auto}
27
+ .nib-complete-detail{color:var(--nib-editor-completion-detail);overflow:hidden;text-overflow:ellipsis}
28
+ `;
29
+ const apple = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform);
30
+ /** Rows PageUp/PageDown move. */
31
+ const PAGE = 8;
32
+ let popups = 0;
33
+ /**
34
+ * The completion popup: anchored at the start of the word before the caret, fed by every
35
+ * registered CompletionSource. Typing a word opens it after `minPrefix` characters and a short
36
+ * pause. While it shows, a high-priority keymap takes ArrowUp/Down, PageUp/Down, Enter and Tab
37
+ * (accept) and Escape (close); closed, those keys are untouched. It closes on blur, when the caret
38
+ * leaves the word, on any edit that isn't typing or deleting in it, and when nothing matches.
39
+ * Composition closes it and never updates it, and keys pressed while composing never reach the
40
+ * keymap. Ctrl-Space asks explicitly.
41
+ *
42
+ * Accessibility: the popup is a listbox of options. In textarea mode the textarea gets
43
+ * aria-activedescendant and aria-controls pointing into it. In EditContext mode the focused
44
+ * element is the host, which cannot reference ids inside its own shadow root, so the listbox is
45
+ * shown but not wired.
46
+ */
47
+ export function autocomplete(options) {
48
+ const minPrefix = options.minPrefix ?? 2;
49
+ const delay = options.delay ?? 50;
50
+ return (ctx) => {
51
+ const { core, root, host, signal } = ctx;
52
+ const doc = root.ownerDocument;
53
+ const win = doc.defaultView ?? window;
54
+ // Constructed in the shadow root's own window: a sheet can only be adopted by the document that
55
+ // made it, and this extension is installed again on every connection (a move across windows).
56
+ const sheet = new win.CSSStyleSheet();
57
+ sheet.replaceSync(completeCss);
58
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
59
+ const id = `nib-complete-${++popups}`;
60
+ const popup = doc.createElement('div');
61
+ popup.className = 'nib-complete';
62
+ popup.id = id;
63
+ popup.part.add('completion');
64
+ popup.setAttribute('role', 'listbox');
65
+ popup.setAttribute('aria-label', 'Suggestions');
66
+ const usePopover = 'popover' in popup;
67
+ if (usePopover)
68
+ popup.popover = 'manual';
69
+ root.appendChild(popup);
70
+ const target = ctx.focusTarget;
71
+ const wired = target !== host;
72
+ if (wired)
73
+ target.setAttribute('aria-autocomplete', 'list');
74
+ let active = null;
75
+ let request = null;
76
+ let keys = null;
77
+ let frame = 0;
78
+ const cancel = () => {
79
+ if (!request)
80
+ return;
81
+ request.ac.abort();
82
+ if (request.timer)
83
+ clearTimeout(request.timer);
84
+ request = null;
85
+ };
86
+ const close = () => {
87
+ cancel();
88
+ if (!active)
89
+ return;
90
+ active = null;
91
+ keys?.abort();
92
+ keys = null;
93
+ cancelAnimationFrame(frame);
94
+ if (usePopover && popup.matches(':popover-open'))
95
+ popup.hidePopover();
96
+ popup.classList.remove('nib-open');
97
+ popup.replaceChildren();
98
+ if (wired) {
99
+ target.removeAttribute('aria-activedescendant');
100
+ target.removeAttribute('aria-controls');
101
+ }
102
+ };
103
+ /** Where the caret's word starts, or the caret when no word precedes it. */
104
+ const anchorNow = () => {
105
+ const sel = core.state.selection;
106
+ if (!isCursor(sel.primary))
107
+ return null;
108
+ const pos = sel.primary.head;
109
+ const word = wordBefore(core.state.text, pos);
110
+ return { anchor: word?.from ?? pos, word };
111
+ };
112
+ const ask = (explicit) => {
113
+ cancel();
114
+ const req = { ac: new AbortController(), timer: null, since: null, explicit };
115
+ request = req;
116
+ const run = () => {
117
+ req.timer = null;
118
+ // Edits during the pause are already in the state asked about.
119
+ req.since = null;
120
+ const at = anchorNow();
121
+ if (!at || (!explicit && (at.word?.text.length ?? 0) < minPrefix))
122
+ return void (request === req && close());
123
+ const state = core.state;
124
+ const cc = { state, pos: state.selection.primary.head, word: at.word, explicit, signal: req.ac.signal };
125
+ const answers = options.sources().map((s) => Promise.resolve()
126
+ .then(() => s.complete(cc))
127
+ .then((r) => ({ fallback: !!s.fallback, r }), () => ({ fallback: !!s.fallback, r: null })));
128
+ void Promise.all(answers).then((all) => {
129
+ if (req.ac.signal.aborted || request !== req)
130
+ return;
131
+ request = null;
132
+ const map = (r) => (req.since ? { ...r, from: req.since.mapPos(r.from, -1) } : r);
133
+ const primary = all.filter((a) => !a.fallback && a.r && a.r.items.length > 0);
134
+ const chosen = (primary.length > 0 ? primary : all.filter((a) => a.fallback && a.r)).map((a) => map(a.r));
135
+ const now = anchorNow();
136
+ const anchor = req.since ? req.since.mapPos(at.anchor, -1) : at.anchor;
137
+ if (!now || now.anchor !== anchor)
138
+ return close();
139
+ const prev = active?.options[active.selected]?.item.label;
140
+ active = { anchor, explicit: explicit || !!active?.explicit, asked: now.word?.text ?? '', results: chosen, options: [], selected: 0 };
141
+ refilter(prev);
142
+ });
143
+ };
144
+ if (explicit)
145
+ run();
146
+ else
147
+ req.timer = setTimeout(run, delay);
148
+ };
149
+ /** Filters the active results against the current word; closes on no matches. */
150
+ const refilter = (keep) => {
151
+ const a = active;
152
+ const pos = core.state.selection.primary.head;
153
+ a.options = rankOptions(core.state, pos, a.results);
154
+ if (a.options.length === 0) {
155
+ // Shorter words or incomplete results may still match once asked again.
156
+ if (request)
157
+ return render();
158
+ return close();
159
+ }
160
+ const i = keep === undefined ? -1 : a.options.findIndex((o) => o.item.label === keep);
161
+ a.selected = Math.max(0, i);
162
+ render();
163
+ };
164
+ const render = () => {
165
+ const a = active;
166
+ if (!a)
167
+ return;
168
+ if (a.options.length === 0) {
169
+ popup.classList.remove('nib-open');
170
+ if (usePopover && popup.matches(':popover-open'))
171
+ popup.hidePopover();
172
+ return;
173
+ }
174
+ const rows = a.options.map((o, i) => {
175
+ const row = doc.createElement('div');
176
+ row.className = 'nib-complete-option';
177
+ row.part.add('completion-option');
178
+ row.id = `${id}-${i}`;
179
+ row.setAttribute('role', 'option');
180
+ row.setAttribute('aria-selected', String(i === a.selected));
181
+ const label = doc.createElement('span');
182
+ label.className = 'nib-complete-label';
183
+ const m = Math.min(o.matched, o.item.label.length);
184
+ if (m > 0) {
185
+ const b = doc.createElement('b');
186
+ b.textContent = o.item.label.slice(0, m);
187
+ label.append(b);
188
+ }
189
+ label.append(o.item.label.slice(m));
190
+ row.append(label);
191
+ if (o.item.detail) {
192
+ const d = doc.createElement('span');
193
+ d.className = 'nib-complete-detail';
194
+ d.textContent = o.item.detail;
195
+ row.append(d);
196
+ }
197
+ return row;
198
+ });
199
+ popup.replaceChildren(...rows);
200
+ if (!keys) {
201
+ keys = new AbortController();
202
+ ctx.keymap(bindings, 100, keys.signal);
203
+ }
204
+ popup.classList.add('nib-open');
205
+ if (usePopover && !popup.matches(':popover-open'))
206
+ popup.showPopover();
207
+ select(a.selected);
208
+ cancelAnimationFrame(frame);
209
+ // After the view's frame for this update, so the caret's line is laid out.
210
+ frame = requestAnimationFrame(place);
211
+ };
212
+ const select = (i) => {
213
+ const a = active;
214
+ popup.children[a.selected]?.setAttribute('aria-selected', 'false');
215
+ a.selected = i;
216
+ const row = popup.children[i];
217
+ if (!row)
218
+ return;
219
+ row.setAttribute('aria-selected', 'true');
220
+ if (wired) {
221
+ target.setAttribute('aria-controls', id);
222
+ target.setAttribute('aria-activedescendant', row.id);
223
+ }
224
+ if (row.offsetTop < popup.scrollTop)
225
+ popup.scrollTop = row.offsetTop;
226
+ else if (row.offsetTop + row.offsetHeight > popup.scrollTop + popup.clientHeight)
227
+ popup.scrollTop = row.offsetTop + row.offsetHeight - popup.clientHeight;
228
+ };
229
+ /** Below the anchor's line, or above it when there is no room below; left edge on the word. */
230
+ const place = () => {
231
+ if (!active)
232
+ return;
233
+ const r = ctx.coordsAtPos(active.anchor);
234
+ const bounds = host.getBoundingClientRect();
235
+ // Scrolled out of the editor: nothing to point at, and keys shouldn't go to a hidden list.
236
+ if (!r || r.bottom <= bounds.top || r.top >= bounds.bottom)
237
+ return close();
238
+ const box = popup.getBoundingClientRect();
239
+ const vw = win.innerWidth;
240
+ const vh = win.innerHeight;
241
+ const pad = parseFloat(getComputedStyle(popup.firstElementChild ?? popup).paddingLeft) || 0;
242
+ const left = Math.max(4, Math.min(r.left - pad - 1, vw - box.width - 4));
243
+ const below = r.bottom + box.height <= vh || r.top - box.height < 0;
244
+ popup.style.left = `${left}px`;
245
+ popup.style.top = `${below ? r.bottom : r.top - box.height}px`;
246
+ };
247
+ const move = (by, wrap) => () => {
248
+ const a = active;
249
+ if (!a || a.options.length === 0)
250
+ return null;
251
+ const n = a.options.length;
252
+ let i = a.selected + by;
253
+ i = wrap ? ((i % n) + n) % n : Math.max(0, Math.min(n - 1, i));
254
+ select(i);
255
+ return { origin: 'select' };
256
+ };
257
+ const accept = (i) => {
258
+ const a = active;
259
+ const option = a?.options[i ?? a.selected];
260
+ if (!option)
261
+ return null;
262
+ const spec = acceptOption(core.state, option);
263
+ close();
264
+ return spec;
265
+ };
266
+ const bindings = [
267
+ { key: 'ArrowDown', run: move(1, true) },
268
+ { key: 'ArrowUp', run: move(-1, true) },
269
+ { key: 'PageDown', run: move(PAGE, false) },
270
+ { key: 'PageUp', run: move(-PAGE, false) },
271
+ { key: 'Enter', run: () => accept() },
272
+ { key: 'Tab', run: () => accept() },
273
+ { key: 'Escape', run: () => (active ? (close(), { origin: 'select' }) : null) },
274
+ ];
275
+ // Ctrl-Space everywhere: on Apple platforms Cmd-Space is the system's.
276
+ ctx.keymap([{ key: apple ? 'Ctrl- ' : 'Mod- ', run: () => (ask(true), { origin: 'select' }) }]);
277
+ ctx.onUpdate((u) => {
278
+ if (request && u.docChanged)
279
+ request.since = request.since ? request.since.compose(u.changes) : u.changes;
280
+ if (u.origin === 'input.compose')
281
+ return close();
282
+ if (!active && !request) {
283
+ if (u.origin === 'input.type' && u.docChanged) {
284
+ const at = anchorNow();
285
+ if (at?.word && at.word.text.length >= minPrefix)
286
+ ask(false);
287
+ }
288
+ return;
289
+ }
290
+ if (u.origin !== 'input.type' && u.origin !== 'input.delete' && u.origin !== 'select' && u.origin !== 'remote')
291
+ return close();
292
+ if (!u.docChanged && u.before.selection.eq(u.after.selection))
293
+ return;
294
+ const at = anchorNow();
295
+ const explicit = active?.explicit || request?.explicit || false;
296
+ if (active && u.docChanged) {
297
+ active.anchor = u.changes.mapPos(active.anchor, -1);
298
+ active.results = active.results.map((r) => ({ ...r, from: u.changes.mapPos(r.from, -1) }));
299
+ }
300
+ const anchor = active?.anchor ?? at?.anchor;
301
+ if (!at || at.anchor !== anchor || (!explicit && (at.word?.text.length ?? 0) < minPrefix)) {
302
+ close();
303
+ // Typing straight into a new word (after a deletion joined two, say) starts over.
304
+ if (at?.word && u.origin === 'input.type' && at.word.text.length >= minPrefix)
305
+ ask(false);
306
+ return;
307
+ }
308
+ if (!active) {
309
+ // Still waiting on the pause: restart it, so a burst of typing asks once.
310
+ if (u.origin === 'input.type' || u.origin === 'input.delete')
311
+ ask(request.explicit);
312
+ return;
313
+ }
314
+ const word = at.word?.text ?? '';
315
+ if (u.origin !== 'remote' && (active.results.some((r) => r.incomplete) || !word.startsWith(active.asked)))
316
+ ask(active.explicit);
317
+ refilter(active.options[active.selected]?.item.label);
318
+ });
319
+ host.addEventListener('focusout', close, { signal });
320
+ // Clicks on the popup keep focus in the editor and never reach the element's own mousedown,
321
+ // which would move the caret under the pointer.
322
+ popup.addEventListener('mousedown', (e) => {
323
+ e.preventDefault();
324
+ e.stopPropagation();
325
+ const row = e.target.closest?.('.nib-complete-option');
326
+ if (!row || e.button !== 0)
327
+ return;
328
+ const spec = accept([...popup.children].indexOf(row));
329
+ if (spec)
330
+ core.apply(spec);
331
+ }, { signal });
332
+ const reposition = () => {
333
+ if (!active)
334
+ return;
335
+ cancelAnimationFrame(frame);
336
+ frame = requestAnimationFrame(place);
337
+ };
338
+ root.addEventListener('scroll', reposition, { capture: true, passive: true, signal });
339
+ win.addEventListener('scroll', reposition, { capture: true, passive: true, signal });
340
+ win.addEventListener('resize', reposition, { passive: true, signal });
341
+ signal.addEventListener('abort', () => {
342
+ close();
343
+ popup.remove();
344
+ if (wired)
345
+ target.removeAttribute('aria-autocomplete');
346
+ root.adoptedStyleSheets = root.adoptedStyleSheets.filter((s) => s !== sheet);
347
+ }, { once: true });
348
+ };
349
+ }
350
+ /** Index slice per task while the word index builds: a few ms, off the typing path. */
351
+ const SLICE_LINES = 2000;
352
+ /**
353
+ * Document words as a fallback CompletionSource. The index starts building, in slices between
354
+ * tasks, the first time completion is asked for, and follows every edit after that.
355
+ */
356
+ export function wordCompletions() {
357
+ return (ctx) => {
358
+ const index = new WordIndex();
359
+ let started = false;
360
+ let timer = null;
361
+ const pump = () => {
362
+ timer = null;
363
+ if (!index.scan(ctx.core.state.text, SLICE_LINES))
364
+ timer = setTimeout(pump, 0);
365
+ };
366
+ const resume = () => {
367
+ if (started && !timer && !index.complete)
368
+ timer = setTimeout(pump, 0);
369
+ };
370
+ ctx.onUpdate((u) => {
371
+ if (!u.docChanged)
372
+ return;
373
+ if (u.origin === 'host.set')
374
+ index.clear();
375
+ else
376
+ index.apply(u.changes, u.before.text, u.after.text);
377
+ resume();
378
+ });
379
+ ctx.completions(wordSource(() => {
380
+ started = true;
381
+ resume();
382
+ return index;
383
+ }));
384
+ ctx.signal.addEventListener('abort', () => timer && clearTimeout(timer), { once: true });
385
+ };
386
+ }
@@ -0,0 +1,72 @@
1
+ import type { Snapshot, TransactionSpec } from '../state/core.ts';
2
+ /**
3
+ * What a source is asked. Positions are document offsets in `state`, which is the snapshot the
4
+ * request was made for: by the time an async source answers, the document may have moved on, and
5
+ * the popup maps or drops the answer itself.
6
+ */
7
+ export interface CompletionContext {
8
+ readonly state: Snapshot;
9
+ /** The primary cursor. Completion runs only for a bare cursor. */
10
+ readonly pos: number;
11
+ /** The word before the caret, [from, pos), or null when the caret follows no word. */
12
+ readonly word: {
13
+ readonly from: number;
14
+ readonly text: string;
15
+ } | null;
16
+ /** The user asked (Ctrl-Space) rather than typed. A source may then answer with no word. */
17
+ readonly explicit: boolean;
18
+ /** Aborted when a newer request supersedes this one or the popup closes. */
19
+ readonly signal: AbortSignal;
20
+ }
21
+ /** One suggestion. The shape LSP's CompletionItem maps onto. */
22
+ export interface CompletionItem {
23
+ readonly label: string;
24
+ /** Replaces [from, pos) on accept. Defaults to `label`. */
25
+ readonly insert?: string;
26
+ /** Shown dimmed after the label (a type, a module). */
27
+ readonly detail?: string;
28
+ /** What the typed text is matched against. Defaults to `label` (LSP's filterText). */
29
+ readonly filter?: string;
30
+ }
31
+ export interface CompletionResult {
32
+ /** Where the replaced text starts. Items are filtered against [from, pos). */
33
+ readonly from: number;
34
+ /** In relevance order. The popup keeps that order within each match class. */
35
+ readonly items: readonly CompletionItem[];
36
+ /**
37
+ * More typing in the same word can change the answer (LSP's isIncomplete, or a capped list):
38
+ * ask again on every keystroke. Otherwise the popup filters these items as the word grows.
39
+ */
40
+ readonly incomplete?: boolean;
41
+ }
42
+ /**
43
+ * Anything that suggests completions: document words, an LSP client. Registered with
44
+ * `EditorContext.completions`, and asked after typing settles. May answer asynchronously.
45
+ */
46
+ export interface CompletionSource {
47
+ complete(ctx: CompletionContext): CompletionResult | null | Promise<CompletionResult | null>;
48
+ /** Asked only for its answer to be shown when no other source has items: document words step
49
+ * aside once a language server answers. */
50
+ readonly fallback?: boolean;
51
+ }
52
+ /** An item the popup shows, with the result it came from. */
53
+ export interface Option {
54
+ readonly item: CompletionItem;
55
+ readonly from: number;
56
+ /** Length of the label prefix the typed text matched, for highlighting. */
57
+ readonly matched: number;
58
+ }
59
+ /**
60
+ * Pure. Items from `results` whose filter text starts with what was typed since each result's
61
+ * `from`: an exact-case prefix ranks before a case-insensitive one, and otherwise the sources'
62
+ * order stands. An item that would insert exactly what is already there is dropped, so a finished
63
+ * word doesn't hold Enter hostage.
64
+ */
65
+ export declare function rankOptions(state: Snapshot, pos: number, results: readonly CompletionResult[], limit?: number): Option[];
66
+ /**
67
+ * Pure. Replaces [from, pos) at the primary cursor with the option's insert text. Under
68
+ * multicursor, every other bare cursor preceded by the same word text (the usual case after
69
+ * Mod-d or typing at several cursors) gets the same replacement; any other range is left alone,
70
+ * since the option was ranked against the primary's word only.
71
+ */
72
+ export declare function acceptOption(state: Snapshot, option: Option): TransactionSpec | null;
@@ -0,0 +1,52 @@
1
+ import { perRange } from "../commands/commands.js";
2
+ import { cursor, isCursor } from "../state/selection.js";
3
+ import { endsWithWordChar } from "./words.js";
4
+ /**
5
+ * Pure. Items from `results` whose filter text starts with what was typed since each result's
6
+ * `from`: an exact-case prefix ranks before a case-insensitive one, and otherwise the sources'
7
+ * order stands. An item that would insert exactly what is already there is dropped, so a finished
8
+ * word doesn't hold Enter hostage.
9
+ */
10
+ export function rankOptions(state, pos, results, limit = 200) {
11
+ const exact = [];
12
+ const loose = [];
13
+ for (const r of results) {
14
+ if (r.from > pos)
15
+ continue;
16
+ const typed = state.text.slice(r.from, pos);
17
+ const lower = typed.toLowerCase();
18
+ for (const item of r.items) {
19
+ const f = item.filter ?? item.label;
20
+ if ((item.insert ?? item.label) === typed)
21
+ continue;
22
+ if (f.startsWith(typed))
23
+ exact.push({ item, from: r.from, matched: typed.length });
24
+ else if (f.slice(0, typed.length).toLowerCase() === lower)
25
+ loose.push({ item, from: r.from, matched: typed.length });
26
+ }
27
+ }
28
+ return exact.concat(loose).slice(0, limit);
29
+ }
30
+ /**
31
+ * Pure. Replaces [from, pos) at the primary cursor with the option's insert text. Under
32
+ * multicursor, every other bare cursor preceded by the same word text (the usual case after
33
+ * Mod-d or typing at several cursors) gets the same replacement; any other range is left alone,
34
+ * since the option was ranked against the primary's word only.
35
+ */
36
+ export function acceptOption(state, option) {
37
+ const { text, selection } = state;
38
+ const p = selection.primary;
39
+ if (!isCursor(p) || option.from > p.head)
40
+ return null;
41
+ const len = p.head - option.from;
42
+ const typed = text.slice(option.from, p.head);
43
+ const insert = option.item.insert ?? option.item.label;
44
+ return perRange(state, 'command', (r) => {
45
+ const from = r.head - len;
46
+ const same = r === p ||
47
+ (isCursor(r) && from >= 0 && text.slice(from, r.head) === typed && !(from > 0 && endsWithWordChar(text.slice(Math.max(0, from - 2), from))));
48
+ if (!same)
49
+ return { range: r };
50
+ return { change: { from, to: r.head, insert }, range: cursor(from + insert.length) };
51
+ });
52
+ }