import { useState, useRef, useEffect } from 'react' import { Button } from '@/components/ui/button' import { Textarea } from '@/components/ui/textarea' import { Loader2 } from 'lucide-react' import { Dialog, DialogContent, DialogHeader, DialogFooter, DialogTitle } from '@/components/ui/dialog' import type { OpenCodeConfig } from '@/api/types/settings' import { parseJsonc } from '@/lib/jsonc' import { FetchError } from '@/api/fetchWrapper' interface OpenCodeConfigEditorProps { config: OpenCodeConfig | null isOpen: boolean onClose: () => void onUpdate: (content: string) => Promise isUpdating: boolean } export function OpenCodeConfigEditor({ config, isOpen, onClose, onUpdate, isUpdating }: OpenCodeConfigEditorProps) { const [editConfigContent, setEditConfigContent] = useState('') const [editError, setEditError] = useState('') const [editErrorLine, setEditErrorLine] = useState(null) const editTextareaRef = useRef(null) useEffect(() => { if (config && isOpen) { setEditConfigContent(config.rawContent || JSON.stringify(config.content, null, 2)) setEditError('') setEditErrorLine(null) } }, [config, isOpen]) useEffect(() => { if (isOpen && editTextareaRef.current) { editTextareaRef.current.focus() } }, [isOpen]) const updateConfig = async () => { if (!config) return try { parseJsonc>(editConfigContent) await onUpdate(editConfigContent) onClose() } catch (error) { if (error instanceof SyntaxError) { const lineMatch = error.message.match(/line\s+(\d+)/i) const line = lineMatch ? parseInt(lineMatch[1]) : null setEditErrorLine(line) if (line && editTextareaRef.current) { highlightErrorLine(editTextareaRef.current, line) } setEditError(`Invalid JSON/JSONC: ${error.message}`) } else if (error instanceof FetchError) { setEditError(error.detail || error.message) } else if (error instanceof Error) { setEditError(error.message) } else { setEditError('Failed to save configuration') } } } const highlightErrorLine = (textarea: HTMLTextAreaElement, line: number) => { const lines = textarea.value.split('\n') if (line > lines.length) return let charIndex = 0 for (let i = 0; i < line - 1; i++) { charIndex += lines[i].length + 1 } textarea.focus() textarea.setSelectionRange(charIndex, charIndex + lines[line - 1].length) // Scroll to make the error line visible const lineHeight = textarea.scrollHeight / lines.length const targetPosition = lineHeight * (line - 1) textarea.scrollTop = targetPosition - textarea.clientHeight / 2 + lineHeight / 2 } if (!config) return null return ( !open && onClose()}> {`Edit Config: ${config.name}`}