File size: 8,709 Bytes
9332ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import type React from 'react';
import { useEffect, useState, useRef, useCallback } from 'react';
import { Box, Text } from 'ink';
import { theme } from '../semantic-colors.js';
import type { ExtensionManager } from '../../config/extension-manager.js';
import {
  configureExtension,
  configureSpecificSetting,
  configureAllExtensions,
  type ConfigLogger,
  type RequestSettingCallback,
  type RequestConfirmationCallback,
} from '../../commands/extensions/utils.js';
import {
  ExtensionSettingScope,
  type ExtensionSetting,
} from '../../config/extensions/extensionSettings.js';
import { TextInput } from './shared/TextInput.js';
import { useTextBuffer } from './shared/text-buffer.js';
import { DialogFooter } from './shared/DialogFooter.js';
import { type Key, useKeypress } from '../hooks/useKeypress.js';

export interface ConfigExtensionDialogProps {
  extensionManager: ExtensionManager;
  onClose: () => void;
  extensionName?: string;
  settingKey?: string;
  scope?: ExtensionSettingScope;
  configureAll?: boolean;
  loggerAdapter: ConfigLogger;
}

type DialogState =
  | { type: 'IDLE' }
  | { type: 'BUSY'; message?: string }
  | {
      type: 'ASK_SETTING';
      setting: ExtensionSetting;
      resolve: (val: string) => void;
      initialValue?: string;
    }
  | {
      type: 'ASK_CONFIRMATION';
      message: string;
      resolve: (val: boolean) => void;
    }
  | { type: 'DONE' }
  | { type: 'ERROR'; error: Error };

export const ConfigExtensionDialog: React.FC<ConfigExtensionDialogProps> = ({
  extensionManager,
  onClose,
  extensionName,
  settingKey,
  scope = ExtensionSettingScope.USER,
  configureAll,
  loggerAdapter,
}) => {
  const [state, setState] = useState<DialogState>({ type: 'IDLE' });
  const [logMessages, setLogMessages] = useState<string[]>([]);

  // Buffers for input
  const settingBuffer = useTextBuffer({
    initialText: '',
    viewport: { width: 80, height: 1 },
    singleLine: true,
    escapePastedPaths: true,
  });

  const mounted = useRef(true);

  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
    };
  }, []);

  const addLog = useCallback(
    (msg: string) => {
      setLogMessages((prev) => [...prev, msg].slice(-5)); // Keep last 5
      loggerAdapter.log(msg);
    },
    [loggerAdapter],
  );

  const requestSetting: RequestSettingCallback = useCallback(
    async (setting) =>
      new Promise<string>((resolve) => {
        if (!mounted.current) return;
        settingBuffer.setText(''); // Clear buffer
        setState({
          type: 'ASK_SETTING',
          setting,
          resolve: (val) => {
            resolve(val);
            setState({ type: 'BUSY', message: 'Updating...' });
          },
        });
      }),
    [settingBuffer],
  );

  const requestConfirmation: RequestConfirmationCallback = useCallback(
    async (message) =>
      new Promise<boolean>((resolve) => {
        if (!mounted.current) return;
        setState({
          type: 'ASK_CONFIRMATION',
          message,
          resolve: (val) => {
            resolve(val);
            setState({ type: 'BUSY', message: 'Processing...' });
          },
        });
      }),
    [],
  );

  useEffect(() => {
    async function run() {
      try {
        setState({ type: 'BUSY', message: 'Initializing...' });

        // Wrap logger to capture logs locally too
        const localLogger: ConfigLogger = {
          log: (msg) => {
            addLog(msg);
          },
          error: (msg) => {
            addLog('Error: ' + msg);
            loggerAdapter.error(msg);
          },
        };

        if (configureAll) {
          await configureAllExtensions(
            extensionManager,
            scope,
            localLogger,
            requestSetting,
            requestConfirmation,
          );
        } else if (extensionName && settingKey) {
          await configureSpecificSetting(
            extensionManager,
            extensionName,
            settingKey,
            scope,
            localLogger,
            requestSetting,
          );
        } else if (extensionName) {
          await configureExtension(
            extensionManager,
            extensionName,
            scope,
            localLogger,
            requestSetting,
            requestConfirmation,
          );
        }

        if (mounted.current) {
          setState({ type: 'DONE' });
          // Delay close slightly to show done
          setTimeout(onClose, 1000);
        }
      } catch (err: unknown) {
        if (mounted.current) {
          const error = err instanceof Error ? err : new Error(String(err));
          setState({ type: 'ERROR', error });
          loggerAdapter.error(error.message);
        }
      }
    }

    // Only run once
    if (state.type === 'IDLE') {
      void run();
    }
  }, [
    extensionManager,
    extensionName,
    settingKey,
    scope,
    configureAll,
    loggerAdapter,
    requestSetting,
    requestConfirmation,
    addLog,
    onClose,
    state.type,
  ]);

  // Handle Input Submission
  const handleSettingSubmit = (val: string) => {
    if (state.type === 'ASK_SETTING') {
      state.resolve(val);
    }
  };

  // Handle Keys for Confirmation
  useKeypress(
    (key: Key) => {
      if (state.type === 'ASK_CONFIRMATION') {
        if (key.name === 'y' || key.name === 'enter') {
          state.resolve(true);
          return true;
        }
        if (key.name === 'n' || key.name === 'escape') {
          state.resolve(false);
          return true;
        }
      }
      if (state.type === 'DONE' || state.type === 'ERROR') {
        if (key.name === 'enter' || key.name === 'escape') {
          onClose();
          return true;
        }
      }
      return false;
    },
    {
      isActive:
        state.type === 'ASK_CONFIRMATION' ||
        state.type === 'DONE' ||
        state.type === 'ERROR',
    },
  );

  if (state.type === 'BUSY' || state.type === 'IDLE') {
    return (
      <Box
        flexDirection="column"
        borderStyle="round"
        borderColor={theme.border.default}
        paddingX={1}
      >
        <Text color={theme.text.secondary}>
          {state.type === 'BUSY' ? state.message : 'Starting...'}
        </Text>
        {logMessages.map((msg, i) => (
          <Text key={i}>{msg}</Text>
        ))}
      </Box>
    );
  }

  if (state.type === 'ASK_SETTING') {
    return (
      <Box
        flexDirection="column"
        borderStyle="round"
        borderColor={theme.border.default}
        paddingX={1}
      >
        <Text bold color={theme.text.primary}>
          Configure {state.setting.name}
        </Text>
        <Text color={theme.text.secondary}>
          {state.setting.description || state.setting.envVar}
        </Text>
        <Box flexDirection="row" marginTop={1}>
          <Text color={theme.text.accent}>{'> '}</Text>
          <TextInput
            buffer={settingBuffer}
            onSubmit={handleSettingSubmit}
            focus={true}
            placeholder={`Enter value for ${state.setting.name}`}
          />
        </Box>
        <DialogFooter primaryAction="Enter to submit" />
      </Box>
    );
  }

  if (state.type === 'ASK_CONFIRMATION') {
    return (
      <Box
        flexDirection="column"
        borderStyle="round"
        borderColor={theme.border.default}
        paddingX={1}
      >
        <Text color={theme.status.warning} bold>
          Confirmation Required
        </Text>
        <Text>{state.message}</Text>
        <Box marginTop={1}>
          <Text color={theme.text.secondary}>
            Press{' '}
            <Text color={theme.text.accent} bold>
              Y
            </Text>{' '}
            to confirm or{' '}
            <Text color={theme.text.accent} bold>
              N
            </Text>{' '}
            to cancel
          </Text>
        </Box>
      </Box>
    );
  }

  if (state.type === 'ERROR') {
    return (
      <Box
        flexDirection="column"
        borderStyle="round"
        borderColor={theme.status.error}
        paddingX={1}
      >
        <Text color={theme.status.error} bold>
          Error
        </Text>
        <Text>{state.error.message}</Text>
        <DialogFooter primaryAction="Enter to close" />
      </Box>
    );
  }

  return (
    <Box
      flexDirection="column"
      borderStyle="round"
      borderColor={theme.status.success}
      paddingX={1}
    >
      <Text color={theme.status.success} bold>
        Configuration Complete
      </Text>
      <DialogFooter primaryAction="Enter to close" />
    </Box>
  );
};