summaryrefslogtreecommitdiff
path: root/packages/cli/src/ui/components/SettingsDialog.tsx
blob: 80e2339f6ef9a668c0c9abb3fac27b20a549e6c6 (plain)
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect } from 'react';
import { Box, Text, useInput } from 'ink';
import { Colors } from '../colors.js';
import {
  LoadedSettings,
  SettingScope,
  Settings,
} from '../../config/settings.js';
import {
  getScopeItems,
  getScopeMessageForSetting,
} from '../../utils/dialogScopeUtils.js';
import { RadioButtonSelect } from './shared/RadioButtonSelect.js';
import {
  getDialogSettingKeys,
  getSettingValue,
  setPendingSettingValue,
  getDisplayValue,
  hasRestartRequiredSettings,
  saveModifiedSettings,
  getSettingDefinition,
  isDefaultValue,
  requiresRestart,
  getRestartRequiredFromModified,
  getDefaultValue,
} from '../../utils/settingsUtils.js';
import { useVimMode } from '../contexts/VimModeContext.js';

interface SettingsDialogProps {
  settings: LoadedSettings;
  onSelect: (settingName: string | undefined, scope: SettingScope) => void;
  onRestartRequest?: () => void;
}

const maxItemsToShow = 8;

export function SettingsDialog({
  settings,
  onSelect,
  onRestartRequest,
}: SettingsDialogProps): React.JSX.Element {
  // Get vim mode context to sync vim mode changes
  const { vimEnabled, toggleVimEnabled } = useVimMode();

  // Focus state: 'settings' or 'scope'
  const [focusSection, setFocusSection] = useState<'settings' | 'scope'>(
    'settings',
  );
  // Scope selector state (User by default)
  const [selectedScope, setSelectedScope] = useState<SettingScope>(
    SettingScope.User,
  );
  // Active indices
  const [activeSettingIndex, setActiveSettingIndex] = useState(0);
  // Scroll offset for settings
  const [scrollOffset, setScrollOffset] = useState(0);
  const [showRestartPrompt, setShowRestartPrompt] = useState(false);

  // Local pending settings state for the selected scope
  const [pendingSettings, setPendingSettings] = useState<Settings>(() =>
    // Deep clone to avoid mutation
    structuredClone(settings.forScope(selectedScope).settings),
  );

  // Track which settings have been modified by the user
  const [modifiedSettings, setModifiedSettings] = useState<Set<string>>(
    new Set(),
  );

  // Track the intended values for modified settings
  const [modifiedValues, setModifiedValues] = useState<Map<string, boolean>>(
    new Map(),
  );

  // Track restart-required settings across scope changes
  const [restartRequiredSettings, setRestartRequiredSettings] = useState<
    Set<string>
  >(new Set());

  useEffect(() => {
    setPendingSettings(
      structuredClone(settings.forScope(selectedScope).settings),
    );
    // Don't reset modifiedSettings when scope changes - preserve user's pending changes
    if (restartRequiredSettings.size === 0) {
      setShowRestartPrompt(false);
    }
  }, [selectedScope, settings, restartRequiredSettings]);

  // Preserve pending changes when scope changes
  useEffect(() => {
    if (modifiedSettings.size > 0) {
      setPendingSettings((prevPending) => {
        let updatedPending = { ...prevPending };

        // Reapply all modified settings to the new pending settings using stored values
        modifiedSettings.forEach((key) => {
          const storedValue = modifiedValues.get(key);
          if (storedValue !== undefined) {
            updatedPending = setPendingSettingValue(
              key,
              storedValue,
              updatedPending,
            );
          }
        });

        return updatedPending;
      });
    }
  }, [selectedScope, modifiedSettings, modifiedValues, settings]);

  const generateSettingsItems = () => {
    const settingKeys = getDialogSettingKeys();

    return settingKeys.map((key: string) => {
      const currentValue = getSettingValue(key, pendingSettings, {});
      const definition = getSettingDefinition(key);

      return {
        label: definition?.label || key,
        value: key,
        checked: currentValue,
        toggle: () => {
          const newValue = !currentValue;

          setPendingSettings((prev) =>
            setPendingSettingValue(key, newValue, prev),
          );

          if (!requiresRestart(key)) {
            const immediateSettings = new Set([key]);
            const immediateSettingsObject = setPendingSettingValue(
              key,
              newValue,
              {},
            );

            console.log(
              `[DEBUG SettingsDialog] Saving ${key} immediately with value:`,
              newValue,
            );
            saveModifiedSettings(
              immediateSettings,
              immediateSettingsObject,
              settings,
              selectedScope,
            );

            // Special handling for vim mode to sync with VimModeContext
            if (key === 'vimMode' && newValue !== vimEnabled) {
              // Call toggleVimEnabled to sync the VimModeContext local state
              toggleVimEnabled().catch((error) => {
                console.error('Failed to toggle vim mode:', error);
              });
            }

            // Capture the current modified settings before updating state
            const currentModifiedSettings = new Set(modifiedSettings);

            // Remove the saved setting from modifiedSettings since it's now saved
            setModifiedSettings((prev) => {
              const updated = new Set(prev);
              updated.delete(key);
              return updated;
            });

            // Remove from modifiedValues as well
            setModifiedValues((prev) => {
              const updated = new Map(prev);
              updated.delete(key);
              return updated;
            });

            // Also remove from restart-required settings if it was there
            setRestartRequiredSettings((prev) => {
              const updated = new Set(prev);
              updated.delete(key);
              return updated;
            });

            setPendingSettings((_prevPending) => {
              let updatedPending = structuredClone(
                settings.forScope(selectedScope).settings,
              );

              currentModifiedSettings.forEach((modifiedKey) => {
                if (modifiedKey !== key) {
                  const modifiedValue = modifiedValues.get(modifiedKey);
                  if (modifiedValue !== undefined) {
                    updatedPending = setPendingSettingValue(
                      modifiedKey,
                      modifiedValue,
                      updatedPending,
                    );
                  }
                }
              });

              return updatedPending;
            });
          } else {
            // For restart-required settings, store the actual value
            setModifiedValues((prev) => {
              const updated = new Map(prev);
              updated.set(key, newValue);
              return updated;
            });

            setModifiedSettings((prev) => {
              const updated = new Set(prev).add(key);
              const needsRestart = hasRestartRequiredSettings(updated);
              console.log(
                `[DEBUG SettingsDialog] Modified settings:`,
                Array.from(updated),
                'Needs restart:',
                needsRestart,
              );
              if (needsRestart) {
                setShowRestartPrompt(true);
                setRestartRequiredSettings((prevRestart) =>
                  new Set(prevRestart).add(key),
                );
              }
              return updated;
            });
          }
        },
      };
    });
  };

  const items = generateSettingsItems();

  // Scope selector items
  const scopeItems = getScopeItems();

  const handleScopeHighlight = (scope: SettingScope) => {
    setSelectedScope(scope);
  };

  const handleScopeSelect = (scope: SettingScope) => {
    handleScopeHighlight(scope);
    setFocusSection('settings');
  };

  // Scroll logic for settings
  const visibleItems = items.slice(scrollOffset, scrollOffset + maxItemsToShow);
  // Always show arrows for consistent UI and to indicate circular navigation
  const showScrollUp = true;
  const showScrollDown = true;

  useInput((input, key) => {
    if (key.tab) {
      setFocusSection((prev) => (prev === 'settings' ? 'scope' : 'settings'));
    }
    if (focusSection === 'settings') {
      if (key.upArrow || input === 'k') {
        const newIndex =
          activeSettingIndex > 0 ? activeSettingIndex - 1 : items.length - 1;
        setActiveSettingIndex(newIndex);
        // Adjust scroll offset for wrap-around
        if (newIndex === items.length - 1) {
          setScrollOffset(Math.max(0, items.length - maxItemsToShow));
        } else if (newIndex < scrollOffset) {
          setScrollOffset(newIndex);
        }
      } else if (key.downArrow || input === 'j') {
        const newIndex =
          activeSettingIndex < items.length - 1 ? activeSettingIndex + 1 : 0;
        setActiveSettingIndex(newIndex);
        // Adjust scroll offset for wrap-around
        if (newIndex === 0) {
          setScrollOffset(0);
        } else if (newIndex >= scrollOffset + maxItemsToShow) {
          setScrollOffset(newIndex - maxItemsToShow + 1);
        }
      } else if (key.return || input === ' ') {
        items[activeSettingIndex]?.toggle();
      } else if ((key.ctrl && input === 'c') || (key.ctrl && input === 'l')) {
        // Ctrl+C or Ctrl+L: Clear current setting and reset to default
        const currentSetting = items[activeSettingIndex];
        if (currentSetting) {
          const defaultValue = getDefaultValue(currentSetting.value);
          // Ensure defaultValue is a boolean for setPendingSettingValue
          const booleanDefaultValue =
            typeof defaultValue === 'boolean' ? defaultValue : false;

          // Update pending settings to default value
          setPendingSettings((prev) =>
            setPendingSettingValue(
              currentSetting.value,
              booleanDefaultValue,
              prev,
            ),
          );

          // Remove from modified settings since it's now at default
          setModifiedSettings((prev) => {
            const updated = new Set(prev);
            updated.delete(currentSetting.value);
            return updated;
          });

          // Remove from restart-required settings if it was there
          setRestartRequiredSettings((prev) => {
            const updated = new Set(prev);
            updated.delete(currentSetting.value);
            return updated;
          });

          // If this setting doesn't require restart, save it immediately
          if (!requiresRestart(currentSetting.value)) {
            const immediateSettings = new Set([currentSetting.value]);
            const immediateSettingsObject = setPendingSettingValue(
              currentSetting.value,
              booleanDefaultValue,
              {},
            );

            saveModifiedSettings(
              immediateSettings,
              immediateSettingsObject,
              settings,
              selectedScope,
            );
          }
        }
      }
    }
    if (showRestartPrompt && input === 'r') {
      // Only save settings that require restart (non-restart settings were already saved immediately)
      const restartRequiredSettings =
        getRestartRequiredFromModified(modifiedSettings);
      const restartRequiredSet = new Set(restartRequiredSettings);

      if (restartRequiredSet.size > 0) {
        saveModifiedSettings(
          restartRequiredSet,
          pendingSettings,
          settings,
          selectedScope,
        );
      }

      setShowRestartPrompt(false);
      setRestartRequiredSettings(new Set()); // Clear restart-required settings
      if (onRestartRequest) onRestartRequest();
    }
    if (key.escape) {
      onSelect(undefined, selectedScope);
    }
  });

  return (
    <Box
      borderStyle="round"
      borderColor={Colors.Gray}
      flexDirection="row"
      padding={1}
      width="100%"
      height="100%"
    >
      <Box flexDirection="column" flexGrow={1}>
        <Text bold color={Colors.AccentBlue}>
          Settings
        </Text>
        <Box height={1} />
        {showScrollUp && <Text color={Colors.Gray}>▲</Text>}
        {visibleItems.map((item, idx) => {
          const isActive =
            focusSection === 'settings' &&
            activeSettingIndex === idx + scrollOffset;

          const scopeSettings = settings.forScope(selectedScope).settings;
          const mergedSettings = settings.merged;
          const displayValue = getDisplayValue(
            item.value,
            scopeSettings,
            mergedSettings,
            modifiedSettings,
            pendingSettings,
          );
          const shouldBeGreyedOut = isDefaultValue(item.value, scopeSettings);

          // Generate scope message for this setting
          const scopeMessage = getScopeMessageForSetting(
            item.value,
            selectedScope,
            settings,
          );

          return (
            <React.Fragment key={item.value}>
              <Box flexDirection="row" alignItems="center">
                <Box minWidth={2} flexShrink={0}>
                  <Text color={isActive ? Colors.AccentGreen : Colors.Gray}>
                    {isActive ? '●' : ''}
                  </Text>
                </Box>
                <Box minWidth={50}>
                  <Text
                    color={isActive ? Colors.AccentGreen : Colors.Foreground}
                  >
                    {item.label}
                    {scopeMessage && (
                      <Text color={Colors.Gray}> {scopeMessage}</Text>
                    )}
                  </Text>
                </Box>
                <Box minWidth={3} />
                <Text
                  color={
                    isActive
                      ? Colors.AccentGreen
                      : shouldBeGreyedOut
                        ? Colors.Gray
                        : Colors.Foreground
                  }
                >
                  {displayValue}
                </Text>
              </Box>
              <Box height={1} />
            </React.Fragment>
          );
        })}
        {showScrollDown && <Text color={Colors.Gray}>▼</Text>}

        <Box height={1} />

        <Box marginTop={1} flexDirection="column">
          <Text bold={focusSection === 'scope'} wrap="truncate">
            {focusSection === 'scope' ? '> ' : '  '}Apply To
          </Text>
          <RadioButtonSelect
            items={scopeItems}
            initialIndex={0}
            onSelect={handleScopeSelect}
            onHighlight={handleScopeHighlight}
            isFocused={focusSection === 'scope'}
            showNumbers={focusSection === 'scope'}
          />
        </Box>

        <Box height={1} />
        <Text color={Colors.Gray}>
          (Use Enter to select, Tab to change focus)
        </Text>
        {showRestartPrompt && (
          <Text color={Colors.AccentYellow}>
            To see changes, Gemini CLI must be restarted. Press r to exit and
            apply changes now.
          </Text>
        )}
      </Box>
    </Box>
  );
}