@nibling/editor 0.0.0-stage → 0.0.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 (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 +64 -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,58 @@
1
+ import type { EditorCore, UpdateListener } from './state/core.ts';
2
+ import type { KeyBinding } from './commands/keymap.ts';
3
+ import type { Command } from './commands/commands.ts';
4
+ import type { LineClassSource, OverlaySource, RemoteCursorSource } from './view/decorations.ts';
5
+ import type { CompletionSource } from './complete/source.ts';
6
+ /**
7
+ * What an extension gets. Everything it registers is removed when `signal` aborts, which happens
8
+ * when the host calls the disposer `use()` returned or the element disconnects. There is no
9
+ * per-registration disposer to forget.
10
+ *
11
+ * Contributions are registrations, not configuration: no facets, no extension-owned fields in
12
+ * the Snapshot. An extension keeps its own state in its closure and derives it from updates, so
13
+ * the core's per-keystroke cost does not grow with the number of extensions that are loaded but
14
+ * idle.
15
+ */
16
+ export interface EditorContext {
17
+ readonly core: EditorCore;
18
+ readonly signal: AbortSignal;
19
+ /** The element, for events and anchor-positioned popups (LSP UI). */
20
+ readonly host: HTMLElement;
21
+ /** Its shadow root, to adopt an extension's stylesheet. */
22
+ readonly root: ShadowRoot;
23
+ /** The element that holds focus: the host for EditContext, the textarea inside `root` otherwise.
24
+ * Where popups wire aria-activedescendant. */
25
+ readonly focusTarget: HTMLElement;
26
+ /** `signal` removes these bindings sooner than the extension's own (a popup's keys, bound only
27
+ * while it shows). */
28
+ keymap(bindings: readonly KeyBinding[], priority?: number, signal?: AbortSignal): void;
29
+ overlays(source: OverlaySource): void;
30
+ /** Collaborators' carets, name labels, and selections. */
31
+ remoteCursors(source: RemoteCursorSource): void;
32
+ lineClasses(source: LineClassSource): void;
33
+ /** Suggestions for the completion popup (an LSP client's, say). Document words are a fallback
34
+ * source, shown only when no other source has items. */
35
+ completions(source: CompletionSource): void;
36
+ onUpdate(listener: UpdateListener): void;
37
+ /**
38
+ * Take over undo and redo for the extension's lifetime, as a collaboration binding does with
39
+ * Loro's UndoManager. Throws if another extension already owns them.
40
+ */
41
+ undo(owner: UndoProvider): void;
42
+ /** Geometry for popups. null when the position is not mounted. */
43
+ coordsAtPos(pos: number): DOMRect | null;
44
+ }
45
+ /**
46
+ * Undo and redo as commands. A command that already changed the document itself (by writing to
47
+ * the CRDT, whose event applies the change) returns a selection-only spec, or `{ origin: 'select' }`
48
+ * to just claim the key. null declines: nothing to undo.
49
+ */
50
+ export interface UndoProvider {
51
+ readonly undo: Command;
52
+ readonly redo: Command;
53
+ }
54
+ /**
55
+ * A plain function. May be async, so `use(lsp({ transport }))` can await its lazy UI chunks.
56
+ * A rejected promise aborts the extension's signal and rethrows from `use`'s promise.
57
+ */
58
+ export type Extension = (ctx: EditorContext) => void | Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ import type { Extension } from '../extension.ts';
2
+ /**
3
+ * Find and replace, as an extension the element installs by default. The search itself is
4
+ * headless (search.ts); this owns the bar in the shadow root, the `match`/`match-current`
5
+ * overlays, the keys, and the count.
6
+ *
7
+ * Frame budget (VISION Goal 1): painting queries only the mounted range, which is what the view
8
+ * asks an OverlaySource for. The total comes from a SearchIndex counted in idle slices of a few
9
+ * milliseconds and kept through edits block by block. Typing a query jumps to a match only if one
10
+ * is near; otherwise the jump waits for the count, which lets navigation skip empty blocks.
11
+ */
12
+ export declare function findReplace(): Extension;
@@ -0,0 +1,469 @@
1
+ import { wordAt } from "../commands/commands.js";
2
+ import { normalizeKey } from "../commands/keymap.js";
3
+ import { Selection, isCursor, rangeFrom, rangeTo } from "../state/selection.js";
4
+ import { ChangeSet } from "../text/changeset.js";
5
+ import { OVERLAY_BUDGET } from "../view/decorations.js";
6
+ import { SearchIndex, Searcher, searcher } from "./search.js";
7
+ const apple = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform);
8
+ /** Blocks typing may scan for the match to jump to before it waits for the count. */
9
+ const TYPE_AHEAD_BLOCKS = 8;
10
+ /** One counting slice, in ms: well inside a frame, so counting a 100k-line file never drops one. */
11
+ const SLICE_MS = 4;
12
+ /**
13
+ * The bar's look. Knobs default to nibling's semantics, then to mixes of the theme's colors, as
14
+ * docs/design/theming.md asks. The match colors themselves are overlay kinds (view.ts).
15
+ */
16
+ const css = `
17
+ :host{
18
+ --nib-editor-find-bg:var(--nib-color-surface,color-mix(in srgb,var(--nib-fg,#d4d4d4) 6%,var(--nib-bg,#1e1e1e)));
19
+ --nib-editor-find-fg:var(--nib-color-text,var(--nib-fg,#d4d4d4));
20
+ --nib-editor-find-muted:var(--nib-color-text-muted,color-mix(in srgb,var(--nib-fg,#d4d4d4) 60%,var(--nib-bg,#1e1e1e)));
21
+ --nib-editor-find-border:var(--nib-color-border,color-mix(in srgb,var(--nib-fg,#d4d4d4) 20%,var(--nib-bg,#1e1e1e)));
22
+ --nib-editor-find-input-bg:var(--nib-color-canvas,var(--nib-bg,#1e1e1e));
23
+ --nib-editor-find-active:var(--nib-color-selected,color-mix(in srgb,var(--nib-fg,#d4d4d4) 18%,transparent));
24
+ --nib-editor-find-hover:var(--nib-color-hover,color-mix(in srgb,var(--nib-fg,#d4d4d4) 10%,transparent));
25
+ --nib-editor-find-focus:var(--nib-color-focus-ring,#007fd4);
26
+ }
27
+ .nib-find{position:absolute;top:0;right:16px;z-index:5;display:flex;flex-direction:column;gap:4px;padding:4px 6px;
28
+ max-width:calc(100% - 32px);box-sizing:border-box;
29
+ background:var(--nib-editor-find-bg);color:var(--nib-editor-find-fg);
30
+ border:1px solid var(--nib-editor-find-border);border-top:none;border-radius:0 0 4px 4px;
31
+ box-shadow:0 2px 8px color-mix(in srgb,#000 30%,transparent);font:12px/16px system-ui,sans-serif}
32
+ .nib-find[hidden],.nib-find-row[hidden]{display:none}
33
+ .nib-find-row{display:flex;align-items:center;gap:2px;min-width:0}
34
+ .nib-find input{flex:1 1 12em;min-width:6em;box-sizing:border-box;height:24px;padding:0 6px;margin-right:4px;
35
+ font:inherit;color:inherit;background:var(--nib-editor-find-input-bg);
36
+ border:1px solid var(--nib-editor-find-border);border-radius:3px;outline:none}
37
+ .nib-find input:focus{border-color:var(--nib-editor-find-focus)}
38
+ .nib-find input[aria-invalid=true]{border-color:var(--nib-editor-error)}
39
+ .nib-find button{flex:none;min-width:24px;height:24px;padding:0 4px;font:inherit;color:inherit;background:none;
40
+ border:1px solid transparent;border-radius:3px;cursor:pointer}
41
+ .nib-find button:hover{background:var(--nib-editor-find-hover)}
42
+ .nib-find button:focus-visible{outline:1px solid var(--nib-editor-find-focus);outline-offset:-1px}
43
+ .nib-find button[aria-pressed=true]{background:var(--nib-editor-find-active);border-color:var(--nib-editor-find-focus)}
44
+ .nib-find button:disabled{opacity:.5;cursor:default;background:none}
45
+ .nib-find-word{text-decoration:underline;text-underline-offset:2px}
46
+ .nib-find-count{flex:none;min-width:7em;padding:0 4px;color:var(--nib-editor-find-muted);white-space:nowrap}
47
+ `;
48
+ /**
49
+ * Find and replace, as an extension the element installs by default. The search itself is
50
+ * headless (search.ts); this owns the bar in the shadow root, the `match`/`match-current`
51
+ * overlays, the keys, and the count.
52
+ *
53
+ * Frame budget (VISION Goal 1): painting queries only the mounted range, which is what the view
54
+ * asks an OverlaySource for. The total comes from a SearchIndex counted in idle slices of a few
55
+ * milliseconds and kept through edits block by block. Typing a query jumps to a match only if one
56
+ * is near; otherwise the jump waits for the count, which lets navigation skip empty blocks.
57
+ */
58
+ export function findReplace() {
59
+ return (ctx) => void new FindReplace(ctx);
60
+ }
61
+ class FindReplace {
62
+ #ctx;
63
+ #bar;
64
+ #find;
65
+ #replace;
66
+ #replaceRow;
67
+ #count;
68
+ #toggles;
69
+ #expand;
70
+ #actions;
71
+ #invalidators = new Set();
72
+ #open = false;
73
+ #searcher = null;
74
+ #index = null;
75
+ #counting = null;
76
+ #statusFrame = 0;
77
+ /** Typing found no match nearby: jump once the count lets navigation skip empty blocks. */
78
+ #pendingJump = null;
79
+ constructor(ctx) {
80
+ this.#ctx = ctx;
81
+ const { root, signal } = ctx;
82
+ const doc = root.ownerDocument;
83
+ const win = doc.defaultView;
84
+ // From the element's own window, so a host moved into a popup adopts a sheet of its document.
85
+ const sheet = new win.CSSStyleSheet();
86
+ sheet.replaceSync(css);
87
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
88
+ const el = (tag, props = {}, attrs = {}) => {
89
+ const e = Object.assign(doc.createElement(tag), props);
90
+ for (const [k, v] of Object.entries(attrs))
91
+ e.setAttribute(k, v);
92
+ return e;
93
+ };
94
+ const button = (label, text, title, run, attrs = {}) => {
95
+ const b = el('button', { type: 'button', textContent: text, title }, { 'aria-label': label, ...attrs });
96
+ b.addEventListener('click', run, { signal });
97
+ return b;
98
+ };
99
+ const mod = apple ? '⌘' : 'Ctrl+';
100
+ const alt = apple ? '⌥' : 'Alt+';
101
+ this.#bar = el('div', { className: 'nib-find', hidden: true }, { role: 'search', 'aria-label': 'Find and replace' });
102
+ this.#bar.part.add('find');
103
+ this.#find = el('input', { type: 'text', placeholder: 'Find', spellcheck: false, autocomplete: 'off' }, { 'aria-label': 'Find' });
104
+ this.#replace = el('input', { type: 'text', placeholder: 'Replace', spellcheck: false, autocomplete: 'off' }, { 'aria-label': 'Replace' });
105
+ this.#count = el('span', { className: 'nib-find-count' }, { role: 'status', 'aria-live': 'polite' });
106
+ const toggle = (key, label, text, shortcut) => {
107
+ const b = button(label, text, `${label} (${alt}${shortcut})`, () => this.#flip(key), { 'aria-pressed': 'false' });
108
+ if (key === 'wholeWord')
109
+ b.classList.add('nib-find-word');
110
+ return b;
111
+ };
112
+ this.#toggles = {
113
+ caseSensitive: toggle('caseSensitive', 'Match case', 'Aa', 'C'),
114
+ wholeWord: toggle('wholeWord', 'Match whole word', 'ab', 'W'),
115
+ regexp: toggle('regexp', 'Use regular expression', '.*', 'R'),
116
+ };
117
+ this.#expand = button('Toggle replace', '›', `Toggle replace (${mod}${alt}F)`, () => this.#showReplace(this.#replaceRow.hidden, true), { 'aria-expanded': 'false' });
118
+ const prev = button('Previous match', '↑', 'Previous match (Shift+Enter)', () => this.#go(-1));
119
+ const next = button('Next match', '↓', 'Next match (Enter)', () => this.#go(1));
120
+ const close = button('Close', '×', 'Close (Escape)', () => this.close(true));
121
+ const one = button('Replace', 'Replace', 'Replace (Enter)', () => this.#replaceOne());
122
+ const all = button('Replace all', 'All', `Replace all (${mod}${alt}Enter)`, () => this.#replaceAll());
123
+ this.#actions = [prev, next, one, all];
124
+ const findRow = el('div', { className: 'nib-find-row' });
125
+ findRow.append(this.#expand, this.#find, this.#toggles.caseSensitive, this.#toggles.wholeWord, this.#toggles.regexp, this.#count, prev, next, close);
126
+ this.#replaceRow = el('div', { className: 'nib-find-row', hidden: true });
127
+ // Lines the replace input up under the find input.
128
+ const spacer = el('span', {}, { 'aria-hidden': 'true' });
129
+ spacer.style.cssText = 'flex:none;width:24px';
130
+ this.#replaceRow.append(spacer, this.#replace, one, all);
131
+ this.#bar.append(findRow, this.#replaceRow);
132
+ this.#expand.setAttribute('aria-controls', (this.#replaceRow.id = `nib-find-replace-${++ids}`));
133
+ // The bar is inside the editor's shadow root; its keys, clicks, and clipboard are its own and
134
+ // must not reach the editor's surface, rail, or mousedown handlers.
135
+ for (const type of ['mousedown', 'keydown', 'keyup', 'copy', 'cut', 'paste'])
136
+ this.#bar.addEventListener(type, (e) => e.stopPropagation(), { signal });
137
+ this.#bar.addEventListener('keydown', (e) => this.#onKey(e), { signal });
138
+ this.#find.addEventListener('input', () => this.#onQuery(true), { signal });
139
+ root.appendChild(this.#bar);
140
+ ctx.overlays(this.#source);
141
+ ctx.keymap(this.#keymap, 1);
142
+ ctx.onUpdate((u) => {
143
+ const index = this.#index;
144
+ if (index && u.docChanged) {
145
+ index.map(u.changes, u.before.text, u.after.text);
146
+ this.#startCounting();
147
+ }
148
+ if (this.#open)
149
+ this.#status();
150
+ });
151
+ this.#update();
152
+ signal.addEventListener('abort', () => {
153
+ this.#stopCounting();
154
+ win.cancelAnimationFrame(this.#statusFrame);
155
+ this.#bar.remove();
156
+ root.adoptedStyleSheets = root.adoptedStyleSheets.filter((s) => s !== sheet);
157
+ }, { once: true });
158
+ }
159
+ get #state() {
160
+ return this.#ctx.core.state;
161
+ }
162
+ #query() {
163
+ const t = this.#toggles;
164
+ return {
165
+ search: this.#find.value,
166
+ caseSensitive: t.caseSensitive.getAttribute('aria-pressed') === 'true',
167
+ wholeWord: t.wholeWord.getAttribute('aria-pressed') === 'true',
168
+ regexp: t.regexp.getAttribute('aria-pressed') === 'true',
169
+ };
170
+ }
171
+ // Overlays: the mounted range only, as the view asks. The current match is the one the primary
172
+ // selection covers exactly, so it follows the selection through edits and undo for free.
173
+ #source = {
174
+ query: (state, from, to) => {
175
+ const s = this.#searcher;
176
+ if (!this.#open || !(s instanceof Searcher))
177
+ return [];
178
+ const p = state.selection.primary;
179
+ const a = rangeFrom(p);
180
+ const b = rangeTo(p);
181
+ return s.matches(state.text, from, to, OVERLAY_BUDGET).map((m) => ({ kind: m.from === a && m.to === b ? 'match-current' : 'match', from: m.from, to: m.to }));
182
+ },
183
+ subscribe: (invalidate) => {
184
+ this.#invalidators.add(invalidate);
185
+ return () => this.#invalidators.delete(invalidate);
186
+ },
187
+ };
188
+ #repaint() {
189
+ for (const f of this.#invalidators)
190
+ f();
191
+ }
192
+ // Keys while the editor has focus. Priority 1: Escape closes the bar before it collapses the
193
+ // selection. Each declines when it has nothing to do, so the defaults still run.
194
+ #keymap = (() => {
195
+ const open = (replace) => (ctx) => (this.open(replace, ctx.state), { origin: 'select' });
196
+ const go = (dir) => (ctx) => {
197
+ if (!(this.#searcher instanceof Searcher))
198
+ return this.open(false, ctx.state), { origin: 'select' };
199
+ return this.#navigate(ctx.state, dir) ?? { origin: 'select' };
200
+ };
201
+ const bindings = [
202
+ { key: 'Mod-f', run: open(false) },
203
+ // With Alt held, `key` is the Option character on Apple platforms.
204
+ { key: 'Mod-Alt-f', run: open(true) },
205
+ { key: 'Mod-Alt-ƒ', run: open(true) },
206
+ { key: 'F3', run: go(1) },
207
+ { key: 'Shift-F3', run: go(-1) },
208
+ { key: 'Mod-g', run: go(1) },
209
+ { key: 'Mod-Shift-g', run: go(-1) },
210
+ { key: 'Mod-Shift-G', run: go(-1) },
211
+ { key: 'Escape', run: () => (this.#open ? (this.close(false), { origin: 'select' }) : null) },
212
+ ];
213
+ return bindings;
214
+ })();
215
+ /** Open the bar, seeded from a one-line selection (or the word at the cursor when the input
216
+ * is empty), and focus it. */
217
+ open(replace, state = this.#state) {
218
+ const p = state.selection.primary;
219
+ let seed = null;
220
+ if (!isCursor(p)) {
221
+ const s = state.text.slice(rangeFrom(p), rangeTo(p));
222
+ if (!s.includes('\n'))
223
+ seed = s;
224
+ }
225
+ else if (this.#find.value === '') {
226
+ const w = wordAt(state.text, p.head);
227
+ if (w)
228
+ seed = state.text.slice(w.from, w.to);
229
+ }
230
+ if (seed !== null && this.#query().regexp)
231
+ seed = seed.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&');
232
+ const wasOpen = this.#open;
233
+ this.#open = true;
234
+ this.#bar.hidden = false;
235
+ if (replace)
236
+ this.#showReplace(true, false);
237
+ else if (!wasOpen)
238
+ this.#showReplace(false, false);
239
+ const seeded = seed !== null && seed !== this.#find.value;
240
+ if (seeded)
241
+ this.#find.value = seed;
242
+ const target = replace && this.#find.value !== '' ? this.#replace : this.#find;
243
+ target.focus();
244
+ target.select();
245
+ // Seeding from the selection keeps it: it is already the current match.
246
+ if (seeded || !wasOpen)
247
+ this.#onQuery(false);
248
+ }
249
+ /** Close the bar and stop painting. `refocus` hands focus back to the editor. */
250
+ close(refocus) {
251
+ if (!this.#open)
252
+ return;
253
+ const active = this.#ctx.root.activeElement;
254
+ const hadFocus = active instanceof HTMLElement && this.#bar.contains(active);
255
+ // With delegatesFocus, focusing the host while focus is already inside its shadow tree does
256
+ // nothing, and hiding the bar then drops focus to the body. Let go of it first.
257
+ if (hadFocus)
258
+ active.blur();
259
+ this.#open = false;
260
+ this.#bar.hidden = true;
261
+ this.#index = null;
262
+ this.#pendingJump = null;
263
+ this.#stopCounting();
264
+ this.#repaint();
265
+ if (refocus || hadFocus)
266
+ this.#ctx.host.focus({ preventScroll: true });
267
+ }
268
+ #showReplace(show, focus) {
269
+ this.#replaceRow.hidden = !show;
270
+ this.#expand.setAttribute('aria-expanded', String(show));
271
+ this.#expand.textContent = show ? '⌄' : '›';
272
+ if (show && focus)
273
+ this.#replace.focus();
274
+ if (!show && focus)
275
+ this.#find.focus();
276
+ }
277
+ #flip(key) {
278
+ const b = this.#toggles[key];
279
+ b.setAttribute('aria-pressed', String(b.getAttribute('aria-pressed') !== 'true'));
280
+ this.#onQuery(true);
281
+ }
282
+ /** The query changed: compile it, start counting, repaint, and (when typing) jump to the first
283
+ * match at or after the selection's start. */
284
+ #onQuery(jump) {
285
+ this.#searcher = searcher(this.#query());
286
+ const s = this.#searcher;
287
+ this.#index = s instanceof Searcher ? new SearchIndex(s, this.#state.text) : null;
288
+ this.#pendingJump = null;
289
+ this.#count.textContent = '';
290
+ this.#update();
291
+ this.#repaint();
292
+ this.#startCounting();
293
+ if (jump && s instanceof Searcher) {
294
+ const from = rangeFrom(this.#state.selection.primary);
295
+ const m = s.next(this.#state.text, from, undefined, TYPE_AHEAD_BLOCKS);
296
+ if (m)
297
+ this.#select(m);
298
+ else if (m === undefined)
299
+ this.#pendingJump = from;
300
+ }
301
+ this.#status();
302
+ }
303
+ #select(m) {
304
+ this.#ctx.core.apply({ selection: Selection.single(m.from, m.to), origin: 'select', scrollIntoView: true });
305
+ }
306
+ /** The next (1) or previous (-1) match from the selection, as a spec. null when there is none. */
307
+ #navigate(state, dir) {
308
+ const s = this.#searcher;
309
+ if (!(s instanceof Searcher))
310
+ return null;
311
+ const index = this.#index?.text === state.text ? this.#index : null;
312
+ const p = state.selection.primary;
313
+ const empty = index?.empty;
314
+ const m = dir > 0 ? s.next(state.text, isCursor(p) ? p.head : rangeTo(p), empty) : s.prev(state.text, rangeFrom(p), empty);
315
+ if (!m)
316
+ return null;
317
+ return { selection: Selection.single(m.from, m.to), origin: 'select', scrollIntoView: true };
318
+ }
319
+ #go(dir) {
320
+ const spec = this.#navigate(this.#state, dir);
321
+ if (spec)
322
+ this.#ctx.core.apply(spec);
323
+ }
324
+ /** Replace the current match and select the next, as one undo step. With no current match,
325
+ * only move to the next one, so the first press shows what the second replaces. */
326
+ #replaceOne() {
327
+ const s = this.#searcher;
328
+ if (!(s instanceof Searcher))
329
+ return;
330
+ const state = this.#state;
331
+ const p = state.selection.primary;
332
+ const m = s.matchAt(state.text, rangeFrom(p), rangeTo(p));
333
+ if (!m)
334
+ return this.#go(1);
335
+ const insert = s.replacement(m, this.#replace.value);
336
+ const changes = ChangeSet.of([{ from: m.from, to: m.to, insert }], state.text.length);
337
+ const after = changes.apply(state.text);
338
+ const end = m.from + insert.length;
339
+ const next = s.next(after, end);
340
+ // Wrapping back onto the text just inserted would replace it again on the next press.
341
+ const selection = next && !(next.from >= m.from && next.to <= end && next.from < end) ? Selection.single(next.from, next.to) : Selection.single(end);
342
+ this.#ctx.core.apply({ changes, selection, origin: 'command', scrollIntoView: true });
343
+ }
344
+ #replaceAll() {
345
+ const s = this.#searcher;
346
+ if (!(s instanceof Searcher))
347
+ return;
348
+ const changes = s.replaceAll(this.#state.text, this.#replace.value);
349
+ if (changes.isEmpty)
350
+ return;
351
+ this.#ctx.core.apply({ changes, origin: 'command' });
352
+ }
353
+ #onKey(e) {
354
+ const name = normalizeKey(e, apple);
355
+ const inFind = e.target === this.#find;
356
+ const inReplace = e.target === this.#replace;
357
+ let handled = true;
358
+ if (name === 'Escape')
359
+ this.close(true);
360
+ else if (name === 'Enter' && inFind)
361
+ this.#go(1);
362
+ else if (name === 'Shift-Enter' && inFind)
363
+ this.#go(-1);
364
+ else if (name === 'Enter' && inReplace)
365
+ this.#replaceOne();
366
+ else if (name === 'Mod-Alt-Enter')
367
+ this.#replaceAll();
368
+ else if (name === 'F3' || name === 'Mod-g')
369
+ this.#go(1);
370
+ else if (name === 'Shift-F3' || name === 'Mod-Shift-g' || name === 'Mod-Shift-G')
371
+ this.#go(-1);
372
+ else if (name === 'Mod-f') {
373
+ this.#find.focus();
374
+ this.#find.select();
375
+ }
376
+ else if (name === 'Mod-Alt-f' || name === 'Mod-Alt-ƒ')
377
+ this.#showReplace(this.#replaceRow.hidden, true);
378
+ // By physical key: with Alt held on Apple platforms, `key` is the Option character.
379
+ else if (e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey && e.code === 'KeyC')
380
+ this.#flip('caseSensitive');
381
+ else if (e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey && e.code === 'KeyW')
382
+ this.#flip('wholeWord');
383
+ else if (e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey && e.code === 'KeyR')
384
+ this.#flip('regexp');
385
+ else
386
+ handled = false;
387
+ if (handled)
388
+ e.preventDefault();
389
+ }
390
+ /** Count in idle slices until the index is complete; then update the status and make any jump
391
+ * typing deferred. */
392
+ #startCounting() {
393
+ if (this.#counting || !this.#index || this.#index.complete)
394
+ return;
395
+ const win = this.#ctx.root.ownerDocument.defaultView;
396
+ const run = (deadline) => {
397
+ this.#counting = null;
398
+ const index = this.#index;
399
+ if (!index || this.#ctx.signal.aborted)
400
+ return;
401
+ const budget = Math.min(SLICE_MS, deadline ? Math.max(1, deadline.timeRemaining()) : SLICE_MS);
402
+ const end = performance.now() + budget;
403
+ if (!index.step(() => performance.now() >= end))
404
+ return this.#startCounting();
405
+ const jump = this.#pendingJump;
406
+ this.#pendingJump = null;
407
+ if (jump !== null) {
408
+ const m = index.next(jump);
409
+ if (m)
410
+ this.#select(m);
411
+ }
412
+ this.#status();
413
+ };
414
+ if (typeof win.requestIdleCallback === 'function') {
415
+ const id = win.requestIdleCallback(run, { timeout: 100 });
416
+ this.#counting = () => win.cancelIdleCallback(id);
417
+ }
418
+ else {
419
+ const id = win.setTimeout(run, 0);
420
+ this.#counting = () => win.clearTimeout(id);
421
+ }
422
+ }
423
+ #stopCounting() {
424
+ this.#counting?.();
425
+ this.#counting = null;
426
+ }
427
+ /** Recompute "3 of 120" once per frame at most. */
428
+ #status() {
429
+ if (this.#statusFrame)
430
+ return;
431
+ const win = this.#ctx.root.ownerDocument.defaultView;
432
+ this.#statusFrame = win.requestAnimationFrame(() => {
433
+ this.#statusFrame = 0;
434
+ this.#update();
435
+ });
436
+ }
437
+ #update() {
438
+ const s = this.#searcher;
439
+ const invalid = !!s && !(s instanceof Searcher);
440
+ this.#find.setAttribute('aria-invalid', String(invalid));
441
+ for (const b of this.#actions)
442
+ b.disabled = !(s instanceof Searcher);
443
+ if (!this.#open)
444
+ return;
445
+ let text;
446
+ if (!s)
447
+ text = '';
448
+ else if (!(s instanceof Searcher))
449
+ text = 'Invalid regular expression';
450
+ else {
451
+ const index = this.#index;
452
+ const total = index?.text === this.#state.text ? index.total : null;
453
+ // Counting: keep the last answer rather than flash a placeholder on every edit.
454
+ if (total === null || !index)
455
+ return;
456
+ if (total === 0)
457
+ text = 'No results';
458
+ else {
459
+ const p = this.#state.selection.primary;
460
+ const m = s.matchAt(this.#state.text, rangeFrom(p), rangeTo(p));
461
+ const i = m ? index.indexOf(m) : null;
462
+ text = i !== null ? `${i + 1} of ${total}` : total === 1 ? '1 result' : `${total} results`;
463
+ }
464
+ }
465
+ if (this.#count.textContent !== text)
466
+ this.#count.textContent = text;
467
+ }
468
+ }
469
+ let ids = 0;
@@ -0,0 +1,81 @@
1
+ import { ChangeSet } from '../text/changeset.ts';
2
+ import type { Text } from '../text/text.ts';
3
+ /** What the find bar asks for. No DOM: a terminal editor drives the same functions. */
4
+ export interface SearchQuery {
5
+ readonly search: string;
6
+ readonly caseSensitive?: boolean;
7
+ readonly wholeWord?: boolean;
8
+ /** `search` is a JavaScript regular expression. A match never spans a line break. */
9
+ readonly regexp?: boolean;
10
+ }
11
+ /** A match in document offsets. `groups` are the regexp's captures, for `$1` in a replacement. */
12
+ export interface Match {
13
+ readonly from: number;
14
+ readonly to: number;
15
+ readonly groups?: RegExpExecArray;
16
+ }
17
+ /** Lines per block: the unit `SearchIndex` counts in, and the slice a scan reads from the rope. */
18
+ export declare const BLOCK = 512;
19
+ /** Compiles a query. null for an empty search; `{ error }` for a regexp that does not parse. */
20
+ export declare function searcher(query: SearchQuery): Searcher | {
21
+ readonly error: string;
22
+ } | null;
23
+ /**
24
+ * Finds matches of one query in any Text. Stateless over the document: every method takes the
25
+ * Text, so a snapshot's matches never go stale. Reads the rope a block of lines at a time and runs
26
+ * the regexp over each line on its own, so a match cannot cross a line break.
27
+ */
28
+ export declare class Searcher {
29
+ #private;
30
+ readonly query: SearchQuery;
31
+ constructor(query: SearchQuery, re: RegExp);
32
+ /**
33
+ * Calls `f` for each match on lines `fromLine..toLine` (1-based, inclusive), in document order.
34
+ * Stops when `f` returns false.
35
+ */
36
+ scan(text: Text, fromLine: number, toLine: number, f: (m: Match) => boolean | void): void;
37
+ /** Matches on the lines spanning [from, to], at most `limit` of them. */
38
+ matches(text: Text, from: number, to: number, limit?: number): Match[];
39
+ /** The match exactly covering [from, to), or null. */
40
+ matchAt(text: Text, from: number, to: number): Match | null;
41
+ /**
42
+ * The first match starting at or after `pos`, wrapping to the top. `empty(block)` may say a block
43
+ * (lines `block * BLOCK + 1 ..`) is known to hold no match, so the scan skips it. With `limit`,
44
+ * scans at most that many blocks past the cursor's line and returns undefined if it gave up.
45
+ */
46
+ next(text: Text, pos: number, empty?: (block: number) => boolean): Match | null;
47
+ next(text: Text, pos: number, empty: ((block: number) => boolean) | undefined, limit: number): Match | null | undefined;
48
+ /** The last match starting before `pos`, wrapping to the bottom. */
49
+ prev(text: Text, pos: number, empty?: (block: number) => boolean): Match | null;
50
+ /** What a match is replaced with: the text as typed, or with `$&`, `$1`, `$<name>`, `$$`
51
+ * expanded for a regexp. */
52
+ replacement(m: Match, replace: string): string;
53
+ /** One ChangeSet replacing every match in the document: one undo step. Empty when none. */
54
+ replaceAll(text: Text, replace: string): ChangeSet;
55
+ }
56
+ /**
57
+ * Match counts per block of lines, filled in a slice at a time off the hot path, so a 100k-line
58
+ * document never scans in one go. Gives the total, the index of a match ("3 of 120"), and lets
59
+ * navigation skip blocks known to be empty. A follower of the document: `map` keeps it current
60
+ * through an edit by forgetting only the blocks the edit touched.
61
+ */
62
+ export declare class SearchIndex {
63
+ #private;
64
+ readonly searcher: Searcher;
65
+ constructor(searcher: Searcher, text: Text);
66
+ get text(): Text;
67
+ get complete(): boolean;
68
+ /** Every match in the document, or null while some block is uncounted. */
69
+ get total(): number | null;
70
+ /** Count blocks until `stop()` says the slice is spent. True once every block is counted. */
71
+ step(stop: () => boolean): boolean;
72
+ /** Follow an edit from `before` to `after`. Blocks the edit did not touch keep their counts. */
73
+ map(changes: ChangeSet, before: Text, after: Text): void;
74
+ /** Whether block `b` is counted and holds no match. */
75
+ readonly empty: (b: number) => boolean;
76
+ /** The 0-based index of match `m` among all matches, or null while blocks before it are
77
+ * uncounted. Scans at most one block. */
78
+ indexOf(m: Match): number | null;
79
+ next(pos: number): Match | null;
80
+ prev(pos: number): Match | null;
81
+ }