-
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathhistoryStore.test.ts
More file actions
1514 lines (1236 loc) · 55.3 KB
/
Copy pathhistoryStore.test.ts
File metadata and controls
1514 lines (1236 loc) · 55.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
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { getHistoryStateView, useHistoryStore, initHistoryStoreRefs, setHistoryCallbacks, captureSnapshot as captureSnapshotFn, undo as undoFn, redo as redoFn, startBatch as startBatchFn, endBatch as endBatchFn, serializeHistoryStateForProject, hydrateHistoryStateFromProject, setHistoryDisabledForDebug, isHistoryDisabledForDebug } from '../../src/stores/historyStore';
import { findHistoryStateBoundaryViolations } from '../../src/stores/timeline/historyTimelineEditState';
import { timelineRuntimeCoordinator } from '../../src/services/timeline/timelineRuntimeCoordinator';
import type { Layer, TimelineClip } from '../../src/types';
import { createMockClip } from '../helpers/mockData';
type HistoryStoreRefs = Parameters<typeof initHistoryStoreRefs>[0];
type TimelineMockState = ReturnType<HistoryStoreRefs['timeline']['getState']>;
type MediaMockState = ReturnType<HistoryStoreRefs['media']['getState']>;
type DockMockState = ReturnType<HistoryStoreRefs['dock']['getState']>;
type LegacyClip = TimelineClip & {
startFrame?: number;
endFrame?: number;
mediaId?: string;
};
function mockClip(overrides: Partial<LegacyClip>): LegacyClip {
return {
...createMockClip({
id: overrides.id ?? 'clip-1',
trackId: overrides.trackId ?? 'v1',
}),
...overrides,
};
}
function mockLayer(overrides: Partial<Layer>): Layer {
return {
id: overrides.id ?? 'L1',
name: overrides.name ?? 'Layer 1',
visible: true,
opacity: 1,
blendMode: 'normal',
source: null,
effects: [],
position: { x: 0, y: 0, z: 0 },
scale: { x: 1, y: 1 },
rotation: 0,
...overrides,
};
}
function mockMediaFile(overrides: Partial<MediaMockState['files'][number]>): MediaMockState['files'][number] {
return {
id: overrides.id ?? 'file-1',
name: overrides.name ?? 'file.mp4',
type: overrides.type ?? 'video',
parentId: null,
createdAt: 0,
url: '',
...overrides,
};
}
function mockComposition(overrides: Partial<MediaMockState['compositions'][number]>): MediaMockState['compositions'][number] {
return {
id: overrides.id ?? 'comp-1',
name: overrides.name ?? 'Composition',
type: 'composition',
parentId: null,
createdAt: 0,
width: 1920,
height: 1080,
frameRate: 30,
duration: 10,
backgroundColor: '#000000',
...overrides,
};
}
function mockFolder(overrides: Partial<MediaMockState['folders'][number]>): MediaMockState['folders'][number] {
return {
id: overrides.id ?? 'folder-1',
name: overrides.name ?? 'Folder',
parentId: null,
isExpanded: false,
createdAt: 0,
...overrides,
};
}
function mockTextItem(overrides: Partial<MediaMockState['textItems'][number]>): MediaMockState['textItems'][number] {
return {
id: overrides.id ?? 'text-1',
name: overrides.name ?? 'Text',
type: 'text',
parentId: null,
createdAt: 0,
text: '',
fontFamily: 'Inter',
fontSize: 48,
color: '#ffffff',
duration: 5,
...overrides,
};
}
function mockSolidItem(overrides: Partial<MediaMockState['solidItems'][number]>): MediaMockState['solidItems'][number] {
return {
id: overrides.id ?? 'solid-1',
name: overrides.name ?? 'Solid',
type: 'solid',
parentId: null,
createdAt: 0,
color: '#ffffff',
width: 1920,
height: 1080,
duration: 5,
...overrides,
};
}
// Mock the external store references the history store reads from
function createMockStores() {
let timelineState: TimelineMockState = {
clips: [],
tracks: [{ id: 'v1', name: 'V1', type: 'video' as const, height: 60, muted: false, visible: true, solo: false }],
selectedClipIds: new Set<string>(),
zoom: 50,
scrollX: 0,
layers: [],
selectedLayerId: null,
clipKeyframes: new Map(),
markers: [],
isExporting: false,
};
let mediaState: MediaMockState = {
files: [],
compositions: [],
folders: [],
selectedIds: [],
expandedFolderIds: [],
textItems: [],
solidItems: [],
};
let dockState: DockMockState = { layout: null };
return {
timeline: {
getState: () => timelineState,
setState: (s: Partial<TimelineMockState>) => { timelineState = { ...timelineState, ...s }; },
},
media: {
getState: () => mediaState,
setState: (s: Partial<MediaMockState>) => { mediaState = { ...mediaState, ...s }; },
},
dock: {
getState: () => dockState,
setState: (s: Partial<DockMockState>) => { dockState = { ...dockState, ...s }; },
},
// Helpers to simulate changes
setTimelineState: (s: Partial<TimelineMockState>) => { timelineState = { ...timelineState, ...s }; },
setMediaState: (s: Partial<MediaMockState>) => { mediaState = { ...mediaState, ...s }; },
};
}
describe('historyStore', () => {
let mocks: ReturnType<typeof createMockStores>;
beforeEach(() => {
setHistoryDisabledForDebug(false);
// Reset history store state
useHistoryStore.setState({
nodes: {},
rootId: null,
activeNodeId: null,
lastVisitedChildByNodeId: {},
eventLog: [],
maxHistoryNodes: 150,
isApplying: false,
batchId: null,
batchLabel: null,
});
mocks = createMockStores();
initHistoryStoreRefs(mocks);
timelineRuntimeCoordinator.clearResources();
});
afterEach(() => {
timelineRuntimeCoordinator.clearResources();
});
it('captureSnapshot: first capture sets currentSnapshot', () => {
getHistoryStateView().captureSnapshot('first');
const state = getHistoryStateView();
expect(state.currentSnapshot).not.toBeNull();
expect(state.currentSnapshot!.label).toBe('first');
expect(state.undoStack.length).toBe(0);
});
it('captureSnapshot: stores a runtime-free timeline edit sidecar', () => {
const runtimeClip = mockClip({
id: 'runtime-clip',
file: { name: 'clip.mp4' } as File,
source: {
type: 'video',
mediaFileId: 'media-1',
file: { name: 'clip.mp4' } as File,
videoElement: { tagName: 'VIDEO' } as HTMLVideoElement,
naturalDuration: 12,
},
audioState: {
sourceAnalysisRefs: { waveformPyramidId: 'waveform-ref' },
processedAnalysisRefs: { processedWaveformPyramidId: 'processed-waveform-ref' },
},
});
const runtimeLayer = mockLayer({
id: 'runtime-layer',
sourceClipId: 'runtime-clip',
source: {
type: 'video',
mediaFileId: 'media-1',
file: { name: 'layer-source.mp4' } as File,
videoElement: { tagName: 'VIDEO' } as HTMLVideoElement,
} as NonNullable<Layer['source']>,
});
mocks.setTimelineState({
clips: [runtimeClip],
selectedClipIds: new Set(['runtime-clip']),
layers: [runtimeLayer],
selectedLayerId: 'runtime-layer',
});
getHistoryStateView().captureSnapshot('with runtime');
const timelineEditState = getHistoryStateView().currentSnapshot?.timelineEditState;
expect(timelineEditState).toBeDefined();
expect(findHistoryStateBoundaryViolations(timelineEditState)).toEqual([]);
expect(JSON.parse(JSON.stringify(timelineEditState))).toEqual(timelineEditState);
expect(timelineEditState?.timeline.clips[0].runtimeRef).toEqual({
kind: 'media-file',
sourceType: 'video',
mediaFileId: 'media-1',
naturalDuration: 12,
});
expect(timelineEditState?.timeline.layers[0].sourceRef).toEqual({
type: 'video',
sourceClipId: 'runtime-clip',
mediaFileId: 'media-1',
});
});
it('captureSnapshot: derives legacy timeline data from the runtime-free sidecar', () => {
const runtimeFile = new File(['video'], 'clip.mp4', { type: 'video/mp4' });
const runtimeVideo = { tagName: 'VIDEO', runtimeId: 'snapshot-video' } as unknown as HTMLVideoElement;
const runtimeLayerSource = {
type: 'video',
mediaFileId: 'media-1',
file: runtimeFile,
videoElement: runtimeVideo,
} as NonNullable<Layer['source']>;
mocks.setTimelineState({
clips: [
mockClip({
id: 'runtime-clip',
file: runtimeFile,
source: {
type: 'video',
mediaFileId: 'media-1',
file: runtimeFile,
videoElement: runtimeVideo,
naturalDuration: 12,
},
mediaFileId: 'media-1',
}),
],
layers: [
mockLayer({
id: 'runtime-layer',
sourceClipId: 'runtime-clip',
source: runtimeLayerSource,
}),
],
});
getHistoryStateView().captureSnapshot('with runtime');
const snapshot = getHistoryStateView().currentSnapshot;
const legacyClip = snapshot?.timeline.clips[0];
const legacyLayer = snapshot?.timeline.layers[0];
expect(legacyClip?.source?.videoElement).toBeUndefined();
expect(legacyClip?.source?.webCodecsPlayer).toBeUndefined();
expect(legacyClip?.source?.file).toBeUndefined();
expect(legacyClip?.file).not.toBe(runtimeFile);
expect(legacyClip?.file instanceof File).toBe(false);
expect(legacyLayer?.source?.videoElement).toBeUndefined();
expect(legacyLayer?.source?.file).toBeUndefined();
});
it('captureSnapshot: second capture pushes first to undoStack', () => {
getHistoryStateView().captureSnapshot('first');
getHistoryStateView().captureSnapshot('second');
const state = getHistoryStateView();
expect(state.undoStack.length).toBe(1);
expect(state.undoStack[0].label).toBe('first');
expect(state.currentSnapshot!.label).toBe('second');
});
it('captureSnapshot: clears redo stack on new action', () => {
getHistoryStateView().captureSnapshot('first');
getHistoryStateView().captureSnapshot('second');
getHistoryStateView().captureSnapshot('third');
// Undo to create redo stack
getHistoryStateView().undo();
expect(getHistoryStateView().redoStack.length).toBe(1);
// New action clears redo
getHistoryStateView().captureSnapshot('new-action');
expect(getHistoryStateView().redoStack.length).toBe(0);
});
it('captureSnapshot: does not capture during isApplying', () => {
useHistoryStore.setState({ isApplying: true });
getHistoryStateView().captureSnapshot('should-not-capture');
expect(getHistoryStateView().currentSnapshot).toBeNull();
});
it('debug disable: suppresses captures and batches', () => {
setHistoryDisabledForDebug(true);
expect(isHistoryDisabledForDebug()).toBe(true);
getHistoryStateView().captureSnapshot('hidden');
getHistoryStateView().startBatch('hidden batch');
getHistoryStateView().endBatch();
const state = getHistoryStateView();
expect(state.currentSnapshot).toBeNull();
expect(state.undoStack).toEqual([]);
expect(state.batchId).toBeNull();
});
it('captureSnapshot: does not capture during batch', () => {
getHistoryStateView().captureSnapshot('initial');
getHistoryStateView().startBatch('batch');
getHistoryStateView().captureSnapshot('during-batch');
// Still only 1 snapshot (initial), nothing new pushed
expect(getHistoryStateView().undoStack.length).toBe(0);
});
it('undo: restores previous state', () => {
// Capture initial state
getHistoryStateView().captureSnapshot('add track');
// Change state
mocks.setTimelineState({ zoom: 100 });
getHistoryStateView().captureSnapshot('zoom change');
expect(getHistoryStateView().undoStack.length).toBe(1);
// Undo
getHistoryStateView().undo();
// Timeline state should be restored
expect(mocks.timeline.getState().zoom).toBe(50); // original value
expect(getHistoryStateView().undoStack.length).toBe(0);
expect(getHistoryStateView().redoStack.length).toBe(1);
});
it('undo: restores from timelineEditState and reuses compatible current runtime', () => {
const oldVideo = { tagName: 'VIDEO', runtimeId: 'old-video' } as unknown as HTMLVideoElement;
const currentVideo = { tagName: 'VIDEO', runtimeId: 'current-video' } as unknown as HTMLVideoElement;
const firstClip = mockClip({
id: 'runtime-clip',
startTime: 0,
mediaFileId: 'media-1',
source: {
type: 'video',
mediaFileId: 'media-1',
videoElement: oldVideo,
naturalDuration: 12,
},
});
const secondClip = mockClip({
...firstClip,
startTime: 5,
source: {
type: 'video',
mediaFileId: 'media-1',
videoElement: currentVideo,
naturalDuration: 12,
},
});
mocks.setTimelineState({ clips: [firstClip] });
getHistoryStateView().captureSnapshot('initial runtime');
mocks.setTimelineState({ clips: [secondClip] });
getHistoryStateView().captureSnapshot('moved runtime');
getHistoryStateView().undo();
const restoredClip = mocks.timeline.getState().clips[0];
expect(restoredClip.startTime).toBe(0);
expect(restoredClip.source?.videoElement).toBe(currentVideo);
expect(restoredClip.source?.videoElement).not.toBe(oldVideo);
});
it('undo: reports rehydrated compatible runtime resources after restore', () => {
const oldVideo = document.createElement('video');
oldVideo.src = 'blob:old-video';
const currentVideo = document.createElement('video');
currentVideo.src = 'blob:current-video';
const firstClip = mockClip({
id: 'runtime-clip',
startTime: 0,
mediaFileId: 'media-1',
source: {
type: 'video',
mediaFileId: 'media-1',
runtimeSourceId: 'media:media-1',
runtimeSessionKey: 'interactive:old',
videoElement: oldVideo,
naturalDuration: 12,
},
});
const secondClip = mockClip({
...firstClip,
startTime: 5,
source: {
type: 'video',
mediaFileId: 'media-1',
runtimeSourceId: 'media:media-1',
runtimeSessionKey: 'interactive:current',
videoElement: currentVideo,
naturalDuration: 12,
},
});
mocks.setTimelineState({ clips: [firstClip] });
getHistoryStateView().captureSnapshot('initial runtime');
mocks.setTimelineState({ clips: [secondClip] });
getHistoryStateView().captureSnapshot('moved runtime');
timelineRuntimeCoordinator.clearResources();
getHistoryStateView().undo();
const resources = timelineRuntimeCoordinator.getBridgeStats().policies.interactive.resources;
expect(resources.map((resource) => resource.owner.ownerId).toSorted()).toEqual([
'history-rehydrate:runtime-clip',
'history-rehydrate:runtime-clip',
]);
expect(JSON.stringify(resources)).toContain('interactive:current');
expect(JSON.stringify(resources)).not.toContain('interactive:old');
});
it('undo: restores deleted clips as data-only lazy reload entries', () => {
const oldVideo = { tagName: 'VIDEO', runtimeId: 'deleted-video' } as unknown as HTMLVideoElement;
const firstClip = mockClip({
id: 'deleted-runtime-clip',
mediaFileId: 'media-1',
source: {
type: 'video',
mediaFileId: 'media-1',
videoElement: oldVideo,
naturalDuration: 12,
},
});
mocks.setTimelineState({ clips: [firstClip] });
getHistoryStateView().captureSnapshot('initial runtime');
mocks.setTimelineState({ clips: [] });
getHistoryStateView().captureSnapshot('delete runtime');
getHistoryStateView().undo();
const restoredClip = mocks.timeline.getState().clips[0];
expect(restoredClip.id).toBe('deleted-runtime-clip');
expect(restoredClip.source?.videoElement).toBeUndefined();
expect(restoredClip.source?.mediaFileId).toBe('media-1');
expect(restoredClip.mediaFileId).toBe('media-1');
expect(restoredClip.needsReload).toBe(true);
});
it('undo: returns the label of the action being undone', () => {
getHistoryStateView().captureSnapshot('initial');
mocks.setTimelineState({ zoom: 100 });
getHistoryStateView().captureSnapshot('zoom change');
const result = getHistoryStateView().undo();
expect(result).toEqual({ operation: 'undo', label: 'zoom change' });
});
it('redo: restores undone state', () => {
getHistoryStateView().captureSnapshot('initial');
mocks.setTimelineState({ zoom: 100 });
getHistoryStateView().captureSnapshot('zoom 100');
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(50);
getHistoryStateView().redo();
expect(mocks.timeline.getState().zoom).toBe(100);
expect(getHistoryStateView().redoStack.length).toBe(0);
expect(getHistoryStateView().undoStack.length).toBe(1);
});
it('redo: returns the label of the action being redone', () => {
getHistoryStateView().captureSnapshot('initial');
mocks.setTimelineState({ zoom: 100 });
getHistoryStateView().captureSnapshot('zoom 100');
getHistoryStateView().undo();
const result = getHistoryStateView().redo();
expect(result).toEqual({ operation: 'redo', label: 'zoom 100' });
});
it('canUndo / canRedo: reflect stack state', () => {
expect(getHistoryStateView().canUndo()).toBe(false);
expect(getHistoryStateView().canRedo()).toBe(false);
getHistoryStateView().captureSnapshot('a');
getHistoryStateView().captureSnapshot('b');
expect(getHistoryStateView().canUndo()).toBe(true);
expect(getHistoryStateView().canRedo()).toBe(false);
getHistoryStateView().undo();
expect(getHistoryStateView().canUndo()).toBe(false);
expect(getHistoryStateView().canRedo()).toBe(true);
});
it('getHistoryEntries: lists undoable, current, and redoable snapshots', () => {
getHistoryStateView().captureSnapshot('a');
getHistoryStateView().captureSnapshot('b');
getHistoryStateView().captureSnapshot('c');
getHistoryStateView().undo();
expect(getHistoryStateView().getHistoryEntries().map((entry) => ({
kind: entry.kind,
label: entry.label,
}))).toEqual([
{ kind: 'undoable', label: 'a' },
{ kind: 'current', label: 'b' },
{ kind: 'redoable', label: 'c' },
]);
});
it('project persistence: serializes and hydrates visible history metadata', () => {
mocks.setTimelineState({ zoom: 10 });
getHistoryStateView().captureSnapshot('zoom 10');
mocks.setTimelineState({ zoom: 20 });
getHistoryStateView().captureSnapshot('zoom 20');
const persisted = serializeHistoryStateForProject();
getHistoryStateView().clearHistory();
mocks.setTimelineState({ zoom: 999 });
hydrateHistoryStateFromProject(persisted);
expect(getHistoryStateView().getHistoryEntries().map((entry) => entry.label))
.toEqual(['zoom 10', 'zoom 20']);
expect(getHistoryStateView().undo()).toMatchObject({ operation: 'undo', label: 'zoom 20' });
expect(mocks.timeline.getState().zoom).toBe(10);
});
it('project persistence: strips browser-only media payloads from snapshots', () => {
const file = new File(['payload'], 'clip.mp4', { type: 'video/mp4' });
mocks.setMediaState({
files: [
mockMediaFile({
file,
url: 'blob:video-url',
thumbnailUrl: 'blob:thumb-url',
proxyVideoUrl: 'blob:proxy-url',
}),
],
});
getHistoryStateView().captureSnapshot('with media file');
const serialized = JSON.stringify(serializeHistoryStateForProject());
expect(serialized).not.toContain('blob:');
expect(serialized).not.toContain('"file"');
});
// ─── Batch operations ────────────────────────────────────────────────
it('startBatch / endBatch: groups changes into one undo step', () => {
getHistoryStateView().captureSnapshot('initial');
expect(getHistoryStateView().undoStack.length).toBe(0);
getHistoryStateView().startBatch('batch op');
// Multiple state changes during batch
mocks.setTimelineState({ zoom: 80 });
mocks.setTimelineState({ zoom: 120 });
getHistoryStateView().endBatch();
// Only one entry should be in undo stack
expect(getHistoryStateView().undoStack.length).toBe(1);
expect(getHistoryStateView().currentSnapshot!.label).toBe('batch op');
});
it('startBatch: ignored if already batching', () => {
getHistoryStateView().startBatch('first');
const batchId = getHistoryStateView().batchId;
getHistoryStateView().startBatch('second');
// Should not change
expect(getHistoryStateView().batchId).toBe(batchId);
expect(getHistoryStateView().batchLabel).toBe('first');
getHistoryStateView().endBatch();
});
it('endBatch: no-op if not batching', () => {
getHistoryStateView().endBatch(); // should not throw
expect(getHistoryStateView().batchId).toBeNull();
});
// ─── Map serialization ───────────────────────────────────────────────
it('snapshot serializes Map<string, Keyframe[]> to Record', () => {
const keyframeMap = new Map([
['clip-1', [{ id: 'kf1', clipId: 'clip-1', time: 0, property: 'opacity', value: 1, easing: 'linear' }]],
]);
mocks.setTimelineState({ clipKeyframes: keyframeMap });
getHistoryStateView().captureSnapshot('with keyframes');
const snapshot = getHistoryStateView().currentSnapshot!;
// Should be serialized to Record, not Map
expect(snapshot.timeline.clipKeyframes).toHaveProperty('clip-1');
expect(Array.isArray(snapshot.timeline.clipKeyframes['clip-1'])).toBe(true);
});
it('undo restores Map from Record (deserialization)', () => {
// Set up initial state with Map
const keyframeMap = new Map([
['clip-1', [{ id: 'kf1', clipId: 'clip-1', time: 0, property: 'opacity', value: 1, easing: 'linear' }]],
]);
mocks.setTimelineState({ clipKeyframes: keyframeMap });
getHistoryStateView().captureSnapshot('with keyframes');
// Change keyframes
mocks.setTimelineState({ clipKeyframes: new Map() });
getHistoryStateView().captureSnapshot('removed keyframes');
// Undo should restore the Map
getHistoryStateView().undo();
const restored = mocks.timeline.getState().clipKeyframes;
expect(restored instanceof Map).toBe(true);
expect(restored.get('clip-1')?.length).toBe(1);
});
it('undo restores Set from array (selectedClipIds)', () => {
mocks.setTimelineState({ selectedClipIds: new Set(['a', 'b']) });
getHistoryStateView().captureSnapshot('with selection');
mocks.setTimelineState({ selectedClipIds: new Set() });
getHistoryStateView().captureSnapshot('cleared');
getHistoryStateView().undo();
const restored = mocks.timeline.getState().selectedClipIds;
expect(restored instanceof Set).toBe(true);
expect(restored.has('a')).toBe(true);
expect(restored.has('b')).toBe(true);
});
// ─── clearHistory ────────────────────────────────────────────────────
it('clearHistory: resets all stacks', () => {
getHistoryStateView().captureSnapshot('a');
getHistoryStateView().captureSnapshot('b');
getHistoryStateView().clearHistory();
const state = getHistoryStateView();
expect(state.undoStack.length).toBe(0);
expect(state.redoStack.length).toBe(0);
expect(state.currentSnapshot).toBeNull();
});
// ─── History size limit ──────────────────────────────────────────────
it('respects maxHistorySize', () => {
useHistoryStore.setState({ maxHistoryNodes: 3 });
for (let i = 0; i < 6; i++) {
getHistoryStateView().captureSnapshot(`action-${i}`);
}
// 5 captures create 5 undo entries (first becomes current, next 5 push)
// But capped at 3
expect(getHistoryStateView().undoStack.length).toBeLessThanOrEqual(3);
});
it('respects maxHistorySize: oldest entries are removed first', () => {
useHistoryStore.setState({ maxHistoryNodes: 3 });
for (let i = 0; i < 6; i++) {
getHistoryStateView().captureSnapshot(`action-${i}`);
}
const state = getHistoryStateView();
// The oldest labels should have been shifted out
const labels = state.undoStack.map((s) => s.label);
expect(labels).not.toContain('action-0');
expect(labels).not.toContain('action-1');
// Current snapshot should be the latest
expect(state.currentSnapshot!.label).toBe('action-5');
});
// ─── Undo edge cases ──────────────────────────────────────────────
it('undo: no-op when undo stack is empty', () => {
getHistoryStateView().captureSnapshot('only');
const stateBefore = getHistoryStateView();
expect(stateBefore.undoStack.length).toBe(0);
getHistoryStateView().undo(); // should not throw
const stateAfter = getHistoryStateView();
expect(stateAfter.undoStack.length).toBe(0);
expect(stateAfter.redoStack.length).toBe(0);
expect(stateAfter.currentSnapshot!.label).toBe('only');
});
it('undo: no-op when no snapshots exist at all', () => {
getHistoryStateView().undo(); // should not throw
expect(getHistoryStateView().currentSnapshot).toBeNull();
expect(getHistoryStateView().undoStack.length).toBe(0);
expect(getHistoryStateView().redoStack.length).toBe(0);
});
it('redo: no-op when redo stack is empty', () => {
getHistoryStateView().captureSnapshot('a');
getHistoryStateView().captureSnapshot('b');
getHistoryStateView().redo(); // should not throw, redo is empty
const state = getHistoryStateView();
expect(state.currentSnapshot!.label).toBe('b');
expect(state.undoStack.length).toBe(1);
expect(state.redoStack.length).toBe(0);
});
// ─── Multiple sequential undo/redo ─────────────────────────────────
it('undo/redo: blocked while timeline export is active', () => {
mocks.setTimelineState({ zoom: 10 });
getHistoryStateView().captureSnapshot('zoom-10');
mocks.setTimelineState({ zoom: 20 });
getHistoryStateView().captureSnapshot('zoom-20');
mocks.setTimelineState({ isExporting: true });
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(20);
expect(getHistoryStateView().currentSnapshot!.label).toBe('zoom-20');
mocks.setTimelineState({ isExporting: false });
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(10);
mocks.setTimelineState({ isExporting: true });
getHistoryStateView().redo();
expect(mocks.timeline.getState().zoom).toBe(10);
});
it('multiple sequential undos restore state correctly', () => {
mocks.setTimelineState({ zoom: 10 });
getHistoryStateView().captureSnapshot('zoom-10');
mocks.setTimelineState({ zoom: 20 });
getHistoryStateView().captureSnapshot('zoom-20');
mocks.setTimelineState({ zoom: 30 });
getHistoryStateView().captureSnapshot('zoom-30');
// Undo to zoom-20
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(20);
expect(getHistoryStateView().undoStack.length).toBe(1);
expect(getHistoryStateView().redoStack.length).toBe(1);
// Undo to zoom-10
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(10);
expect(getHistoryStateView().undoStack.length).toBe(0);
expect(getHistoryStateView().redoStack.length).toBe(2);
});
it('multiple sequential redos restore state correctly', () => {
mocks.setTimelineState({ zoom: 10 });
getHistoryStateView().captureSnapshot('zoom-10');
mocks.setTimelineState({ zoom: 20 });
getHistoryStateView().captureSnapshot('zoom-20');
mocks.setTimelineState({ zoom: 30 });
getHistoryStateView().captureSnapshot('zoom-30');
// Undo twice
getHistoryStateView().undo();
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(10);
// Redo to zoom-20
getHistoryStateView().redo();
expect(mocks.timeline.getState().zoom).toBe(20);
expect(getHistoryStateView().redoStack.length).toBe(1);
// Redo to zoom-30
getHistoryStateView().redo();
expect(mocks.timeline.getState().zoom).toBe(30);
expect(getHistoryStateView().redoStack.length).toBe(0);
});
it('interleaved undo/redo preserves state correctly', () => {
mocks.setTimelineState({ zoom: 10 });
getHistoryStateView().captureSnapshot('z10');
mocks.setTimelineState({ zoom: 20 });
getHistoryStateView().captureSnapshot('z20');
mocks.setTimelineState({ zoom: 30 });
getHistoryStateView().captureSnapshot('z30');
// Undo to z20
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(20);
// Redo back to z30
getHistoryStateView().redo();
expect(mocks.timeline.getState().zoom).toBe(30);
// Undo to z20 again
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(20);
// Undo to z10
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(10);
// Redo to z20
getHistoryStateView().redo();
expect(mocks.timeline.getState().zoom).toBe(20);
});
// ─── Undo/redo ends stuck batches ──────────────────────────────────
it('undo: ends stuck batch before undoing', () => {
getHistoryStateView().captureSnapshot('initial');
mocks.setTimelineState({ zoom: 80 });
getHistoryStateView().captureSnapshot('zoom-80');
// Start a batch but "forget" to end it (simulate lost mouseup)
getHistoryStateView().startBatch('stuck-batch');
mocks.setTimelineState({ zoom: 150 });
// Undo should first end the batch, then undo
getHistoryStateView().undo();
// Batch should be ended
expect(getHistoryStateView().batchId).toBeNull();
expect(getHistoryStateView().batchLabel).toBeNull();
});
it('redo: ends stuck batch before redoing', () => {
getHistoryStateView().captureSnapshot('initial');
mocks.setTimelineState({ zoom: 80 });
getHistoryStateView().captureSnapshot('zoom-80');
// Undo to create redo entry
getHistoryStateView().undo();
// Start a batch but "forget" to end it
getHistoryStateView().startBatch('stuck-batch');
// Redo should first end the batch
getHistoryStateView().redo();
expect(getHistoryStateView().batchId).toBeNull();
expect(getHistoryStateView().batchLabel).toBeNull();
});
// ─── Batch advanced scenarios ──────────────────────────────────────
it('endBatch: clears redo stack', () => {
getHistoryStateView().captureSnapshot('initial');
mocks.setTimelineState({ zoom: 80 });
getHistoryStateView().captureSnapshot('zoom-80');
// Undo to create redo entries
getHistoryStateView().undo();
expect(getHistoryStateView().redoStack.length).toBe(1);
// Start and end a batch — should clear redo
getHistoryStateView().startBatch('new-batch');
mocks.setTimelineState({ zoom: 200 });
getHistoryStateView().endBatch();
expect(getHistoryStateView().redoStack.length).toBe(0);
});
it('startBatch: creates currentSnapshot if none exists', () => {
expect(getHistoryStateView().currentSnapshot).toBeNull();
getHistoryStateView().startBatch('from-scratch');
// startBatch should have auto-created a snapshot
expect(getHistoryStateView().currentSnapshot).not.toBeNull();
expect(getHistoryStateView().currentSnapshot!.label).toBe('initial');
expect(getHistoryStateView().batchId).not.toBeNull();
getHistoryStateView().endBatch();
});
it('endBatch without prior currentSnapshot: only sets currentSnapshot', () => {
// Manually reset to ensure no currentSnapshot
useHistoryStore.setState({
nodes: {},
rootId: null,
activeNodeId: null,
lastVisitedChildByNodeId: {},
batchId: Date.now(),
batchLabel: 'test',
});
getHistoryStateView().endBatch();
// When currentSnapshot is null during endBatch, it should just set the final snapshot
const state = getHistoryStateView();
expect(state.currentSnapshot).not.toBeNull();
expect(state.currentSnapshot!.label).toBe('test');
expect(state.undoStack.length).toBe(0); // no previous snapshot to push
expect(state.batchId).toBeNull();
expect(state.batchLabel).toBeNull();
});
it('endBatch respects maxHistorySize', () => {
// Tree capacity includes the current snapshot in addition to undoable nodes.
useHistoryStore.setState({ maxHistoryNodes: 3 });
// Fill undo stack
getHistoryStateView().captureSnapshot('a');
getHistoryStateView().captureSnapshot('b');
getHistoryStateView().captureSnapshot('c');
// undoStack should already be capped at 2
expect(getHistoryStateView().undoStack.length).toBe(2);
// Do a batch — should also respect cap
getHistoryStateView().startBatch('batch');
mocks.setTimelineState({ zoom: 999 });
getHistoryStateView().endBatch();
expect(getHistoryStateView().undoStack.length).toBeLessThanOrEqual(2);
});
it('batch then undo restores pre-batch state', () => {
mocks.setTimelineState({ zoom: 50 });
getHistoryStateView().captureSnapshot('initial');
getHistoryStateView().startBatch('drag resize');
mocks.setTimelineState({ zoom: 60 });
mocks.setTimelineState({ zoom: 70 });
mocks.setTimelineState({ zoom: 80 });
getHistoryStateView().endBatch();
expect(mocks.timeline.getState().zoom).toBe(80);
// Undo the entire batch
getHistoryStateView().undo();
expect(mocks.timeline.getState().zoom).toBe(50);
});
it('batch undo restores legacy transition links and removes the upgraded composition', () => {
const legacyLink = { id: 'transition-1', type: 'crossfade' as const, duration: 1, linkedClipId: 'in', compositionId: 'legacy' };
const outgoing = mockClip({ id: 'out', transitionOut: legacyLink });
const incoming = mockClip({ id: 'in', transitionIn: { ...legacyLink, linkedClipId: 'out' } });
const parent = mockComposition({
id: 'parent',
timelineData: { tracks: [], clips: [outgoing, incoming], duration: 10 } as never,
});
const legacy = mockComposition({
id: 'legacy',
transitionComp: {
kind: 'transition-comp',
sourceLayout: 'legacy-segmented',
parentCompositionId: parent.id,
parentTransitionId: legacyLink.id,
parentOutgoingClipId: outgoing.id,
parentIncomingClipId: incoming.id,
linkedOutgoingClipId: 'legacy-out',
linkedIncomingClipId: 'legacy-in',
innerTransitionId: 'legacy-inner',
paddingBefore: 0,
paddingAfter: 0,
bodyStart: 0,
bodyEnd: 1,
},
});
const mappedId = 'mapped';
const upgradedParent = {
...parent,
timelineData: {
...parent.timelineData!,
clips: parent.timelineData!.clips.map((clip) => (