@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
@@ -4,12 +4,24 @@
4
4
  */
5
5
 
6
6
  /**
7
- * The write half of the file-editing contract: POST one buffer to
8
- * `/api/fs/action` and report whether the server took it.
7
+ * The write-conflict verdict: "the file on disk moved since you read it".
9
8
  *
10
- * Kept out of `useFileEditor` because the multipart shape, the scope fields and
11
- * the failure rule are one self-contained concern, and because the hook carries
12
- * the read, cache and history concerns already.
9
+ * The save path wrote unconditionally, so two tabs on one file — or one tab and a
10
+ * tool call — silently last-writer-wins. The read route now reports the file's
11
+ * `mtimeMs`, the save sends it back as `baseMtime`, and the server refuses with
12
+ * `409` when the bytes on disk are not the ones the buffer was built from.
13
+ *
14
+ * Three rules make this safe rather than annoying:
15
+ *
16
+ * - **A save with no `baseMtime` keeps the old behaviour.** A handle-backed file
17
+ * (a PWA launch) has no server path and no mtime to send, and an older client
18
+ * sends none; neither may be turned into a refusal.
19
+ * - **A file that does not exist yet is not a conflict.** Creating the file the
20
+ * tab names is what `confirmSaveMissing` exists to allow, and `mtimeMs` is
21
+ * `null` there.
22
+ * - **A refusal is a VERDICT, not a failure.** It carries the current mtime, so
23
+ * the panel can offer "Reload" (discard mine) or "Keep mine" (write anyway,
24
+ * passing the new mtime) instead of reporting that the save failed.
13
25
  */
14
26
 
15
27
  import type { LineEnding } from '@/shared/lib/code/line-endings';
@@ -22,10 +34,27 @@ interface SavableFile {
22
34
  handleId?: string;
23
35
  }
24
36
 
37
+ /** What a save attempt answers. */
38
+ export type SaveOutcome =
39
+ | { status: 'written' }
40
+ /** The buffer is behind the disk copy: `diskMtimeMs` is what is there now. */
41
+ | { status: 'conflict'; diskMtimeMs: number | null }
42
+ /** The write was refused for a reason that is not a conflict (a 4xx/5xx, a drop). */
43
+ | { status: 'failed' }
44
+ /** A handle-backed file needs a user gesture to grant write access. */
45
+ | { status: 'needs-permission' };
46
+
47
+ /** The shape `/api/fs/action` answers for a save. */
48
+ interface SaveResponse {
49
+ success?: unknown;
50
+ error?: unknown;
51
+ /** Present on a `409`: the mtime the file holds now. */
52
+ mtimeMs?: unknown;
53
+ conflict?: unknown;
54
+ }
55
+
25
56
  /**
26
- * Writes `lfText` to `file.path` in the file's own `eol`. Returns false on any
27
- * refusal — a non-2xx response, an `error` body, or a dropped connection —
28
- * because the caller's only decision is whether to mark the buffer clean.
57
+ * Writes `lfText` to `file.path` in the file's own `eol`.
29
58
  *
30
59
  * The ending travels as its own field and the server rebuilds the bytes: a
31
60
  * multipart body normalizes bare LF to CRLF, so the payload cannot carry the
@@ -33,30 +62,37 @@ interface SavableFile {
33
62
  *
34
63
  * A file a PWA launch (or a Finder drop) handed over has NO server-reachable
35
64
  * path — its `path` is only a display name — so the write goes through the live
36
- * handle instead. Sending it to `/api/fs/action` would resolve that name
37
- * against the default root and write an unrelated file, which is why the branch
38
- * comes first and a missing handle is a REFUSAL rather than a fallback.
65
+ * handle instead. Sending it to `/api/fs/action` would resolve that name against
66
+ * the default root and write an unrelated file, which is why the branch comes
67
+ * first and a missing handle is a REFUSAL rather than a fallback.
39
68
  *
40
69
  * `interactive` says whether a user gesture is behind this call (a click, a
41
70
  * Ctrl+S) or a timer (the autosave). It is passed straight through because the
42
- * handle write needs the distinction to decide between asking for permission
43
- * and reporting that a click is required — see `writeThroughHandle`.
71
+ * handle write needs the distinction to decide between asking for permission and
72
+ * reporting that a click is required.
73
+ *
74
+ * `baseMtimeMs` is the mtime the buffer was read from. Omit it for a handle write
75
+ * and for a caller that has none; the server then writes unconditionally, which
76
+ * is the pre-existing contract.
44
77
  */
45
78
  export async function saveEditorFile(
46
79
  file: SavableFile,
47
80
  lfText: string,
48
81
  eol: LineEnding,
49
- options: { interactive: boolean } = { interactive: false },
50
- ): Promise<HandleWriteResult> {
82
+ options: { interactive: boolean; baseMtimeMs?: number | null },
83
+ ): Promise<SaveOutcome> {
51
84
  if (file.handleId) {
52
- // The disk bytes carry the file's own ending; the buffer is LF-only.
53
- return writeThroughHandle(
85
+ const result: HandleWriteResult = await writeThroughHandle(
54
86
  file.handleId,
55
87
  eol === 'crlf' ? lfText.replace(/\n/g, '\r\n') : lfText,
56
88
  { interactive: options.interactive },
57
89
  );
90
+ if (result === 'written') return { status: 'written' };
91
+ if (result === 'needs-permission') return { status: 'needs-permission' };
92
+ return { status: 'failed' };
58
93
  }
59
- if (!file.path) return 'failed';
94
+ if (!file.path) return { status: 'failed' };
95
+
60
96
  const formData = new FormData();
61
97
  formData.append('actionType', 'save');
62
98
  formData.append('path', file.path);
@@ -64,25 +100,34 @@ export async function saveEditorFile(
64
100
  formData.append('eol', eol);
65
101
  if (file.root) formData.append('root', file.root);
66
102
  if (file.repo && file.repo !== '.') formData.append('repo', file.repo);
103
+ // `null`/absent is deliberately NOT sent: the server treats a missing field as
104
+ // "no expectation", and sending the string "null" would fail every save.
105
+ if (typeof options.baseMtimeMs === 'number') formData.append('baseMtime', String(options.baseMtimeMs));
106
+
67
107
  try {
68
108
  const res = await fetch('/api/fs/action', { method: 'POST', body: formData });
69
- const data = await res.json().catch(() => null);
70
- return res.ok && data?.success ? 'written' : 'failed';
109
+ const data = (await res.json().catch(() => null)) as SaveResponse | null;
110
+ if (res.status === 409) {
111
+ const diskMtimeMs = typeof data?.mtimeMs === 'number' ? data.mtimeMs : null;
112
+ return { status: 'conflict', diskMtimeMs };
113
+ }
114
+ if (res.ok && data?.success) return { status: 'written' };
115
+ return { status: 'failed' };
71
116
  } catch {
72
- return 'failed';
117
+ return { status: 'failed' };
73
118
  }
74
119
  }
75
120
 
76
121
  /**
77
- * Keeps only `keep`'s keys, returning the same object when nothing was
78
- * dropped so a render whose tab set is unchanged does not re-key its children.
122
+ * Keeps only `keep`'s keys, returning the same object when nothing was dropped so
123
+ * a render whose tab set is unchanged does not re-key its children.
79
124
  */
80
125
  export function retainKeys<T>(record: Record<string, T>, keep: Set<string>): Record<string, T> {
81
- const keys = Object.keys(record);
82
- if (keys.every((key) => keep.has(key))) return record;
83
126
  const next: Record<string, T> = {};
84
- for (const key of keys) {
85
- if (keep.has(key)) next[key] = record[key];
127
+ let dropped = false;
128
+ for (const [key, value] of Object.entries(record)) {
129
+ if (keep.has(key)) next[key] = value;
130
+ else dropped = true;
86
131
  }
87
- return next;
132
+ return dropped ? next : record;
88
133
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The typing settings.
8
+ *
9
+ * Both default ON — that is what every editor does, and a user who never opens Settings
10
+ * must not get an editor whose typing behaves unlike every other. Each key falls back
11
+ * INDEPENDENTLY, so a stored `autocomplete: false` does not also disable auto-close.
12
+ */
13
+
14
+ import { afterAll, afterEach, describe, expect, test } from 'bun:test';
15
+ import { Window } from 'happy-dom';
16
+
17
+ import {
18
+ DEFAULT_EDITOR_TYPING,
19
+ EDITOR_TYPING_CHANGED_EVENT,
20
+ currentEditorTyping,
21
+ } from '@/client/hooks/editor/typing-settings';
22
+ import { primeKabmoSettings } from '@/shared/lib/settings/client';
23
+
24
+ const DOM_GLOBALS = ['window', 'document', 'navigator', 'Event', 'CustomEvent'] as const;
25
+ const native: Partial<Record<(typeof DOM_GLOBALS)[number], unknown>> = {};
26
+ const win = new Window({ url: 'http://localhost' });
27
+ for (const key of DOM_GLOBALS) {
28
+ const target = globalThis as unknown as Record<string, unknown>;
29
+ native[key] = target[key];
30
+ target[key] = (win as unknown as Record<string, unknown>)[key];
31
+ }
32
+
33
+ afterAll(() => {
34
+ const target = globalThis as unknown as Record<string, unknown>;
35
+ for (const key of DOM_GLOBALS) target[key] = native[key];
36
+ });
37
+
38
+ afterEach(() => {
39
+ primeKabmoSettings({});
40
+ });
41
+
42
+ describe('currentEditorTyping', () => {
43
+ test('both default ON', () => {
44
+ expect(currentEditorTyping()).toEqual(DEFAULT_EDITOR_TYPING);
45
+ expect(DEFAULT_EDITOR_TYPING).toEqual({ autoCloseBrackets: true, autocomplete: true });
46
+ });
47
+
48
+ test('each key falls back on its own', () => {
49
+ primeKabmoSettings({ kabmo_settings: { editorAutocomplete: false } });
50
+ // Turning the completer off must not also turn auto-close off: they are two
51
+ // decisions, and a shared fallback would couple them.
52
+ expect(currentEditorTyping()).toEqual({ autoCloseBrackets: true, autocomplete: false });
53
+
54
+ primeKabmoSettings({ kabmo_settings: { editorAutoCloseBrackets: false } });
55
+ expect(currentEditorTyping()).toEqual({ autoCloseBrackets: false, autocomplete: true });
56
+ });
57
+
58
+ test('a non-boolean value falls back rather than being coerced', () => {
59
+ primeKabmoSettings({ kabmo_settings: { editorAutocomplete: 'no', editorAutoCloseBrackets: 0 } });
60
+ expect(currentEditorTyping()).toEqual(DEFAULT_EDITOR_TYPING);
61
+ });
62
+
63
+ test('an explicit false is honoured, which is the whole point of the setting', () => {
64
+ primeKabmoSettings({ kabmo_settings: { editorAutocomplete: false, editorAutoCloseBrackets: false } });
65
+ expect(currentEditorTyping()).toEqual({ autoCloseBrackets: false, autocomplete: false });
66
+ });
67
+ });
68
+
69
+ describe('the live event', () => {
70
+ test('the name is the one the editor subscribes to', () => {
71
+ expect(EDITOR_TYPING_CHANGED_EVENT).toBe('omp:editor-typing-changed');
72
+ });
73
+ });
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The two BEHAVIOUR settings for the editor: auto-close brackets, and the
8
+ * document-words completer.
9
+ *
10
+ * They are settings rather than always-on because both change what TYPING does. A view
11
+ * preference can be ignored by a user who does not like it; an auto-inserted `}` cannot.
12
+ * Both default ON, because that is what every editor does and a user who has never seen
13
+ * the setting would otherwise wonder why typing is different here.
14
+ *
15
+ * ## The completer is not LSP
16
+ *
17
+ * It suggests words that already appear near the caret. That works in every language with
18
+ * no server, which is the same reason the surface has no grammar — and it is bounded to a
19
+ * window around the caret, because a whole-document scan per keystroke is exactly the cost
20
+ * the CodeMirror migration removed.
21
+ *
22
+ * ## Reaching an open editor
23
+ *
24
+ * Through `omp:editor-typing-changed`, the same shape the font, theme and indent settings
25
+ * use: `appSettings` is a boot-time prop, so a value read once would not reach the editor
26
+ * already on screen.
27
+ */
28
+
29
+ import { useEffect, useState } from 'preact/hooks';
30
+ import { readKabmoSetting } from '@/shared/lib/settings/client';
31
+
32
+ import type { EditorTypingOptions } from '@/client/components/common/code-surface/typing';
33
+
34
+ /** Broadcast on every typing-setting write. Detail is the resolved pair. */
35
+ export const EDITOR_TYPING_CHANGED_EVENT = 'omp:editor-typing-changed';
36
+
37
+ /** Both ON: what every editor does, and what a user who never opens Settings expects. */
38
+ export const DEFAULT_EDITOR_TYPING: EditorTypingOptions = { autoCloseBrackets: true, autocomplete: true };
39
+
40
+ /** The stored pair, falling back per key so one unset does not disable the other. */
41
+ export function currentEditorTyping(): EditorTypingOptions {
42
+ if (typeof window === 'undefined') return DEFAULT_EDITOR_TYPING;
43
+ const close = readKabmoSetting<boolean>('editorAutoCloseBrackets');
44
+ const complete = readKabmoSetting<boolean>('editorAutocomplete');
45
+ return {
46
+ autoCloseBrackets: typeof close === 'boolean' ? close : DEFAULT_EDITOR_TYPING.autoCloseBrackets,
47
+ autocomplete: typeof complete === 'boolean' ? complete : DEFAULT_EDITOR_TYPING.autocomplete,
48
+ };
49
+ }
50
+
51
+ /** The stored pair, kept in step with writes from the settings modal. */
52
+ export function useEditorTyping(): EditorTypingOptions {
53
+ const [typing, setTyping] = useState<EditorTypingOptions>(currentEditorTyping);
54
+
55
+ useEffect(() => {
56
+ const onChange = (event: Event) => {
57
+ const detail = (event as CustomEvent<EditorTypingOptions>).detail;
58
+ setTyping(detail ?? currentEditorTyping());
59
+ };
60
+ window.addEventListener(EDITOR_TYPING_CHANGED_EVENT, onChange);
61
+ return () => window.removeEventListener(EDITOR_TYPING_CHANGED_EVENT, onChange);
62
+ }, []);
63
+
64
+ return typing;
65
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The close guard, as one hook.
8
+ *
9
+ * The panel owns three things here and each needs the others: the dirty set the
10
+ * editor publishes, the tab a close was asked for, and the buffer that has to be
11
+ * written if the answer is "Save & close". Keeping them in the panel pushed that
12
+ * file past the repository's line ceiling, and the cluster is self-contained —
13
+ * one state, one dialog, one decision.
14
+ *
15
+ * ## Why only DIRTY tabs ask
16
+ *
17
+ * A confirm on every close is one people learn to dismiss without reading, which
18
+ * is worse than none. A clean tab closes instantly; the dialog appears only where
19
+ * there is something to lose.
20
+ *
21
+ * ## Why `saveNow` is not enough on its own
22
+ *
23
+ * `saveNow` writes the ACTIVE file. A background tab is saved by activating it
24
+ * first, which is what the panel's `onSelectFile` does — and the activation has
25
+ * to happen BEFORE the save call, because the hook reads its target from the
26
+ * render it was built in.
27
+ */
28
+
29
+ import { useCallback, useState } from 'preact/hooks';
30
+
31
+ import { isTabDirty } from '@/client/lib/editor-dirty-tabs';
32
+ import { useUnloadGuard, type DirtyCloseAnswer } from '@/client/hooks/editor/use-unload-guard';
33
+ import type { OpenedFile } from '@/shared/types/fs';
34
+
35
+ interface UseCloseGuardOptions {
36
+ openedFiles: OpenedFile[];
37
+ activeFileId: number | string | null;
38
+ onSelectFile: (id: number | string) => void;
39
+ onCloseFile: (id: number | string) => void;
40
+ /** Writes the ACTIVE buffer; the caller activates the tab first. */
41
+ saveNow: () => void;
42
+ }
43
+
44
+ export interface CloseGuard {
45
+ /** Close a tab, asking first when it holds edits that are not on disk. */
46
+ requestClose: (id: number | string) => void;
47
+ /** The tab the dialog is asking about, or null. */
48
+ pending: OpenedFile | null;
49
+ /** The dialog's answer. */
50
+ answer: (answer: DirtyCloseAnswer) => void;
51
+ }
52
+
53
+ export function useCloseGuard({
54
+ openedFiles,
55
+ activeFileId,
56
+ onSelectFile,
57
+ onCloseFile,
58
+ saveNow,
59
+ }: UseCloseGuardOptions): CloseGuard {
60
+ const [pending, setPending] = useState<OpenedFile | null>(null);
61
+ // Armed only while something is dirty — see the hook's own note.
62
+ useUnloadGuard();
63
+
64
+ const requestClose = useCallback(
65
+ (id: number | string) => {
66
+ const file = openedFiles.find((entry) => entry.id === id);
67
+ if (file && isTabDirty(id)) {
68
+ setPending(file);
69
+ return;
70
+ }
71
+ onCloseFile(id);
72
+ },
73
+ [openedFiles, onCloseFile],
74
+ );
75
+
76
+ const answer = useCallback(
77
+ (decision: DirtyCloseAnswer) => {
78
+ const file = pending;
79
+ if (!file) return;
80
+ if (decision === 'cancel') {
81
+ setPending(null);
82
+ return;
83
+ }
84
+ if (decision === 'save') {
85
+ // `saveNow` writes the ACTIVE file, so a background tab is activated
86
+ // first. The dialog closes with the tab either way; a failed write is
87
+ // reported by the toolbar's own status, not here.
88
+ if (file.id !== activeFileId) onSelectFile(file.id);
89
+ saveNow();
90
+ }
91
+ setPending(null);
92
+ onCloseFile(file.id);
93
+ },
94
+ [pending, activeFileId, onSelectFile, saveNow, onCloseFile],
95
+ );
96
+
97
+ return { requestClose, pending, answer };
98
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The editor drop target's OVERLAY state.
8
+ *
9
+ * Every case here was a way the overlay could stay lit with the pointer nowhere
10
+ * near the panel, which is what a user reports as "the drop target is stuck":
11
+ *
12
+ * - `dragenter` fires for every nested child the pointer crosses, so the counter
13
+ * this replaced rose with each crossing while a `dragleave` to a node still
14
+ * inside was ignored. Measured in Chromium against the real app: five child
15
+ * crossings inside the chat left the counter at 5 after one exit, and the
16
+ * "Drop a file to open it" overlay stayed drawn.
17
+ * - A drag cancelled with Escape (or released outside the window) delivers NO
18
+ * `dragleave` and NO `dragend` for an OS file drag — measured — so only the
19
+ * pointer can report that the gesture is over.
20
+ *
21
+ * Split from `use-editor-drop.test.ts` for the per-file ceiling.
22
+ */
23
+
24
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
25
+ import { Window } from 'happy-dom';
26
+ import { h, render } from 'preact';
27
+ import { act } from 'preact/test-utils';
28
+ import { useEditorDrop, type UseEditorDropResult } from '@/client/hooks/editor/use-editor-drop';
29
+
30
+ const DOM_GLOBALS = ['window', 'document', 'navigator', 'Node', 'Element', 'HTMLElement', 'Event', 'CustomEvent', 'fetch'] as const;
31
+ const nativeGlobals: Partial<Record<(typeof DOM_GLOBALS)[number], unknown>> = {};
32
+
33
+ beforeAll(() => {
34
+ const win = new Window({ url: 'http://localhost' });
35
+ const target = globalThis as unknown as Record<string, unknown>;
36
+ for (const key of DOM_GLOBALS) {
37
+ nativeGlobals[key] = target[key];
38
+ target[key] = (win as unknown as Record<string, unknown>)[key];
39
+ }
40
+ globalThis.fetch = (async () => ({ ok: true, status: 200, json: async () => ({}) })) as unknown as typeof globalThis.fetch;
41
+ });
42
+
43
+ afterAll(() => {
44
+ const target = globalThis as unknown as Record<string, unknown>;
45
+ for (const key of DOM_GLOBALS) {
46
+ if (nativeGlobals[key] === undefined) delete target[key];
47
+ else target[key] = nativeGlobals[key];
48
+ }
49
+ });
50
+
51
+ /** A `DataTransfer` carrying one `text/uri-list` reference, as a Finder drop does. */
52
+ function fileTransfer(reference: string): DataTransfer {
53
+ return {
54
+ types: ['text/uri-list'],
55
+ files: [],
56
+ getData: (type: string) => (type.toLowerCase() === 'text/uri-list' ? reference : ''),
57
+ } as unknown as DataTransfer;
58
+ }
59
+
60
+ interface Harness {
61
+ api: () => UseEditorDropResult;
62
+ /** A node INSIDE the bound target, for the between-children case. */
63
+ child: Node;
64
+ }
65
+
66
+ let container: HTMLElement;
67
+
68
+ async function mount(enabled = true): Promise<Harness> {
69
+ container = document.body.appendChild(document.createElement('div'));
70
+ const target = container.appendChild(document.createElement('div'));
71
+ const child = target.appendChild(document.createElement('div'));
72
+
73
+ let api: UseEditorDropResult | null = null;
74
+ const Probe = () => {
75
+ api = useEditorDrop({ enabled, onResult: () => {} });
76
+ return null;
77
+ };
78
+ await act(async () => {
79
+ render(h(Probe, {}), container);
80
+ });
81
+ return { api: () => api!, child };
82
+ }
83
+
84
+ /** A drag event as the DOM delivers it: `currentTarget` is the bound element. */
85
+ function dragEvent(transfer: DataTransfer, related: Node | null) {
86
+ const event = new window.Event('dragover', { bubbles: true, cancelable: true });
87
+ Object.defineProperty(event, 'dataTransfer', { value: transfer });
88
+ Object.defineProperty(event, 'currentTarget', { value: container.firstElementChild });
89
+ Object.defineProperty(event, 'relatedTarget', { value: related });
90
+ return event as never;
91
+ }
92
+
93
+ beforeEach(() => {
94
+ container?.remove();
95
+ });
96
+
97
+ describe('useEditorDrop overlay', () => {
98
+ test('child crossings keep it lit and one real exit clears it', async () => {
99
+ const harness = await mount();
100
+ const transfer = fileTransfer('file:///repo/src/app.ts');
101
+
102
+ await act(async () => { harness.api().dropProps.onDragEnter(dragEvent(transfer, null)); });
103
+ expect(harness.api().isDragging).toBe(true);
104
+
105
+ // A sweep across nested children: the pointer never leaves the panel, so
106
+ // every leave names a node still inside it.
107
+ for (let pass = 0; pass < 5; pass += 1) {
108
+ await act(async () => { harness.api().dropProps.onDragOver(dragEvent(transfer, null)); });
109
+ await act(async () => { harness.api().dropProps.onDragLeave(dragEvent(transfer, harness.child)); });
110
+ }
111
+ expect(harness.api().isDragging).toBe(true);
112
+
113
+ await act(async () => { harness.api().dropProps.onDragLeave(dragEvent(transfer, null)); });
114
+ expect(harness.api().isDragging).toBe(false);
115
+ });
116
+
117
+ test('a drag cancelled with no leave at all is cleared by a pointer move', async () => {
118
+ const harness = await mount();
119
+ await act(async () => { harness.api().dropProps.onDragEnter(dragEvent(fileTransfer('file:///repo/a.ts'), null)); });
120
+ expect(harness.api().isDragging).toBe(true);
121
+
122
+ // A held button is a gesture still in progress, so the overlay stays.
123
+ const move = (buttons: number) => {
124
+ const event = new window.PointerEvent('pointermove', { bubbles: true });
125
+ Object.defineProperty(event, 'buttons', { value: buttons });
126
+ window.dispatchEvent(event);
127
+ };
128
+ await act(async () => { move(1); });
129
+ expect(harness.api().isDragging).toBe(true);
130
+
131
+ await act(async () => { move(0); });
132
+ expect(harness.api().isDragging).toBe(false);
133
+ });
134
+
135
+ test('a target with no workspace behind it never lights up', async () => {
136
+ // A drop there can only be refused, and an overlay that promises an open it
137
+ // will not perform is worse than one that stays dark.
138
+ const harness = await mount(false);
139
+ const transfer = fileTransfer('file:///repo/src/app.ts');
140
+ await act(async () => { harness.api().dropProps.onDragEnter(dragEvent(transfer, null)); });
141
+ await act(async () => { harness.api().dropProps.onDragOver(dragEvent(transfer, null)); });
142
+ expect(harness.api().isDragging).toBe(false);
143
+ });
144
+
145
+ test('a drop clears it, so the overlay does not outlive the gesture', async () => {
146
+ const harness = await mount();
147
+ const transfer = fileTransfer('file:///repo/src/app.ts');
148
+ await act(async () => { harness.api().dropProps.onDragEnter(dragEvent(transfer, null)); });
149
+ expect(harness.api().isDragging).toBe(true);
150
+
151
+ await act(async () => {
152
+ harness.api().dropProps.onDrop(dragEvent(transfer, null));
153
+ });
154
+ for (let pass = 0; pass < 4; pass += 1) {
155
+ await act(async () => { await Promise.resolve(); });
156
+ }
157
+ expect(harness.api().isDragging).toBe(false);
158
+ });
159
+ });