@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
@@ -1,127 +1,16 @@
1
- import { useCallback, useEffect, useRef, useState } from 'preact/hooks';
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
2
2
  import { getLanguageFromPath } from '@/shared/lib/code/language';
3
- import { type ViewerKind } from '@/shared/lib/fs/document-kind';
4
3
  import { resolveViewer } from '@/client/hooks/editor/resolve-viewer';
5
4
  import { detectLineEnding, toDiskText, toLf, type LineEnding } from '@/shared/lib/code/line-endings';
6
5
  import { retainKeys } from '@/client/hooks/editor/save-file';
7
6
  import { fileHandleFor } from '@/client/lib/launch/file-handlers';
8
- import { type ByteSource } from '@/client/components/workspace/editor/viewers/bytes';
9
7
  import { useFileRead } from '@/client/hooks/editor/use-file-read';
10
8
  import { useFileTransfer } from '@/client/hooks/editor/use-file-transfer';
11
9
  import { useFileWrites } from '@/client/hooks/editor/use-file-writes';
10
+ import { useWriteConflict } from '@/client/hooks/editor/use-write-conflict';
11
+ import type { FileEditorSaveStatus, FileEditorTarget, UseFileEditorOptions, UseFileEditorResult } from '@/client/hooks/editor/file-editor-types';
12
12
 
13
- export type FileEditorSaveStatus = 'idle' | 'saving' | 'saved' | 'error' | 'needs-permission';
14
-
15
- /** The single file a code surface is editing; `id` keys the in-memory cache. */
16
- export interface FileEditorTarget {
17
- id?: number | string;
18
- name: string;
19
- path?: string;
20
- content?: string;
21
- root?: string;
22
- repo?: string;
23
- /** The live handle a PWA launch opened this file through, when there is one. */
24
- handleId?: string;
25
- }
26
-
27
- export interface UseFileEditorOptions {
28
- /** Flush a pending debounced write on unmount so closing the editor cannot drop an edit. */
29
- flushOnUnmount?: boolean;
30
- /** Mark a failed write as `'error'`; otherwise the status returns to `'idle'`. */
31
- reportSaveError?: boolean;
32
- /** Blob MIME type for downloads. */
33
- downloadMimeType?: string;
34
- /** Fired after a write lands, so workspace panels can refresh. */
35
- onFileSaved?: () => void;
36
- /**
37
- * The file this tab names is gone from disk (the tab strip strikes it
38
- * through; see `useMissingFiles`).
39
- *
40
- * A save then means something the user did not ask for — writing the buffer
41
- * back would CREATE the file again — so the debounced autosave stands down
42
- * and an explicit Save asks first. Without this, a keystroke in a tab whose
43
- * file was deleted a moment ago silently resurrected it on disk.
44
- */
45
- missing?: boolean;
46
- }
47
-
48
- export interface UseFileEditorResult {
49
- content: string;
50
- onChange: (next: string) => void;
51
- isLoading: boolean;
52
- /**
53
- * The current file's bytes have arrived (or it is an image / carries inline
54
- * content). Distinguishes "the buffer is empty" from "the buffer is not read
55
- * yet" — `isLoading` cannot, because it starts `false` on the first render and
56
- * a consumer that trusted it would act on an empty buffer.
57
- */
58
- loaded: boolean;
59
- loadError: string | null;
60
- /**
61
- * The server refused this file as a document (binary, or larger than the
62
- * editor opens), with its own sentence. Distinct from `loadError` only in
63
- * WORDING — both leave an empty buffer and disable Save — but the difference
64
- * is what the user needs: a zip was read fine and is simply not text.
65
- */
66
- unsupported: string | null;
67
- saveStatus: FileEditorSaveStatus;
68
- copied: boolean;
69
- isDirty: boolean;
70
- language: string;
71
- /**
72
- * A handle-backed tab whose live handle is gone — the page reloaded since the
73
- * file was launched, and a `FileSystemFileHandle` cannot be persisted. Save
74
- * is refused (there is nothing to write through), so the surface says why
75
- * instead of showing a button that silently fails.
76
- */
77
- handleMissing: boolean;
78
- /** True for raster images: the surface renders `imageUrl`, not `content`. */
79
- isImage: boolean;
80
- /** Raw-byte URL of the active image (cache-busted per revision), else null. */
81
- imageUrl: string | null;
82
- /**
83
- * Which surface draws this file (see `shared/lib/fs/document-kind`). The pane
84
- * dispatches on it, and `isImage` is now one case of it rather than its own
85
- * axis.
86
- */
87
- viewerKind: ViewerKind;
88
- /**
89
- * The bytes a byte-drawing viewer reads, from the tab's path or its live
90
- * handle. `loadBytes` is null for a text viewer and for an inline attachment
91
- * (nothing to fetch); `url` is additionally null when the file came from a
92
- * handle rather than a workspace path.
93
- */
94
- byteSource: ByteSource;
95
- /**
96
- * True for the viewers that read BYTES rather than the text buffer (image,
97
- * PDF, DOCX, workbook). Their read path is skipped and their writes refused,
98
- * because a byte surface has no buffer to save.
99
- */
100
- isBinaryViewer: boolean;
101
- /**
102
- * Bumped by `reset()` (a workspace refresh). A byte viewer that fetches its
103
- * own bytes has no read effect to re-run, so it takes this as its re-read
104
- * lever; the text path already re-reads through `useFileRead`.
105
- */
106
- revision: number;
107
- saveNow: () => void;
108
- copy: () => void;
109
- download: () => void;
110
- /**
111
- * Re-read every cached file from disk (e.g. a workspace refresh). Content
112
- * already on screen stays until the fresh bytes land, and a file with
113
- * unsaved edits is left alone.
114
- */
115
- reset: () => void;
116
- /** Drop cached content for files no longer open. */
117
- retain: (ids: Array<number | string>) => void;
118
- /** The file was deleted, so a Save is waiting on the user's answer. */
119
- saveMissingConfirm: boolean;
120
- /** Write the buffer anyway — this recreates the file on disk. */
121
- confirmSaveMissing: () => void;
122
- /** Dismiss the dialog; nothing is written and the buffer stays dirty. */
123
- cancelSaveMissing: () => void;
124
- }
13
+ export type { FileEditorSaveStatus, FileEditorTarget, UseFileEditorOptions, UseFileEditorResult } from '@/client/hooks/editor/file-editor-types';
125
14
 
126
15
  function targetKey(target: FileEditorTarget): string {
127
16
  return String(target.id ?? target.path ?? target.name);
@@ -153,6 +42,15 @@ export function useFileEditor(
153
42
  * CRLF file would be rewritten as LF by a one-character edit.
154
43
  */
155
44
  const [lineEndings, setLineEndings] = useState<Record<string, LineEnding>>({});
45
+ /**
46
+ * The mtime each cached file was READ at.
47
+ *
48
+ * The save path sends it as `baseMtime`, and a write whose base no longer
49
+ * matches the disk is refused (`409`) instead of clobbering a change made by an
50
+ * agent, another tab or another editor. `null` means "no expectation" — an
51
+ * inline attachment, a handle-backed file, or a read that failed.
52
+ */
53
+ const [mtimes, setMtimes] = useState<Record<string, number | null>>({});
156
54
  const [saveStatus, setSaveStatus] = useState<FileEditorSaveStatus>('idle');
157
55
  /** Bumped by `reset()` to re-run the read effect for the active file. */
158
56
  const [revision, setRevision] = useState(0);
@@ -162,6 +60,19 @@ export function useFileEditor(
162
60
  // feeds is LF-only — normalizing here keeps `isDirty` comparing like with like.
163
61
  const content = target ? (contents[key] ?? (target.content !== undefined ? toLf(target.content) : '')) : '';
164
62
  const isDirty = content !== (baselines[key] ?? content);
63
+ /**
64
+ * The dirty set, derived from the two caches rather than tracked separately:
65
+ * a second copy would be a second thing to keep in step, and the comparison is
66
+ * a string identity check per open buffer.
67
+ */
68
+ const dirtyKeys = useMemo(() => {
69
+ const next = new Set<string>();
70
+ for (const [bufferKey, text] of Object.entries(contents)) {
71
+ const baseline = baselines[bufferKey];
72
+ if (baseline !== undefined && text !== baseline) next.add(bufferKey);
73
+ }
74
+ return next;
75
+ }, [contents, baselines]);
165
76
 
166
77
  // The viewer, its bytes and the image URL — see `resolve-viewer.ts` for the
167
78
  // three rules this derivation encodes (the kind comes from the path; a
@@ -184,8 +95,10 @@ export function useFileEditor(
184
95
  // live mirror rather than captured in its closure.
185
96
  const lineEndingsRef = useRef(lineEndings);
186
97
  lineEndingsRef.current = lineEndings;
98
+ const mtimesRef = useRef(mtimes);
99
+ mtimesRef.current = mtimes;
187
100
 
188
- const remember = useCallback((fileKey: string, text: string) => {
101
+ const remember = useCallback((fileKey: string, text: string, mtimeMs: number | null) => {
189
102
  // The buffer holds LF only; the style the bytes arrived with is kept beside
190
103
  // it so the write can put the file back the way it was found.
191
104
  const ending = detectLineEnding(text);
@@ -193,6 +106,7 @@ export function useFileEditor(
193
106
  setContents((prev) => ({ ...prev, [fileKey]: lf }));
194
107
  setBaselines((prev) => ({ ...prev, [fileKey]: lf }));
195
108
  setLineEndings((prev) => ({ ...prev, [fileKey]: ending }));
109
+ setMtimes((prev) => ({ ...prev, [fileKey]: mtimeMs }));
196
110
  }, []);
197
111
 
198
112
  /**
@@ -226,6 +140,7 @@ export function useFileEditor(
226
140
  missing,
227
141
  contentsRef,
228
142
  lineEndingsRef,
143
+ mtimesRef,
229
144
  pendingRef,
230
145
  flushOnUnmount,
231
146
  onSaveStart: () => setSaveStatus('saving'),
@@ -238,10 +153,38 @@ export function useFileEditor(
238
153
  // Not a failure: the buffer is intact and one Save (a real gesture) grants
239
154
  // the access a handle-backed file needs.
240
155
  onNeedsPermission: () => setSaveStatus('needs-permission'),
156
+ // A conflict is a verdict, not a failure: the buffer is intact and the disk
157
+ // holds someone else's bytes. `saveStatus` stays `idle` because the write did
158
+ // not happen, and the panel's own strip owns the Reload/Keep choice.
159
+ onConflict: (fileKey, diskMtimeMs) => {
160
+ // Not a failure: the buffer is intact and the panel's own strip owns the
161
+ // Reload/Keep choice, so the toolbar's save status stays idle.
162
+ setSaveStatus('idle');
163
+ conflictState.report(fileKey, diskMtimeMs);
164
+ },
241
165
  });
242
166
  const writesRef = useRef(writes);
243
167
  writesRef.current = writes;
244
168
 
169
+ /**
170
+ * The conflict state machine.
171
+ *
172
+ * Built after the write hook because its "Keep mine" answer writes through
173
+ * `writesRef` — the same path the toolbar's Save uses, so there is one write
174
+ * implementation rather than two that can disagree about the base mtime.
175
+ */
176
+ const conflictState = useWriteConflict({
177
+ key,
178
+ saveNow: () => writesRef.current.saveNow(),
179
+ mtimesRef,
180
+ setMtimes,
181
+ contentsRef,
182
+ setContents,
183
+ setBaselines,
184
+ loadedRef,
185
+ bumpRevision: () => setRevision((prev) => prev + 1),
186
+ });
187
+
245
188
  useEffect(() => {
246
189
  if (saveStatus !== 'saved') return;
247
190
  const timer = window.setTimeout(() => setSaveStatus('idle'), 1500);
@@ -290,6 +233,17 @@ export function useFileEditor(
290
233
  setRevision((prev) => prev + 1);
291
234
  }, []);
292
235
 
236
+ /**
237
+ * Switch the ending this buffer saves in.
238
+ *
239
+ * Only the ending moves: the BUFFER is LF-only either way, and the bytes are built
240
+ * at write time, so nothing on screen changes and no re-read is needed.
241
+ */
242
+ const setEol = useCallback((next: LineEnding) => {
243
+ if (!target) return;
244
+ setLineEndings((prev) => ({ ...prev, [targetKey(target)]: next }));
245
+ }, [target]);
246
+
293
247
  const retain = useCallback((ids: Array<number | string>) => {
294
248
  const keep = new Set(ids.map(String));
295
249
  for (const loaded of Array.from(loadedRef.current)) {
@@ -297,6 +251,7 @@ export function useFileEditor(
297
251
  }
298
252
  setContents((prev) => retainKeys(prev, keep));
299
253
  setLineEndings((prev) => retainKeys(prev, keep));
254
+ setMtimes((prev) => retainKeys(prev, keep));
300
255
  }, []);
301
256
 
302
257
  return {
@@ -311,6 +266,10 @@ export function useFileEditor(
311
266
  saveStatus,
312
267
  copied,
313
268
  isDirty,
269
+ eol: lineEndings[key] ?? 'lf',
270
+ setEol,
271
+ baseMtimeMs: mtimes[key] ?? null,
272
+ dirtyKeys,
314
273
  language: target ? getLanguageFromPath(target.name) : 'javascript',
315
274
  isImage,
316
275
  imageUrl,
@@ -327,5 +286,13 @@ export function useFileEditor(
327
286
  saveMissingConfirm: writes.saveMissingConfirm,
328
287
  confirmSaveMissing: writes.confirmSaveMissing,
329
288
  cancelSaveMissing: writes.cancelSaveMissing,
289
+ conflict: conflictState.conflict,
290
+ resolveConflictByReload: conflictState.reload,
291
+ resolveConflictByKeepingMine: conflictState.keepMine,
292
+ // Revert and Reload are the same operation: throw the buffer away and take the
293
+ // disk copy. Two names because the reason differs — a Revert is the user's own
294
+ // choice, a Reload is an answer to a conflict — and neither needs its own path.
295
+ revertToDisk: conflictState.reload,
296
+ adoptDiskMtime: conflictState.adopt,
330
297
  };
331
298
  }
@@ -70,8 +70,14 @@ export interface UseFileReadOptions {
70
70
  baselinesRef: LiveRef<Record<string, string>>;
71
71
  /** The queued write, which owns the key if it is still pending. */
72
72
  pendingRef: LiveRef<PendingWrite | null>;
73
- /** Store bytes (and the line ending they arrived with) for a key. */
74
- remember: (fileKey: string, text: string) => void;
73
+ /**
74
+ * Store bytes, the line ending they arrived with, and the mtime they were read
75
+ * at.
76
+ *
77
+ * The mtime is the save path's conflict base: a write whose base no longer
78
+ * matches the disk is refused rather than clobbering another writer's change.
79
+ */
80
+ remember: (fileKey: string, text: string, mtimeMs: number | null) => void;
75
81
  }
76
82
 
77
83
  export interface FileReadState {
@@ -121,7 +127,9 @@ export function useFileRead({
121
127
  }
122
128
 
123
129
  if (target.content !== undefined) {
124
- remember(fileKey, target.content);
130
+ // Inline content (an attachment chip) has no file behind it, so there is no
131
+ // mtime to check a later write against.
132
+ remember(fileKey, target.content, null);
125
133
  setLoadError(null);
126
134
  setUnsupported(null);
127
135
  return;
@@ -148,7 +156,7 @@ export function useFileRead({
148
156
  fetch(`/api/fs/read?${params.toString()}`)
149
157
  .then(async (res) => {
150
158
  const data = (await res.json().catch(() => null)) as
151
- | { content?: unknown; error?: string; kind?: 'binary' | 'too-large' }
159
+ | { content?: unknown; error?: string; kind?: 'binary' | 'too-large'; mtimeMs?: unknown }
152
160
  | null;
153
161
  if (!res.ok || !data || typeof data.content !== 'string') {
154
162
  const error: FileReadError = new Error(data?.error || `HTTP ${res.status}`);
@@ -158,9 +166,9 @@ export function useFileRead({
158
166
  else if (res.status === 415) error.kind = 'binary';
159
167
  throw error;
160
168
  }
161
- return data.content;
169
+ return { text: data.content, mtimeMs: typeof data.mtimeMs === 'number' ? data.mtimeMs : null };
162
170
  })
163
- .then((text) => {
171
+ .then(({ text, mtimeMs }) => {
164
172
  if (cancelled) return;
165
173
  // These bytes were read before the response arrived, so anything typed
166
174
  // since is newer. Applying them would replace those keystrokes (and,
@@ -170,7 +178,7 @@ export function useFileRead({
170
178
  if (typed !== undefined && typed !== baselinesRef.current[fileKey]) return;
171
179
  const queued = pendingRef.current;
172
180
  if (queued && targetKey(queued.file) === fileKey) return;
173
- remember(fileKey, text);
181
+ remember(fileKey, text, mtimeMs);
174
182
  })
175
183
  .catch((err: unknown) => {
176
184
  if (cancelled) return;
@@ -178,7 +186,7 @@ export function useFileRead({
178
186
  if (!firstLoad) return;
179
187
  // An empty buffer, never a substitute: the next save would write the
180
188
  // substitute over the real file.
181
- remember(fileKey, '');
189
+ remember(fileKey, '', null);
182
190
  const message = err instanceof Error ? err.message : 'Failed to read file';
183
191
  const kind = (err as FileReadError)?.kind;
184
192
  setUnsupported(kind ? message : null);
@@ -58,6 +58,14 @@ export interface FileWriteDeps {
58
58
  contentsRef: LiveRef<Record<string, string>>;
59
59
  /** The live line endings, so the write restores the file's own style. */
60
60
  lineEndingsRef: LiveRef<Record<string, LineEnding>>;
61
+ /**
62
+ * The mtime each buffer was READ at — the save path's conflict base.
63
+ *
64
+ * Read at FIRE time like every other mirror here: a debounced write captured an
65
+ * older render, and a base that moved since would refuse a write the user had
66
+ * already seen succeed elsewhere.
67
+ */
68
+ mtimesRef: LiveRef<Record<string, number | null>>;
61
69
  /** Owned by the caller: the read effect consults it to yield to a queued write. */
62
70
  pendingRef: LiveRef<PendingWrite | null>;
63
71
  /** Flush a pending debounced write on unmount so closing cannot drop an edit. */
@@ -74,6 +82,13 @@ export interface FileWriteDeps {
74
82
  * intact and one Save fixes it.
75
83
  */
76
84
  onNeedsPermission: () => void;
85
+ /**
86
+ * The disk copy moved since this buffer was read, so the write was refused.
87
+ *
88
+ * Reported apart from a failure because it is not one: the buffer is intact and
89
+ * the user has a real choice (reload the disk copy, or write over it).
90
+ */
91
+ onConflict: (fileKey: string, diskMtimeMs: number | null) => void;
77
92
  }
78
93
 
79
94
  export interface FileWrites {
@@ -99,12 +114,14 @@ export function useFileWrites({
99
114
  missing,
100
115
  contentsRef,
101
116
  lineEndingsRef,
117
+ mtimesRef,
102
118
  pendingRef,
103
119
  flushOnUnmount,
104
120
  onSaveStart,
105
121
  onSaved,
106
122
  onSaveFailed,
107
123
  onNeedsPermission,
124
+ onConflict,
108
125
  }: FileWriteDeps): FileWrites {
109
126
  const [saveMissingConfirm, setSaveMissingConfirm] = useState(false);
110
127
 
@@ -134,14 +151,22 @@ export function useFileWrites({
134
151
  // `interactive` travels with the write because a handle-backed file needs
135
152
  // a USER GESTURE to grant write access: the explicit Save has one, the
136
153
  // autosave does not, and asking from a timer is refused by the browser.
154
+ //
155
+ // `baseMtimeMs` is the mtime the buffer was read at, so the server can refuse
156
+ // a write that would clobber another writer. `allowMissing` deliberately
157
+ // passes NO base: the file was deleted, so there is nothing to conflict with
158
+ // and recreating it is the decision the user just made.
159
+ const baseMtimeMs = options.allowMissing ? null : mtimesRef.current[fileKey] ?? null;
137
160
  const outcome = await saveEditorFile(file, text, lineEndingsRef.current[fileKey] ?? 'lf', {
138
161
  interactive: options.interactive === true,
162
+ baseMtimeMs,
139
163
  });
140
- if (outcome === 'written') onSaved(fileKey, text);
141
- else if (outcome === 'needs-permission') onNeedsPermission();
164
+ if (outcome.status === 'written') onSaved(fileKey, text);
165
+ else if (outcome.status === 'needs-permission') onNeedsPermission();
166
+ else if (outcome.status === 'conflict') onConflict(fileKey, outcome.diskMtimeMs);
142
167
  else onSaveFailed();
143
168
  },
144
- [lineEndingsRef, onNeedsPermission, onSaveFailed, onSaveStart, onSaved],
169
+ [lineEndingsRef, mtimesRef, onConflict, onNeedsPermission, onSaveFailed, onSaveStart, onSaved],
145
170
  );
146
171
 
147
172
  const persistRef = useRef(persist);
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The phone editor's find bar, and the search row's hand-off, as one call.
8
+ *
9
+ * Both are the DESKTOP's own hooks (`useEditorFind`, `useMobileReveal`) — the phone was
10
+ * the one surface with no way to search a file, and a second implementation would be a
11
+ * second answer to "which occurrences count". What this module adds is the pairing: the
12
+ * marks a search row asks to paint and the marks the bar paints are the same field, so a
13
+ * caller that wired them separately would have to decide which one wins.
14
+ *
15
+ * The bar wins while it is open: a user who typed a query is asking about THAT, and the
16
+ * row's hit is already where the caret is.
17
+ */
18
+
19
+ import type { CodeSurfaceHandle } from '@/client/components/common/code-surface';
20
+ import { useEditorFind } from '@/client/hooks/editor/use-editor-find';
21
+ import type { EditorFindState } from '@/client/hooks/editor/find-state';
22
+ import { useMobileReveal } from '@/client/hooks/editor/use-mobile-reveal';
23
+
24
+ interface UseMobileEditorFindOptions {
25
+ path: string | null;
26
+ content: string;
27
+ documentKey: string;
28
+ ready: boolean;
29
+ surfaceRef: { current: CodeSurfaceHandle | null };
30
+ toggleWordWrap: () => void;
31
+ }
32
+
33
+ export interface MobileEditorFind {
34
+ find: EditorFindState;
35
+ /** The marks to paint, or undefined when there is nothing to paint. */
36
+ revealMarks: readonly { start: number; end: number }[] | undefined;
37
+ currentMark: number;
38
+ }
39
+
40
+ export function useMobileEditorFind({
41
+ path,
42
+ content,
43
+ documentKey,
44
+ ready,
45
+ surfaceRef,
46
+ toggleWordWrap,
47
+ }: UseMobileEditorFindOptions): MobileEditorFind {
48
+ const reveal = useMobileReveal({ path, content, ready, surfaceRef });
49
+ const find = useEditorFind({
50
+ text: content,
51
+ documentKey,
52
+ readSelection: () => surfaceRef.current?.getSelection() ?? null,
53
+ select: (start, end, focus = true) => surfaceRef.current?.select(start, end, focus),
54
+ reveal: (offset) => surfaceRef.current?.revealOffset(offset),
55
+ applyDocument: (value, caretStart, caretEnd) => surfaceRef.current?.applyDocument(value, caretStart, caretEnd),
56
+ toggleWordWrap,
57
+ });
58
+
59
+ // The bar's own matches take over while it is open: the query is what the user is
60
+ // asking about, and the row's hit is already under the caret.
61
+ if (find.open && find.matches.length > 0) {
62
+ return { find, revealMarks: find.matches, currentMark: find.currentIndex };
63
+ }
64
+ return {
65
+ find,
66
+ revealMarks: reveal.matches.length > 0 ? reveal.matches : undefined,
67
+ currentMark: reveal.currentIndex,
68
+ };
69
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Serving a search row's hand-off in the PHONE's full-screen editor.
8
+ *
9
+ * The desktop pane paints the hit through its find bar (so every occurrence is
10
+ * highlighted and the bar explains the count). The phone has no bar open at that
11
+ * moment — the editor is a whole screen, and the row that was tapped is behind it — so
12
+ * the same request becomes the marks PLUS a caret placement, with no query re-seeded.
13
+ *
14
+ * The "fire once per request" rule is the subtle half and it is the reason this is a
15
+ * hook: the resolved target is recomputed on every edit, so keying an effect on the
16
+ * target would drag the caret back to the match after every keystroke.
17
+ */
18
+
19
+ import { useEffect, useRef } from 'preact/hooks';
20
+
21
+ import type { CodeSurfaceHandle } from '@/client/components/common/code-surface';
22
+ import { useSearchRevealTarget } from '@/client/hooks/editor/use-search-reveal';
23
+
24
+ interface UseMobileRevealOptions {
25
+ path: string | null;
26
+ content: string;
27
+ ready: boolean;
28
+ surfaceRef: { current: CodeSurfaceHandle | null };
29
+ }
30
+
31
+ export interface MobileReveal {
32
+ matches: readonly { start: number; end: number }[];
33
+ currentIndex: number;
34
+ }
35
+
36
+ export function useMobileReveal({ path, content, ready, surfaceRef }: UseMobileRevealOptions): MobileReveal {
37
+ const target = useSearchRevealTarget(path, content, ready);
38
+ /** The request already served, so a re-render cannot re-fire the jump. */
39
+ const firedRef = useRef<unknown>(null);
40
+
41
+ useEffect(() => {
42
+ if (!target || firedRef.current === target.request) return;
43
+ firedRef.current = target.request;
44
+ const match = target.matches[target.currentIndex];
45
+ if (!match) return;
46
+ // No focus: the user is coming from a search row, and stealing focus into the
47
+ // document would pop the soft keyboard over the text they just landed on.
48
+ surfaceRef.current?.select(match.start, match.end, false);
49
+ surfaceRef.current?.revealOffset(match.start);
50
+ }, [target, surfaceRef]);
51
+
52
+ return { matches: target?.matches ?? [], currentIndex: target?.currentIndex ?? -1 };
53
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Landing a search row's hit in the editor.
8
+ *
9
+ * The hand-off has one subtle rule and it is the whole reason this is a hook: the
10
+ * resolved target is RECOMPUTED on every edit (its marks track the live buffer),
11
+ * but the JUMP must fire once per request. Keying an effect on the target itself
12
+ * would drag the view back to the match after every keystroke — the user types one
13
+ * character and the caret jumps away.
14
+ *
15
+ * The request object is the identity: `useSearchRevealTarget` hands back the same
16
+ * object for the same request and a new one for a new hit, so comparing it is both
17
+ * necessary and sufficient.
18
+ */
19
+
20
+ import { useEffect, useRef } from 'preact/hooks';
21
+
22
+ import type { FindOptions } from '@/shared/lib/code/editor/find-scan';
23
+
24
+ /** What `useSearchRevealTarget` answers, as this hook needs it. */
25
+ export interface SearchRevealTarget {
26
+ request: {
27
+ query: string;
28
+ options: FindOptions;
29
+ line: number;
30
+ };
31
+ }
32
+
33
+ interface UseSearchRevealJumpOptions {
34
+ /** The resolved target, or null while the buffer is not trustworthy. */
35
+ searchReveal: SearchRevealTarget | null;
36
+ revealMatch: (request: { query: string; options: FindOptions; line: number }) => void;
37
+ }
38
+
39
+ export function useSearchRevealJump({ searchReveal, revealMatch }: UseSearchRevealJumpOptions): void {
40
+ // The callback is rebuilt whenever the find state moves, so it is read through a
41
+ // ref: putting it in the dependency list would re-run the jump on every keystroke
42
+ // in the query field.
43
+ const revealRef = useRef(revealMatch);
44
+ revealRef.current = revealMatch;
45
+ /** The request already served, so a re-render cannot re-fire it. */
46
+ const firedRef = useRef<unknown>(null);
47
+
48
+ useEffect(() => {
49
+ if (!searchReveal || firedRef.current === searchReveal.request) return;
50
+ firedRef.current = searchReveal.request;
51
+ revealRef.current({
52
+ query: searchReveal.request.query,
53
+ options: searchReveal.request.options,
54
+ line: searchReveal.request.line,
55
+ });
56
+ }, [searchReveal]);
57
+ }