@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,229 @@
1
+ import { nextVisibleLine, spanIndex } from "../state/folds.js";
2
+ /** First slice: every line is `lineHeight` tall. All queries are arithmetic. */
3
+ export class FixedHeightMap {
4
+ lines;
5
+ lineHeight;
6
+ constructor(lines, lineHeight) {
7
+ this.lines = lines;
8
+ this.lineHeight = lineHeight;
9
+ }
10
+ get totalHeight() {
11
+ return this.lines * this.lineHeight;
12
+ }
13
+ lineAt(y) {
14
+ return Math.min(this.lines, Math.max(1, Math.floor(y / this.lineHeight) + 1));
15
+ }
16
+ topOf(line) {
17
+ return (line - 1) * this.lineHeight;
18
+ }
19
+ heightOf() {
20
+ return this.lineHeight;
21
+ }
22
+ next(line, dir) {
23
+ return Math.max(0, Math.min(this.lines + 1, line + dir));
24
+ }
25
+ blockSpace() {
26
+ return 0;
27
+ }
28
+ update(_changes, _before, after) {
29
+ return after.lines === this.lines ? this : new FixedHeightMap(after.lines, this.lineHeight);
30
+ }
31
+ measured() {
32
+ return this;
33
+ }
34
+ }
35
+ /**
36
+ * Fixed-height lines with folded ones at zero height. Built from merged hidden spans; every query
37
+ * is a binary search over them, so cost grows with log(folds), never with lines. It reads the spans
38
+ * again from `hidden` on each update, so it never maps folds itself: FoldState, which listens to
39
+ * the core before the view, already has.
40
+ */
41
+ export class FoldedHeightMap {
42
+ lines;
43
+ lineHeight;
44
+ #hidden;
45
+ #spans;
46
+ /** Hidden lines in spans [0, i]. */
47
+ #through;
48
+ /** Visible lines before span i's first line. */
49
+ #visBefore;
50
+ /** A FixedHeightMap when nothing is hidden, so an unfolded document pays nothing. */
51
+ static create(lines, lineHeight, hidden) {
52
+ const spans = hidden().filter((s) => s[0] <= lines);
53
+ return spans.length === 0 ? new FixedHeightMap(lines, lineHeight) : new FoldedHeightMap(lines, lineHeight, spans, hidden);
54
+ }
55
+ constructor(lines, lineHeight, spans, hidden) {
56
+ this.lines = lines;
57
+ this.lineHeight = lineHeight;
58
+ this.#hidden = hidden;
59
+ this.#spans = spans.map((s) => [s[0], Math.min(s[1], lines)]);
60
+ this.#through = new Int32Array(spans.length);
61
+ this.#visBefore = new Int32Array(spans.length);
62
+ let total = 0;
63
+ this.#spans.forEach((s, i) => {
64
+ this.#visBefore[i] = s[0] - 1 - total;
65
+ total += s[1] - s[0] + 1;
66
+ this.#through[i] = total;
67
+ });
68
+ }
69
+ get #hiddenTotal() {
70
+ return this.#through[this.#through.length - 1] ?? 0;
71
+ }
72
+ get totalHeight() {
73
+ return (this.lines - this.#hiddenTotal) * this.lineHeight;
74
+ }
75
+ lineAt(y) {
76
+ const visible = this.lines - this.#hiddenTotal;
77
+ const v = Math.min(visible - 1, Math.max(0, Math.floor(y / this.lineHeight)));
78
+ // Spans that start at or before visible index v all lie above the line it names.
79
+ let lo = 0;
80
+ let hi = this.#spans.length;
81
+ while (lo < hi) {
82
+ const mid = (lo + hi) >> 1;
83
+ if (this.#visBefore[mid] <= v)
84
+ lo = mid + 1;
85
+ else
86
+ hi = mid;
87
+ }
88
+ return v + 1 + (lo > 0 ? this.#through[lo - 1] : 0);
89
+ }
90
+ topOf(line) {
91
+ // Hidden lines above `line`: whole spans before it, plus the part of the one it is in.
92
+ let lo = 0;
93
+ let hi = this.#spans.length;
94
+ while (lo < hi) {
95
+ const mid = (lo + hi) >> 1;
96
+ if (this.#spans[mid][0] < line)
97
+ lo = mid + 1;
98
+ else
99
+ hi = mid;
100
+ }
101
+ let above = 0;
102
+ if (lo > 0) {
103
+ const s = this.#spans[lo - 1];
104
+ above = (lo > 1 ? this.#through[lo - 2] : 0) + Math.min(s[1], line - 1) - s[0] + 1;
105
+ }
106
+ return (line - 1 - above) * this.lineHeight;
107
+ }
108
+ heightOf(line) {
109
+ return spanIndex(this.#spans, line) >= 0 ? 0 : this.lineHeight;
110
+ }
111
+ next(line, dir) {
112
+ return nextVisibleLine(this.#spans, line, dir, this.lines);
113
+ }
114
+ blockSpace() {
115
+ return 0;
116
+ }
117
+ update(_changes, _before, after) {
118
+ return FoldedHeightMap.create(after.lines, this.lineHeight, this.#hidden);
119
+ }
120
+ measured() {
121
+ return this;
122
+ }
123
+ }
124
+ /**
125
+ * Block widgets layered over any base map (fixed, folded, and later wrapped): FoldedHeightMap
126
+ * removes spans, this inserts them. A slot whose anchor line the base hides takes no space, so a
127
+ * fold over a call site hides its expansion too.
128
+ *
129
+ * Built from slots sorted by line. `#start[i]` is where slot i begins in the combined geometry and
130
+ * `#cum[i]` the space of the slots before it, so every query is a binary search over slots plus one
131
+ * base query: O(log blocks + log folds), never O(lines) or O(blocks). Building it is O(blocks)
132
+ * base queries, once per Update or per measured resize, as FoldedHeightMap is O(folds) per Update.
133
+ * Like FoldedHeightMap it never maps anchors itself: it reads `slots()` again on update, from the
134
+ * follower that already has.
135
+ */
136
+ export class BlockHeightMap {
137
+ #base;
138
+ #slots;
139
+ /** Anchor line of each slot, ascending. */
140
+ #line;
141
+ /** Space each slot takes: its height, or 0 under a fold. */
142
+ #height;
143
+ /** Space of slots [0, i); length + 1 entries. */
144
+ #cum;
145
+ /** Top of slot i in the combined geometry. */
146
+ #start;
147
+ /** The base itself when there are no slots, so a document without widgets pays nothing. */
148
+ static create(base, slots) {
149
+ const list = slots();
150
+ return list.length === 0 ? base : new BlockHeightMap(base, list, slots);
151
+ }
152
+ constructor(base, list, slots) {
153
+ this.#base = base;
154
+ this.#slots = slots;
155
+ const n = list.length;
156
+ this.#line = new Int32Array(n);
157
+ this.#height = new Float64Array(n);
158
+ this.#cum = new Float64Array(n + 1);
159
+ this.#start = new Float64Array(n);
160
+ const lines = base.lines;
161
+ let prev = 0;
162
+ for (let i = 0; i < n; i++) {
163
+ const s = list[i];
164
+ if (s.line < prev)
165
+ throw new RangeError('block slots must be sorted by line');
166
+ prev = s.line;
167
+ const shown = s.line >= 1 && s.line <= lines && base.heightOf(s.line) > 0;
168
+ const h = shown ? Math.max(0, s.height) : 0;
169
+ this.#line[i] = s.line;
170
+ this.#height[i] = h;
171
+ this.#start[i] = base.topOf(s.line) + base.heightOf(s.line) + this.#cum[i];
172
+ this.#cum[i + 1] = this.#cum[i] + h;
173
+ }
174
+ }
175
+ /** Slots anchored at lines < line: the first index whose line is >= line. */
176
+ #before(line) {
177
+ let lo = 0;
178
+ let hi = this.#line.length;
179
+ while (lo < hi) {
180
+ const mid = (lo + hi) >> 1;
181
+ if (this.#line[mid] < line)
182
+ lo = mid + 1;
183
+ else
184
+ hi = mid;
185
+ }
186
+ return lo;
187
+ }
188
+ get totalHeight() {
189
+ return this.#base.totalHeight + this.#cum[this.#line.length];
190
+ }
191
+ lineAt(y) {
192
+ // The last slot starting at or before y. Slots never overlap and are sorted, so if y is inside
193
+ // a slot it is this one, and every slot up to it lies wholly above y otherwise.
194
+ let lo = 0;
195
+ let hi = this.#start.length;
196
+ while (lo < hi) {
197
+ const mid = (lo + hi) >> 1;
198
+ if (this.#start[mid] <= y)
199
+ lo = mid + 1;
200
+ else
201
+ hi = mid;
202
+ }
203
+ const i = lo - 1;
204
+ if (i >= 0 && y < this.#start[i] + this.#height[i])
205
+ return this.#line[i];
206
+ return this.#base.lineAt(y - (i >= 0 ? this.#cum[i + 1] : 0));
207
+ }
208
+ topOf(line) {
209
+ return this.#base.topOf(line) + this.#cum[this.#before(line)];
210
+ }
211
+ heightOf(line) {
212
+ return this.#base.heightOf(line);
213
+ }
214
+ next(line, dir) {
215
+ return this.#base.next(line, dir);
216
+ }
217
+ get lines() {
218
+ return this.#base.lines;
219
+ }
220
+ blockSpace(line) {
221
+ return this.#cum[this.#before(line + 1)] - this.#cum[this.#before(line)];
222
+ }
223
+ update(changes, before, after) {
224
+ return BlockHeightMap.create(this.#base.update(changes, before, after), this.#slots);
225
+ }
226
+ measured(heights) {
227
+ return BlockHeightMap.create(this.#base.measured(heights), this.#slots);
228
+ }
229
+ }
@@ -0,0 +1,54 @@
1
+ import type { LineTokens, StyleDef } from '../tokens/protocol.ts';
2
+ /**
3
+ * A mounted line. The view keeps one per line in the mounted range, keyed by line number and
4
+ * reused across frames. `text` and `tokens` are the inputs the DOM was built from; a rerender is
5
+ * skipped when both are identical (string === and array identity), which is what makes a token
6
+ * batch that only touches two lines repaint two lines.
7
+ */
8
+ export interface LineBox {
9
+ readonly el: HTMLDivElement;
10
+ line: number;
11
+ text: string;
12
+ tokens: LineTokens | undefined;
13
+ classes: string | undefined;
14
+ /** Whitespace runs drawn with marks, flat `[from, to)` pairs (state/whitespace.ts). Part of the
15
+ * line's identity: a rerender is skipped only when these match too. */
16
+ ws: readonly number[];
17
+ /** Start offset of each child node, parallel to el.childNodes. Binary searched for DOM points. */
18
+ starts: Uint32Array;
19
+ /** True when offsets map to x by arithmetic: monospace-safe characters only (see measure.ts). */
20
+ simple: boolean;
21
+ /** Cached client rects per character boundary for non-simple lines. Cleared on rerender. */
22
+ rects: Float64Array | null;
23
+ }
24
+ /** The single owner of token-style class names. */
25
+ export declare const styleClass: (id: number) => string;
26
+ /**
27
+ * CSS for one style. Font styles are ordinary properties because syntax is spans (D1). Token
28
+ * backgrounds are ignored, as in VS Code: themes resolve them to the editor background, and an
29
+ * opaque span would cover what the line draws beneath its text (indent guides, overlays).
30
+ */
31
+ export declare function styleRule(def: StyleDef): string;
32
+ /** Printable ASCII and tab: one column per code unit (tabs expand to stops) in a monospace font. */
33
+ export declare function isSimpleText(text: string): boolean;
34
+ export declare const NO_RUNS: readonly number[];
35
+ /** Whether two flat run lists are the same runs. */
36
+ export declare function sameRuns(a: readonly number[], b: readonly number[]): boolean;
37
+ /**
38
+ * Build the line's children: a bare text node for style-0 runs, one span per other run, no
39
+ * empty nodes. With no tokens, one text node. Sets `starts`, `simple`, clears `rects`.
40
+ *
41
+ * Marked whitespace (`ws`) splits the runs it crosses: each stretch of spaces becomes a
42
+ * `nib-ws` span and each tab a `nib-ws-tab` span, carrying the token's style class too. The marks
43
+ * are drawn by CSS on those spans, so the line's text, and every offset in `starts`, is exactly
44
+ * what it would be without them. With `reveal` (marks follow the selection), a mark that appears
45
+ * on a line whose text and tokens didn't change gets `nib-ws-enter`, which fades it in.
46
+ */
47
+ export declare function renderLine(box: LineBox, text: string, tokens: LineTokens | undefined, classes: string | undefined, ws?: readonly number[], reveal?: boolean): void;
48
+ /** The DOM point for an offset within the line, for StaticRange construction. */
49
+ export declare function domPoint(box: LineBox, offset: number): {
50
+ node: Node;
51
+ offset: number;
52
+ };
53
+ /** Inverse of domPoint, for caretPositionFromPoint results on non-simple lines. */
54
+ export declare function offsetOfDomPoint(box: LineBox, node: Node, offset: number): number | null;
@@ -0,0 +1,168 @@
1
+ /** The single owner of token-style class names. */
2
+ export const styleClass = (id) => `s${id}`;
3
+ /**
4
+ * CSS for one style. Font styles are ordinary properties because syntax is spans (D1). Token
5
+ * backgrounds are ignored, as in VS Code: themes resolve them to the editor background, and an
6
+ * opaque span would cover what the line draws beneath its text (indent guides, overlays).
7
+ */
8
+ export function styleRule(def) {
9
+ let body = '';
10
+ if (def.fg)
11
+ body += `color:${def.fg};`;
12
+ if (def.fontStyle & 1)
13
+ body += 'font-style:italic;';
14
+ if (def.fontStyle & 2)
15
+ body += 'font-weight:bold;';
16
+ const deco = [def.fontStyle & 4 ? 'underline' : '', def.fontStyle & 8 ? 'line-through' : ''].filter(Boolean).join(' ');
17
+ if (deco)
18
+ body += `text-decoration:${deco};`;
19
+ return `.${styleClass(def.id)}{${body}}`;
20
+ }
21
+ /** Printable ASCII and tab: one column per code unit (tabs expand to stops) in a monospace font. */
22
+ export function isSimpleText(text) {
23
+ for (let i = 0; i < text.length; i++) {
24
+ const c = text.charCodeAt(i);
25
+ if ((c < 0x20 && c !== 0x09) || c > 0x7e)
26
+ return false;
27
+ }
28
+ return true;
29
+ }
30
+ export const NO_RUNS = [];
31
+ /** Whether two flat run lists are the same runs. */
32
+ export function sameRuns(a, b) {
33
+ if (a === b)
34
+ return true;
35
+ if (a.length !== b.length)
36
+ return false;
37
+ for (let i = 0; i < a.length; i++)
38
+ if (a[i] !== b[i])
39
+ return false;
40
+ return true;
41
+ }
42
+ /** Whether [from, to) lies inside one of `runs`. */
43
+ function within(runs, from, to) {
44
+ for (let i = 0; i < runs.length; i += 2)
45
+ if (runs[i] <= from && to <= runs[i + 1])
46
+ return true;
47
+ return false;
48
+ }
49
+ /**
50
+ * Build the line's children: a bare text node for style-0 runs, one span per other run, no
51
+ * empty nodes. With no tokens, one text node. Sets `starts`, `simple`, clears `rects`.
52
+ *
53
+ * Marked whitespace (`ws`) splits the runs it crosses: each stretch of spaces becomes a
54
+ * `nib-ws` span and each tab a `nib-ws-tab` span, carrying the token's style class too. The marks
55
+ * are drawn by CSS on those spans, so the line's text, and every offset in `starts`, is exactly
56
+ * what it would be without them. With `reveal` (marks follow the selection), a mark that appears
57
+ * on a line whose text and tokens didn't change gets `nib-ws-enter`, which fades it in.
58
+ */
59
+ export function renderLine(box, text, tokens, classes, ws = NO_RUNS, reveal = false) {
60
+ const doc = box.el.ownerDocument;
61
+ const nodes = [];
62
+ const starts = [];
63
+ const shown = reveal && box.text === text && box.tokens === tokens ? box.ws : null;
64
+ const node = (from, to, style, mark) => {
65
+ const t = doc.createTextNode(text.slice(from, to));
66
+ if (style === 0 && !mark)
67
+ nodes.push(t);
68
+ else {
69
+ const span = doc.createElement('span');
70
+ let cls = style === 0 ? mark : mark ? `${styleClass(style)} ${mark}` : styleClass(style);
71
+ if (mark && shown && !within(shown, from, to))
72
+ cls += ' nib-ws-enter';
73
+ span.className = cls;
74
+ span.appendChild(t);
75
+ nodes.push(span);
76
+ }
77
+ starts.push(from);
78
+ };
79
+ let w = 0;
80
+ const push = (from, to, style) => {
81
+ let p = from;
82
+ while (p < to) {
83
+ while (w < ws.length && ws[w + 1] <= p)
84
+ w += 2;
85
+ const a = w < ws.length ? Math.max(ws[w], p) : to;
86
+ if (a >= to) {
87
+ node(p, to, style, '');
88
+ return;
89
+ }
90
+ if (a > p)
91
+ node(p, a, style, '');
92
+ const b = Math.min(ws[w + 1], to);
93
+ for (let q = a; q < b;) {
94
+ if (text.charCodeAt(q) === 9) {
95
+ node(q, q + 1, style, 'nib-ws-tab');
96
+ q++;
97
+ }
98
+ else {
99
+ let e = q + 1;
100
+ while (e < b && text.charCodeAt(e) !== 9)
101
+ e++;
102
+ node(q, e, style, 'nib-ws');
103
+ q = e;
104
+ }
105
+ }
106
+ p = b;
107
+ }
108
+ };
109
+ if (!tokens || tokens.length === 0)
110
+ push(0, text.length, 0);
111
+ else {
112
+ push(0, Math.min(tokens[0], text.length), 0);
113
+ for (let i = 0; i < tokens.length; i += 2) {
114
+ const from = Math.min(tokens[i], text.length);
115
+ const to = i + 2 < tokens.length ? Math.min(tokens[i + 2], text.length) : text.length;
116
+ push(from, to, tokens[i + 1]);
117
+ }
118
+ }
119
+ box.el.replaceChildren(...nodes);
120
+ const cls = classes ? `nib-line ${classes}` : 'nib-line';
121
+ if (box.el.className !== cls)
122
+ box.el.className = cls;
123
+ box.text = text;
124
+ box.tokens = tokens;
125
+ box.classes = classes;
126
+ box.ws = ws;
127
+ box.starts = Uint32Array.from(starts);
128
+ box.simple = isSimpleText(text);
129
+ box.rects = null;
130
+ }
131
+ function childIndexAt(starts, offset) {
132
+ let lo = 0;
133
+ let hi = starts.length - 1;
134
+ while (lo < hi) {
135
+ const mid = (lo + hi + 1) >> 1;
136
+ if (starts[mid] <= offset)
137
+ lo = mid;
138
+ else
139
+ hi = mid - 1;
140
+ }
141
+ return lo;
142
+ }
143
+ const textOf = (child) => (child.nodeType === Node.TEXT_NODE ? child : child.firstChild ?? child);
144
+ /** The DOM point for an offset within the line, for StaticRange construction. */
145
+ export function domPoint(box, offset) {
146
+ const kids = box.el.childNodes;
147
+ if (kids.length === 0)
148
+ return { node: box.el, offset: 0 };
149
+ const i = childIndexAt(box.starts, offset);
150
+ const node = textOf(kids[i]);
151
+ return { node, offset: Math.min(offset - box.starts[i], node.textContent?.length ?? 0) };
152
+ }
153
+ /** Inverse of domPoint, for caretPositionFromPoint results on non-simple lines. */
154
+ export function offsetOfDomPoint(box, node, offset) {
155
+ const kids = box.el.childNodes;
156
+ if (node === box.el)
157
+ return offset >= kids.length ? box.text.length : (box.starts[offset] ?? box.text.length);
158
+ let child = node;
159
+ while (child && child.parentNode !== box.el)
160
+ child = child.parentNode;
161
+ if (!child)
162
+ return null;
163
+ const i = Array.prototype.indexOf.call(kids, child);
164
+ const start = box.starts[i];
165
+ if (node.nodeType === Node.TEXT_NODE)
166
+ return start + offset;
167
+ return offset === 0 ? start : start + (child.textContent?.length ?? 0);
168
+ }
@@ -0,0 +1,37 @@
1
+ import { type LineBox } from './line-dom.ts';
2
+ /**
3
+ * Horizontal geometry within a line (D1 measurement). Vertical geometry is the HeightMap's.
4
+ *
5
+ * Fast path: `box.simple` lines map column -> x as `col * charWidth` with tab stops expanded.
6
+ * A line is simple when every code unit is printable ASCII, a tab, or in a precomputed set of
7
+ * BMP characters verified single-width for the current font (empty in the first slice). The test
8
+ * runs once per rerender of the line.
9
+ * Slow path: `Range.getClientRects` over each boundary of the line, cached in `box.rects` until
10
+ * the line rerenders.
11
+ */
12
+ export declare class Measurer {
13
+ #private;
14
+ /**
15
+ * Measure the font once (and again on font load / resize via ResizeObserver on a probe span).
16
+ * `probe` is a block element holding one span of PROBE_CHARS 'x' characters, so its height is
17
+ * the line height and the span's width is PROBE_CHARS columns.
18
+ */
19
+ calibrate(probe: HTMLElement): void;
20
+ get charWidth(): number;
21
+ get lineHeight(): number;
22
+ /** Columns per tab stop, from the content's CSS `tab-size`. */
23
+ get tabSize(): number;
24
+ /** x relative to the line's content start. */
25
+ xAt(box: LineBox, offset: number): number;
26
+ /** Nearest offset to x (character midpoints decide), relative to the line's content start. */
27
+ offsetAt(box: LineBox, x: number): number;
28
+ /**
29
+ * Arithmetic offsetAt for a line with no box (vertical motion onto an unmounted line). Exact on
30
+ * simple text; on other text it treats each code unit as one column, never landing mid-pair.
31
+ */
32
+ offsetAtText(text: string, x: number): number;
33
+ /** Predicate behind `LineBox.simple`. */
34
+ isSimple(text: string): boolean;
35
+ /** Drop every slow-path cache, after the font changed. */
36
+ invalidate(boxes: Iterable<LineBox>): void;
37
+ }
@@ -0,0 +1,136 @@
1
+ import { domPoint, isSimpleText } from "./line-dom.js";
2
+ const PROBE_CHARS = 64;
3
+ /**
4
+ * Horizontal geometry within a line (D1 measurement). Vertical geometry is the HeightMap's.
5
+ *
6
+ * Fast path: `box.simple` lines map column -> x as `col * charWidth` with tab stops expanded.
7
+ * A line is simple when every code unit is printable ASCII, a tab, or in a precomputed set of
8
+ * BMP characters verified single-width for the current font (empty in the first slice). The test
9
+ * runs once per rerender of the line.
10
+ * Slow path: `Range.getClientRects` over each boundary of the line, cached in `box.rects` until
11
+ * the line rerenders.
12
+ */
13
+ export class Measurer {
14
+ #charWidth = 0;
15
+ #lineHeight = 0;
16
+ #tabSize = 4;
17
+ /**
18
+ * Measure the font once (and again on font load / resize via ResizeObserver on a probe span).
19
+ * `probe` is a block element holding one span of PROBE_CHARS 'x' characters, so its height is
20
+ * the line height and the span's width is PROBE_CHARS columns.
21
+ */
22
+ calibrate(probe) {
23
+ const span = probe.firstElementChild;
24
+ if (!span)
25
+ throw new Error('Measurer.calibrate: probe needs a span child');
26
+ if (span.textContent !== 'x'.repeat(PROBE_CHARS))
27
+ span.textContent = 'x'.repeat(PROBE_CHARS);
28
+ this.#lineHeight = probe.getBoundingClientRect().height;
29
+ this.#charWidth = span.getBoundingClientRect().width / PROBE_CHARS;
30
+ const tab = parseInt(getComputedStyle(probe).tabSize, 10);
31
+ if (tab > 0)
32
+ this.#tabSize = tab;
33
+ }
34
+ get charWidth() {
35
+ return this.#charWidth;
36
+ }
37
+ get lineHeight() {
38
+ return this.#lineHeight;
39
+ }
40
+ /** Columns per tab stop, from the content's CSS `tab-size`. */
41
+ get tabSize() {
42
+ return this.#tabSize;
43
+ }
44
+ /** x relative to the line's content start. */
45
+ xAt(box, offset) {
46
+ if (box.simple)
47
+ return this.#columnOf(box.text, offset) * this.#charWidth;
48
+ const xs = this.#rects(box);
49
+ return xs[Math.max(0, Math.min(offset, box.text.length))];
50
+ }
51
+ /** Nearest offset to x (character midpoints decide), relative to the line's content start. */
52
+ offsetAt(box, x) {
53
+ if (box.simple)
54
+ return this.offsetAtText(box.text, x);
55
+ const xs = this.#rects(box);
56
+ const text = box.text;
57
+ let best = 0;
58
+ let bestD = Infinity;
59
+ for (let i = 0; i <= text.length; i++) {
60
+ if (i > 0 && i < text.length && isLowSurrogate(text.charCodeAt(i)))
61
+ continue;
62
+ const d = Math.abs(xs[i] - x);
63
+ if (d < bestD) {
64
+ bestD = d;
65
+ best = i;
66
+ }
67
+ }
68
+ return best;
69
+ }
70
+ /**
71
+ * Arithmetic offsetAt for a line with no box (vertical motion onto an unmounted line). Exact on
72
+ * simple text; on other text it treats each code unit as one column, never landing mid-pair.
73
+ */
74
+ offsetAtText(text, x) {
75
+ const cw = this.#charWidth || 1;
76
+ if (text.indexOf('\t') < 0) {
77
+ let off = Math.max(0, Math.min(text.length, Math.round(x / cw)));
78
+ if (off > 0 && off < text.length && isLowSurrogate(text.charCodeAt(off)))
79
+ off--;
80
+ return off;
81
+ }
82
+ let col = 0;
83
+ for (let i = 0; i < text.length; i++) {
84
+ const next = text.charCodeAt(i) === 9 ? (Math.floor(col / this.#tabSize) + 1) * this.#tabSize : col + 1;
85
+ if (x < ((col + next) / 2) * cw)
86
+ return i;
87
+ col = next;
88
+ }
89
+ return text.length;
90
+ }
91
+ /** Predicate behind `LineBox.simple`. */
92
+ isSimple(text) {
93
+ return isSimpleText(text);
94
+ }
95
+ /** Drop every slow-path cache, after the font changed. */
96
+ invalidate(boxes) {
97
+ for (const b of boxes)
98
+ b.rects = null;
99
+ }
100
+ #columnOf(text, offset) {
101
+ const end = Math.min(offset, text.length);
102
+ if (text.indexOf('\t') < 0)
103
+ return end;
104
+ let col = 0;
105
+ for (let i = 0; i < end; i++)
106
+ col = text.charCodeAt(i) === 9 ? (Math.floor(col / this.#tabSize) + 1) * this.#tabSize : col + 1;
107
+ return col;
108
+ }
109
+ #rects(box) {
110
+ if (box.rects)
111
+ return box.rects;
112
+ const text = box.text;
113
+ const xs = new Float64Array(text.length + 1);
114
+ const base = box.el.getBoundingClientRect().left;
115
+ const range = box.el.ownerDocument.createRange();
116
+ let right = 0;
117
+ for (let i = 0; i < text.length;) {
118
+ const w = isHighSurrogate(text.charCodeAt(i)) && i + 1 < text.length && isLowSurrogate(text.charCodeAt(i + 1)) ? 2 : 1;
119
+ const a = domPoint(box, i);
120
+ const b = domPoint(box, i + w);
121
+ range.setStart(a.node, a.offset);
122
+ range.setEnd(b.node, b.offset);
123
+ const r = range.getBoundingClientRect();
124
+ xs[i] = r.left - base;
125
+ if (w === 2)
126
+ xs[i + 1] = xs[i];
127
+ right = r.right - base;
128
+ i += w;
129
+ }
130
+ xs[text.length] = right;
131
+ box.rects = xs;
132
+ return xs;
133
+ }
134
+ }
135
+ const isHighSurrogate = (c) => c >= 0xd800 && c <= 0xdbff;
136
+ const isLowSurrogate = (c) => c >= 0xdc00 && c <= 0xdfff;
@@ -0,0 +1,32 @@
1
+ import { type Overlay, type OverlayKind } from './decorations.ts';
2
+ import { type LineBox } from './line-dom.ts';
3
+ import type { Text } from '../text/text.ts';
4
+ /**
5
+ * Owns this instance's entries in the document-wide `CSS.highlights` registry: one Highlight per
6
+ * overlay kind, named `nib-<instance>-<kind>`, registered on first use and deleted on dispose.
7
+ *
8
+ * `paint` diffs the new overlay list against what is registered (by kind, from, to) and touches
9
+ * a Highlight only when its membership changed, because any change makes Chrome walk every
10
+ * registered range. Overlays outside mounted lines are clipped away here, so a source may return
11
+ * more than is visible. The budget is enforced here and only here.
12
+ */
13
+ export declare class OverlayPainter {
14
+ #private;
15
+ /** Segments that fit on mounted lines but not in the budget, in the last paint. */
16
+ dropped: number;
17
+ constructor(instance: string);
18
+ /** The `::highlight()` rules for this instance, for the adopted stylesheet. */
19
+ css(colors: Readonly<Record<OverlayKind, string>>): string;
20
+ /**
21
+ * Overlays must be sorted by (kind priority desc, from). A range spanning several lines is split
22
+ * at line boundaries into one StaticRange per mounted line, each built from domPoint on its box.
23
+ */
24
+ paint(overlays: readonly Overlay[], text: Text, boxes: ReadonlyMap<number, LineBox>): void;
25
+ /**
26
+ * Mounted lines rerendered this frame invalidate the StaticRanges that point into them, even if
27
+ * the overlay list is unchanged (StaticRange does not track DOM mutation). The view passes those
28
+ * lines; their ranges are rebuilt.
29
+ */
30
+ invalidateLines(lines: Iterable<number>): void;
31
+ dispose(): void;
32
+ }