import { useState, useRef } from 'react' import { Loader2 } from 'lucide-react' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Textarea } from '@/components/ui/textarea' import { Switch } from '@/components/ui/switch' import { parseJsonc } from '@/lib/jsonc' interface CreateConfigDialogProps { isOpen: boolean onOpenChange: (open: boolean) => void onCreate: (name: string, content: string, isDefault: boolean) => Promise isUpdating: boolean } export function CreateConfigDialog({ isOpen, onOpenChange, onCreate, isUpdating }: CreateConfigDialogProps) { const [name, setName] = useState('') const [content, setContent] = useState('') const [isDefault, setIsDefault] = useState(false) const [error, setError] = useState('') const [errorLine, setErrorLine] = useState(null) const textareaRef = useRef(null) const handleSubmit = async (event?: React.MouseEvent) => { event?.preventDefault() event?.stopPropagation() if (!name.trim() || !content.trim()) return try { await onCreate(name.trim(), content.trim(), isDefault) setName('') setContent('') setIsDefault(false) setError('') setErrorLine(null) } catch (error: unknown) { if (error instanceof SyntaxError) { const match = error.message.match(/line (\d+)/i) const line = match ? parseInt(match[1]) : null setErrorLine(line) setError(`JSON Error: ${error.message}`) if (line && textareaRef.current) { highlightErrorLine(textareaRef.current, line) } } else if (error instanceof Error) { setError(error.message) setErrorLine(null) } else { setError('Failed to create configuration') setErrorLine(null) } } } const handleFileUpload = (event: React.ChangeEvent) => { const file = event.target.files?.[0] if (!file) return const reader = new FileReader() reader.onload = (e) => { const fileContent = e.target?.result as string try { parseJsonc(fileContent) setContent(fileContent) setName(file.name.replace('.json', '').replace('.jsonc', '')) setError('') setErrorLine(null) } catch (err) { if (err instanceof SyntaxError) { const match = err.message.match(/line (\d+)/i) const line = match ? parseInt(match[1]) : null setErrorLine(line) setError(`Invalid JSON/JSONC file: ${err.message}`) } else { setError('Invalid JSON/JSONC file') setErrorLine(null) } } } reader.readAsText(file) } 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) } const handleContentChange = (value: string) => { setContent(value) setError('') setErrorLine(null) } return ( Create OpenCode Config
setName(e.target.value)} placeholder="my-config" />