-
-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathstate-store.ts
More file actions
390 lines (333 loc) · 12.3 KB
/
state-store.ts
File metadata and controls
390 lines (333 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import type { RefObject } from "react";
import { create } from "zustand";
import { subscribeWithSelector } from "zustand/middleware";
import { EDITOR_CONSTANTS } from "@/features/editor/config/constants";
import { isDragScrolling } from "@/features/editor/hooks/use-drag-scroll";
import type { Cursor, MultiCursorState, Position, Range } from "@/features/editor/types/editor";
import { getLineHeight } from "@/features/editor/utils/position";
import { createSelectors } from "@/utils/zustand-selectors";
import { useBufferStore } from "./buffer-store";
import { useEditorSettingsStore } from "./settings-store";
// Types for editor state caching
export interface EditorViewState {
cursor: Position;
scrollTop: number;
scrollLeft: number;
}
// Editor View State Cache Manager - caches cursor position and scroll offset per buffer
class EditorViewStateCacheManager {
private cache = new Map<string, EditorViewState>();
private readonly MAX_CACHE_SIZE = EDITOR_CONSTANTS.MAX_POSITION_CACHE_SIZE;
setCursor(bufferId: string, position: Position): void {
const cached = this.cache.get(bufferId);
if (cached && this.positionsEqual(cached.cursor, position)) {
return;
}
this.ensureCacheSize(bufferId);
const existing = this.cache.get(bufferId);
this.cache.set(bufferId, {
cursor: { ...position },
scrollTop: existing?.scrollTop ?? 0,
scrollLeft: existing?.scrollLeft ?? 0,
});
}
setScroll(bufferId: string, scrollTop: number, scrollLeft: number): void {
const existing = this.cache.get(bufferId);
if (existing && existing.scrollTop === scrollTop && existing.scrollLeft === scrollLeft) {
return;
}
this.ensureCacheSize(bufferId);
this.cache.set(bufferId, {
cursor: existing?.cursor ?? { line: 0, column: 0, offset: 0 },
scrollTop,
scrollLeft,
});
}
get(bufferId: string): EditorViewState | null {
const cached = this.cache.get(bufferId);
if (!cached) return null;
return {
cursor: { ...cached.cursor },
scrollTop: cached.scrollTop,
scrollLeft: cached.scrollLeft,
};
}
getCursor(bufferId: string): Position | null {
const cached = this.cache.get(bufferId);
if (!cached) return null;
return { ...cached.cursor };
}
clear(bufferId?: string): void {
if (bufferId) {
this.cache.delete(bufferId);
} else {
this.cache.clear();
}
}
private ensureCacheSize(bufferId: string): void {
if (this.cache.size >= this.MAX_CACHE_SIZE && !this.cache.has(bufferId)) {
const firstKey = this.cache.keys().next().value;
if (firstKey) {
this.cache.delete(firstKey);
}
}
}
private positionsEqual(pos1: Position, pos2: Position): boolean {
return pos1.line === pos2.line && pos1.column === pos2.column && pos1.offset === pos2.offset;
}
}
const viewStateCache = new EditorViewStateCacheManager();
const ensureCursorVisible = (position: Position) => {
if (typeof window === "undefined") return;
// Skip scroll adjustment during drag selection auto-scroll
if (isDragScrolling()) return;
const viewport = document.querySelector(".editor-viewport") as HTMLDivElement | null;
if (!viewport) return;
const fontSize = useEditorSettingsStore.getState().fontSize;
const lineHeight = getLineHeight(fontSize);
const targetTop = position.line * lineHeight;
const targetBottom = targetTop + lineHeight;
const currentScrollTop = viewport.scrollTop;
const viewportHeight = viewport.clientHeight || 0;
if (targetTop < currentScrollTop) {
viewport.scrollTop = targetTop;
} else if (targetBottom > currentScrollTop + viewportHeight) {
viewport.scrollTop = Math.max(0, targetBottom - viewportHeight);
}
const textarea = document.querySelector(".editor-textarea") as HTMLTextAreaElement | null;
if (textarea && textarea.scrollTop !== viewport.scrollTop) {
textarea.scrollTop = viewport.scrollTop;
}
};
// State Interface
interface EditorState {
// Cursor state
cursorPosition: Position;
selection?: Range;
desiredColumn?: number;
cursorVisible: boolean;
// Multi-cursor state
multiCursorState: MultiCursorState | null;
// Layout state
scrollTop: number;
scrollLeft: number;
viewportHeight: number;
// Instance state
value: string;
onChange: (value: string) => void;
filePath: string;
editorRef: RefObject<HTMLDivElement | null> | null;
placeholder?: string;
disabled: boolean;
// Actions
actions: EditorStateActions;
}
interface EditorStateActions {
// Cursor actions
setCursorPosition: (position: Position) => void;
setSelection: (selection?: Range) => void;
setDesiredColumn: (column?: number) => void;
setCursorVisibility: (visible: boolean) => void;
getCachedPosition: (bufferId: string) => Position | null;
clearPositionCache: (bufferId?: string) => void;
restorePositionForFile: (bufferId: string) => EditorViewState;
resetOnBufferSwitch: () => void;
// Multi-cursor actions
enableMultiCursor: () => void;
disableMultiCursor: () => void;
addCursor: (position: Position, selection?: Range) => void;
removeCursor: (cursorId: string) => void;
updateCursor: (cursorId: string, position: Position, selection?: Range) => void;
clearSecondaryCursors: () => void;
// Layout actions
setScroll: (scrollTop: number, scrollLeft: number) => void;
setScrollForBuffer: (bufferId: string | null, scrollTop: number, scrollLeft: number) => void;
setViewportHeight: (height: number) => void;
// Instance actions
setRefs: (refs: { editorRef: RefObject<HTMLDivElement | null> }) => void;
setContent: (value: string, onChange: (value: string) => void) => void;
setFileInfo: (filePath: string) => void;
setPlaceholder: (placeholder?: string) => void;
setDisabled: (disabled: boolean) => void;
}
export const useEditorStateStore = createSelectors(
create<EditorState>()(
subscribeWithSelector((set) => ({
// Cursor state
cursorPosition: { line: 0, column: 0, offset: 0 },
cursorVisible: false,
selection: undefined,
desiredColumn: undefined,
// Multi-cursor state
multiCursorState: null,
// Layout state
scrollTop: 0,
scrollLeft: 0,
viewportHeight: EDITOR_CONSTANTS.DEFAULT_VIEWPORT_HEIGHT,
// Instance state
value: "",
onChange: () => {},
filePath: "",
editorRef: null,
placeholder: undefined,
disabled: false,
// Actions
actions: {
// Cursor actions
setCursorPosition: (position) => {
const activeBufferId = useBufferStore.getState().activeBufferId;
if (activeBufferId) {
viewStateCache.setCursor(activeBufferId, position);
}
set({ cursorPosition: position });
ensureCursorVisible(position);
},
setSelection: (selection) => set({ selection }),
setDesiredColumn: (column) => set({ desiredColumn: column }),
setCursorVisibility: (visible) => set({ cursorVisible: visible }),
getCachedPosition: (bufferId) => viewStateCache.getCursor(bufferId),
clearPositionCache: (bufferId) => viewStateCache.clear(bufferId),
restorePositionForFile: (bufferId) => {
const cachedState = viewStateCache.get(bufferId);
const restoredState = cachedState ?? {
cursor: { line: 0, column: 0, offset: 0 },
scrollTop: 0,
scrollLeft: 0,
};
set({
cursorPosition: restoredState.cursor,
scrollTop: restoredState.scrollTop,
scrollLeft: restoredState.scrollLeft,
});
return restoredState;
},
resetOnBufferSwitch: () => {
set({
multiCursorState: null,
selection: undefined,
desiredColumn: undefined,
});
},
// Multi-cursor actions
enableMultiCursor: () =>
set((state) => {
if (state.multiCursorState) return state;
const primaryCursorId = `cursor-${Date.now()}-0`;
return {
multiCursorState: {
cursors: [
{
id: primaryCursorId,
position: state.cursorPosition,
selection: state.selection,
},
],
primaryCursorId,
},
};
}),
disableMultiCursor: () => set({ multiCursorState: null }),
addCursor: (position, selection) =>
set((state) => {
if (!state.multiCursorState) return state;
// Check for duplicate cursor at the same position
const isDuplicate = state.multiCursorState.cursors.some(
(cursor) =>
cursor.position.line === position.line &&
cursor.position.column === position.column,
);
if (isDuplicate) return state;
const newCursorId = `cursor-${Date.now()}-${state.multiCursorState.cursors.length}`;
const newCursor: Cursor = {
id: newCursorId,
position,
selection,
};
return {
multiCursorState: {
...state.multiCursorState,
cursors: [...state.multiCursorState.cursors, newCursor],
},
};
}),
removeCursor: (cursorId) =>
set((state) => {
if (!state.multiCursorState) return state;
const cursors = state.multiCursorState.cursors.filter((c) => c.id !== cursorId);
if (cursors.length === 0) {
return { multiCursorState: null };
}
let primaryCursorId = state.multiCursorState.primaryCursorId;
if (cursorId === primaryCursorId && cursors.length > 0) {
primaryCursorId = cursors[0].id;
}
return {
multiCursorState: {
cursors,
primaryCursorId,
},
};
}),
updateCursor: (cursorId, position, selection) =>
set((state) => {
if (!state.multiCursorState) return state;
const cursors = state.multiCursorState.cursors.map((cursor) =>
cursor.id === cursorId
? { ...cursor, position, selection: selection ?? cursor.selection }
: cursor,
);
return {
multiCursorState: {
...state.multiCursorState,
cursors,
},
};
}),
clearSecondaryCursors: () =>
set((state) => {
if (!state.multiCursorState) return state;
const primaryCursor = state.multiCursorState.cursors.find(
(c) => c.id === state.multiCursorState!.primaryCursorId,
);
if (!primaryCursor) {
return { multiCursorState: null };
}
return {
multiCursorState: {
cursors: [primaryCursor],
primaryCursorId: primaryCursor.id,
},
cursorPosition: primaryCursor.position,
selection: primaryCursor.selection,
};
}),
// Layout actions
setScroll: (scrollTop, scrollLeft) => {
const activeBufferId = useBufferStore.getState().activeBufferId;
if (activeBufferId) {
viewStateCache.setScroll(activeBufferId, scrollTop, scrollLeft);
}
set({ scrollTop, scrollLeft });
},
setScrollForBuffer: (bufferId, scrollTop, scrollLeft) => {
// Cache scroll for the specified buffer (avoids race condition when buffer switches)
if (bufferId) {
viewStateCache.setScroll(bufferId, scrollTop, scrollLeft);
}
// Only update global state if this is still the active buffer
const activeBufferId = useBufferStore.getState().activeBufferId;
if (bufferId === activeBufferId) {
set({ scrollTop, scrollLeft });
}
},
setViewportHeight: (height) => set({ viewportHeight: height }),
// Instance actions
setRefs: (refs) => set(refs),
setContent: (value, onChange) => set({ value, onChange }),
setFileInfo: (filePath) => set({ filePath }),
setPlaceholder: (placeholder) => set({ placeholder }),
setDisabled: (disabled) => set({ disabled }),
},
})),
),
);