@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,125 @@
1
+ import { rangeFrom, rangeTo } from "../state/selection.js";
2
+ import { WINDOW_MARGIN, diffStrings, keyEvent, listenClipboard, windowAround, } from "./surface.js";
3
+ const css = 'position:fixed;left:0;top:0;width:1px;height:1em;padding:0;margin:0;border:0;outline:none;resize:none;' +
4
+ 'overflow:hidden;white-space:pre;opacity:0;color:transparent;background:transparent;caret-color:transparent;' +
5
+ 'pointer-events:none;font:inherit;z-index:-1';
6
+ /**
7
+ * Fallback path. A transparent textarea in the shadow root, positioned at the primary caret so
8
+ * IME candidate windows appear there. Its value is the TextWindow; its selection mirrors the
9
+ * primary range.
10
+ *
11
+ * - input: diff the textarea's value against the last synced window (common prefix and suffix,
12
+ * which is O(edit) for typing), emit 'replace' in document coordinates.
13
+ * - compositionstart/end: track composing; the commit is diffed at compositionend, before engines
14
+ * that fire the last input event after it.
15
+ * - paste/cut/copy: ClipboardEvent, handled before the textarea changes.
16
+ * - keydown: forwarded as 'key'.
17
+ *
18
+ * The textarea never holds more than the window, so select-all and very long selections are the
19
+ * editor's own state, not the textarea's.
20
+ */
21
+ export class TextareaSurface {
22
+ focusTarget;
23
+ #window = { from: 0, text: '' };
24
+ #composing = false;
25
+ /** Selection last written to or read from the textarea, window coordinates. */
26
+ #sel = { start: 0, end: 0 };
27
+ #read = () => '';
28
+ #sink;
29
+ #lifetime = new AbortController();
30
+ constructor(host, sink) {
31
+ this.#sink = sink;
32
+ const ta = host.ownerDocument.createElement('textarea');
33
+ ta.style.cssText = css;
34
+ ta.tabIndex = -1; // the host is the tab stop; its shadow root delegates focus here
35
+ ta.spellcheck = false;
36
+ ta.wrap = 'off';
37
+ for (const [k, v] of [['autocomplete', 'off'], ['autocorrect', 'off'], ['autocapitalize', 'off'], ['aria-multiline', 'true']])
38
+ ta.setAttribute(k, v);
39
+ // First in the shadow root, so delegated focus (host.focus(), Tab) lands here and not in a
40
+ // focusable element inside the content, such as an inline expansion's editor.
41
+ host.shadowRoot.prepend(ta);
42
+ this.focusTarget = ta;
43
+ const signal = this.#lifetime.signal;
44
+ const on = (type, l) => ta.addEventListener(type, l, { signal });
45
+ on('keydown', (e) => sink(keyEvent(e)));
46
+ on('beforeinput', (e) => {
47
+ // The textarea's own undo stack holds window rewrites, not the user's edits.
48
+ if (e.inputType === 'historyUndo' || e.inputType === 'historyRedo')
49
+ e.preventDefault();
50
+ });
51
+ on('input', () => this.#readInput());
52
+ // Unbound keys (Alt-arrows, Ctrl-A/E on macOS) and assistive tech move the native caret.
53
+ on('selectionchange', () => this.#readSelection());
54
+ on('keyup', () => this.#readSelection());
55
+ on('compositionstart', () => {
56
+ this.#composing = true;
57
+ });
58
+ on('compositionend', () => {
59
+ this.#readInput();
60
+ this.#composing = false;
61
+ sink({ kind: 'composition-end' });
62
+ });
63
+ on('focus', () => sink({ kind: 'focus', focused: true }));
64
+ on('blur', () => sink({ kind: 'focus', focused: false }));
65
+ listenClipboard(ta, () => true, sink, () => this.#read(), signal);
66
+ }
67
+ get composing() {
68
+ return this.#composing;
69
+ }
70
+ #readInput() {
71
+ const ta = this.focusTarget;
72
+ const value = ta.value;
73
+ const old = this.#window.text;
74
+ if (value === old)
75
+ return;
76
+ // The caret now sits after the inserted text, so the edit starts no later than the caret minus
77
+ // what was inserted. Without the cap, typing "a" before "a" would diff as an insert after it.
78
+ const cap = Math.max(0, ta.selectionStart - Math.max(value.length - old.length, 0));
79
+ const d = diffStrings(old, value, cap);
80
+ this.#window = { from: this.#window.from, text: value };
81
+ this.#sel = { start: ta.selectionStart, end: ta.selectionEnd };
82
+ this.#sink({ kind: 'replace', from: this.#window.from + d.start, to: this.#window.from + d.endA, text: value.slice(d.start, d.endB), composing: this.#composing });
83
+ }
84
+ #readSelection() {
85
+ const ta = this.focusTarget;
86
+ if (this.#composing || ta.value !== this.#window.text)
87
+ return;
88
+ const { selectionStart: start, selectionEnd: end } = ta;
89
+ if (start === this.#sel.start && end === this.#sel.end)
90
+ return;
91
+ this.#sel = { start, end };
92
+ const from = this.#window.from;
93
+ const back = ta.selectionDirection === 'backward';
94
+ this.#sink({ kind: 'select', anchor: from + (back ? end : start), head: from + (back ? start : end) });
95
+ }
96
+ sync(state, geometry) {
97
+ const ta = this.focusTarget;
98
+ if (geometry.caret) {
99
+ ta.style.left = `${geometry.caret.left}px`;
100
+ ta.style.top = `${geometry.caret.top}px`;
101
+ }
102
+ // Writing value or selection mid-composition cancels the IME in WebKit and Gecko.
103
+ if (this.#composing)
104
+ return;
105
+ const w = windowAround(state, WINDOW_MARGIN);
106
+ if (w.from !== this.#window.from || w.text !== this.#window.text) {
107
+ ta.value = w.text;
108
+ this.#window = w;
109
+ }
110
+ const p = state.selection.primary;
111
+ const start = rangeFrom(p) - w.from;
112
+ const end = rangeTo(p) - w.from;
113
+ const dir = p.head < p.anchor ? 'backward' : 'forward';
114
+ if (ta.selectionStart !== start || ta.selectionEnd !== end || (start !== end && ta.selectionDirection !== dir))
115
+ ta.setSelectionRange(start, end, dir);
116
+ this.#sel = { start, end };
117
+ }
118
+ setClipboardSource(read) {
119
+ this.#read = read;
120
+ }
121
+ dispose() {
122
+ this.#lifetime.abort();
123
+ this.focusTarget.remove();
124
+ }
125
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * A constructed stylesheet from `node`'s own window. A sheet can only be adopted by the document
3
+ * whose window constructed it, so a host moved into another window (a popup it was torn off into)
4
+ * needs sheets from that window, not the global `CSSStyleSheet` of the module's.
5
+ */
6
+ export declare function sheetFor(node: Node, css?: string): CSSStyleSheet;
package/dist/sheet.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * A constructed stylesheet from `node`'s own window. A sheet can only be adopted by the document
3
+ * whose window constructed it, so a host moved into another window (a popup it was torn off into)
4
+ * needs sheets from that window, not the global `CSSStyleSheet` of the module's.
5
+ */
6
+ export function sheetFor(node, css) {
7
+ const win = (node.ownerDocument ?? node).defaultView;
8
+ const sheet = win ? new win.CSSStyleSheet() : new CSSStyleSheet();
9
+ if (css !== undefined)
10
+ sheet.replaceSync(css);
11
+ return sheet;
12
+ }
@@ -0,0 +1,73 @@
1
+ import { ChangeSet, type ChangeSpec } from '../text/changeset.ts';
2
+ import { Text } from '../text/text.ts';
3
+ import { Selection } from './selection.ts';
4
+ /**
5
+ * Monotonic document version. Bumps by exactly 1 per update whose ChangeSet is non-empty.
6
+ * Selection-only updates keep the version. The token bridge and future LSP/collab adapters key
7
+ * everything on it.
8
+ */
9
+ export type Version = number & {
10
+ readonly __brand: 'Version';
11
+ };
12
+ export declare const initialVersion: Version;
13
+ export declare const nextVersion: (v: Version) => Version;
14
+ /**
15
+ * Where an update came from. A closed union so History's grouping table and the collab adapter's
16
+ * "is this mine" test are exhaustive switches, not string prefix checks.
17
+ */
18
+ export type Origin = 'input.type' | 'input.compose' | 'input.paste' | 'input.delete' | 'input.newline' | 'select' | 'command' | 'history.undo' | 'history.redo' | 'host.set' | 'host.apply' | 'remote';
19
+ /** An immutable value. Cheap to keep: Text shares structure across versions. */
20
+ export interface Snapshot {
21
+ readonly version: Version;
22
+ readonly text: Text;
23
+ readonly selection: Selection;
24
+ }
25
+ /**
26
+ * What a command or the host asks for. Changes are in the coordinates of the snapshot the spec
27
+ * was computed from, which must be the current one (apply throws on a length mismatch, which is
28
+ * the only cheap staleness check a ChangeSet carries).
29
+ */
30
+ export interface TransactionSpec {
31
+ readonly changes?: ChangeSet | readonly ChangeSpec[];
32
+ /** Absent: the old selection mapped through the changes. */
33
+ readonly selection?: Selection;
34
+ readonly origin: Origin;
35
+ /** Ask the view to bring the primary head into view after this update. */
36
+ readonly scrollIntoView?: boolean;
37
+ }
38
+ /** What listeners receive. `changes` is the identity set for selection-only updates. */
39
+ export interface Update {
40
+ readonly before: Snapshot;
41
+ readonly after: Snapshot;
42
+ readonly changes: ChangeSet;
43
+ readonly origin: Origin;
44
+ readonly docChanged: boolean;
45
+ readonly scrollIntoView: boolean;
46
+ }
47
+ export type UpdateListener = (u: Update) => void;
48
+ /**
49
+ * The single writer. Owns one mutable cell (the current Snapshot) and a listener list. Nothing
50
+ * else in the system mutates document or selection state; everything else is a follower that
51
+ * keeps its own state and derives it from Updates (separate-before-serializing).
52
+ *
53
+ * Runs with no DOM: in Node, in a worker, under `node --test`.
54
+ */
55
+ export declare class EditorCore {
56
+ #private;
57
+ constructor(doc?: string | Text, selection?: Selection);
58
+ get state(): Snapshot;
59
+ /**
60
+ * Apply synchronously and notify listeners in registration order. Returns null when the spec
61
+ * changes nothing (no changes and an equal selection), so callers can tell a command declined.
62
+ *
63
+ * Invariants:
64
+ * - Not reentrant. A listener that calls apply throws. Follow-up edits are commands or are
65
+ * queued by their owner; there are no transaction filters.
66
+ * - Idempotent per spec value only in the sense that a no-op returns null and notifies no one.
67
+ */
68
+ apply(spec: TransactionSpec): Update | null;
69
+ /** Replace the whole document. Origin 'host.set'; History treats it as a reset. */
70
+ reset(doc: string | Text): Update | null;
71
+ /** Returns an unsubscribe function. Also unsubscribes when `signal` aborts. */
72
+ listen(listener: UpdateListener, signal?: AbortSignal): () => void;
73
+ }
@@ -0,0 +1,86 @@
1
+ import { ChangeSet } from "../text/changeset.js";
2
+ import { Text } from "../text/text.js";
3
+ import { Selection } from "./selection.js";
4
+ export const initialVersion = 0;
5
+ export const nextVersion = (v) => (v + 1);
6
+ /**
7
+ * The single writer. Owns one mutable cell (the current Snapshot) and a listener list. Nothing
8
+ * else in the system mutates document or selection state; everything else is a follower that
9
+ * keeps its own state and derives it from Updates (separate-before-serializing).
10
+ *
11
+ * Runs with no DOM: in Node, in a worker, under `node --test`.
12
+ */
13
+ export class EditorCore {
14
+ #state;
15
+ #listeners = [];
16
+ #dispatching = false;
17
+ constructor(doc = '', selection) {
18
+ const text = typeof doc === 'string' ? Text.of(doc) : doc;
19
+ this.#state = { version: initialVersion, text, selection: selection ?? Selection.single(0) };
20
+ }
21
+ get state() {
22
+ return this.#state;
23
+ }
24
+ /**
25
+ * Apply synchronously and notify listeners in registration order. Returns null when the spec
26
+ * changes nothing (no changes and an equal selection), so callers can tell a command declined.
27
+ *
28
+ * Invariants:
29
+ * - Not reentrant. A listener that calls apply throws. Follow-up edits are commands or are
30
+ * queued by their owner; there are no transaction filters.
31
+ * - Idempotent per spec value only in the sense that a no-op returns null and notifies no one.
32
+ */
33
+ apply(spec) {
34
+ if (this.#dispatching)
35
+ throw new Error('EditorCore.apply is not reentrant');
36
+ const before = this.#state;
37
+ const changes = spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes ?? [], before.text.length);
38
+ if (changes.length !== before.text.length)
39
+ throw new RangeError('stale changes');
40
+ const docChanged = !changes.isEmpty;
41
+ const text = docChanged ? changes.apply(before.text) : before.text;
42
+ const selection = spec.selection ?? before.selection.map(changes);
43
+ if (!docChanged && selection.eq(before.selection))
44
+ return null;
45
+ const after = { version: docChanged ? nextVersion(before.version) : before.version, text, selection };
46
+ this.#state = after;
47
+ const u = {
48
+ before,
49
+ after,
50
+ changes,
51
+ origin: spec.origin,
52
+ docChanged,
53
+ scrollIntoView: !!spec.scrollIntoView,
54
+ };
55
+ this.#dispatching = true;
56
+ try {
57
+ for (const l of this.#listeners)
58
+ l(u);
59
+ }
60
+ finally {
61
+ this.#dispatching = false;
62
+ }
63
+ return u;
64
+ }
65
+ /** Replace the whole document. Origin 'host.set'; History treats it as a reset. */
66
+ reset(doc) {
67
+ const text = typeof doc === 'string' ? Text.of(doc) : doc;
68
+ return this.apply({ changes: [{ from: 0, to: this.#state.text.length, insert: text.toString() }], selection: Selection.single(0), origin: 'host.set' });
69
+ }
70
+ /** Returns an unsubscribe function. Also unsubscribes when `signal` aborts. */
71
+ listen(listener, signal) {
72
+ this.#listeners.push(listener);
73
+ const off = () => {
74
+ const i = this.#listeners.indexOf(listener);
75
+ if (i >= 0)
76
+ this.#listeners.splice(i, 1);
77
+ };
78
+ if (signal) {
79
+ if (signal.aborted)
80
+ off();
81
+ else
82
+ signal.addEventListener('abort', off, { once: true });
83
+ }
84
+ return off;
85
+ }
86
+ }
@@ -0,0 +1,41 @@
1
+ import type { Text } from '../text/text.ts';
2
+ import type { EditorCore } from './core.ts';
3
+ import type { FoldRange } from './folds.ts';
4
+ /**
5
+ * What can fold. Indentation is the first source; an LSP `foldingRange` source (D7) implements the
6
+ * same interface from the server's ranges, mapped through Updates like any other follower, and a
7
+ * caller can prefer it where it has an answer.
8
+ */
9
+ export interface FoldRangeSource {
10
+ /** Whether a fold starts at `line`. Cheap and bounded: the rail asks for every mounted line. */
11
+ startsFold(line: number): boolean;
12
+ /** The fold starting at `line`, or null. May scan to the end of the region; called on demand. */
13
+ rangeAt(line: number): FoldRange | null;
14
+ /** The innermost fold with `line` strictly inside it (header < line <= end), or null. */
15
+ enclosing(line: number): FoldRange | null;
16
+ /** Called when `startsFold` may answer differently for a line whose number did not change. */
17
+ subscribe(invalidate: () => void): () => void;
18
+ }
19
+ /**
20
+ * VS Code's indentation fallback as a pure function. A non-blank line starts a fold when the next
21
+ * non-blank line is indented deeper; the fold runs to the last deeper line before one that is not.
22
+ * Blank lines at the end of the region stay outside it, and so does a closing `}` at the header's
23
+ * indent. O(region).
24
+ */
25
+ export declare function indentFoldAt(text: Text, line: number, tabSize?: number, indent?: (n: number) => number): FoldRange | null;
26
+ /**
27
+ * Indentation folding as a follower of EditorCore. It keeps the indents of the lines the rail
28
+ * asked about and moves them through each Update, so a frame after a keystroke or a scroll reads
29
+ * indents from the cache and slices only lines it has not seen. Nothing is O(document) per frame:
30
+ * `startsFold` looks at most BLANK_LIMIT lines ahead.
31
+ */
32
+ export declare class IndentFolds implements FoldRangeSource {
33
+ #private;
34
+ constructor(core: EditorCore, options?: {
35
+ tabSize?: number;
36
+ }, signal?: AbortSignal);
37
+ startsFold(line: number): boolean;
38
+ rangeAt(line: number): FoldRange | null;
39
+ enclosing(line: number): FoldRange | null;
40
+ subscribe(invalidate: () => void): () => void;
41
+ }
@@ -0,0 +1,167 @@
1
+ import { lineIndent } from "./indent.js";
2
+ /** Blank lines skipped when looking for the line after a header. */
3
+ const BLANK_LIMIT = 256;
4
+ /** Lines walked upward to find the header around a line, for the fold command. */
5
+ const UP_LIMIT = 20_000;
6
+ /** Cached indents kept between frames; cleared past this. */
7
+ const CACHE_LIMIT = 1024;
8
+ /** Changes in one update past which the cache is dropped instead of mapped. */
9
+ const BURST = 16;
10
+ /**
11
+ * VS Code's indentation fallback as a pure function. A non-blank line starts a fold when the next
12
+ * non-blank line is indented deeper; the fold runs to the last deeper line before one that is not.
13
+ * Blank lines at the end of the region stay outside it, and so does a closing `}` at the header's
14
+ * indent. O(region).
15
+ */
16
+ export function indentFoldAt(text, line, tabSize = 4, indent = (n) => lineIndent(text, n, tabSize)) {
17
+ const i = indent(line);
18
+ if (i < 0)
19
+ return null;
20
+ let end = 0;
21
+ for (let n = line + 1; n <= text.lines; n++) {
22
+ const j = indent(n);
23
+ if (j < 0)
24
+ continue;
25
+ if (j <= i)
26
+ break;
27
+ end = n;
28
+ }
29
+ return end > line ? { line, end } : null;
30
+ }
31
+ /**
32
+ * Indentation folding as a follower of EditorCore. It keeps the indents of the lines the rail
33
+ * asked about and moves them through each Update, so a frame after a keystroke or a scroll reads
34
+ * indents from the cache and slices only lines it has not seen. Nothing is O(document) per frame:
35
+ * `startsFold` looks at most BLANK_LIMIT lines ahead.
36
+ */
37
+ export class IndentFolds {
38
+ #core;
39
+ #tabSize;
40
+ #cache = new Map();
41
+ #listeners = [];
42
+ constructor(core, options = {}, signal) {
43
+ this.#core = core;
44
+ this.#tabSize = options.tabSize ?? 4;
45
+ core.listen((u) => this.#onUpdate(u), signal);
46
+ }
47
+ startsFold(line) {
48
+ const text = this.#core.state.text;
49
+ if (line < 1 || line >= text.lines)
50
+ return false;
51
+ const i = this.#indent(line);
52
+ if (i < 0)
53
+ return false;
54
+ for (let n = line + 1, k = 0; n <= text.lines && k < BLANK_LIMIT; n++, k++) {
55
+ const j = this.#indent(n);
56
+ if (j >= 0)
57
+ return j > i;
58
+ }
59
+ return false;
60
+ }
61
+ rangeAt(line) {
62
+ const text = this.#core.state.text;
63
+ if (line < 1 || line >= text.lines || !this.startsFold(line))
64
+ return null;
65
+ return indentFoldAt(text, line, this.#tabSize, (n) => this.#cache.get(n) ?? lineIndent(text, n, this.#tabSize));
66
+ }
67
+ enclosing(line) {
68
+ const text = this.#core.state.text;
69
+ if (line < 1 || line > text.lines)
70
+ return null;
71
+ const read = (n) => this.#cache.get(n) ?? lineIndent(text, n, this.#tabSize);
72
+ // A blank line belongs to the region around the next non-blank line.
73
+ let target = read(line);
74
+ for (let n = line + 1; target < 0 && n <= text.lines; n++)
75
+ target = read(n);
76
+ if (target <= 0)
77
+ return null;
78
+ for (let n = line - 1, k = 0; n >= 1 && k < UP_LIMIT; n--, k++) {
79
+ const j = read(n);
80
+ if (j < 0 || j >= target)
81
+ continue;
82
+ const r = this.rangeAt(n);
83
+ return r && r.end >= line ? r : null;
84
+ }
85
+ return null;
86
+ }
87
+ subscribe(invalidate) {
88
+ this.#listeners.push(invalidate);
89
+ return () => {
90
+ this.#listeners = this.#listeners.filter((l) => l !== invalidate);
91
+ };
92
+ }
93
+ #indent(n) {
94
+ let v = this.#cache.get(n);
95
+ if (v === undefined) {
96
+ if (this.#cache.size >= CACHE_LIMIT)
97
+ this.#cache.clear();
98
+ v = lineIndent(this.#core.state.text, n, this.#tabSize);
99
+ this.#cache.set(n, v);
100
+ }
101
+ return v;
102
+ }
103
+ /**
104
+ * Cached lines an edit did not touch keep their indent and move to their new number. Touched
105
+ * ones are dropped. When no edit changes its line count nothing else moves the rail, so a touched
106
+ * line whose indent changed (a blank line typed into, a tab removed) is reported.
107
+ */
108
+ #onUpdate(u) {
109
+ if (!u.docChanged || this.#cache.size === 0)
110
+ return;
111
+ const before = u.before.text;
112
+ const after = u.after.text;
113
+ const raw = [];
114
+ u.changes.iterChanges((fromA, toA, fromB, toB) => void raw.push(fromA, toA, fromB, toB));
115
+ // A burst (a remote transaction, a multi-cursor edit) would cost four line lookups per change;
116
+ // re-reading the ~100 lines the rail shows is cheaper and bounded.
117
+ if (raw.length > 4 * BURST) {
118
+ this.#cache = new Map();
119
+ for (const l of this.#listeners)
120
+ l();
121
+ return;
122
+ }
123
+ const edits = [];
124
+ for (let i = 0; i < raw.length; i += 4) {
125
+ edits.push([before.lineAt(raw[i]).number, before.lineAt(raw[i + 1]).number, after.lineAt(raw[i + 2]).number, after.lineAt(raw[i + 3]).number]);
126
+ }
127
+ const old = this.#cache;
128
+ const next = new Map();
129
+ for (const [n, v] of old) {
130
+ // The last edit starting at or before n: n is inside it, or after it and shifted by it.
131
+ let lo = 0;
132
+ let hi = edits.length - 1;
133
+ let at = -1;
134
+ while (lo <= hi) {
135
+ const mid = (lo + hi) >> 1;
136
+ if (edits[mid][0] <= n) {
137
+ at = mid;
138
+ lo = mid + 1;
139
+ }
140
+ else
141
+ hi = mid - 1;
142
+ }
143
+ if (at < 0)
144
+ next.set(n, v);
145
+ else if (n > edits[at][1])
146
+ next.set(n + edits[at][3] - edits[at][1], v);
147
+ }
148
+ this.#cache = next;
149
+ // An edit that adds or removes lines makes the view re-place every mounted line anyway.
150
+ if (edits.some(([oldLo, oldHi, newLo, newHi]) => oldHi - oldLo !== newHi - newLo))
151
+ return;
152
+ let changed = false;
153
+ for (const [oldLo, oldHi, newLo] of edits) {
154
+ for (let k = 0; k <= oldHi - oldLo; k++) {
155
+ const was = old.get(oldLo + k);
156
+ if (was === undefined)
157
+ continue;
158
+ const now = this.#indent(newLo + k);
159
+ if (now !== was)
160
+ changed = true;
161
+ }
162
+ }
163
+ if (changed)
164
+ for (const l of this.#listeners)
165
+ l();
166
+ }
167
+ }
@@ -0,0 +1,45 @@
1
+ import type { EditorCore } from './core.ts';
2
+ /** A folded region. Line `line` stays visible; lines `line + 1` through `end` are hidden. 1-based. */
3
+ export interface FoldRange {
4
+ readonly line: number;
5
+ readonly end: number;
6
+ }
7
+ /** A run of hidden lines, 1-based and inclusive. */
8
+ export type HiddenSpan = readonly [from: number, to: number];
9
+ /** Index of the span containing `line`, or -1. Spans are sorted and disjoint. */
10
+ export declare function spanIndex(spans: readonly HiddenSpan[], line: number): number;
11
+ /**
12
+ * The nearest line from `line` in `dir` that is not hidden: 0 above the first line, `lines + 1`
13
+ * below the last. Merged spans never touch, so one jump is enough.
14
+ */
15
+ export declare function nextVisibleLine(spans: readonly HiddenSpan[], line: number, dir: -1 | 1, lines: number): number;
16
+ /**
17
+ * Which regions are folded. A follower of EditorCore with no DOM, so a terminal view can use it
18
+ * as the element does. Discovering what *can* fold is a separate FoldRangeSource.
19
+ *
20
+ * Every Update maps each fold through its ChangeSet in one sweep: O(folds + changes x log lines).
21
+ * A fold is dropped when an edit deletes its header's line break (the header line is gone or
22
+ * merged into the next), or when it ends up hiding no lines. Edits inside a fold keep it.
23
+ *
24
+ * When a selection head lands on a hidden line, every fold hiding that line opens. Vertical motion
25
+ * skips hidden lines, so only jumps put a head there: find, undo, a host or remote selection, or
26
+ * a horizontal step across the fold's edge. Opening is the one answer that is right for all of
27
+ * them, because the caret is never invisible.
28
+ */
29
+ export declare class FoldState {
30
+ #private;
31
+ constructor(core: EditorCore, signal?: AbortSignal);
32
+ /** Folded regions, sorted by header line, current as of `core.state`. */
33
+ get ranges(): readonly FoldRange[];
34
+ /** Hidden lines as merged, sorted spans. */
35
+ get hidden(): readonly HiddenSpan[];
36
+ isFolded(line: number): boolean;
37
+ isHidden(line: number): boolean;
38
+ /** Fold `range`. False when it hides nothing or is already folded. */
39
+ fold(range: FoldRange): boolean;
40
+ /** Open the fold whose header is `line`. False when there is none. */
41
+ unfold(line: number): boolean;
42
+ unfoldAll(): boolean;
43
+ /** Called after any fold opens, closes, or is dropped. Not called when an edit only moves them. */
44
+ subscribe(listener: () => void): () => void;
45
+ }