-
Notifications
You must be signed in to change notification settings - Fork 14.2k
Expand file tree
/
Copy pathtext-buffer.test.ts
More file actions
3205 lines (2873 loc) · 107 KB
/
Copy pathtext-buffer.test.ts
File metadata and controls
3205 lines (2873 loc) · 107 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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import stripAnsi from 'strip-ansi';
import { act } from 'react';
import {
renderHook,
renderHookWithProviders,
} from '../../../test-utils/render.js';
import type {
Viewport,
TextBuffer,
TextBufferState,
TextBufferAction,
Transformation,
VisualLayout,
TextBufferOptions,
} from './text-buffer.js';
import {
useTextBuffer,
offsetToLogicalPos,
logicalPosToOffset,
textBufferReducer,
findWordEndInLine,
findNextWordStartInLine,
isWordCharStrict,
calculateTransformationsForLine,
calculateTransformedLine,
getTransformUnderCursor,
getTransformedImagePath,
} from './text-buffer.js';
import { cpLen } from '../../utils/textUtils.js';
const defaultVisualLayout: VisualLayout = {
visualLines: [''],
logicalToVisualMap: [[[0, 0]]],
visualToLogicalMap: [[0, 0]],
transformedToLogicalMaps: [[]],
visualToTransformedMap: [],
};
const initialState: TextBufferState = {
lines: [''],
cursorRow: 0,
cursorCol: 0,
preferredCol: null,
undoStack: [],
redoStack: [],
clipboard: null,
selectionAnchor: null,
viewportWidth: 80,
viewportHeight: 24,
transformationsByLine: [[]],
visualLayout: defaultVisualLayout,
pastedContent: {},
expandedPaste: null,
};
/**
* Helper to create a TextBufferState with properly calculated transformations.
*/
function createStateWithTransformations(
partial: Partial<TextBufferState>,
): TextBufferState {
const state = { ...initialState, ...partial };
return {
...state,
transformationsByLine: state.lines.map((l) =>
calculateTransformationsForLine(l),
),
};
}
describe('textBufferReducer', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('should return the initial state if state is undefined', () => {
const action = { type: 'unknown_action' } as unknown as TextBufferAction;
const state = textBufferReducer(initialState, action);
expect(state).toHaveOnlyValidCharacters();
expect(state).toEqual(initialState);
});
describe('set_text action', () => {
it('should set new text and move cursor to the end', () => {
const action: TextBufferAction = {
type: 'set_text',
payload: 'hello\nworld',
};
const state = textBufferReducer(initialState, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['hello', 'world']);
expect(state.cursorRow).toBe(1);
expect(state.cursorCol).toBe(5);
expect(state.undoStack.length).toBe(1);
});
it('should not create an undo snapshot if pushToUndo is false', () => {
const action: TextBufferAction = {
type: 'set_text',
payload: 'no undo',
pushToUndo: false,
};
const state = textBufferReducer(initialState, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['no undo']);
expect(state.undoStack.length).toBe(0);
});
});
describe('insert action', () => {
it('should insert a character', () => {
const action: TextBufferAction = { type: 'insert', payload: 'a' };
const state = textBufferReducer(initialState, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['a']);
expect(state.cursorCol).toBe(1);
});
it('should insert a newline', () => {
const stateWithText = { ...initialState, lines: ['hello'] };
const action: TextBufferAction = { type: 'insert', payload: '\n' };
const state = textBufferReducer(stateWithText, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['', 'hello']);
expect(state.cursorRow).toBe(1);
expect(state.cursorCol).toBe(0);
});
});
describe('insert action with options', () => {
it('should filter input using inputFilter option', () => {
const action: TextBufferAction = { type: 'insert', payload: 'a1b2c3' };
const options: TextBufferOptions = {
inputFilter: (text) => text.replace(/[0-9]/g, ''),
};
const state = textBufferReducer(initialState, action, options);
expect(state.lines).toEqual(['abc']);
expect(state.cursorCol).toBe(3);
});
it('should strip newlines when singleLine option is true', () => {
const action: TextBufferAction = {
type: 'insert',
payload: 'hello\nworld',
};
const options: TextBufferOptions = { singleLine: true };
const state = textBufferReducer(initialState, action, options);
expect(state.lines).toEqual(['helloworld']);
expect(state.cursorCol).toBe(10);
});
it('should apply both inputFilter and singleLine options', () => {
const action: TextBufferAction = {
type: 'insert',
payload: 'h\ne\nl\nl\no\n1\n2\n3',
};
const options: TextBufferOptions = {
singleLine: true,
inputFilter: (text) => text.replace(/[0-9]/g, ''),
};
const state = textBufferReducer(initialState, action, options);
expect(state.lines).toEqual(['hello']);
expect(state.cursorCol).toBe(5);
});
});
describe('add_pasted_content action', () => {
it('should add content to pastedContent Record', () => {
const action: TextBufferAction = {
type: 'add_pasted_content',
payload: { id: '[Pasted Text: 6 lines]', text: 'large content' },
};
const state = textBufferReducer(initialState, action);
expect(state.pastedContent).toEqual({
'[Pasted Text: 6 lines]': 'large content',
});
});
});
describe('backspace action', () => {
it('should remove a character', () => {
const stateWithText: TextBufferState = {
...initialState,
lines: ['a'],
cursorRow: 0,
cursorCol: 1,
};
const action: TextBufferAction = { type: 'backspace' };
const state = textBufferReducer(stateWithText, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['']);
expect(state.cursorCol).toBe(0);
});
it('should join lines if at the beginning of a line', () => {
const stateWithText: TextBufferState = {
...initialState,
lines: ['hello', 'world'],
cursorRow: 1,
cursorCol: 0,
};
const action: TextBufferAction = { type: 'backspace' };
const state = textBufferReducer(stateWithText, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['helloworld']);
expect(state.cursorRow).toBe(0);
expect(state.cursorCol).toBe(5);
});
});
describe('atomic placeholder deletion', () => {
describe('paste placeholders', () => {
it('backspace at end of paste placeholder removes entire placeholder', () => {
const placeholder = '[Pasted Text: 6 lines]';
const stateWithPlaceholder = createStateWithTransformations({
lines: [placeholder],
cursorRow: 0,
cursorCol: placeholder.length, // cursor at end
pastedContent: {
[placeholder]: 'line1\nline2\nline3\nline4\nline5\nline6',
},
});
const action: TextBufferAction = { type: 'backspace' };
const state = textBufferReducer(stateWithPlaceholder, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['']);
expect(state.cursorCol).toBe(0);
// pastedContent should be cleaned up
expect(state.pastedContent[placeholder]).toBeUndefined();
});
it('delete at start of paste placeholder removes entire placeholder', () => {
const placeholder = '[Pasted Text: 6 lines]';
const stateWithPlaceholder = createStateWithTransformations({
lines: [placeholder],
cursorRow: 0,
cursorCol: 0, // cursor at start
pastedContent: {
[placeholder]: 'line1\nline2\nline3\nline4\nline5\nline6',
},
});
const action: TextBufferAction = { type: 'delete' };
const state = textBufferReducer(stateWithPlaceholder, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['']);
expect(state.cursorCol).toBe(0);
// pastedContent should be cleaned up
expect(state.pastedContent[placeholder]).toBeUndefined();
});
it('backspace inside paste placeholder does normal deletion', () => {
const placeholder = '[Pasted Text: 6 lines]';
const stateWithPlaceholder = createStateWithTransformations({
lines: [placeholder],
cursorRow: 0,
cursorCol: 10, // cursor in middle
pastedContent: {
[placeholder]: 'line1\nline2\nline3\nline4\nline5\nline6',
},
});
const action: TextBufferAction = { type: 'backspace' };
const state = textBufferReducer(stateWithPlaceholder, action);
expect(state).toHaveOnlyValidCharacters();
// Should only delete one character
expect(state.lines[0].length).toBe(placeholder.length - 1);
expect(state.cursorCol).toBe(9);
// pastedContent should NOT be cleaned up (placeholder is broken)
expect(state.pastedContent[placeholder]).toBeDefined();
});
});
describe('image placeholders', () => {
it('backspace at end of image path removes entire path', () => {
const imagePath = '@test.png';
const stateWithImage = createStateWithTransformations({
lines: [imagePath],
cursorRow: 0,
cursorCol: imagePath.length, // cursor at end
});
const action: TextBufferAction = { type: 'backspace' };
const state = textBufferReducer(stateWithImage, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['']);
expect(state.cursorCol).toBe(0);
});
it('delete at start of image path removes entire path', () => {
const imagePath = '@test.png';
const stateWithImage = createStateWithTransformations({
lines: [imagePath],
cursorRow: 0,
cursorCol: 0, // cursor at start
});
const action: TextBufferAction = { type: 'delete' };
const state = textBufferReducer(stateWithImage, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['']);
expect(state.cursorCol).toBe(0);
});
it('backspace inside image path does normal deletion', () => {
const imagePath = '@test.png';
const stateWithImage = createStateWithTransformations({
lines: [imagePath],
cursorRow: 0,
cursorCol: 5, // cursor in middle
});
const action: TextBufferAction = { type: 'backspace' };
const state = textBufferReducer(stateWithImage, action);
expect(state).toHaveOnlyValidCharacters();
// Should only delete one character
expect(state.lines[0].length).toBe(imagePath.length - 1);
expect(state.cursorCol).toBe(4);
});
});
describe('undo behavior', () => {
it('undo after placeholder deletion restores everything', () => {
const placeholder = '[Pasted Text: 6 lines]';
const pasteContent = 'line1\nline2\nline3\nline4\nline5\nline6';
const stateWithPlaceholder = createStateWithTransformations({
lines: [placeholder],
cursorRow: 0,
cursorCol: placeholder.length,
pastedContent: { [placeholder]: pasteContent },
});
// Delete the placeholder
const deleteAction: TextBufferAction = { type: 'backspace' };
const stateAfterDelete = textBufferReducer(
stateWithPlaceholder,
deleteAction,
);
expect(stateAfterDelete.lines).toEqual(['']);
expect(stateAfterDelete.pastedContent[placeholder]).toBeUndefined();
// Undo should restore
const undoAction: TextBufferAction = { type: 'undo' };
const stateAfterUndo = textBufferReducer(stateAfterDelete, undoAction);
expect(stateAfterUndo).toHaveOnlyValidCharacters();
expect(stateAfterUndo.lines).toEqual([placeholder]);
expect(stateAfterUndo.pastedContent[placeholder]).toBe(pasteContent);
});
});
});
describe('undo/redo actions', () => {
it('should undo and redo a change', () => {
// 1. Insert text
const insertAction: TextBufferAction = {
type: 'insert',
payload: 'test',
};
const stateAfterInsert = textBufferReducer(initialState, insertAction);
expect(stateAfterInsert).toHaveOnlyValidCharacters();
expect(stateAfterInsert.lines).toEqual(['test']);
expect(stateAfterInsert.undoStack.length).toBe(1);
// 2. Undo
const undoAction: TextBufferAction = { type: 'undo' };
const stateAfterUndo = textBufferReducer(stateAfterInsert, undoAction);
expect(stateAfterUndo).toHaveOnlyValidCharacters();
expect(stateAfterUndo.lines).toEqual(['']);
expect(stateAfterUndo.undoStack.length).toBe(0);
expect(stateAfterUndo.redoStack.length).toBe(1);
// 3. Redo
const redoAction: TextBufferAction = { type: 'redo' };
const stateAfterRedo = textBufferReducer(stateAfterUndo, redoAction);
expect(stateAfterRedo).toHaveOnlyValidCharacters();
expect(stateAfterRedo.lines).toEqual(['test']);
expect(stateAfterRedo.undoStack.length).toBe(1);
expect(stateAfterRedo.redoStack.length).toBe(0);
});
});
describe('create_undo_snapshot action', () => {
it('should create a snapshot without changing state', () => {
const stateWithText: TextBufferState = {
...initialState,
lines: ['hello'],
cursorRow: 0,
cursorCol: 5,
};
const action: TextBufferAction = { type: 'create_undo_snapshot' };
const state = textBufferReducer(stateWithText, action);
expect(state).toHaveOnlyValidCharacters();
expect(state.lines).toEqual(['hello']);
expect(state.cursorRow).toBe(0);
expect(state.cursorCol).toBe(5);
expect(state.undoStack.length).toBe(1);
expect(state.undoStack[0].lines).toEqual(['hello']);
expect(state.undoStack[0].cursorRow).toBe(0);
expect(state.undoStack[0].cursorCol).toBe(5);
});
});
describe('delete_word_left action', () => {
const createSingleLineState = (
text: string,
col: number,
): TextBufferState => ({
...initialState,
lines: [text],
cursorRow: 0,
cursorCol: col,
});
it.each([
{
input: 'hello world',
cursorCol: 11,
expectedLines: ['hello '],
expectedCol: 6,
desc: 'simple word',
},
{
input: 'path/to/file',
cursorCol: 12,
expectedLines: ['path/to/'],
expectedCol: 8,
desc: 'path segment',
},
{
input: 'variable_name',
cursorCol: 13,
expectedLines: ['variable_'],
expectedCol: 9,
desc: 'variable_name parts',
},
])(
'should delete $desc',
({ input, cursorCol, expectedLines, expectedCol }) => {
const state = textBufferReducer(
createSingleLineState(input, cursorCol),
{ type: 'delete_word_left' },
);
expect(state.lines).toEqual(expectedLines);
expect(state.cursorCol).toBe(expectedCol);
},
);
it('should act like backspace at the beginning of a line', () => {
const stateWithText: TextBufferState = {
...initialState,
lines: ['hello', 'world'],
cursorRow: 1,
cursorCol: 0,
};
const state = textBufferReducer(stateWithText, {
type: 'delete_word_left',
});
expect(state.lines).toEqual(['helloworld']);
expect(state.cursorRow).toBe(0);
expect(state.cursorCol).toBe(5);
});
});
describe('delete_word_right action', () => {
const createSingleLineState = (
text: string,
col: number,
): TextBufferState => ({
...initialState,
lines: [text],
cursorRow: 0,
cursorCol: col,
});
it.each([
{
input: 'hello world',
cursorCol: 0,
expectedLines: ['world'],
expectedCol: 0,
desc: 'simple word',
},
{
input: 'variable_name',
cursorCol: 0,
expectedLines: ['_name'],
expectedCol: 0,
desc: 'variable_name parts',
},
])(
'should delete $desc',
({ input, cursorCol, expectedLines, expectedCol }) => {
const state = textBufferReducer(
createSingleLineState(input, cursorCol),
{ type: 'delete_word_right' },
);
expect(state.lines).toEqual(expectedLines);
expect(state.cursorCol).toBe(expectedCol);
},
);
it('should delete path segments progressively', () => {
const stateWithText: TextBufferState = {
...initialState,
lines: ['path/to/file'],
cursorRow: 0,
cursorCol: 0,
};
let state = textBufferReducer(stateWithText, {
type: 'delete_word_right',
});
expect(state.lines).toEqual(['/to/file']);
state = textBufferReducer(state, { type: 'delete_word_right' });
expect(state.lines).toEqual(['to/file']);
});
it('should act like delete at the end of a line', () => {
const stateWithText: TextBufferState = {
...initialState,
lines: ['hello', 'world'],
cursorRow: 0,
cursorCol: 5,
};
const state = textBufferReducer(stateWithText, {
type: 'delete_word_right',
});
expect(state.lines).toEqual(['helloworld']);
expect(state.cursorRow).toBe(0);
expect(state.cursorCol).toBe(5);
});
});
describe('toggle_paste_expansion action', () => {
const placeholder = '[Pasted Text: 6 lines]';
const content = 'line1\nline2\nline3\nline4\nline5\nline6';
it('should expand a placeholder correctly', () => {
const stateWithPlaceholder = createStateWithTransformations({
lines: ['prefix ' + placeholder + ' suffix'],
cursorRow: 0,
cursorCol: 0,
pastedContent: { [placeholder]: content },
});
const action: TextBufferAction = {
type: 'toggle_paste_expansion',
payload: { id: placeholder, row: 0, col: 7 },
};
const state = textBufferReducer(stateWithPlaceholder, action);
expect(state.lines).toEqual([
'prefix line1',
'line2',
'line3',
'line4',
'line5',
'line6 suffix',
]);
expect(state.expandedPaste?.id).toBe(placeholder);
const info = state.expandedPaste;
expect(info).toEqual({
id: placeholder,
startLine: 0,
lineCount: 6,
prefix: 'prefix ',
suffix: ' suffix',
});
// Cursor should be at the end of expanded content (before suffix)
expect(state.cursorRow).toBe(5);
expect(state.cursorCol).toBe(5); // length of 'line6'
});
it('should collapse an expanded placeholder correctly', () => {
const expandedState = createStateWithTransformations({
lines: [
'prefix line1',
'line2',
'line3',
'line4',
'line5',
'line6 suffix',
],
cursorRow: 5,
cursorCol: 5,
pastedContent: { [placeholder]: content },
expandedPaste: {
id: placeholder,
startLine: 0,
lineCount: 6,
prefix: 'prefix ',
suffix: ' suffix',
},
});
const action: TextBufferAction = {
type: 'toggle_paste_expansion',
payload: { id: placeholder, row: 0, col: 7 },
};
const state = textBufferReducer(expandedState, action);
expect(state.lines).toEqual(['prefix ' + placeholder + ' suffix']);
expect(state.expandedPaste).toBeNull();
// Cursor should be at the end of the collapsed placeholder
expect(state.cursorRow).toBe(0);
expect(state.cursorCol).toBe(('prefix ' + placeholder).length);
});
it('should expand single-line content correctly', () => {
const singleLinePlaceholder = '[Pasted Text: 10 chars]';
const singleLineContent = 'some text';
const stateWithPlaceholder = createStateWithTransformations({
lines: [singleLinePlaceholder],
cursorRow: 0,
cursorCol: 0,
pastedContent: { [singleLinePlaceholder]: singleLineContent },
});
const state = textBufferReducer(stateWithPlaceholder, {
type: 'toggle_paste_expansion',
payload: { id: singleLinePlaceholder, row: 0, col: 0 },
});
expect(state.lines).toEqual(['some text']);
expect(state.cursorRow).toBe(0);
expect(state.cursorCol).toBe(9);
});
it('should return current state if placeholder ID not found in pastedContent', () => {
const action: TextBufferAction = {
type: 'toggle_paste_expansion',
payload: { id: 'unknown', row: 0, col: 0 },
};
const state = textBufferReducer(initialState, action);
expect(state).toBe(initialState);
});
it('should preserve expandedPaste when lines change from edits outside the region', () => {
// Start with an expanded paste at line 0 (3 lines long)
const placeholder = '[Pasted Text: 3 lines]';
const expandedState = createStateWithTransformations({
lines: ['line1', 'line2', 'line3', 'suffix'],
cursorRow: 3,
cursorCol: 0,
pastedContent: { [placeholder]: 'line1\nline2\nline3' },
expandedPaste: {
id: placeholder,
startLine: 0,
lineCount: 3,
prefix: '',
suffix: '',
},
});
expect(expandedState.expandedPaste).not.toBeNull();
// Insert a newline at the end - this changes lines but is OUTSIDE the expanded region
const stateAfterInsert = textBufferReducer(expandedState, {
type: 'insert',
payload: '\n',
});
// Lines changed, but expandedPaste should be PRESERVED and optionally shifted (no shift here since edit is after)
expect(stateAfterInsert.expandedPaste).not.toBeNull();
expect(stateAfterInsert.expandedPaste?.id).toBe(placeholder);
});
});
});
const getBufferState = (result: { current: TextBuffer }) => {
expect(result.current).toHaveOnlyValidCharacters();
return {
text: result.current.text,
lines: [...result.current.lines], // Clone for safety
cursor: [...result.current.cursor] as [number, number],
allVisualLines: [...result.current.allVisualLines],
viewportVisualLines: [...result.current.viewportVisualLines],
visualCursor: [...result.current.visualCursor] as [number, number],
visualScrollRow: result.current.visualScrollRow,
preferredCol: result.current.preferredCol,
};
};
describe('useTextBuffer', () => {
let viewport: Viewport;
beforeEach(() => {
viewport = { width: 10, height: 3 }; // Default viewport for tests
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('Initialization', () => {
it('should initialize with empty text and cursor at (0,0) by default', () => {
const { result } = renderHook(() =>
useTextBuffer({ viewport, isValidPath: () => false }),
);
const state = getBufferState(result);
expect(state.text).toBe('');
expect(state.lines).toEqual(['']);
expect(state.cursor).toEqual([0, 0]);
expect(state.allVisualLines).toEqual(['']);
expect(state.viewportVisualLines).toEqual(['']);
expect(state.visualCursor).toEqual([0, 0]);
expect(state.visualScrollRow).toBe(0);
});
it('should initialize with provided initialText', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: 'hello',
viewport,
isValidPath: () => false,
}),
);
const state = getBufferState(result);
expect(state.text).toBe('hello');
expect(state.lines).toEqual(['hello']);
expect(state.cursor).toEqual([0, 0]); // Default cursor if offset not given
expect(state.allVisualLines).toEqual(['hello']);
expect(state.viewportVisualLines).toEqual(['hello']);
expect(state.visualCursor).toEqual([0, 0]);
});
it('should initialize with initialText and initialCursorOffset', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: 'hello\nworld',
initialCursorOffset: 7, // Should be at 'o' in 'world'
viewport,
isValidPath: () => false,
}),
);
const state = getBufferState(result);
expect(state.text).toBe('hello\nworld');
expect(state.lines).toEqual(['hello', 'world']);
expect(state.cursor).toEqual([1, 1]); // Logical cursor at 'o' in "world"
expect(state.allVisualLines).toEqual(['hello', 'world']);
expect(state.viewportVisualLines).toEqual(['hello', 'world']);
expect(state.visualCursor[0]).toBe(1); // On the second visual line
expect(state.visualCursor[1]).toBe(1); // At 'o' in "world"
});
it('should wrap visual lines', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: 'The quick brown fox jumps over the lazy dog.',
initialCursorOffset: 2, // After '好'
viewport: { width: 15, height: 4 },
isValidPath: () => false,
}),
);
const state = getBufferState(result);
expect(state.allVisualLines).toEqual([
'The quick',
'brown fox',
'jumps over the',
'lazy dog.',
]);
});
it('should wrap visual lines with multiple spaces', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: 'The quick brown fox jumps over the lazy dog.',
viewport: { width: 15, height: 4 },
isValidPath: () => false,
}),
);
const state = getBufferState(result);
// Including multiple spaces at the end of the lines like this is
// consistent with Google docs behavior and makes it intuitive to edit
// the spaces as needed.
expect(state.allVisualLines).toEqual([
'The quick ',
'brown fox ',
'jumps over the',
'lazy dog.',
]);
});
it('should wrap visual lines even without spaces', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: '123456789012345ABCDEFG', // 4 chars, 12 bytes
viewport: { width: 15, height: 2 },
isValidPath: () => false,
}),
);
const state = getBufferState(result);
// Including multiple spaces at the end of the lines like this is
// consistent with Google docs behavior and makes it intuitive to edit
// the spaces as needed.
expect(state.allVisualLines).toEqual(['123456789012345', 'ABCDEFG']);
});
it('should initialize with multi-byte unicode characters and correct cursor offset', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: '你好世界', // 4 chars, 12 bytes
initialCursorOffset: 2, // After '好'
viewport: { width: 5, height: 2 },
isValidPath: () => false,
}),
);
const state = getBufferState(result);
expect(state.text).toBe('你好世界');
expect(state.lines).toEqual(['你好世界']);
expect(state.cursor).toEqual([0, 2]);
// Visual: "你好" (width 4), "世"界" (width 4) with viewport width 5
expect(state.allVisualLines).toEqual(['你好', '世界']);
expect(state.visualCursor).toEqual([1, 0]);
});
});
describe('Basic Editing', () => {
it('insert: should insert a character and update cursor', () => {
const { result } = renderHook(() =>
useTextBuffer({ viewport, isValidPath: () => false }),
);
act(() => result.current.insert('a'));
let state = getBufferState(result);
expect(state.text).toBe('a');
expect(state.cursor).toEqual([0, 1]);
expect(state.visualCursor).toEqual([0, 1]);
act(() => result.current.insert('b'));
state = getBufferState(result);
expect(state.text).toBe('ab');
expect(state.cursor).toEqual([0, 2]);
expect(state.visualCursor).toEqual([0, 2]);
});
it('insert: should insert text in the middle of a line', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: 'abc',
viewport,
isValidPath: () => false,
}),
);
act(() => result.current.move('right'));
act(() => result.current.insert('-NEW-'));
const state = getBufferState(result);
expect(state.text).toBe('a-NEW-bc');
expect(state.cursor).toEqual([0, 6]);
});
it('insert: should use placeholder for large text paste', () => {
const { result } = renderHook(() =>
useTextBuffer({ viewport, isValidPath: () => false }),
);
const largeText = '1\n2\n3\n4\n5\n6';
act(() => result.current.insert(largeText, { paste: true }));
const state = getBufferState(result);
expect(state.text).toBe('[Pasted Text: 6 lines]');
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
largeText,
);
});
it('insert: should NOT use placeholder for large text if NOT a paste', () => {
const { result } = renderHook(() =>
useTextBuffer({ viewport, isValidPath: () => false }),
);
const largeText = '1\n2\n3\n4\n5\n6';
act(() => result.current.insert(largeText, { paste: false }));
const state = getBufferState(result);
expect(state.text).toBe(largeText);
});
it('insert: should clean up pastedContent when placeholder is deleted', () => {
const { result } = renderHook(() =>
useTextBuffer({ viewport, isValidPath: () => false }),
);
const largeText = '1\n2\n3\n4\n5\n6';
act(() => result.current.insert(largeText, { paste: true }));
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
largeText,
);
// Delete the placeholder using setText
act(() => result.current.setText(''));
expect(Object.keys(result.current.pastedContent)).toHaveLength(0);
});
it('insert: should clean up pastedContent when placeholder is removed via atomic backspace', () => {
const { result } = renderHook(() =>
useTextBuffer({ viewport, isValidPath: () => false }),
);
const largeText = '1\n2\n3\n4\n5\n6';
act(() => result.current.insert(largeText, { paste: true }));
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
largeText,
);
// Single backspace at end of placeholder removes entire placeholder
act(() => {
result.current.backspace();
});
expect(getBufferState(result).text).toBe('');
// pastedContent is cleaned up when placeholder is deleted atomically
expect(Object.keys(result.current.pastedContent)).toHaveLength(0);
});
it('newline: should create a new line and move cursor', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: 'ab',
viewport,
isValidPath: () => false,
}),
);
act(() => result.current.move('end')); // cursor at [0,2]
act(() => result.current.newline());
const state = getBufferState(result);
expect(state.text).toBe('ab\n');
expect(state.lines).toEqual(['ab', '']);
expect(state.cursor).toEqual([1, 0]);
expect(state.allVisualLines).toEqual(['ab', '']);
expect(state.viewportVisualLines).toEqual(['ab', '']); // viewport height 3
expect(state.visualCursor).toEqual([1, 0]); // On the new visual line
});
it('backspace: should delete char to the left or merge lines', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: 'a\nb',
viewport,
isValidPath: () => false,
}),
);
act(() => {
result.current.move('down');
});
act(() => {
result.current.move('end'); // cursor to [1,1] (end of 'b')
});
act(() => result.current.backspace()); // delete 'b'
let state = getBufferState(result);
expect(state.text).toBe('a\n');
expect(state.cursor).toEqual([1, 0]);
act(() => result.current.backspace()); // merge lines
state = getBufferState(result);
expect(state.text).toBe('a');
expect(state.cursor).toEqual([0, 1]); // cursor after 'a'
expect(state.allVisualLines).toEqual(['a']);
expect(state.viewportVisualLines).toEqual(['a']);
expect(state.visualCursor).toEqual([0, 1]);
});
it('del: should delete char to the right or merge lines', () => {
const { result } = renderHook(() =>
useTextBuffer({
initialText: 'a\nb',
viewport,
isValidPath: () => false,
}),
);
// cursor at [0,0]
act(() => result.current.del()); // delete 'a'
let state = getBufferState(result);
expect(state.text).toBe('\nb');
expect(state.cursor).toEqual([0, 0]);
act(() => result.current.del()); // merge lines (deletes newline)
state = getBufferState(result);
expect(state.text).toBe('b');
expect(state.cursor).toEqual([0, 0]);
expect(state.allVisualLines).toEqual(['b']);
expect(state.viewportVisualLines).toEqual(['b']);
expect(state.visualCursor).toEqual([0, 0]);
});
});
describe('Drag and Drop File Paths', () => {
it('should prepend @ to a valid file path on insert', () => {
const { result } = renderHook(() =>
useTextBuffer({ viewport, isValidPath: () => true }),
);
const filePath = '/path/to/a/valid/file.txt';
act(() => result.current.insert(filePath, { paste: true }));
expect(getBufferState(result).text).toBe(`@${filePath} `);
});
it('should not prepend @ to an invalid file path on insert', () => {
const { result } = renderHook(() =>
useTextBuffer({ viewport, isValidPath: () => false }),
);
const notAPath = 'this is just some long text';
act(() => result.current.insert(notAPath, { paste: true }));
expect(getBufferState(result).text).toBe(notAPath);