-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathuseVersionsStore.ts
More file actions
627 lines (535 loc) · 18.1 KB
/
Copy pathuseVersionsStore.ts
File metadata and controls
627 lines (535 loc) · 18.1 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
/**
* Versions Store
*
* Global state management for undo/redo functionality
* Tracks version history and current position for each entity
*/
'use client';
import { create } from 'zustand';
import type { Version, VersionEntityType, VersionHistoryItem } from '@/types';
// Entity key for tracking (combines type and id)
type EntityKey = `${VersionEntityType}:${string}`;
// Hard cap on cached version payloads. Each version carries layer/style/etc.
// snapshots, so an unbounded cache grows quickly with every save during a
// session.
const MAX_VERSION_CACHE_SIZE = 200;
/**
* Drop versions not referenced by any entity stack. Falls back to oldest-first
* eviction when everything is still referenced and the cap is exceeded.
*/
function pruneVersionCacheForced(
versionCache: Record<string, Version>,
entityStates: Record<EntityKey, UndoRedoState>
): Record<string, Version> {
const referenced = new Set<string>();
for (const state of Object.values(entityStates)) {
for (const id of state.undoStack) referenced.add(id);
for (const id of state.redoStack) referenced.add(id);
}
const kept: Record<string, Version> = {};
let droppedAny = false;
for (const key of Object.keys(versionCache)) {
if (referenced.has(key)) {
kept[key] = versionCache[key];
} else {
droppedAny = true;
}
}
const keptKeys = Object.keys(kept);
if (keptKeys.length <= MAX_VERSION_CACHE_SIZE) {
return droppedAny ? kept : versionCache;
}
const trimmed: Record<string, Version> = {};
const startIdx = keptKeys.length - MAX_VERSION_CACHE_SIZE;
for (let i = startIdx; i < keptKeys.length; i++) {
trimmed[keptKeys[i]] = kept[keptKeys[i]];
}
return trimmed;
}
/** Skip pruning when the cache is below the cap. */
function pruneVersionCache(
versionCache: Record<string, Version>,
entityStates: Record<EntityKey, UndoRedoState>
): Record<string, Version> {
if (Object.keys(versionCache).length <= MAX_VERSION_CACHE_SIZE) {
return versionCache;
}
return pruneVersionCacheForced(versionCache, entityStates);
}
interface UndoRedoState {
// Stack of version IDs we can undo (most recent at end)
undoStack: string[];
// Stack of version IDs we can redo (most recent at end)
redoStack: string[];
// Whether we can undo/redo
canUndo: boolean;
canRedo: boolean;
// Loading state for this entity
isLoading: boolean;
}
interface VersionsState {
// Undo/redo state per entity
entityStates: Record<EntityKey, UndoRedoState>;
// Cached version data
versionCache: Record<string, Version>;
// History summaries for UI display
historySummaries: Record<EntityKey, VersionHistoryItem[]>;
// Global loading state
isLoading: boolean;
// Error state
error: string | null;
// Session ID for grouping operations
sessionId: string | null;
// Whether undo/redo is in progress (prevents recursive tracking)
isUndoRedoInProgress: boolean;
}
interface VersionsActions {
// Initialize session
initSession: () => string;
getSessionId: () => string;
// Entity state management
initEntityState: (entityType: VersionEntityType, entityId: string) => void;
getEntityState: (entityType: VersionEntityType, entityId: string) => UndoRedoState | null;
// Load version history from server
loadVersionHistory: (entityType: VersionEntityType, entityId: string, currentStateHash?: string) => Promise<void>;
// Record a new version (called after save operations)
recordVersion: (version: Version) => void;
// Undo/Redo operations
undo: (entityType: VersionEntityType, entityId: string) => Promise<Version | null>;
redo: (entityType: VersionEntityType, entityId: string) => Promise<Version | null>;
// Check undo/redo availability
canUndo: (entityType: VersionEntityType, entityId: string) => boolean;
canRedo: (entityType: VersionEntityType, entityId: string) => boolean;
// Get version at specific position
getVersionAtPosition: (entityType: VersionEntityType, entityId: string, position: number) => Promise<Version | null>;
// Clear history for an entity
clearHistory: (entityType: VersionEntityType, entityId: string) => void;
// Clear redo stack when new change is made
clearRedoStack: (entityType: VersionEntityType, entityId: string) => void;
// Error management
setError: (error: string | null) => void;
clearError: () => void;
// Undo/redo progress tracking
setUndoRedoInProgress: (inProgress: boolean) => void;
}
type VersionsStore = VersionsState & VersionsActions;
function createEntityKey(entityType: VersionEntityType, entityId: string): EntityKey {
return `${entityType}:${entityId}`;
}
function generateSessionId(): string {
return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
export const useVersionsStore = create<VersionsStore>((set, get) => ({
// Initial state
entityStates: {},
versionCache: {},
historySummaries: {},
isLoading: false,
error: null,
sessionId: null,
isUndoRedoInProgress: false,
// Initialize or get session ID
initSession: () => {
let { sessionId } = get();
if (!sessionId) {
sessionId = generateSessionId();
set({ sessionId });
}
return sessionId;
},
getSessionId: () => {
return get().sessionId || get().initSession();
},
// Initialize entity state
initEntityState: (entityType, entityId) => {
const key = createEntityKey(entityType, entityId);
const { entityStates } = get();
if (!entityStates[key]) {
set({
entityStates: {
...entityStates,
[key]: {
undoStack: [],
redoStack: [],
canUndo: false,
canRedo: false,
isLoading: false,
},
},
});
}
},
// Get entity state
getEntityState: (entityType, entityId) => {
const key = createEntityKey(entityType, entityId);
return get().entityStates[key] || null;
},
// Load version history from server
loadVersionHistory: async (entityType, entityId, currentStateHash?: string) => {
const key = createEntityKey(entityType, entityId);
set((state) => ({
entityStates: {
...state.entityStates,
[key]: {
...(state.entityStates[key] || {
undoStack: [],
redoStack: [],
canUndo: false,
canRedo: false,
}),
isLoading: true,
},
},
}));
try {
const response = await fetch(
`/ycode/api/versions?entityType=${entityType}&entityId=${entityId}&limit=100`
);
const result = await response.json();
if (result.error) {
set({ error: result.error });
return;
}
const versions: Version[] = result.data || [];
const versionsSorted = [...versions].reverse(); // Oldest to newest
// Cache versions
const newCache: Record<string, Version> = {};
versions.forEach((v) => {
newCache[v.id] = v;
});
// Determine which versions go in undo vs redo stacks
let undoStack: string[] = [];
let redoStack: string[] = [];
if (currentStateHash && versions.length > 0) {
// Find where we are in the version history
let foundMatch = false;
for (let i = 0; i < versionsSorted.length; i++) {
const version = versionsSorted[i];
// Case 1: Current state matches this version's current_hash
// We're AFTER this version - it and all before it can be undone
if (version.current_hash === currentStateHash) {
// All versions up to and including this one go in undoStack
undoStack = versionsSorted.slice(0, i + 1).map(v => v.id);
// Remaining versions go in redoStack
redoStack = versionsSorted.slice(i + 1).map(v => v.id);
foundMatch = true;
break;
}
// Case 2: Current state matches this version's previous_hash
// We're BEFORE this version - versions before can be undone, this and after can be redone
if (version.previous_hash === currentStateHash) {
// Versions before this go in undoStack
undoStack = versionsSorted.slice(0, i).map(v => v.id);
// This version and after go in redoStack
redoStack = versionsSorted.slice(i).map(v => v.id);
foundMatch = true;
break;
}
}
if (!foundMatch) {
// At latest - all versions can be undone
undoStack = versionsSorted.map(v => v.id);
redoStack = [];
}
} else {
// No hash provided - assume at latest
undoStack = versionsSorted.map(v => v.id);
redoStack = [];
}
const canUndo = undoStack.length > 0;
const canRedo = redoStack.length > 0;
set((state) => {
const nextEntityStates = {
...state.entityStates,
[key]: {
undoStack,
redoStack,
canUndo,
canRedo,
isLoading: false,
},
};
return {
versionCache: pruneVersionCache(
{ ...state.versionCache, ...newCache },
nextEntityStates
),
entityStates: nextEntityStates,
historySummaries: {
...state.historySummaries,
[key]: versions.map((v) => ({
id: v.id,
action_type: v.action_type,
description: v.description,
created_at: v.created_at,
})),
},
};
});
} catch (error) {
console.error('Failed to load version history:', error);
set({ error: 'Failed to load version history' });
set((state) => ({
entityStates: {
...state.entityStates,
[key]: {
...(state.entityStates[key] || {
undoStack: [],
redoStack: [],
canUndo: false,
canRedo: false,
}),
isLoading: false,
},
},
}));
}
},
// Record a new version
recordVersion: (version) => {
// Don't record during undo/redo operations
if (get().isUndoRedoInProgress) {
return;
}
const key = createEntityKey(version.entity_type, version.entity_id);
const { entityStates, versionCache } = get();
const entityState = entityStates[key] || {
undoStack: [],
redoStack: [],
canUndo: false,
canRedo: false,
isLoading: false,
};
// When recording a new version:
// 1. Add it to undo stack (push to end)
// 2. Clear redo stack (we've made a new change, any redo history is now invalid)
const newUndoStack = [...entityState.undoStack, version.id];
const nextEntityStates = {
...entityStates,
[key]: {
...entityState,
undoStack: newUndoStack,
redoStack: [], // Clear redo stack
canUndo: true,
canRedo: false,
},
};
set({
versionCache: pruneVersionCache(
{ ...versionCache, [version.id]: version },
nextEntityStates
),
entityStates: nextEntityStates,
});
},
// Undo operation
undo: async (entityType, entityId) => {
const key = createEntityKey(entityType, entityId);
const { entityStates, versionCache } = get();
const entityState = entityStates[key];
if (!entityState || entityState.undoStack.length === 0) {
return null;
}
// Pop the most recent version from undo stack
const versionId = entityState.undoStack[entityState.undoStack.length - 1];
let version = versionCache[versionId];
// Fetch if not cached
if (!version) {
try {
const response = await fetch(`/ycode/api/versions/${versionId}`);
const result = await response.json();
if (result.data) {
version = result.data;
set((state) => ({
versionCache: { ...state.versionCache, [versionId]: version! },
}));
}
} catch (error) {
console.error('Failed to fetch version:', error);
return null;
}
}
if (!version) {
return null;
}
// Move version from undo stack to redo stack
const newUndoStack = entityState.undoStack.slice(0, -1); // Remove last
const newRedoStack = [...entityState.redoStack, versionId]; // Add to end
// Get the previous version's metadata (N-1) to restore selection from
let previousVersionMetadata = null;
if (newUndoStack.length > 0) {
const previousVersionId = newUndoStack[newUndoStack.length - 1];
let previousVersion = versionCache[previousVersionId];
// Fetch if not cached
if (!previousVersion) {
try {
const response = await fetch(`/ycode/api/versions/${previousVersionId}`);
const result = await response.json();
if (result.data) {
previousVersion = result.data;
set((state) => ({
versionCache: { ...state.versionCache, [previousVersionId]: previousVersion! },
}));
}
} catch (error) {
console.error('Failed to fetch previous version for metadata:', error);
}
}
if (previousVersion?.metadata) {
previousVersionMetadata = previousVersion.metadata;
}
}
set((state) => ({
entityStates: {
...state.entityStates,
[key]: {
...state.entityStates[key],
undoStack: newUndoStack,
redoStack: newRedoStack,
canUndo: newUndoStack.length > 0,
canRedo: true,
},
},
}));
// Attach previous version metadata for selection restoration
return {
...version,
previousVersionMetadata,
};
},
// Redo operation
redo: async (entityType, entityId) => {
const key = createEntityKey(entityType, entityId);
const { entityStates, versionCache } = get();
const entityState = entityStates[key];
if (!entityState || entityState.redoStack.length === 0) {
return null;
}
// Pop the most recent version from redo stack
const versionId = entityState.redoStack[entityState.redoStack.length - 1];
let version = versionCache[versionId];
// Fetch if not cached
if (!version) {
try {
const response = await fetch(`/ycode/api/versions/${versionId}`);
const result = await response.json();
if (result.data) {
version = result.data;
set((state) => ({
versionCache: { ...state.versionCache, [versionId]: version! },
}));
}
} catch (error) {
console.error('Failed to fetch version:', error);
return null;
}
}
if (!version) {
return null;
}
// Move version from redo stack to undo stack
const newRedoStack = entityState.redoStack.slice(0, -1); // Remove last
const newUndoStack = [...entityState.undoStack, versionId]; // Add to end
set((state) => ({
entityStates: {
...state.entityStates,
[key]: {
...state.entityStates[key],
undoStack: newUndoStack,
redoStack: newRedoStack,
canUndo: true,
canRedo: newRedoStack.length > 0,
},
},
}));
return version;
},
// Check if can undo
canUndo: (entityType, entityId) => {
const key = createEntityKey(entityType, entityId);
const entityState = get().entityStates[key];
return entityState?.canUndo ?? false;
},
// Check if can redo
canRedo: (entityType, entityId) => {
const key = createEntityKey(entityType, entityId);
const entityState = get().entityStates[key];
return entityState?.canRedo ?? false;
},
// Get version at position (position in combined history: undo + redo stacks)
getVersionAtPosition: async (entityType, entityId, position) => {
const key = createEntityKey(entityType, entityId);
const { entityStates, versionCache } = get();
const entityState = entityStates[key];
if (!entityState) {
return null;
}
// Combined history: undo stack + redo stack
const allVersions = [...entityState.undoStack, ...entityState.redoStack];
if (position < 0 || position >= allVersions.length) {
return null;
}
const versionId = allVersions[position];
let version = versionCache[versionId];
if (!version) {
try {
const response = await fetch(`/ycode/api/versions/${versionId}`);
const result = await response.json();
if (result.data) {
version = result.data;
set((state) => ({
versionCache: { ...state.versionCache, [versionId]: version! },
}));
}
} catch (error) {
console.error('Failed to fetch version:', error);
return null;
}
}
return version || null;
},
// Clear history for an entity
clearHistory: (entityType, entityId) => {
const key = createEntityKey(entityType, entityId);
set((state) => {
const newEntityStates = { ...state.entityStates };
delete newEntityStates[key];
const newHistorySummaries = { ...state.historySummaries };
delete newHistorySummaries[key];
// Drop versions that were only referenced by the cleared entity.
// Temporarily fill above the cap so pruneVersionCache runs the orphan
// sweep regardless of current cache size.
const versionCache = pruneVersionCacheForced(state.versionCache, newEntityStates);
return {
entityStates: newEntityStates,
historySummaries: newHistorySummaries,
versionCache,
};
});
},
// Clear redo stack when new change is made (before save)
clearRedoStack: (entityType, entityId) => {
const key = createEntityKey(entityType, entityId);
const { entityStates } = get();
const entityState = entityStates[key];
if (!entityState) return;
// Only update if redo stack is not empty
if (entityState.redoStack.length > 0) {
set({
entityStates: {
...entityStates,
[key]: {
...entityState,
redoStack: [],
canRedo: false,
},
},
});
}
},
// Error management
setError: (error) => set({ error }),
clearError: () => set({ error: null }),
// Undo/redo progress tracking
setUndoRedoInProgress: (inProgress) => set({ isUndoRedoInProgress: inProgress }),
}));