@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
@@ -0,0 +1,123 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Loading a stream mode on demand, and telling the surface when it lands.
8
+ *
9
+ * The mode table is 49 entries but the modules behind them are lazy for the same
10
+ * reason `LANG_LOADERS` is: all 38 modes in one bundle is +85 KB gzip, and a tab
11
+ * opened on a README should pay for none of it. A mode is fetched the first time
12
+ * a document in that language is opened.
13
+ *
14
+ * The notification exists because a `StreamLanguage` is a COMPARTMENT payload:
15
+ * the surface mounts with none, and the tree (and therefore token-aware bracket
16
+ * matching) only exists after the reconfigure. Without the signal a file would
17
+ * keep the textual matcher for its whole life, with nothing on screen to say a
18
+ * better answer was available.
19
+ *
20
+ * Shaped after `theme-loader.ts`, deliberately: same per-process registry on a
21
+ * module-level map, same in-flight dedupe, same "never reject" contract — a mode
22
+ * that fails to load leaves the textual matcher, which is a worse answer rather
23
+ * than a broken editor.
24
+ */
25
+
26
+ import type { StreamLanguage } from '@codemirror/language';
27
+ import { streamModeLoader, STREAM_MODE_EXPORTS } from '@/shared/lib/code/editor/stream-modes';
28
+
29
+ /**
30
+ * A defined stream language — the CM6 extension a mode becomes.
31
+ *
32
+ * Named here rather than spelled `ReturnType<typeof StreamLanguage.define>`
33
+ * because the type argument is what a consumer holds; the alias keeps the
34
+ * generic out of every call site.
35
+ */
36
+ export type StreamLanguageInstance = StreamLanguage<unknown>;
37
+
38
+ /** Ids whose mode is loaded and ready to install. */
39
+ const loaded = new Map<string, StreamLanguageInstance>();
40
+ /** In-flight loads, so two surfaces on one language share a fetch. */
41
+ const pending = new Map<string, Promise<StreamLanguageInstance | null>>();
42
+ const listeners = new Set<(language: string) => void>();
43
+
44
+ function notifyReady(language: string): void {
45
+ for (const listener of [...listeners]) {
46
+ try {
47
+ listener(language);
48
+ } catch {
49
+ // A listener must never break the others.
50
+ }
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Fires when a mode lands, so a surface that mounted without it can reconfigure.
56
+ *
57
+ * Keyed by SHIKI id, not by mode name: that is what the surface holds.
58
+ */
59
+ export function onStreamModeReady(listener: (language: string) => void): () => void {
60
+ listeners.add(listener);
61
+ return () => {
62
+ listeners.delete(listener);
63
+ };
64
+ }
65
+
66
+ /** The mode for `language` if it is already loaded, else null. */
67
+ export function readyStreamMode(language: string): StreamLanguageInstance | null {
68
+ return loaded.get(language) ?? null;
69
+ }
70
+
71
+ /**
72
+ * Load and register the mode for a Shiki id.
73
+ *
74
+ * Resolves `null` for a language this build has no mode for (the honest answer
75
+ * for markdown, html, graphql, …) and for one whose module fails to load. Never
76
+ * rejects: the caller keeps the textual matcher.
77
+ */
78
+ export function loadStreamMode(language: string): Promise<StreamLanguageInstance | null> {
79
+ const ready = loaded.get(language);
80
+ if (ready) return Promise.resolve(ready);
81
+
82
+ const inFlight = pending.get(language);
83
+ if (inFlight) return inFlight;
84
+
85
+ const loader = streamModeLoader(language);
86
+ const exportName = STREAM_MODE_EXPORTS[language];
87
+ if (!loader || !exportName) return Promise.resolve(null);
88
+
89
+ const load = (async () => {
90
+ try {
91
+ const [module, languageModule] = await Promise.all([
92
+ // The LOADER, not a template specifier: a template literal builds but
93
+ // never resolves at runtime in the dev server (measured — the mode
94
+ // silently failed to load and the surface stayed textual).
95
+ loader(),
96
+ import('@codemirror/language'),
97
+ ]);
98
+ const mode = (module as Record<string, unknown>)[exportName];
99
+ if (!mode) return null;
100
+ // `StreamLanguage.define` is the only constructor; the mode object alone is
101
+ // not an extension.
102
+ const instance = languageModule.StreamLanguage.define(mode as never);
103
+ loaded.set(language, instance);
104
+ notifyReady(language);
105
+ return instance;
106
+ } catch {
107
+ // Left out of `loaded`, so a later attempt can still succeed.
108
+ return null;
109
+ } finally {
110
+ pending.delete(language);
111
+ }
112
+ })();
113
+
114
+ pending.set(language, load);
115
+ return load;
116
+ }
117
+
118
+ /** Test seam: forget every registration. */
119
+ export function resetStreamModes(): void {
120
+ loaded.clear();
121
+ pending.clear();
122
+ listeners.clear();
123
+ }
@@ -98,6 +98,39 @@ describe('surface theme', () => {
98
98
  expect(css).toContain('var(--shiki-dark)');
99
99
  });
100
100
 
101
+ test('the bracket pair is painted from the palette, and the FOCUSED rule outranks the package', () => {
102
+ const css = themeCss();
103
+ // The package's own colours are hardcoded hex (`#328c8252`); a themed app
104
+ // that did not restate them showed the package's green.
105
+ expect(css).not.toContain('#328c8252');
106
+ expect(css).toContain('.cm-matchingBracket');
107
+ expect(css).toContain('.cm-nonmatchingBracket');
108
+ // The load-bearing half: the package spells its rule `.ͼ1.cm-focused …`
109
+ // (specificity 0,2,0), so a bare `.cm-matchingBracket` here is 0,1,1 and
110
+ // loses. The focused form must be present or the editor is unthemed while
111
+ // it has focus — which is whenever anyone is looking at it.
112
+ const focused = /\.\S+\.cm-focused \.cm-matchingBracket \{[^}]*background-color: color-mix/.test(css);
113
+ expect(focused).toBe(true);
114
+ });
115
+
116
+ test('the fold placeholder is declared LONGHAND, because style-mod cannot parse a var() shorthand', () => {
117
+ const css = themeCss();
118
+ // Measured: `border: 1px solid var(--x)` is expanded by style-mod into
119
+ // `border-width: var(--x); border-style: var(--x)` — garbage that paints
120
+ // nothing. The longhand form sidesteps the expansion entirely.
121
+ expect(css).toContain('.cm-foldPlaceholder');
122
+ expect(css).not.toMatch(/\.cm-foldPlaceholder \{[^}]*border: 1px solid var\(/);
123
+ expect(css).toMatch(/\.cm-foldPlaceholder \{[^}]*border-width: 1px/);
124
+ expect(css).toMatch(/\.cm-foldPlaceholder \{[^}]*border-style: solid/);
125
+ expect(css).toMatch(/\.cm-foldPlaceholder \{[^}]*border-color: /);
126
+ });
127
+
128
+ test('the fold gutter’s glyph is styled, so its box does not shift as blocks open', () => {
129
+ const css = themeCss();
130
+ expect(css).toContain('.cm-foldGutter .cm-gutterElement');
131
+ expect(css).toContain('min-width: 1.1rem');
132
+ });
133
+
101
134
  test('writing the theme variables on the host repaints without a transaction', () => {
102
135
  const view = new EditorView({ parent: host, state: EditorState.create({ doc: 'const a = 1;', extensions: [surfaceTheme()] }) });
103
136
  try {
@@ -123,6 +156,8 @@ describe('document cache theme reconfigure', () => {
123
156
  wordWrap: false,
124
157
  readOnly: false,
125
158
  themes: SHIKI_THEMES,
159
+ indentUnitText: ' ',
160
+ typing: { autoCloseBrackets: false, autocomplete: false },
126
161
  onDocChange: () => {},
127
162
  onState: () => {},
128
163
  });
@@ -133,10 +168,10 @@ describe('document cache theme reconfigure', () => {
133
168
  documents.stateFor('a', 'typescript', 'const a = 1;');
134
169
 
135
170
  // Nothing moved: no effects, which is what keeps a re-render free.
136
- expect(documents.optionsEffects({ wordWrap: false, readOnly: false, themes: SHIKI_THEMES }, 'a')).toEqual([]);
171
+ expect(documents.optionsEffects({ wordWrap: false, readOnly: false, themes: SHIKI_THEMES, indentUnitText: ' ', typing: { autoCloseBrackets: false, autocomplete: false } }, 'a')).toEqual([]);
137
172
 
138
173
  const effects = documents.optionsEffects(
139
- { wordWrap: false, readOnly: false, themes: { light: 'dracula', dark: 'dracula' } },
174
+ { wordWrap: false, readOnly: false, themes: { light: 'dracula', dark: 'dracula' }, indentUnitText: ' ', typing: { autoCloseBrackets: false, autocomplete: false } },
140
175
  'a',
141
176
  );
142
177
  expect(effects).toHaveLength(1);
@@ -146,7 +181,7 @@ describe('document cache theme reconfigure', () => {
146
181
  const documents = cache();
147
182
  documents.stateFor('a', 'typescript', 'x');
148
183
  const effects = documents.optionsEffects(
149
- { wordWrap: true, readOnly: false, themes: { light: 'nord', dark: 'nord' } },
184
+ { wordWrap: true, readOnly: false, themes: { light: 'nord', dark: 'nord' }, indentUnitText: ' ', typing: { autoCloseBrackets: false, autocomplete: false } },
150
185
  'a',
151
186
  );
152
187
  // Two compartments: one for the wrap, one for the tokenizer.
@@ -175,7 +210,7 @@ describe('document cache theme reconfigure', () => {
175
210
  const documents = cache();
176
211
  documents.stateFor('a', 'typescript', 'a');
177
212
  documents.optionsEffects(
178
- { wordWrap: false, readOnly: false, themes: { light: 'dracula', dark: 'dracula' } },
213
+ { wordWrap: false, readOnly: false, themes: { light: 'dracula', dark: 'dracula' }, indentUnitText: ' ', typing: { autoCloseBrackets: false, autocomplete: false } },
179
214
  'a',
180
215
  );
181
216
  // `currentEffects` is the re-apply `view.setState` owes: a cached state
@@ -192,7 +227,7 @@ describe('document cache theme reconfigure', () => {
192
227
 
193
228
  // Pick the theme while `a` is the live document, then switch to `b` — the
194
229
  // apply path reconfigures BOTH, which is what makes them agree.
195
- documents.optionsEffects({ wordWrap: false, readOnly: false, themes: dracula }, 'a');
230
+ documents.optionsEffects({ wordWrap: false, readOnly: false, themes: dracula, indentUnitText: ' ', typing: { autoCloseBrackets: false, autocomplete: false } }, 'a');
196
231
  documents.currentEffects('b');
197
232
  // ... and back: `a` already holds the theme, so there is nothing to rebuild.
198
233
  const effects = documents.currentEffects('a');
@@ -78,6 +78,94 @@ export function surfaceTheme(): Extension {
78
78
  minWidth: '1.5rem',
79
79
  textAlign: 'right',
80
80
  },
81
+ // The fold gutter, beside the line numbers. Its marker is a text glyph
82
+ // (`⌄` / `›`) inside a span, so the box needs a fixed width or the gutter
83
+ // shifts sideways as a block opens and closes.
84
+ '.cm-foldGutter .cm-gutterElement': {
85
+ padding: '0 4px 0 2px',
86
+ minWidth: '1.1rem',
87
+ textAlign: 'center',
88
+ },
89
+ '.cm-foldGutter .cm-gutterElement span': {
90
+ display: 'inline-block',
91
+ width: '100%',
92
+ cursor: 'pointer',
93
+ color: 'color-mix(in srgb, var(--theme-ink) 45%, transparent)',
94
+ },
95
+ '.cm-foldGutter .cm-gutterElement span:hover': { color: 'var(--theme-ink)' },
96
+ // A folded range's own `…`. Two facts about this rule are load-bearing.
97
+ //
98
+ // 1. The declarations are LONGHAND. `border: 1px solid var(--x)` is a
99
+ // shorthand style-mod tries to EXPAND, and it cannot parse a `var()` —
100
+ // measured: it emits `border-width: var(--theme-ink)` and
101
+ // `border-style: var(--theme-ink)`, i.e. garbage that paints nothing.
102
+ // `borderWidth` / `borderStyle` / `borderColor` sidestep the expansion.
103
+ // 2. The package's own rule is `.ͼ1 .cm-foldPlaceholder` (0,1,0) and ours is
104
+ // `.ͼN .cm-foldPlaceholder` (0,1,0) too — a tie, so ORDER decides, and
105
+ // CM6 mounts our theme after the base one. Verified: our rule is emitted
106
+ // last and wins.
107
+ '.cm-foldPlaceholder': {
108
+ backgroundColor: 'color-mix(in srgb, var(--theme-ink) 7%, var(--theme-canvas))',
109
+ borderWidth: '1px',
110
+ borderStyle: 'solid',
111
+ borderColor: 'color-mix(in srgb, var(--theme-ink) 18%, transparent)',
112
+ color: 'color-mix(in srgb, var(--theme-ink) 55%, transparent)',
113
+ borderRadius: '0.2em',
114
+ margin: '0 1px',
115
+ padding: '0 4px',
116
+ cursor: 'pointer',
117
+ },
118
+ // Bracket matching. The pair is painted by `bracketMatching()`, which is
119
+ // TEXTUAL here — see the note in `extensions.ts` — and the package's own
120
+ // colours are hardcoded hex (`#328c8252`), so they are restated from the
121
+ // palette or this is the one surface that ignores the theme.
122
+ //
123
+ // The FOCUSED rule is spelled with `&.cm-focused` because the package's is
124
+ // `.ͼ1.cm-focused .cm-matchingBracket` — specificity (0,2,0). A bare
125
+ // `.cm-matchingBracket` here is (0,1,1) and LOSES, which is why the editor
126
+ // showed the package's green in a themed app.
127
+ '.cm-matchingBracket': {
128
+ backgroundColor: 'color-mix(in srgb, var(--theme-info) 22%, transparent)',
129
+ outlineWidth: '1px',
130
+ outlineStyle: 'solid',
131
+ outlineColor: 'color-mix(in srgb, var(--theme-info) 55%, transparent)',
132
+ },
133
+ '&.cm-focused .cm-matchingBracket': {
134
+ backgroundColor: 'color-mix(in srgb, var(--theme-info) 30%, transparent)',
135
+ },
136
+ '.cm-nonmatchingBracket': {
137
+ backgroundColor: 'color-mix(in srgb, var(--theme-error) 22%, transparent)',
138
+ outlineWidth: '1px',
139
+ outlineStyle: 'solid',
140
+ outlineColor: 'color-mix(in srgb, var(--theme-error) 60%, transparent)',
141
+ },
142
+ '&.cm-focused .cm-nonmatchingBracket': {
143
+ backgroundColor: 'color-mix(in srgb, var(--theme-error) 30%, transparent)',
144
+ },
145
+ // The bracket pair GUIDE: a vertical rule from the caret's brace to its pair.
146
+ //
147
+ // `--bracket-guide-col` is written per LINE by the decoration, because the
148
+ // column is the opening brace's own — `function f() {` puts the rule at
149
+ // column 13, not at the line's left edge. `ch` is the unit because the
150
+ // surface is monospace on every row.
151
+ //
152
+ // The rule is an absolutely-positioned `::before` on the line rather than a
153
+ // `border-left`, because a border would push the text and a guide must not
154
+ // change the layout. `.cm-line` is `display: block`, so it is the
155
+ // containing block.
156
+ '.cm-line.cm-bracket-guide': { position: 'relative' },
157
+ '.cm-line.cm-bracket-guide::before': {
158
+ content: '""',
159
+ position: 'absolute',
160
+ top: '0',
161
+ bottom: '0',
162
+ // `+ 0.5ch` centres the 1px rule under the brace glyph instead of at its
163
+ // leading edge.
164
+ left: 'calc(var(--bracket-guide-col, 0) * 1ch + 0.5ch)',
165
+ width: '1px',
166
+ backgroundColor: 'color-mix(in srgb, var(--theme-info) 45%, transparent)',
167
+ pointerEvents: 'none',
168
+ },
81
169
  // The selection is drawn by `drawSelection()`; the native one is left to
82
170
  // the browser when the editor is not focused.
83
171
  '.cm-selectionBackground, &.cm-focused .cm-selectionBackground': {
@@ -107,5 +195,30 @@ export function surfaceTheme(): Extension {
107
195
  '.cm-content .shiki-tok': { color: 'var(--shiki-light)' },
108
196
  'html[data-theme-variant="dark"] & .cm-content .shiki-tok': { color: 'var(--shiki-dark)' },
109
197
  '.cm-placeholder': { color: 'color-mix(in srgb, var(--editor-fg, var(--theme-ink)) 35%, transparent)' },
198
+ // The active line. CM6's own colours are hardcoded hex, so they are restated
199
+ // from the palette — the same trap `matchingBracket` documents.
200
+ '.cm-activeLine': {
201
+ backgroundColor: 'var(--editor-active-line, color-mix(in srgb, var(--theme-ink) 4%, transparent))',
202
+ },
203
+ '.cm-activeLineGutter': {
204
+ backgroundColor: 'var(--editor-active-line, color-mix(in srgb, var(--theme-ink) 4%, transparent))',
205
+ color: 'var(--editor-fg, var(--theme-ink))',
206
+ },
207
+ // An indent guide: one rule per nesting level, at the level's column. It must be
208
+ // VISUALLY distinct from the bracket pair guide (which sits under the opening
209
+ // brace), so this is a dim border at the column boundary rather than a band.
210
+ '.cm-indent-guide': {
211
+ backgroundImage:
212
+ 'linear-gradient(to right, var(--editor-indent-guide, color-mix(in srgb, var(--theme-ink) 12%, transparent)) 0 1px, transparent 1px)',
213
+ backgroundRepeat: 'no-repeat',
214
+ backgroundSize: '1px 100%',
215
+ backgroundPosition: 'calc(var(--indent-guide-col, 2ch) - 1px) 0',
216
+ },
217
+ // Other occurrences of the selection. Deliberately SUBTLER than a find match:
218
+ // this is a hint about the word under the caret, and on a common identifier it
219
+ // paints a lot of the viewport.
220
+ '.cm-selectionMatch': {
221
+ backgroundColor: 'var(--editor-selection-match, color-mix(in srgb, var(--theme-info) 14%, transparent))',
222
+ },
110
223
  });
111
224
  }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Auto-close and the document-words completer.
8
+ *
9
+ * The completer's bound is the point: a whole-document scan per keystroke is exactly the
10
+ * cost the CodeMirror migration removed (the old surface re-tokenized the visible window
11
+ * per character). What is pinned here is that the window is a WINDOW, that a short word is
12
+ * not offered, and that the list is capped.
13
+ */
14
+
15
+ import { describe, expect, test } from 'bun:test';
16
+ import { CompletionContext } from '@codemirror/autocomplete';
17
+ import { EditorState } from '@codemirror/state';
18
+
19
+ import {
20
+ COMPLETION_MAX_OPTIONS,
21
+ COMPLETION_MIN_WORD,
22
+ COMPLETION_WINDOW_LINES,
23
+ documentWordCompleter,
24
+ documentWords,
25
+ typingExtensions,
26
+ } from '@/client/components/common/code-surface/typing';
27
+
28
+ describe('documentWords', () => {
29
+ test('collects identifiers, including `$` and `_`', () => {
30
+ expect(documentWords('const alpha = $beta + gamma_one;')).toEqual(
31
+ expect.arrayContaining(['const', 'alpha', '$beta', 'gamma_one']),
32
+ );
33
+ });
34
+
35
+ test('deduplicates', () => {
36
+ expect(documentWords('alpha alpha alpha').filter((word) => word === 'alpha')).toHaveLength(1);
37
+ });
38
+
39
+ test('drops words shorter than the floor', () => {
40
+ // `const` is kept; `ab` is not a useful suggestion.
41
+ expect(documentWords('ab const')).not.toContain('ab');
42
+ expect(COMPLETION_MIN_WORD).toBe(3);
43
+ });
44
+ });
45
+
46
+ describe('documentWordCompleter', () => {
47
+ function complete(doc: string, pos: number, explicit = false) {
48
+ const state = EditorState.create({ doc, selection: { anchor: pos } });
49
+ return documentWordCompleter(new CompletionContext(state, pos, explicit));
50
+ }
51
+
52
+ test('offers words from around the caret when typing an identifier', () => {
53
+ const doc = 'const somethingUseful = 1;\nsome';
54
+ const result = complete(doc, doc.length);
55
+ expect(result).not.toBeNull();
56
+ expect(result!.options.map((option) => option.label)).toContain('somethingUseful');
57
+ });
58
+
59
+ test('a bare keystroke with nothing typed before it offers nothing', () => {
60
+ const doc = 'const alpha = 1; ';
61
+ expect(complete(doc, doc.length)).toBeNull();
62
+ });
63
+
64
+ test('an explicit request offers words even with nothing typed', () => {
65
+ const doc = 'const alpha = 1; ';
66
+ const result = complete(doc, doc.length, true);
67
+ expect(result).not.toBeNull();
68
+ });
69
+
70
+ test('the list is capped, so a common prefix does not paint a thousand rows', () => {
71
+ const doc = Array.from({ length: 400 }, (_, index) => `identifier${index}`).join(' ') + ' ident';
72
+ const result = complete(doc, doc.length);
73
+ expect(result!.options.length).toBeLessThanOrEqual(COMPLETION_MAX_OPTIONS);
74
+ });
75
+
76
+ test('the window is bounded, so a huge file does not offer words from its far end', () => {
77
+ // The document is twice the window: a word only at the top must not be offered from a
78
+ // caret at the bottom.
79
+ const far = Array.from({ length: COMPLETION_WINDOW_LINES * 2 + 20 }, (_, index) => `line${index} filler`).join('\n');
80
+ const doc = `distantIdentifier\n${far}\nident`;
81
+ const result = complete(doc, doc.length);
82
+ const labels = result!.options.map((option) => option.label);
83
+ expect(labels).not.toContain('distantIdentifier');
84
+ });
85
+ });
86
+
87
+ describe('typingExtensions', () => {
88
+ test('both off answers an empty list, which is what makes the setting a real toggle', () => {
89
+ expect(typingExtensions({ autoCloseBrackets: false, autocomplete: false })).toEqual([]);
90
+ });
91
+
92
+ test('either on answers extensions', () => {
93
+ expect(typingExtensions({ autoCloseBrackets: true, autocomplete: false }).length).toBeGreaterThan(0);
94
+ expect(typingExtensions({ autoCloseBrackets: false, autocomplete: true }).length).toBeGreaterThan(0);
95
+ expect(typingExtensions({ autoCloseBrackets: true, autocomplete: true }).length).toBeGreaterThan(1);
96
+ });
97
+ });
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Auto-close brackets and a document-words completer.
8
+ *
9
+ * Both come from `@codemirror/autocomplete`, which is the ONE new dependency the editor
10
+ * has taken since the CM6 migration. `closeBrackets` and `autocompletion` live in it and
11
+ * nowhere else, and a hand-rolled version of either would be a second, worse copy of a
12
+ * well-tested one.
13
+ *
14
+ * ## Both are BEHAVIOUR changes, so both are settings
15
+ *
16
+ * Auto-close alters what typing a `{` does. A document-words completer alters what
17
+ * happens while typing any identifier. Neither is a view preference — a user who does not
18
+ * want them cannot work around them — so each has its own setting, defaulting ON because
19
+ * that is what every editor does.
20
+ *
21
+ * ## The completer is bounded on purpose
22
+ *
23
+ * It reads words from the VIEWPORT (± a window) rather than the whole document: a naive
24
+ * `text.match(/\w+/g)` over a 20 MB file is a scan per keystroke, which is the exact cost
25
+ * the surface was migrated to CM6 to remove. Measured: `const` in this repository matches
26
+ * 19 376 times, and a full-document scan on every completion is not a trade worth making
27
+ * for an identifier that is usually three lines away.
28
+ *
29
+ * This is deliberately NOT LSP. It suggests words that already appear near the caret,
30
+ * which is useful in every language and needs no server.
31
+ */
32
+
33
+ import { type CompletionContext, type CompletionResult, autocompletion, closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete';
34
+ import { type Extension } from '@codemirror/state';
35
+ import { keymap } from '@codemirror/view';
36
+
37
+ /** How far either side of the viewport the completer looks, in lines. */
38
+ export const COMPLETION_WINDOW_LINES = 500;
39
+
40
+ /** Words shorter than this are not offered — a two-letter match is noise. */
41
+ export const COMPLETION_MIN_WORD = 3;
42
+
43
+ /** Cap on the offered list, so a common prefix does not paint a thousand rows. */
44
+ export const COMPLETION_MAX_OPTIONS = 50;
45
+
46
+ /** A word as the completer sees it: identifiers, with `$` and `_` inside them. */
47
+ const WORD = /[\w$]{3,}/g;
48
+
49
+ /**
50
+ * The words around the caret, deduplicated and capped.
51
+ *
52
+ * `doc` is the WHOLE document and `from`/`to` are the window, so the caller decides how
53
+ * much of a large file to look at — this function never walks the whole text.
54
+ */
55
+ export function documentWords(text: string): string[] {
56
+ const seen = new Set<string>();
57
+ for (const match of text.matchAll(WORD)) {
58
+ seen.add(match[0]);
59
+ if (seen.size >= COMPLETION_MAX_OPTIONS * 4) break;
60
+ }
61
+ return [...seen];
62
+ }
63
+
64
+ /**
65
+ * The completer itself.
66
+ *
67
+ * `explicit` (Ctrl+Space) offers everything in the window; a bare keystroke offers only
68
+ * words that START with what has been typed, because a fuzzy match on every keystroke
69
+ * turns a 40-character identifier into a list of unrelated ones.
70
+ */
71
+ export function documentWordCompleter(context: CompletionContext): CompletionResult | null {
72
+ const word = context.matchBefore(WORD);
73
+ if (!word && !context.explicit) return null;
74
+ if (word && word.from === word.to && !context.explicit) return null;
75
+
76
+ // The window is the caret's own lines ± the bound, not the document: the visible text is
77
+ // already what the reader is looking at, and `CompletionContext` carries no viewport
78
+ // (its `view` is optional and absent in synchronous updates).
79
+ const caretLine = context.state.doc.lineAt(context.pos).number;
80
+ const firstLine = Math.max(1, caretLine - COMPLETION_WINDOW_LINES);
81
+ const lastLine = Math.min(context.state.doc.lines, caretLine + COMPLETION_WINDOW_LINES);
82
+ const text = context.state.sliceDoc(
83
+ context.state.doc.line(firstLine).from,
84
+ context.state.doc.line(lastLine).to,
85
+ );
86
+
87
+ const options = documentWords(text)
88
+ .filter((candidate) => candidate.length >= COMPLETION_MIN_WORD)
89
+ .slice(0, COMPLETION_MAX_OPTIONS)
90
+ .map((label) => ({ label }));
91
+
92
+ if (options.length === 0) return null;
93
+ return { from: word ? word.from : context.pos, options };
94
+ }
95
+
96
+ /** What the two settings resolve to. */
97
+ export interface EditorTypingOptions {
98
+ autoCloseBrackets: boolean;
99
+ autocomplete: boolean;
100
+ }
101
+
102
+ /** Both ON — what every editor does, and what a caller that passes nothing gets. */
103
+ export const DEFAULT_EDITOR_TYPING: EditorTypingOptions = { autoCloseBrackets: true, autocomplete: true };
104
+
105
+ /** The extensions for the current settings. An empty list means neither is on. */
106
+ export function typingExtensions({ autoCloseBrackets, autocomplete: complete }: EditorTypingOptions): Extension[] {
107
+ const extensions: Extension[] = [];
108
+ if (autoCloseBrackets) extensions.push(closeBrackets(), keymap.of(closeBracketsKeymap));
109
+ if (complete) extensions.push(autocompletion({ override: [documentWordCompleter], activateOnTyping: true }));
110
+ return extensions;
111
+ }
@@ -123,6 +123,20 @@ async function openMenu(): Promise<void> {
123
123
  });
124
124
  }
125
125
 
126
+ /**
127
+ * The menu lives in `document.body`, NOT inside the row.
128
+ *
129
+ * It is portalled out because the row is `overflow-hidden` and one line tall:
130
+ * an inline `absolute top-full` menu is clipped to nothing, so every row was
131
+ * invisible and unclickable while the trigger said `aria-expanded="true"`
132
+ * (measured: the menu laid out 208×206px and `elementFromPoint` at its centre
133
+ * answered a `.cm-line` in the diff behind it). Querying the menu inside the
134
+ * container would therefore find nothing — which is the bug, not the fixture.
135
+ */
136
+ function menuItems(): HTMLElement[] {
137
+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
138
+ }
139
+
126
140
  describe('ToolbarRow overflow', () => {
127
141
  test('a wide row draws every cluster and no trigger', async () => {
128
142
  await mount(400, [60, 60, 60]);
@@ -144,23 +158,58 @@ describe('ToolbarRow overflow', () => {
144
158
  test('the menu offers the hidden controls, named in words', async () => {
145
159
  await mount(120, [60, 60, 60]);
146
160
  await openMenu();
147
- const items = [...container.querySelectorAll('[role="menuitem"]')].map((item) => item.textContent?.trim());
161
+ const items = menuItems().map((item) => item.textContent?.trim());
148
162
  expect(items).toContain('Word wrap on');
149
163
  // The pinned control is on the row, so it is NOT in the menu.
150
164
  expect(items).not.toContain('Save file');
151
165
  });
152
166
 
167
+ test('the menu is portalled out of the clipping row', async () => {
168
+ await mount(120, [60, 60, 60]);
169
+ await openMenu();
170
+ const menu = document.querySelector('[role="menu"]');
171
+ if (!menu) throw new Error('no menu rendered');
172
+ // The row clips; the menu must not be its descendant.
173
+ expect((container.firstElementChild as HTMLElement).contains(menu)).toBe(false);
174
+ expect(menu.parentElement).toBe(document.body);
175
+ });
176
+
153
177
  test('a menu row runs the same action the button would', async () => {
154
178
  const ran: string[] = [];
155
179
  await mount(120, [60, 60, 60], ran);
156
180
  await openMenu();
157
- const item = [...container.querySelectorAll<HTMLButtonElement>('[role="menuitem"]')].find(
158
- (row) => row.textContent?.trim() === 'Word wrap on',
159
- );
181
+ const item = menuItems().find((row) => row.textContent?.trim() === 'Word wrap on');
160
182
  if (!item) throw new Error('the wrap row is missing from the menu');
161
183
  await act(async () => {
162
184
  item.dispatchEvent(new window.MouseEvent('click', { bubbles: true }) as never);
163
185
  });
164
186
  expect(ran).toEqual(['Word wrap on']);
165
187
  });
188
+
189
+ /**
190
+ * A press on a menu row must not be read as "outside".
191
+ *
192
+ * `useOnClickOutside` watches ONE ref, and the menu is no longer inside the
193
+ * trigger's subtree — so a mousedown on a row closed the menu and the `click`
194
+ * never reached the button. That is the same dead menu in a new shape.
195
+ */
196
+ test('pressing inside the menu keeps it open', async () => {
197
+ const ran: string[] = [];
198
+ await mount(120, [60, 60, 60], ran);
199
+ await openMenu();
200
+ const item = menuItems().find((row) => row.textContent?.trim() === 'Word wrap on');
201
+ if (!item) throw new Error('the wrap row is missing from the menu');
202
+
203
+ await act(async () => {
204
+ item.dispatchEvent(new window.MouseEvent('mousedown', { bubbles: true }) as never);
205
+ });
206
+ // Still open, so the following click can land.
207
+ expect(document.querySelector('[role="menu"]')).not.toBeNull();
208
+
209
+ await act(async () => {
210
+ item.dispatchEvent(new window.MouseEvent('click', { bubbles: true }) as never);
211
+ });
212
+ expect(ran).toEqual(['Word wrap on']);
213
+ expect(document.querySelector('[role="menu"]')).toBeNull();
214
+ });
166
215
  });