'use client' import { useState, useRef, useEffect } from 'react' interface CodeSnippet { code: string language: string title?: string } interface CodeSnippetEditorProps { initialSnippet?: CodeSnippet | null onSave: (snippet: CodeSnippet) => void onClose: () => void } const LANGUAGES = [ { value: 'javascript', label: 'JavaScript' }, { value: 'typescript', label: 'TypeScript' }, { value: 'python', label: 'Python' }, { value: 'go', label: 'Go' }, { value: 'rust', label: 'Rust' }, { value: 'java', label: 'Java' }, { value: 'c', label: 'C' }, { value: 'cpp', label: 'C++' }, { value: 'csharp', label: 'C#' }, { value: 'ruby', label: 'Ruby' }, { value: 'php', label: 'PHP' }, { value: 'swift', label: 'Swift' }, { value: 'kotlin', label: 'Kotlin' }, { value: 'bash', label: 'Bash / Shell' }, { value: 'sql', label: 'SQL' }, { value: 'html', label: 'HTML' }, { value: 'css', label: 'CSS' }, { value: 'scss', label: 'SCSS' }, { value: 'json', label: 'JSON' }, { value: 'yaml', label: 'YAML' }, { value: 'markdown', label: 'Markdown' }, { value: 'jsx', label: 'JSX' }, { value: 'tsx', label: 'TSX' }, { value: 'text', label: 'Plain Text' }, ] export default function CodeSnippetEditor({ initialSnippet, onSave, onClose, }: CodeSnippetEditorProps) { const [code, setCode] = useState(initialSnippet?.code || '') const [language, setLanguage] = useState(initialSnippet?.language || 'javascript') const [title, setTitle] = useState(initialSnippet?.title || '') const [error, setError] = useState('') const textareaRef = useRef(null) useEffect(() => { // Focus textarea on mount if (textareaRef.current) { textareaRef.current.focus() } }, []) // Handle tab key in textarea for indentation const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Tab') { e.preventDefault() const textarea = e.currentTarget const start = textarea.selectionStart const end = textarea.selectionEnd const newValue = code.substring(0, start) + ' ' + code.substring(end) setCode(newValue) // Set cursor position after the tab setTimeout(() => { textarea.selectionStart = textarea.selectionEnd = start + 2 }, 0) } // Cmd/Ctrl+Enter to save if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault() handleSave() } // Escape to close if (e.key === 'Escape') { onClose() } } const handleSave = () => { if (!code.trim()) { setError('Code cannot be empty') return } onSave({ code: code.trim(), language, title: title.trim() || undefined, }) } const lineCount = code.split('\n').length return (
{/* Header */}

Code Snippet

{/* Controls */}
setTitle(e.target.value)} placeholder="Snippet title (optional)" className="w-full px-3 py-2 text-sm bg-background border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary text-foreground placeholder:text-foreground-secondary" />
{/* Editor */}
{/* Line numbers */}
{Array.from({ length: lineCount }, (_, i) => (
{i + 1}
))}
{/* Code textarea */}