@kabmo-labs/kabmo 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +45 -0
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +333 -333
  4. package/dist/client/static/js/index-18xe7655.css +1 -0
  5. package/dist/client/static/js/{index-bpptfkz2.js → index-nxpe7835.js} +768 -763
  6. package/package.json +3 -1
  7. package/src/client/components/common/code-surface/bracket-guide.test.ts +249 -0
  8. package/src/client/components/common/code-surface/bracket-guide.ts +131 -0
  9. package/src/client/components/common/code-surface/documents.test.ts +5 -3
  10. package/src/client/components/common/code-surface/documents.ts +85 -0
  11. package/src/client/components/common/code-surface/extensions.test.ts +5 -0
  12. package/src/client/components/common/code-surface/extensions.ts +140 -7
  13. package/src/client/components/common/code-surface/fold-stack.test.ts +218 -0
  14. package/src/client/components/common/code-surface/fold.test.ts +148 -0
  15. package/src/client/components/common/code-surface/fold.ts +118 -0
  16. package/src/client/components/common/code-surface/indent-guide.ts +104 -0
  17. package/src/client/components/common/code-surface/indent.test.ts +239 -0
  18. package/src/client/components/common/code-surface/indent.ts +124 -0
  19. package/src/client/components/common/code-surface/index.tsx +76 -46
  20. package/src/client/components/common/code-surface/keymap.ts +12 -23
  21. package/src/client/components/common/code-surface/line-commands.test.ts +90 -0
  22. package/src/client/components/common/code-surface/line-commands.ts +103 -0
  23. package/src/client/components/common/code-surface/props.ts +87 -0
  24. package/src/client/components/common/code-surface/stream-language.test.ts +118 -0
  25. package/src/client/components/common/code-surface/stream-language.ts +123 -0
  26. package/src/client/components/common/code-surface/theme.test.ts +40 -5
  27. package/src/client/components/common/code-surface/theme.ts +113 -0
  28. package/src/client/components/common/code-surface/typing.test.ts +97 -0
  29. package/src/client/components/common/code-surface/typing.ts +111 -0
  30. package/src/client/components/common/toolbar-row/index.test.tsx +53 -4
  31. package/src/client/components/common/toolbar-row/index.tsx +101 -30
  32. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +17 -0
  33. package/src/client/components/layout/desktop-layout/index.tsx +18 -0
  34. package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +35 -33
  35. package/src/client/components/mobile/mobile-right-sidebar/Header.tsx +20 -1
  36. package/src/client/components/mobile/mobile-right-sidebar/editor-props.ts +25 -0
  37. package/src/client/components/settings/categories/AppearanceSettings.tsx +6 -0
  38. package/src/client/components/settings/categories/appearance-settings/EditorIndentSection.tsx +87 -0
  39. package/src/client/components/settings/categories/appearance-settings/EditorTypingSection.tsx +99 -0
  40. package/src/client/components/workspace/chat-timeline/chat-input/expansion.ts +9 -4
  41. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +15 -11
  42. package/src/client/components/workspace/chat-timeline/chat-input/stretch-send.test.tsx +165 -0
  43. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/DiffView.test.ts +17 -3
  44. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/DiffView.tsx +10 -6
  45. package/src/client/components/workspace/editor/Body.tsx +24 -0
  46. package/src/client/components/workspace/editor/CommandPalette.tsx +4 -4
  47. package/src/client/components/workspace/editor/ConflictStrip.tsx +77 -0
  48. package/src/client/components/workspace/editor/Dialogs.tsx +53 -0
  49. package/src/client/components/workspace/editor/EmptyEditor.tsx +23 -0
  50. package/src/client/components/workspace/editor/ExternalChangeStrip.tsx +61 -0
  51. package/src/client/components/workspace/editor/FileDocument.tsx +89 -1
  52. package/src/client/components/workspace/editor/FilePane.tsx +43 -0
  53. package/src/client/components/workspace/editor/FindWidget.test.ts +9 -5
  54. package/src/client/components/workspace/editor/FindWidget.tsx +29 -0
  55. package/src/client/components/workspace/editor/GoToLineModal.tsx +123 -0
  56. package/src/client/components/workspace/editor/Notices.tsx +71 -0
  57. package/src/client/components/workspace/editor/Pane.tsx +118 -0
  58. package/src/client/components/workspace/editor/PluginColumn.tsx +32 -0
  59. package/src/client/components/workspace/editor/QuickOpenModal.tsx +146 -0
  60. package/src/client/components/workspace/editor/SaveAsModal.tsx +175 -0
  61. package/src/client/components/workspace/editor/SplitColumn.tsx +98 -0
  62. package/src/client/components/workspace/editor/SplitPane.tsx +57 -0
  63. package/src/client/components/workspace/editor/StatusBar.tsx +106 -0
  64. package/src/client/components/workspace/editor/TabContextMenu.tsx +75 -0
  65. package/src/client/components/workspace/editor/Tabs.tsx +195 -18
  66. package/src/client/components/workspace/editor/Toolbar.tsx +54 -181
  67. package/src/client/components/workspace/editor/index.tsx +199 -189
  68. package/src/client/components/workspace/editor/props.ts +64 -0
  69. package/src/client/components/workspace/editor/toolbar-clusters.tsx +300 -0
  70. package/src/client/components/workspace/file-explorer/Modals.tsx +14 -1
  71. package/src/client/components/workspace/file-explorer/TreeItem.tsx +2 -1
  72. package/src/client/components/workspace/file-explorer/clipboard.test.ts +3 -1
  73. package/src/client/components/workspace/file-explorer/index.test.ts +61 -0
  74. package/src/client/components/workspace/file-explorer/index.tsx +10 -48
  75. package/src/client/components/workspace/file-explorer/local-edit.test.ts +8 -3
  76. package/src/client/components/workspace/search-panel/Body.tsx +6 -1
  77. package/src/client/hooks/chat/composer/file-drop.ts +22 -37
  78. package/src/client/hooks/chat/composer/pipeline.test.ts +76 -0
  79. package/src/client/hooks/chat/composer/pipeline.ts +12 -1
  80. package/src/client/hooks/editor/caret-position.test.ts +58 -0
  81. package/src/client/hooks/editor/caret-position.ts +48 -0
  82. package/src/client/hooks/editor/file-editor-types.ts +200 -0
  83. package/src/client/hooks/editor/find-history.test.ts +132 -0
  84. package/src/client/hooks/editor/find-history.ts +46 -0
  85. package/src/client/hooks/editor/find-selection-range.test.ts +100 -0
  86. package/src/client/hooks/editor/find-selection-range.ts +49 -0
  87. package/src/client/hooks/editor/find-state.ts +13 -0
  88. package/src/client/hooks/editor/font.test.ts +0 -93
  89. package/src/client/hooks/editor/indent-settings.test.ts +104 -0
  90. package/src/client/hooks/editor/indent-settings.ts +88 -0
  91. package/src/client/hooks/editor/quick-open.test.ts +141 -0
  92. package/src/client/hooks/editor/quick-open.ts +127 -0
  93. package/src/client/hooks/editor/save-as.test.ts +156 -0
  94. package/src/client/hooks/editor/save-as.ts +122 -0
  95. package/src/client/hooks/editor/save-file.test.ts +179 -0
  96. package/src/client/hooks/editor/save-file.ts +73 -28
  97. package/src/client/hooks/editor/typing-settings.test.ts +73 -0
  98. package/src/client/hooks/editor/typing-settings.ts +65 -0
  99. package/src/client/hooks/editor/use-close-guard.ts +98 -0
  100. package/src/client/hooks/editor/use-editor-drop-overlay.test.ts +159 -0
  101. package/src/client/hooks/editor/use-editor-drop.shell.test.ts +224 -0
  102. package/src/client/hooks/editor/use-editor-drop.ts +58 -68
  103. package/src/client/hooks/editor/use-editor-find.test.ts +2 -2
  104. package/src/client/hooks/editor/use-editor-find.ts +38 -3
  105. package/src/client/hooks/editor/use-editor-panel-keys.ts +152 -0
  106. package/src/client/hooks/editor/use-editor-tab-state.ts +71 -0
  107. package/src/client/hooks/editor/use-external-change-notice.ts +71 -0
  108. package/src/client/hooks/editor/use-external-change.test.ts +88 -0
  109. package/src/client/hooks/editor/use-external-change.ts +146 -0
  110. package/src/client/hooks/editor/use-file-editor.ts +83 -116
  111. package/src/client/hooks/editor/use-file-read.ts +16 -8
  112. package/src/client/hooks/editor/use-file-writes.ts +28 -3
  113. package/src/client/hooks/editor/use-mobile-editor-find.ts +69 -0
  114. package/src/client/hooks/editor/use-mobile-reveal.ts +53 -0
  115. package/src/client/hooks/editor/use-search-reveal-jump.ts +57 -0
  116. package/src/client/hooks/editor/use-split-editor.test.tsx +169 -0
  117. package/src/client/hooks/editor/use-split-editor.ts +91 -0
  118. package/src/client/hooks/editor/use-unload-guard.tsx +117 -0
  119. package/src/client/hooks/editor/use-write-conflict.test.ts +164 -0
  120. package/src/client/hooks/editor/use-write-conflict.ts +152 -0
  121. package/src/client/hooks/editor/wheel-zoom.test.ts +141 -0
  122. package/src/client/hooks/editor/wheel-zoom.ts +96 -0
  123. package/src/client/hooks/ui/drag-presence.test.ts +193 -0
  124. package/src/client/hooks/ui/drag-presence.ts +108 -0
  125. package/src/client/hooks/ui/settings-modal.test.ts +115 -0
  126. package/src/client/hooks/workspace/file-listing.ts +36 -24
  127. package/src/client/hooks/workspace/file-tabs.test.ts +90 -0
  128. package/src/client/hooks/workspace/file-tabs.ts +46 -0
  129. package/src/client/hooks/workspace/file-tree-edits.ts +103 -0
  130. package/src/client/lib/desktop/dropped-paths.ts +83 -0
  131. package/src/client/lib/editor/tab-menu.test.ts +127 -0
  132. package/src/client/lib/editor/tab-menu.ts +127 -0
  133. package/src/client/lib/editor-dirty-tabs.test.ts +102 -0
  134. package/src/client/lib/editor-dirty-tabs.ts +103 -0
  135. package/src/client/lib/native/resume.test.ts +66 -0
  136. package/src/client/lib/native/resume.ts +42 -0
  137. package/src/client/main.tsx +8 -0
  138. package/src/client/tailwind.css +38 -0
  139. package/src/server/lib/bundler/css.test.ts +31 -0
  140. package/src/server/lib/fs/listing.test.ts +81 -16
  141. package/src/server/lib/fs/listing.ts +72 -5
  142. package/src/server/lib/fs/write-conflict.test.ts +68 -0
  143. package/src/server/lib/fs/write-conflict.ts +84 -0
  144. package/src/server/routes/fs/action-save-as.test.ts +82 -0
  145. package/src/server/routes/fs/action.test.ts +82 -0
  146. package/src/server/routes/fs/action.ts +54 -1
  147. package/src/server/routes/fs/exists.ts +11 -1
  148. package/src/server/routes/fs/read.ts +6 -1
  149. package/src/shared/lib/code/editor/find-replace.test.ts +1 -1
  150. package/src/shared/lib/code/editor/find-scan.test.ts +1 -1
  151. package/src/shared/lib/code/editor/find-scan.ts +22 -1
  152. package/src/shared/lib/code/editor/find-selection.test.ts +56 -0
  153. package/src/shared/lib/code/editor/indent-guide-rule.test.ts +65 -0
  154. package/src/shared/lib/code/editor/indent-guide-rule.ts +47 -0
  155. package/src/shared/lib/code/editor/indent-rules.test.ts +219 -0
  156. package/src/shared/lib/code/editor/indent-rules.ts +198 -0
  157. package/src/shared/lib/code/editor/keymap.test.ts +23 -0
  158. package/src/shared/lib/code/editor/keymap.ts +40 -3
  159. package/src/shared/lib/code/editor/palette.test.ts +25 -2
  160. package/src/shared/lib/code/editor/palette.ts +10 -0
  161. package/src/shared/lib/code/editor/stream-modes.ts +225 -0
  162. package/src/shared/lib/code/syntax-highlight.test.ts +1 -1
  163. package/src/shared/lib/fs/file-tree.test.ts +41 -0
  164. package/src/shared/lib/fs/file-tree.ts +126 -34
  165. package/src/shared/lib/fs/folder-chain.test.ts +87 -0
  166. package/src/shared/lib/fs/folder-chain.ts +91 -0
  167. package/src/shared/lib/fs/fs-helpers.test.ts +4 -50
  168. package/src/shared/lib/realtime/connection.test.ts +5 -1
  169. package/src/shared/lib/realtime/connection.ts +25 -119
  170. package/src/shared/lib/realtime/frozen-recovery.test.ts +93 -0
  171. package/src/shared/lib/realtime/resume.ts +223 -0
  172. package/src/shared/lib/realtime/state.ts +22 -0
  173. package/src/shared/lib/realtime/watchdog-wiring.test.ts +224 -0
  174. package/src/shared/lib/realtime/watchdog.test.ts +99 -0
  175. package/src/shared/lib/realtime/watchdog.ts +72 -0
  176. package/src/shared/lib/workspace/split-editor.test.ts +104 -0
  177. package/src/shared/lib/workspace/split-editor.ts +129 -0
  178. package/src/test-support/file-explorer-disk.test-util.ts +30 -3
  179. package/src/test-support/pristine-globals.ts +7 -0
  180. package/dist/client/static/js/index-k315p1e8.css +0 -1
@@ -38,21 +38,40 @@ import {
38
38
  drawSelection,
39
39
  dropCursor,
40
40
  EditorView,
41
+ highlightActiveLine,
42
+ highlightActiveLineGutter,
43
+ highlightSpecialChars,
41
44
  lineNumbers,
42
45
  rectangularSelection,
46
+ scrollPastEnd,
43
47
  } from '@codemirror/view';
48
+ import { highlightSelectionMatches } from '@codemirror/search';
44
49
  import { history } from '@codemirror/commands';
45
- import { indentUnit } from '@codemirror/language';
50
+ import { bracketMatching, foldGutter, indentUnit } from '@codemirror/language';
46
51
 
47
52
  import { commentSyntaxFor } from '@/shared/lib/code/editor/comment-syntax';
48
53
  import type { EditorCommand } from '@/shared/lib/code/editor/keymap';
54
+ import { bracketGuide } from '@/client/components/common/code-surface/bracket-guide';
55
+ import { indentDataExtension, indentExtensions } from '@/client/components/common/code-surface/indent';
56
+ import { typingExtensions, type EditorTypingOptions } from '@/client/components/common/code-surface/typing';
57
+ import { indentFoldService } from '@/client/components/common/code-surface/fold';
58
+ import { indentGuides } from '@/client/components/common/code-surface/indent-guide';
49
59
  import { findMarksField } from '@/client/components/common/code-surface/marks';
50
60
  import { surfaceKeymap } from '@/client/components/common/code-surface/keymap';
51
61
  import { shikiHighlight, type ShikiThemeNames } from '@/client/components/common/code-surface/shiki';
52
62
  import { surfaceTheme } from '@/client/components/common/code-surface/theme';
53
63
 
54
- /** Indentation the surface inserts, in spaces. */
55
- const INDENT = ' ';
64
+ /**
65
+ * The indentation facets, in one extension.
66
+ *
67
+ * `indentUnit` is what a LEVEL is; `EditorState.tabSize` is what a literal TAB
68
+ * character counts as. They travel together because a tab-indented setting makes
69
+ * them the same number (one tab per level), and a reconfigure of one without the
70
+ * other would measure a level wrong.
71
+ */
72
+ export function indentExtension(indentUnitText: string): Extension {
73
+ return [indentUnit.of(indentUnitText), EditorState.tabSize.of(indentUnitText === '\t' ? 1 : indentUnitText.length)];
74
+ }
56
75
 
57
76
  /** Wrap on: CM6 wraps the content box; the panel no longer measures anything. */
58
77
  export function wrapExtension(wordWrap: boolean): Extension {
@@ -86,16 +105,65 @@ export interface SurfaceExtensionsOptions {
86
105
  * exactly where they were.
87
106
  */
88
107
  themeCompartment: Compartment;
108
+ /**
109
+ * Compartment holding the stream language, when one has loaded.
110
+ *
111
+ * Empty on mount: the mode is a lazy import (`stream-language.ts`), so the
112
+ * surface starts with no parser and the compartment is reconfigured when the
113
+ * module lands. That reconfigure keeps the document, the selection and the
114
+ * history — it only swaps the language — which is why it is a compartment and
115
+ * not a re-mount.
116
+ */
117
+ languageCompartment: Compartment;
118
+ /**
119
+ * Compartment holding the indentation unit.
120
+ *
121
+ * A compartment rather than a value baked into the state, because the setting can
122
+ * change while a document is open and a re-mount would drop the undo history. The
123
+ * indent service reads it through `ctx.unit`, so one reconfigure moves every rule
124
+ * that emits an indent — including the tab-size the gutter measures with.
125
+ */
126
+ indentCompartment: Compartment;
127
+ /**
128
+ * Compartment holding auto-close and the completer.
129
+ *
130
+ * A compartment because both are BEHAVIOUR settings that can change while a document is
131
+ * open; a re-mount would drop the undo history for a preference.
132
+ */
133
+ typingCompartment: Compartment;
89
134
  wordWrap: boolean;
90
135
  readOnly: boolean;
91
136
  /** The two Shiki theme names this surface tokenizes with. */
92
137
  themes: ShikiThemeNames;
138
+ /**
139
+ * Auto-close brackets and the document-words completer.
140
+ *
141
+ * BEHAVIOUR, not view: both change what typing does, so both are settings and both
142
+ * arrive as a value rather than being always-on.
143
+ */
144
+ typing: EditorTypingOptions;
145
+ /**
146
+ * One indentation level, as a whitespace string — `indentUnit.of`'s own shape.
147
+ *
148
+ * `' '` by default; `' '` or `'\t'` from the setting. The surface no longer
149
+ * carries its own constant: a 4-space repository was being indented by 2.
150
+ */
151
+ indentUnitText: string;
93
152
  /** Panel-owned commands the editor delegates instead of running. */
94
153
  onCommand?: (command: EditorCommand) => void;
95
154
  /** Fired for every user edit, with the whole new document. */
96
155
  onDocChange: (value: string) => void;
97
156
  /** Fired on every state that must be remembered (an edit or a selection move). */
98
157
  onState: (state: EditorState) => void;
158
+ /**
159
+ * Fired with the caret's line and column whenever either moves.
160
+ *
161
+ * A separate channel from `onState` because the two have different lifetimes:
162
+ * `onState` feeds a per-document cache (and is dropped when the tab closes), while
163
+ * a status readout wants two numbers and nothing else — keeping the state there
164
+ * would pin a whole document snapshot in a component that prints its line number.
165
+ */
166
+ onCaret?: (position: { line: number; column: number }) => void;
99
167
  }
100
168
 
101
169
  /** Everything the editor needs, built once per document state. */
@@ -104,28 +172,89 @@ export function surfaceExtensions({
104
172
  wordWrapCompartment,
105
173
  readOnlyCompartment,
106
174
  themeCompartment,
175
+ languageCompartment,
176
+ indentCompartment,
177
+ typingCompartment,
107
178
  wordWrap,
108
179
  readOnly,
109
180
  themes,
181
+ typing,
182
+ indentUnitText,
110
183
  onCommand,
111
184
  onDocChange,
112
185
  onState,
186
+ onCaret,
113
187
  }: SurfaceExtensionsOptions): Extension[] {
114
188
  return [
115
189
  lineNumbers(),
190
+ // The active line, so a long file says where the caret is without counting.
191
+ // Both halves: the line band and the gutter row, or the number and the row it
192
+ // belongs to disagree about which line is current.
193
+ highlightActiveLine(),
194
+ highlightActiveLineGutter(),
195
+ // Other occurrences of the selection. Capped by the package, and the band is
196
+ // subtler than the find mark's — this is a hint, not a result.
197
+ highlightSelectionMatches(),
198
+ // Room to scroll past the last line, so the end of a file can be centred
199
+ // instead of pinned to the bottom edge.
200
+ scrollPastEnd(),
201
+ // Control characters drawn as their glyph instead of nothing: a stray NUL or a
202
+ // zero-width space is invisible, which makes a corrupted file look fine.
203
+ highlightSpecialChars(),
204
+ // A rule at every nesting level, from indentation (there is no tree). Deliberately
205
+ // dimmer than `bracketGuide`, which draws ONE line between a brace and its pair.
206
+ indentGuides,
116
207
  history(),
117
208
  drawSelection(),
118
209
  dropCursor(),
119
210
  rectangularSelection(),
120
211
  crosshairCursor(),
121
212
  EditorState.allowMultipleSelections.of(true),
122
- indentUnit.of(INDENT),
123
- // `toggleComment` with no grammar: the tokens are the entire input it needs.
124
- // The provider must return an object KEYED by the data name —
213
+ indentCompartment.of(indentExtension(indentUnitText)),
214
+ // The stream language, when one has loaded. It goes BEFORE the manual
215
+ // `languageData` table below because `languageDataAt` returns every
216
+ // provider's answer in order and the commands take the FIRST — measured: a
217
+ // mode first makes `toggleComment` use the mode's own tokens, while the
218
+ // manual table first overrides them (a wrong manual entry won and `##`
219
+ // commented a Rust line).
220
+ //
221
+ // The tree it builds is what makes bracket matching token-aware. A lezer
222
+ // grammar would too, and was rejected on measurement: +39 KB gzip for
223
+ // JavaScript alone, 24 of 59 languages, and WRONG until its lazy parse
224
+ // catches up (3 wrong pairs at mount on a 176-line file).
225
+ languageCompartment.of([]),
226
+ // `toggleComment` with no mode loaded: the tokens are the entire input it
227
+ // needs. The provider must return an object KEYED by the data name —
125
228
  // `languageDataAt` looks the name up in each result, so returning the tokens
126
229
  // bare yields an empty list and the command silently does nothing.
127
230
  EditorState.languageData.of(() => [{ commentTokens: commentTokens(language) }]),
231
+ // Auto-indent, in two parts. `indentOnInput()` reaches the MODE's own
232
+ // `indentOnInput` regexp where one exists (27 of the 48 modes ship one), and
233
+ // the service answers for the 26 languages whose parser answers nothing —
234
+ // it returns `undefined` for the rest, which is what lets the mode win.
235
+ // The data entry is appended AFTER the manual table for the same
236
+ // first-answer-wins reason the mode sits before it: a language with a rule
237
+ // of its own must not be shadowed by a generic one.
238
+ ...indentExtensions(language),
239
+ indentDataExtension(language),
240
+ // Auto-close brackets and the completer. Empty when both settings are off, which is
241
+ // why this is a spread rather than a condition at the call site.
242
+ typingCompartment.of(typingExtensions(typing)),
128
243
  findMarksField,
244
+ // Bracket matching, plus the vertical guide from the caret's brace to its
245
+ // pair. With a stream language loaded the pairing is token-aware; without
246
+ // one it is TEXTUAL, which is right for code and wrong inside a string
247
+ // (`const a = "{";` … `const c = "}"` pairs the two). The guide reads the
248
+ // same `matchBrackets` call, so the line and the highlight cannot disagree.
249
+ bracketMatching(),
250
+ bracketGuide,
251
+ // Folding, on the same reasoning: `foldGutter` supplies the gutter markers
252
+ // and their click, `indentFoldService` answers "is this line foldable" from
253
+ // indentation because `foldNodeProp` needs a tree. `foldGutter` already
254
+ // includes `codeFolding()`, so a `foldEffect` dispatched without it would be
255
+ // dropped silently — verified: no placeholder, no error.
256
+ indentFoldService,
257
+ foldGutter(),
129
258
  themeCompartment.of(shikiHighlight(language, themes)),
130
259
  surfaceTheme(),
131
260
  wordWrapCompartment.of(wrapExtension(wordWrap)),
@@ -152,9 +281,13 @@ export function surfaceExtensions({
152
281
  // caret specs), and nothing in the app reads them.
153
282
  if (update.docChanged || update.selectionSet) {
154
283
  const range = update.state.selection.main;
284
+ const line = update.state.doc.lineAt(range.from);
155
285
  const attrs = update.view.contentDOM.dataset;
156
286
  attrs.selection = `${range.from},${range.to}`;
157
- attrs.line = String(update.state.doc.lineAt(range.from).number);
287
+ attrs.line = String(line.number);
288
+ // 1-based on both axes, and the column counts CHARACTERS — which is what an
289
+ // editor's `Col` shows and what the user's own selection arithmetic gives.
290
+ onCaret?.({ line: line.number, column: range.from - line.from + 1 });
158
291
  }
159
292
  }),
160
293
  surfaceKeymap(onCommand, readOnly),
@@ -0,0 +1,218 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Folding and bracket matching as the COMPONENT mounts them.
8
+ *
9
+ * `fold.test.ts` pins the indent rule in isolation; this file pins that the
10
+ * stack actually wires it, because every way this feature fails is silent:
11
+ *
12
+ * - `foldGutter()` without a `foldService` draws a gutter and offers no marker —
13
+ * the editor looks like it has folding and does not.
14
+ * - A `foldEffect` dispatched into a state with no `foldState` field is
15
+ * DISCARDED with no error (measured: no placeholder, no throw), which is why
16
+ * `foldGutter()` — not `codeFolding()` — is the entry point here: it brings
17
+ * the field.
18
+ * - `bracketMatching()` is a `ViewPlugin`, so a state-level assertion cannot see
19
+ * it at all. The decorations only exist once a view mounts, which is why the
20
+ * bracket cases mount one.
21
+ *
22
+ * The bracket expectations are TEXTUAL, and that is the documented trade: no
23
+ * lezer grammar is installed, so a brace inside a string can be paired with one
24
+ * in another string. `extensions.ts` states the trade; this file makes sure the
25
+ * behaviour that ships is the behaviour that was decided.
26
+ */
27
+
28
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
29
+ import { Window } from 'happy-dom';
30
+ import { Compartment, EditorState } from '@codemirror/state';
31
+ import { EditorView } from '@codemirror/view';
32
+ import { foldEffect, foldedRanges, foldable, foldState } from '@codemirror/language';
33
+
34
+ import { surfaceExtensions } from '@/client/components/common/code-surface/extensions';
35
+ import { SHIKI_THEMES } from '@/shared/lib/code/shiki-themes';
36
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
37
+
38
+ const EXTRA_GLOBALS = ['MutationObserver', 'requestAnimationFrame', 'cancelAnimationFrame'] as const;
39
+ const native: Partial<Record<(typeof EXTRA_GLOBALS)[number], unknown>> = {};
40
+
41
+ let host: HTMLElement;
42
+
43
+ beforeAll(() => {
44
+ const win = new Window({ url: 'http://localhost' });
45
+ installDomGlobals(win);
46
+ const target = globalThis as unknown as Record<string, unknown>;
47
+ for (const key of EXTRA_GLOBALS) {
48
+ native[key] = target[key];
49
+ target[key] = (win as unknown as Record<string, unknown>)[key];
50
+ }
51
+ host = document.body.appendChild(document.createElement('div'));
52
+ });
53
+
54
+ afterAll(() => {
55
+ const target = globalThis as unknown as Record<string, unknown>;
56
+ for (const key of EXTRA_GLOBALS) {
57
+ if (native[key] === undefined) delete target[key];
58
+ else target[key] = native[key];
59
+ }
60
+ restoreDomGlobals();
61
+ });
62
+
63
+ /** A state from the component's own stack. */
64
+ function stateFor(language: string, doc: string, readOnly = false): EditorState {
65
+ return EditorState.create({
66
+ doc,
67
+ extensions: surfaceExtensions({
68
+ language,
69
+ wordWrapCompartment: new Compartment(),
70
+ readOnlyCompartment: new Compartment(),
71
+ themeCompartment: new Compartment(),
72
+ languageCompartment: new Compartment(),
73
+ indentCompartment: new Compartment(),
74
+ typingCompartment: new Compartment(),
75
+ indentUnitText: ' ',
76
+ typing: { autoCloseBrackets: false, autocomplete: false },
77
+ wordWrap: false,
78
+ readOnly,
79
+ themes: SHIKI_THEMES,
80
+ onDocChange: () => {},
81
+ onState: () => {},
82
+ }),
83
+ });
84
+ }
85
+
86
+ describe('folding', () => {
87
+ test('the stack installs the fold state, so a fold effect is not discarded', () => {
88
+ const state = stateFor('typescript', 'function f() {\n a();\n}\n');
89
+ expect(state.field(foldState, false)).toBeDefined();
90
+ });
91
+
92
+ test('CM6’s own foldable() agrees with the indent rule', () => {
93
+ // `foldable` is what the gutter marker and the fold commands both ask; a
94
+ // service that is registered but never consulted would look identical to a
95
+ // working one from the rule's own tests.
96
+ const state = stateFor('typescript', 'function f() {\n a();\n b();\n}\nafter();\n');
97
+ const line = state.doc.line(1);
98
+ expect(foldable(state, line.from, line.to)).toEqual({
99
+ from: line.to,
100
+ to: state.doc.line(3).to,
101
+ });
102
+ });
103
+
104
+ test('a plain line is not foldable', () => {
105
+ const state = stateFor('typescript', 'const a = 1;\n');
106
+ const line = state.doc.line(1);
107
+ expect(foldable(state, line.from, line.to)).toBeNull();
108
+ });
109
+
110
+ test('folding a range hides its lines and leaves the placeholder', () => {
111
+ const view = new EditorView({
112
+ parent: host,
113
+ state: stateFor('typescript', 'function f() {\n a();\n b();\n}\nafter();\n'),
114
+ });
115
+ try {
116
+ const line = view.state.doc.line(1);
117
+ view.dispatch({
118
+ effects: foldEffect.of({ from: line.to, to: view.state.doc.line(3).to }),
119
+ });
120
+ expect(view.contentDOM.querySelector('.cm-foldPlaceholder')).not.toBeNull();
121
+ const ranges: string[] = [];
122
+ foldedRanges(view.state).between(0, view.state.doc.length, (from, to) => {
123
+ ranges.push(`${from}-${to}`);
124
+ });
125
+ expect(ranges).toEqual([`${line.to}-${view.state.doc.line(3).to}`]);
126
+ } finally {
127
+ view.destroy();
128
+ }
129
+ });
130
+
131
+ test('a read-only viewer still folds — the diff panel and chat cards rely on it', () => {
132
+ const view = new EditorView({
133
+ parent: host,
134
+ state: stateFor('typescript', 'function f() {\n a();\n}\n', true),
135
+ });
136
+ try {
137
+ const line = view.state.doc.line(1);
138
+ view.dispatch({ effects: foldEffect.of({ from: line.to, to: view.state.doc.line(2).to }) });
139
+ expect(view.contentDOM.querySelector('.cm-foldPlaceholder')).not.toBeNull();
140
+ } finally {
141
+ view.destroy();
142
+ }
143
+ });
144
+
145
+ test('the gutter offers a marker on a foldable line and none on a plain one', () => {
146
+ const view = new EditorView({
147
+ parent: host,
148
+ state: stateFor('typescript', 'function f() {\n a();\n}\nconst x = 1;\n'),
149
+ });
150
+ try {
151
+ // `foldGutter` draws an `initialSpacer` marker that reserves the gutter's
152
+ // width: it is a real `.cm-gutterElement` with `visibility: hidden`, so a
153
+ // count over that selector includes it. Only the visible ones are markers
154
+ // the reader can click.
155
+ const markers = Array.from(view.dom.querySelectorAll('.cm-foldGutter .cm-gutterElement span')).filter(
156
+ (node) => !(node.parentElement?.getAttribute('style') ?? '').includes('hidden'),
157
+ );
158
+ // One marker: the foldable line. `const x = 1;` is not foldable.
159
+ expect(markers.length).toBe(1);
160
+ expect(markers[0]?.textContent).toBe('⌄');
161
+ } finally {
162
+ view.destroy();
163
+ }
164
+ });
165
+
166
+ test('a document with nothing foldable draws no visible marker', () => {
167
+ const view = new EditorView({ parent: host, state: stateFor('typescript', 'const a = 1;\nconst b = 2;\n') });
168
+ try {
169
+ const markers = Array.from(view.dom.querySelectorAll('.cm-foldGutter .cm-gutterElement span')).filter(
170
+ (node) => !(node.parentElement?.getAttribute('style') ?? '').includes('hidden'),
171
+ );
172
+ expect(markers).toEqual([]);
173
+ } finally {
174
+ view.destroy();
175
+ }
176
+ });
177
+ });
178
+
179
+ describe('bracket matching', () => {
180
+ /** The classes `bracketMatching()` painted for the caret at `pos`. */
181
+ function marksFor(doc: string, pos: number): string[] {
182
+ const view = new EditorView({ parent: host, state: stateFor('typescript', doc) });
183
+ try {
184
+ view.dispatch({ selection: { anchor: pos } });
185
+ return Array.from(view.contentDOM.querySelectorAll('.cm-matchingBracket, .cm-nonmatchingBracket')).map(
186
+ (node) => node.textContent ?? '',
187
+ );
188
+ } finally {
189
+ view.destroy();
190
+ }
191
+ }
192
+
193
+ test('the caret next to an opening brace paints both ends of the pair', () => {
194
+ const doc = 'function f() {\n a();\n}\n';
195
+ expect(marksFor(doc, doc.indexOf('{') + 1)).toEqual(['{', '}']);
196
+ });
197
+
198
+ test('the caret next to the CLOSING brace paints the same pair', () => {
199
+ const doc = 'function f() {\n a();\n}\n';
200
+ const closing = doc.lastIndexOf('}');
201
+ expect(marksFor(doc, closing)).toEqual(['{', '}']);
202
+ });
203
+
204
+ test('an unmatched brace is painted as unmatched rather than left blank', () => {
205
+ const doc = 'function f() {\n a();\n';
206
+ const view = new EditorView({ parent: host, state: stateFor('typescript', doc) });
207
+ try {
208
+ view.dispatch({ selection: { anchor: doc.indexOf('{') + 1 } });
209
+ expect(view.contentDOM.querySelectorAll('.cm-nonmatchingBracket').length).toBe(1);
210
+ } finally {
211
+ view.destroy();
212
+ }
213
+ });
214
+
215
+ test('a caret in ordinary text paints nothing', () => {
216
+ expect(marksFor('const alpha = 1;\n', 8)).toEqual([]);
217
+ });
218
+ });
@@ -0,0 +1,148 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The indent fold rule, and the two ways it can be wrong.
8
+ *
9
+ * This surface has no lezer parser, so folding is answered from indentation
10
+ * alone. That makes the RULE the whole feature: a wrong boundary folds the next
11
+ * function into this one, and a missing cap turns one gutter repaint into a walk
12
+ * over half a million lines.
13
+ *
14
+ * The assertions are on `indentFoldRange` rather than on a rendered gutter
15
+ * because the rule is the contract; `extensions.test.ts` mounts the real stack
16
+ * and checks that CM6's own `foldable()` agrees with it.
17
+ */
18
+
19
+ import { describe, expect, test } from 'bun:test';
20
+ import { EditorState } from '@codemirror/state';
21
+
22
+ import { indentFoldRange, MAX_FOLD_LINES } from '@/client/components/common/code-surface/fold';
23
+
24
+ function stateOf(doc: string): EditorState {
25
+ return EditorState.create({ doc });
26
+ }
27
+
28
+ /** The fold for line `number` (1-based), as `[startLine, endLine]` or null. */
29
+ function foldAt(state: EditorState, number: number): [number, number] | null {
30
+ const line = state.doc.line(number);
31
+ const range = indentFoldRange(state, line.from, line.to);
32
+ if (!range) return null;
33
+ return [state.doc.lineAt(range.from).number, state.doc.lineAt(range.to).number];
34
+ }
35
+
36
+ describe('indentFoldRange', () => {
37
+ test('a block folds up to the last line indented deeper than its opener', () => {
38
+ const state = stateOf('function f() {\n a();\n b();\n}\nafter();\n');
39
+ expect(foldAt(state, 1)).toEqual([1, 3]);
40
+ });
41
+
42
+ test('a nested block folds to its OWN end, not the outer one', () => {
43
+ const state = stateOf('function f() {\n if (a) {\n b();\n }\n return 1;\n}\n');
44
+ // The outer block runs to line 5 — the last line indented deeper than the
45
+ // opener, which is ` return 1;` (the closing brace dedents).
46
+ expect(foldAt(state, 1)).toEqual([1, 5]);
47
+ // The inner one stops at its own last child: line 4 is ` }`, at the same
48
+ // width as line 2, so the block ends at line 3.
49
+ expect(foldAt(state, 2)).toEqual([2, 3]);
50
+ });
51
+
52
+ test('a blank line does not end a block', () => {
53
+ const state = stateOf('function f() {\n a();\n\n b();\n}\n');
54
+ expect(foldAt(state, 1)).toEqual([1, 4]);
55
+ });
56
+
57
+ test('a line with nothing deeper after it is not foldable', () => {
58
+ const state = stateOf('const a = 1;\nconst b = 2;\n');
59
+ expect(foldAt(state, 1)).toBeNull();
60
+ expect(foldAt(state, 2)).toBeNull();
61
+ });
62
+
63
+ test('a one-line block does not fold, because nothing is deeper', () => {
64
+ // Deliberate: the rule measures indentation, and there is none. A grammar
65
+ // would know `{ … }` is a block; this surface has no grammar.
66
+ const state = stateOf('if (a) { b(); }\nnext();\n');
67
+ expect(foldAt(state, 1)).toBeNull();
68
+ });
69
+
70
+ test('a blank line is never an opener', () => {
71
+ const state = stateOf('\n indented();\n');
72
+ expect(foldAt(state, 1)).toBeNull();
73
+ });
74
+
75
+ test('the fold starts after the opener LINE, so the opener stays visible', () => {
76
+ const state = stateOf('function f() {\n a();\n}\n');
77
+ const line = state.doc.line(1);
78
+ const range = indentFoldRange(state, line.from, line.to);
79
+ expect(range?.from).toBe(line.to);
80
+ });
81
+
82
+ test('the range ends at the last child line, not at the closing brace', () => {
83
+ const doc = 'function f() {\n a();\n}\n';
84
+ const state = stateOf(doc);
85
+ const range = indentFoldRange(state, 0, state.doc.line(1).to);
86
+ expect(range?.to).toBe(state.doc.line(2).to);
87
+ });
88
+
89
+ test('a block that runs past the cap is REFUSED, not truncated', () => {
90
+ // A truncated fold would end at a line the reader never chose. 200 000
91
+ // indented lines is the shape that made this necessary (a generated JSON).
92
+ const state = stateOf('function f() {\n' + ' x();\n'.repeat(MAX_FOLD_LINES + 100) + '}\n');
93
+ expect(foldAt(state, 1)).toBeNull();
94
+ });
95
+
96
+ test('a block that fits the cap still folds', () => {
97
+ const state = stateOf('function f() {\n' + ' x();\n'.repeat(50) + '}\n');
98
+ expect(foldAt(state, 1)).toEqual([1, 51]);
99
+ });
100
+
101
+ test('a block that ends exactly at the document end is not mistaken for a capped one', () => {
102
+ // The cap is `lastLine < doc.lines`; a block whose children reach the last
103
+ // line must still fold, or every file without a trailing newline's tail
104
+ // block would be unfolderable.
105
+ const state = stateOf('function f() {\n a();\n b();');
106
+ expect(foldAt(state, 1)).toEqual([1, 3]);
107
+ });
108
+
109
+ test('tabs count as indentation', () => {
110
+ const state = stateOf('function f() {\n\ta();\n}\n');
111
+ expect(foldAt(state, 1)).toEqual([1, 2]);
112
+ });
113
+
114
+ test('a sibling line at the same width means there is nothing to fold', () => {
115
+ // The rule is strictly DEEPER. Two lines at the same indent are siblings,
116
+ // so the first has no body of its own.
117
+ const state = stateOf(' a();\n b();\nc();\n');
118
+ expect(foldAt(state, 1)).toBeNull();
119
+ });
120
+
121
+ test('a dedent after some children ends the block there', () => {
122
+ const state = stateOf(' a();\n b();\n c();\nd();\n');
123
+ expect(foldAt(state, 1)).toEqual([1, 2]);
124
+ });
125
+
126
+ test('yaml, python and json fold by the same rule', () => {
127
+ // The point of indentation over a grammar: one rule, every language.
128
+ const yaml = stateOf('services:\n web:\n image: nginx\n db:\n image: pg\nother: 1\n');
129
+ // `services:` owns lines 2-5 (both service entries and both images).
130
+ expect(foldAt(yaml, 1)).toEqual([1, 5]);
131
+ expect(foldAt(yaml, 2)).toEqual([2, 3]);
132
+
133
+ const python = stateOf('def f(a):\n if a:\n return 1\n return 0\n\nclass C:\n x = 1\n');
134
+ expect(foldAt(python, 1)).toEqual([1, 4]);
135
+ expect(foldAt(python, 2)).toEqual([2, 3]);
136
+
137
+ const json = stateOf('{\n "a": {\n "b": 1\n }\n}\n');
138
+ expect(foldAt(json, 1)).toEqual([1, 4]);
139
+ expect(foldAt(json, 2)).toEqual([2, 3]);
140
+ });
141
+
142
+ test('markdown folds nothing, because a flat list has no indentation', () => {
143
+ const state = stateOf('# Title\n\n- a\n- b\n\n## Sub\n\ntext\n');
144
+ for (let number = 1; number <= state.doc.lines; number++) {
145
+ expect(foldAt(state, number)).toBeNull();
146
+ }
147
+ });
148
+ });