File size: 26,078 Bytes
52efc7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { renderWithProviders } from '../../../test-utils/render.js';
import { waitFor } from '../../../test-utils/async.js';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { act } from 'react';
import { Text } from 'ink';
import {
  BaseSettingsDialog,
  type BaseSettingsDialogProps,
  type SettingsDialogItem,
} from './BaseSettingsDialog.js';
import { SettingScope } from '../../../config/settings.js';

enum TerminalKeys {
  ENTER = '\u000D',
  TAB = '\t',
  UP_ARROW = '\u001B[A',
  DOWN_ARROW = '\u001B[B',
  LEFT_ARROW = '\u001B[D',
  RIGHT_ARROW = '\u001B[C',
  ESCAPE = '\u001B',
  BACKSPACE = '\u0008',
  CTRL_L = '\u000C',
}

const createMockItems = (count = 4): SettingsDialogItem[] => {
  const items: SettingsDialogItem[] = [
    {
      key: 'boolean-setting',
      label: 'Boolean Setting',
      description: 'A boolean setting for testing',
      displayValue: 'true',
      rawValue: true,
      type: 'boolean',
    },
    {
      key: 'string-setting',
      label: 'String Setting',
      description: 'A string setting for testing',
      displayValue: 'test-value',
      rawValue: 'test-value',
      type: 'string',
    },
    {
      key: 'number-setting',
      label: 'Number Setting',
      description: 'A number setting for testing',
      displayValue: '42',
      rawValue: 42,
      type: 'number',
    },
    {
      key: 'enum-setting',
      label: 'Enum Setting',
      description: 'An enum setting for testing',
      displayValue: 'option-a',
      rawValue: 'option-a',
      type: 'enum',
    },
  ];

  // If count is larger than our base mock items, generate dynamic ones
  if (count > items.length) {
    for (let i = items.length; i < count; i++) {
      items.push({
        key: `extra-setting-${i}`,
        label: `Extra Setting ${i}`,
        displayValue: `value-${i}`,
        type: 'string',
      });
    }
  }

  return items.slice(0, count);
};

describe('BaseSettingsDialog', () => {
  let mockOnItemToggle: ReturnType<typeof vi.fn>;
  let mockOnEditCommit: ReturnType<typeof vi.fn>;
  let mockOnItemClear: ReturnType<typeof vi.fn>;
  let mockOnClose: ReturnType<typeof vi.fn>;
  let mockOnScopeChange: ReturnType<typeof vi.fn>;

  beforeEach(() => {
    vi.clearAllMocks();
    mockOnItemToggle = vi.fn();
    mockOnEditCommit = vi.fn();
    mockOnItemClear = vi.fn();
    mockOnClose = vi.fn();
    mockOnScopeChange = vi.fn();
  });

  const renderDialog = async (props: Partial<BaseSettingsDialogProps> = {}) => {
    const defaultProps: BaseSettingsDialogProps = {
      title: 'Test Settings',
      items: createMockItems(),
      selectedScope: SettingScope.User,
      maxItemsToShow: 8,
      onItemToggle: mockOnItemToggle,
      onEditCommit: mockOnEditCommit,
      onItemClear: mockOnItemClear,
      onClose: mockOnClose,
      ...props,
    };

    const result = await renderWithProviders(
      <BaseSettingsDialog {...defaultProps} />,
    );
    await result.waitUntilReady();
    return result;
  };

  describe('rendering', () => {
    it('should render the dialog with title', async () => {
      const { lastFrame, unmount } = await renderDialog();
      expect(lastFrame()).toContain('Test Settings');
      unmount();
    });

    it('should render all items', async () => {
      const { lastFrame, unmount } = await renderDialog();
      const frame = lastFrame();

      expect(frame).toContain('Boolean Setting');
      expect(frame).toContain('String Setting');
      expect(frame).toContain('Number Setting');
      expect(frame).toContain('Enum Setting');
      unmount();
    });

    it('should render help text with Ctrl+L for reset', async () => {
      const { lastFrame, unmount } = await renderDialog();
      const frame = lastFrame();

      expect(frame).toContain('Use Enter to select');
      expect(frame).toContain('Ctrl+L to reset');
      expect(frame).toContain('Tab to change focus');
      expect(frame).toContain('Esc to close');
      unmount();
    });

    it('should render scope selector when showScopeSelector is true', async () => {
      const { lastFrame, unmount } = await renderDialog({
        showScopeSelector: true,
        onScopeChange: mockOnScopeChange,
      });

      expect(lastFrame()).toContain('Apply To');
      unmount();
    });

    it('should not render scope selector when showScopeSelector is false', async () => {
      const { lastFrame, unmount } = await renderDialog({
        showScopeSelector: false,
      });

      expect(lastFrame({ allowEmpty: true })).not.toContain('Apply To');
      unmount();
    });

    it('should render footer content when provided', async () => {
      const { lastFrame, unmount } = await renderDialog({
        footer: {
          content: <Text>Custom Footer</Text>,
          height: 1,
        },
      });

      expect(lastFrame()).toContain('Custom Footer');
      unmount();
    });
  });

  describe('keyboard navigation', () => {
    it('should close dialog on Escape', async () => {
      const { stdin, waitUntilReady, unmount } = await renderDialog();

      await act(async () => {
        stdin.write(TerminalKeys.ESCAPE);
      });
      // Escape key has a 50ms timeout in KeypressContext, so we need to wrap waitUntilReady in act
      await act(async () => {
        await waitUntilReady();
      });

      await waitFor(() => {
        expect(mockOnClose).toHaveBeenCalled();
      });
      unmount();
    });

    it('should navigate down with arrow key', async () => {
      const { lastFrame, stdin, waitUntilReady, unmount } =
        await renderDialog();

      // Initially first item is active (indicated by bullet point)
      const initialFrame = lastFrame();
      expect(initialFrame).toContain('Boolean Setting');

      // Press down arrow
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();

      // Navigation should move to next item
      await waitFor(() => {
        const frame = lastFrame();
        // The active indicator should now be on a different row
        expect(frame).toContain('String Setting');
      });
      unmount();
    });

    it('should navigate up with arrow key', async () => {
      const { stdin, waitUntilReady, unmount } = await renderDialog();

      // Press down then up
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();

      await act(async () => {
        stdin.write(TerminalKeys.UP_ARROW);
      });
      await waitUntilReady();

      // Should be back at first item
      await waitFor(() => {
        // First item should be active again
        expect(mockOnClose).not.toHaveBeenCalled();
      });
      unmount();
    });

    it('should wrap around when navigating past last item', async () => {
      const items = createMockItems(2); // Only 2 items
      const { stdin, waitUntilReady, unmount } = await renderDialog({ items });

      // Press down twice to go past the last item
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();

      // Should wrap to first item - verify no crash
      await waitFor(() => {
        expect(mockOnClose).not.toHaveBeenCalled();
      });
      unmount();
    });

    it('should wrap around when navigating before first item', async () => {
      const { stdin, waitUntilReady, unmount } = await renderDialog();

      // Press up at first item
      await act(async () => {
        stdin.write(TerminalKeys.UP_ARROW);
      });
      await waitUntilReady();

      // Should wrap to last item - verify no crash
      await waitFor(() => {
        expect(mockOnClose).not.toHaveBeenCalled();
      });
      unmount();
    });

    it('should switch focus with Tab when scope selector is shown', async () => {
      const { lastFrame, stdin, waitUntilReady, unmount } = await renderDialog({
        showScopeSelector: true,
        onScopeChange: mockOnScopeChange,
      });

      // Initially settings section is focused (indicated by >)
      expect(lastFrame()).toContain('> Test Settings');

      // Press Tab to switch to scope selector
      await act(async () => {
        stdin.write(TerminalKeys.TAB);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(lastFrame()).toContain('> Apply To');
      });
      unmount();
    });
  });

  describe('scrolling and resizing list (search filtering)', () => {
    it('should preserve focus on the active item if it remains in the filtered list', async () => {
      const items = createMockItems(5); // items 0 to 4
      const { rerender, stdin, lastFrame, waitUntilReady, unmount } =
        await renderDialog({
          items,
          maxItemsToShow: 5,
        });

      // Move focus down to item 2 ("Number Setting")
      // Separate acts needed so React state updates between keypresses
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();

      // Rerender with a filtered list where "Number Setting" is now at index 1
      const filteredItems = [items[0], items[2], items[4]];
      await act(async () => {
        rerender(
          <BaseSettingsDialog
            title="Test Settings"
            items={filteredItems}
            selectedScope={SettingScope.User}
            maxItemsToShow={5}
            onItemToggle={mockOnItemToggle}
            onEditCommit={mockOnEditCommit}
            onItemClear={mockOnItemClear}
            onClose={mockOnClose}
          />,
        );
      });
      // Verify the dialog hasn't crashed and the items are displayed
      await waitFor(() => {
        const frame = lastFrame();
        expect(frame).toContain('Boolean Setting');
        expect(frame).toContain('Number Setting');
        expect(frame).toContain('Extra Setting 4');
        expect(frame).not.toContain('No matches found.');
      });

      // Press Enter. If focus was preserved, it should be on "Number Setting" (index 1).
      // Since it's a number, it enters edit mode (mockOnItemToggle is NOT called).
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(mockOnItemToggle).not.toHaveBeenCalled();
      });
      unmount();
    });

    it('should reset focus to the top if the active item is filtered out', async () => {
      const items = createMockItems(5);
      const { rerender, stdin, lastFrame, waitUntilReady, unmount } =
        await renderDialog({
          items,
          maxItemsToShow: 5,
        });

      // Move focus down to item 2 ("Number Setting")
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();

      // Rerender with a filtered list that EXCLUDES "Number Setting"
      const filteredItems = [items[0], items[1]];
      await act(async () => {
        rerender(
          <BaseSettingsDialog
            title="Test Settings"
            items={filteredItems}
            selectedScope={SettingScope.User}
            maxItemsToShow={5}
            onItemToggle={mockOnItemToggle}
            onEditCommit={mockOnEditCommit}
            onItemClear={mockOnItemClear}
            onClose={mockOnClose}
          />,
        );
      });
      await waitFor(() => {
        const frame = lastFrame();
        expect(frame).toContain('Boolean Setting');
        expect(frame).toContain('String Setting');
      });

      // Press Enter. Since focus reset to index 0 ("Boolean Setting"), it should toggle.
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(mockOnItemToggle).toHaveBeenCalledWith(
          'boolean-setting',
          expect.anything(),
        );
      });
      unmount();
    });
  });

  describe('item interactions', () => {
    it('should call onItemToggle for boolean items on Enter', async () => {
      const { stdin, waitUntilReady, unmount } = await renderDialog();

      // Press Enter on first item (boolean)
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(mockOnItemToggle).toHaveBeenCalledWith(
          'boolean-setting',
          expect.objectContaining({ type: 'boolean' }),
        );
      });
      unmount();
    });

    it('should call onItemToggle for enum items on Enter', async () => {
      const items = createMockItems(4);
      // Move enum to first position
      const enumItem = items.find((i) => i.type === 'enum')!;
      const { stdin, waitUntilReady, unmount } = await renderDialog({
        items: [enumItem],
      });

      // Press Enter on enum item
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(mockOnItemToggle).toHaveBeenCalledWith(
          'enum-setting',
          expect.objectContaining({ type: 'enum' }),
        );
      });
      unmount();
    });

    it('should enter edit mode for string items on Enter', async () => {
      const items = createMockItems(4);
      const stringItem = items.find((i) => i.type === 'string')!;
      const { lastFrame, stdin, waitUntilReady, unmount } = await renderDialog({
        items: [stringItem],
      });

      // Press Enter to start editing
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      // Should show the edit buffer with cursor
      await waitFor(() => {
        const frame = lastFrame();
        // In edit mode, the value should be displayed (possibly with cursor)
        expect(frame).toContain('test-value');
      });
      unmount();
    });

    it('should enter edit mode for number items on Enter', async () => {
      const items = createMockItems(4);
      const numberItem = items.find((i) => i.type === 'number')!;
      const { lastFrame, stdin, waitUntilReady, unmount } = await renderDialog({
        items: [numberItem],
      });

      // Press Enter to start editing
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      // Should show the edit buffer
      await waitFor(() => {
        const frame = lastFrame();
        expect(frame).toContain('42');
      });
      unmount();
    });

    it('should call onItemClear on Ctrl+L', async () => {
      const { stdin, waitUntilReady, unmount } = await renderDialog();

      // Press Ctrl+L to reset
      await act(async () => {
        stdin.write(TerminalKeys.CTRL_L);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(mockOnItemClear).toHaveBeenCalledWith(
          'boolean-setting',
          expect.objectContaining({ type: 'boolean' }),
        );
      });
      unmount();
    });
  });

  describe('edit mode', () => {
    it('should prioritize editValue over rawValue stringification', async () => {
      const objectItem: SettingsDialogItem = {
        key: 'object-setting',
        label: 'Object Setting',
        description: 'A complex object setting',
        displayValue: '{"foo":"bar"}',
        type: 'object',
        rawValue: { foo: 'bar' },
        editValue: '{"foo":"bar"}',
      };
      const { stdin } = await renderDialog({
        items: [objectItem],
      });

      // Enter edit mode and immediately commit
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });

      await waitFor(() => {
        expect(mockOnEditCommit).toHaveBeenCalledWith(
          'object-setting',
          '{"foo":"bar"}',
          expect.objectContaining({ type: 'object' }),
        );
      });
    });

    it('should commit edit on Enter', async () => {
      const items = createMockItems(4);
      const stringItem = items.find((i) => i.type === 'string')!;
      const { stdin, waitUntilReady, unmount } = await renderDialog({
        items: [stringItem],
      });

      // Enter edit mode
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      // Type some characters
      await act(async () => {
        stdin.write('x');
      });
      await waitUntilReady();

      // Commit with Enter
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(mockOnEditCommit).toHaveBeenCalledWith(
          'string-setting',
          'test-valuex',
          expect.objectContaining({ type: 'string' }),
        );
      });
      unmount();
    });

    it('should commit edit on Escape', async () => {
      const items = createMockItems(4);
      const stringItem = items.find((i) => i.type === 'string')!;
      const { stdin, waitUntilReady, unmount } = await renderDialog({
        items: [stringItem],
      });

      // Enter edit mode
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      // Commit with Escape
      await act(async () => {
        stdin.write(TerminalKeys.ESCAPE);
      });
      // Escape key has a 50ms timeout in KeypressContext, so we need to wrap waitUntilReady in act
      await act(async () => {
        await waitUntilReady();
      });

      await waitFor(() => {
        expect(mockOnEditCommit).toHaveBeenCalled();
      });
      unmount();
    });

    it('should commit edit and navigate on Down arrow', async () => {
      const items = createMockItems(4);
      const stringItem = items.find((i) => i.type === 'string')!;
      const numberItem = items.find((i) => i.type === 'number')!;
      const { stdin, waitUntilReady, unmount } = await renderDialog({
        items: [stringItem, numberItem],
      });

      // Enter edit mode
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      // Press Down to commit and navigate
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(mockOnEditCommit).toHaveBeenCalled();
      });
      unmount();
    });

    it('should commit edit and navigate on Up arrow', async () => {
      const items = createMockItems(4);
      const stringItem = items.find((i) => i.type === 'string')!;
      const numberItem = items.find((i) => i.type === 'number')!;
      const { stdin, waitUntilReady, unmount } = await renderDialog({
        items: [stringItem, numberItem],
      });

      // Navigate to second item
      await act(async () => {
        stdin.write(TerminalKeys.DOWN_ARROW);
      });
      await waitUntilReady();

      // Enter edit mode
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      // Press Up to commit and navigate
      await act(async () => {
        stdin.write(TerminalKeys.UP_ARROW);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(mockOnEditCommit).toHaveBeenCalled();
      });
      unmount();
    });

    it('should allow number input for number fields', async () => {
      const items = createMockItems(4);
      const numberItem = items.find((i) => i.type === 'number')!;
      const { stdin, waitUntilReady, unmount } = await renderDialog({
        items: [numberItem],
      });

      // Enter edit mode
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      // Type numbers one at a time
      await act(async () => {
        stdin.write('1');
      });
      await waitUntilReady();
      await act(async () => {
        stdin.write('2');
      });
      await waitUntilReady();
      await act(async () => {
        stdin.write('3');
      });
      await waitUntilReady();

      // Commit
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(mockOnEditCommit).toHaveBeenCalledWith(
          'number-setting',
          '42123',
          expect.objectContaining({ type: 'number' }),
        );
      });
      unmount();
    });

    it('should support quick number entry for number fields', async () => {
      const items = createMockItems(4);
      const numberItem = items.find((i) => i.type === 'number')!;
      const { stdin, waitUntilReady, unmount } = await renderDialog({
        items: [numberItem],
      });

      // Type a number directly (without Enter first)
      await act(async () => {
        stdin.write('5');
      });
      await waitUntilReady();

      // Should start editing with that number
      await waitFor(async () => {
        // Commit to verify
        await act(async () => {
          stdin.write(TerminalKeys.ENTER);
        });
        await waitUntilReady();
      });

      await waitFor(() => {
        expect(mockOnEditCommit).toHaveBeenCalledWith(
          'number-setting',
          '5',
          expect.objectContaining({ type: 'number' }),
        );
      });
      unmount();
    });

    it('should allow j and k characters to be typed in string edit fields without triggering navigation', async () => {
      const items = createMockItems(4);
      const stringItem = items.find((i) => i.type === 'string')!;
      const { stdin, waitUntilReady, unmount } = await renderDialog({
        items: [stringItem],
      });

      // Enter edit mode
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      // Type 'j' - should appear in field, NOT trigger navigation
      await act(async () => {
        stdin.write('j');
      });
      await waitUntilReady();

      // Type 'k' - should appear in field, NOT trigger navigation
      await act(async () => {
        stdin.write('k');
      });
      await waitUntilReady();

      // Commit with Enter
      await act(async () => {
        stdin.write(TerminalKeys.ENTER);
      });
      await waitUntilReady();

      // j and k should be typed into the field
      await waitFor(() => {
        expect(mockOnEditCommit).toHaveBeenCalledWith(
          'string-setting',
          'test-valuejk', // entered value + j and k
          expect.objectContaining({ type: 'string' }),
        );
      });
      unmount();
    });
  });

  describe('custom key handling', () => {
    it('should call onKeyPress and respect its return value', async () => {
      const customKeyHandler = vi.fn().mockReturnValue(true);
      const { stdin, waitUntilReady, unmount } = await renderDialog({
        onKeyPress: customKeyHandler,
      });

      // Press a key
      await act(async () => {
        stdin.write('r');
      });
      await waitUntilReady();

      await waitFor(() => {
        expect(customKeyHandler).toHaveBeenCalled();
      });

      // Since handler returned true, default behavior should be blocked
      expect(mockOnClose).not.toHaveBeenCalled();
      unmount();
    });
  });

  describe('focus management', () => {
    it('should keep focus on settings when scope selector is hidden', async () => {
      const { lastFrame, stdin, waitUntilReady, unmount } = await renderDialog({
        showScopeSelector: false,
      });

      // Press Tab - should not crash and focus should stay on settings
      await act(async () => {
        stdin.write(TerminalKeys.TAB);
      });
      await waitUntilReady();

      await waitFor(() => {
        // Should still show settings as focused
        expect(lastFrame()).toContain('> Test Settings');
      });
      unmount();
    });
  });

  describe('responsiveness', () => {
    it('should show the scope selector when availableHeight is sufficient (25)', async () => {
      const { lastFrame, unmount } = await renderDialog({
        availableHeight: 25,
        showScopeSelector: true,
      });

      const frame = lastFrame();
      expect(frame).toContain('Apply To');
      unmount();
    });

    it('should hide the scope selector when availableHeight is small (24) to show more items', async () => {
      const { lastFrame, unmount } = await renderDialog({
        availableHeight: 24,
        showScopeSelector: true,
      });

      const frame = lastFrame();
      expect(frame).not.toContain('Apply To');
      unmount();
    });

    it('should reduce the number of visible items based on height', async () => {
      // At height 25, it should show 2 items (math: (25-4 - (10+5))/3 = 2)
      const { lastFrame, unmount } = await renderDialog({
        availableHeight: 25,
        items: createMockItems(10),
      });

      const frame = lastFrame();
      // Items 0 and 1 should be there
      expect(frame).toContain('Boolean Setting');
      expect(frame).toContain('String Setting');
      // Item 2 should NOT be there
      expect(frame).not.toContain('Number Setting');
      unmount();
    });

    it('should show scroll indicators when list is truncated by height', async () => {
      const { lastFrame, unmount } = await renderDialog({
        availableHeight: 25,
        items: createMockItems(10),
      });

      const frame = lastFrame();
      // Shows both scroll indicators when the list is truncated by height
      expect(frame).toContain('▼');
      expect(frame).toContain('▲');
      unmount();
    });
  });
});