'use client'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { formatBytes } from '@/shared/lib/format'; import { useToast } from '@/shared/hooks/useToast'; import { Button } from '@/shared/components/Button'; import { useWorkspaceStore } from '@/features/workspace'; import { FileCode, Minus, Plus, RefreshCw, Save, Search, WrapText, X, } from 'lucide-react'; import { fileService } from '../services/fileService'; interface TabBuffer { content: string; original: string; loading: boolean; error: string; } export function MultiTabEditorView() { const { activeZone, editorTabs, activeEditorPath, setActiveEditorPath, closeEditorTab } = useWorkspaceStore(); const { pushToast } = useToast(); const [buffers, setBuffers] = useState>({}); const [saving, setSaving] = useState(false); const [wordWrap, setWordWrap] = useState(false); const [fontSize, setFontSize] = useState(13); const [findOpen, setFindOpen] = useState(false); const [findQuery, setFindQuery] = useState(''); const [cursorPos, setCursorPos] = useState({ line: 1, col: 1 }); const textareaRef = useRef(null); const gutterRef = useRef(null); const loadBuffer = useCallback( async (filePath: string, force = false) => { if (!activeZone) return; const key = `${activeZone}::${filePath}`; if (!force && buffers[key] && !buffers[key].error) return; setBuffers((prev) => ({ ...prev, [key]: { content: prev[key]?.content || '', original: prev[key]?.original || '', loading: true, error: '' }, })); try { const res = await fileService.readFile(activeZone, filePath); setBuffers((prev) => ({ ...prev, [key]: { content: res.content, original: res.content, loading: false, error: '' }, })); } catch (err: unknown) { setBuffers((prev) => ({ ...prev, [key]: { content: '', original: '', loading: false, error: err instanceof Error ? err.message : 'Không thể đọc tệp', }, })); } }, [activeZone, buffers], ); useEffect(() => { if (activeZone && activeEditorPath) { void loadBuffer(activeEditorPath); } }, [activeZone, activeEditorPath]); const activeKey = activeZone && activeEditorPath ? `${activeZone}::${activeEditorPath}` : ''; const activeBuffer = activeKey ? buffers[activeKey] : undefined; const isDirty = Boolean(activeBuffer && activeBuffer.content !== activeBuffer.original); const handleSave = useCallback(async () => { if (!activeZone || !activeEditorPath || !activeBuffer || saving) return; setSaving(true); try { await fileService.writeFile(activeZone, activeEditorPath, activeBuffer.content); setBuffers((prev) => ({ ...prev, [activeKey]: { ...prev[activeKey], original: activeBuffer.content }, })); pushToast(`Đã lưu ${activeEditorPath}`, 'success'); } catch (err: unknown) { pushToast(err instanceof Error ? err.message : 'Lỗi khi lưu tệp', 'error'); } finally { setSaving(false); } }, [activeZone, activeEditorPath, activeBuffer, activeKey, saving, pushToast]); useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault(); void handleSave(); } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f') { e.preventDefault(); setFindOpen(true); } }; window.addEventListener('keydown', onKeyDown); return () => window.removeEventListener('keydown', onKeyDown); }, [handleSave]); const matchCount = useMemo(() => { if (!findQuery || !activeBuffer?.content) return 0; const q = findQuery.toLowerCase(); const hay = activeBuffer.content.toLowerCase(); let idx = 0; let count = 0; while ((idx = hay.indexOf(q, idx)) !== -1) { count++; idx += q.length; } return count; }, [findQuery, activeBuffer?.content]); const jumpToNextMatch = () => { const el = textareaRef.current; if (!el || !findQuery || !activeBuffer?.content) return; const hay = activeBuffer.content.toLowerCase(); const needle = findQuery.toLowerCase(); const startFrom = (el.selectionEnd || 0); let idx = hay.indexOf(needle, startFrom); if (idx === -1) idx = hay.indexOf(needle, 0); if (idx !== -1) { el.focus(); el.setSelectionRange(idx, idx + needle.length); } }; const updateCursorStats = (el: HTMLTextAreaElement) => { const upto = el.value.slice(0, el.selectionStart || 0).split('\n'); setCursorPos({ line: upto.length, col: (upto[upto.length - 1]?.length || 0) + 1 }); }; const handleTextareaKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Tab') { e.preventDefault(); const el = e.currentTarget; const start = el.selectionStart; const end = el.selectionEnd; const nextVal = `${el.value.slice(0, start)} ${el.value.slice(end)}`; setBuffers((prev) => ({ ...prev, [activeKey]: { ...prev[activeKey], content: nextVal }, })); requestAnimationFrame(() => { el.selectionStart = el.selectionEnd = start + 2; }); } }; if (editorTabs.length === 0 || !activeEditorPath) { return (
); } const linesCount = (activeBuffer?.content || '').split('\n').length; const byteSize = new Blob([activeBuffer?.content || '']).size; return (
{/* Multi-Tab Bar */}
{editorTabs.map((tab) => { const tabKey = `${activeZone}::${tab.path}`; const tabBuf = buffers[tabKey]; const tabDirty = Boolean(tabBuf && tabBuf.content !== tabBuf.original); const active = tab.path === activeEditorPath; return (
); })}
{/* Inline Search Bar */} {findOpen && (
)} {/* Editor Body */} {activeBuffer?.loading ? (
Đang đọc {activeEditorPath}...
) : activeBuffer?.error ? (

{activeBuffer.error}

) : (