Spaces:
Running

Bot / frontend /src /features /file-manager /components /MultiTabEditorView.tsx
ddosvn's picture
Initial deploy of Panel ThTuanIT full stack and Lighthouse-optimized frontend
7e79d39 verified
Raw History Blame Contribute Delete
15.7 kB
'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<Record<string, TabBuffer>>({});
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<HTMLTextAreaElement>(null);
const gutterRef = useRef<HTMLDivElement>(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<HTMLTextAreaElement>) => {
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 (
<div className="flex-1 flex flex-col items-center justify-center bg-canvas p-6 text-center space-y-3">
<FileCode className="w-12 h-12 text-ink-3 stroke-[1.4]" aria-hidden="true" />
<div className="space-y-1 max-w-sm">
<h3 className="text-sm font-bold text-ink-1">Chưa mở tệp nào trong Editor</h3>
<p className="text-xs text-ink-2 leading-relaxed">
Chọn một tệp từ tab <strong>Files</strong> để chỉnh sửa đa tab với Ctrl+F và Ctrl+S.
</p>
</div>
</div>
);
}
const linesCount = (activeBuffer?.content || '').split('\n').length;
const byteSize = new Blob([activeBuffer?.content || '']).size;
return (
<div className="flex-1 flex flex-col h-full bg-canvas overflow-hidden">
{/* Multi-Tab Bar */}
<div className="border-b border-line bg-surface-1 flex items-center justify-between gap-2 px-2 sm:px-4 h-11 flex-shrink-0">
<div role="tablist" aria-label="Các tệp đang mở" className="flex items-center gap-1 overflow-x-auto flex-1">
{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 (
<div
key={tab.path}
className={`inline-flex items-center gap-1 rounded-lg border px-2.5 py-1 text-xs font-mono ${
active
? 'bg-surface-2 border-accent/50 text-ink-1'
: 'border-transparent text-ink-2 hover:bg-surface-2/60'
}`}
>
<button
type="button"
role="tab"
aria-selected={active}
onClick={() => setActiveEditorPath(tab.path)}
className="inline-flex items-center gap-1.5 max-w-[160px] truncate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent rounded"
>
<FileCode className="w-3.5 h-3.5 text-accent flex-shrink-0" aria-hidden="true" />
<span className="truncate">{tab.name}</span>
{tabDirty && (
<span className="w-1.5 h-1.5 rounded-full bg-amber-500 flex-shrink-0" title="Chưa lưu" />
)}
</button>
<button
type="button"
onClick={() => closeEditorTab(tab.path)}
aria-label={`Đóng tab ${tab.name}`}
className="p-0.5 rounded hover:bg-surface-3 text-ink-3 hover:text-ink-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<X className="w-3 h-3" aria-hidden="true" />
</button>
</div>
);
})}
</div>
<div className="flex items-center gap-1 flex-shrink-0">
<button
type="button"
onClick={() => setFindOpen((v) => !v)}
aria-label="Tìm kiếm trong tệp"
className={`p-1.5 min-h-[32px] min-w-[32px] flex items-center justify-center rounded-lg border ${
findOpen ? 'border-accent text-accent bg-accent/10' : 'border-line text-ink-2 hover:bg-surface-2'
}`}
>
<Search className="w-3.5 h-3.5" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => setWordWrap((w) => !w)}
aria-label="Bật tắt tự xuống dòng"
aria-pressed={wordWrap}
className={`p-1.5 min-h-[32px] min-w-[32px] flex items-center justify-center rounded-lg border ${
wordWrap ? 'border-accent text-accent bg-accent/10' : 'border-line text-ink-2 hover:bg-surface-2'
}`}
>
<WrapText className="w-3.5 h-3.5" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => setFontSize((s) => Math.max(11, s - 1))}
aria-label="Giảm cỡ chữ"
className="hidden sm:flex p-1.5 min-h-[32px] min-w-[32px] items-center justify-center rounded-lg border border-line text-ink-2 hover:bg-surface-2"
>
<Minus className="w-3 h-3" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => setFontSize((s) => Math.min(20, s + 1))}
aria-label="Tăng cỡ chữ"
className="hidden sm:flex p-1.5 min-h-[32px] min-w-[32px] items-center justify-center rounded-lg border border-line text-ink-2 hover:bg-surface-2"
>
<Plus className="w-3 h-3" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => void loadBuffer(activeEditorPath, true)}
aria-label="Tải lại nội dung tệp"
className="p-1.5 min-h-[32px] min-w-[32px] flex items-center justify-center rounded-lg border border-line text-ink-2 hover:bg-surface-2"
>
<RefreshCw className="w-3.5 h-3.5" aria-hidden="true" />
</button>
<Button
size="sm"
variant="primary"
disabled={!isDirty}
loading={saving}
onClick={() => void handleSave()}
className="min-h-[32px]"
>
<Save className="w-3.5 h-3.5" aria-hidden="true" />
<span>{saving ? 'Đang lưu...' : 'Lưu'}</span>
</Button>
</div>
</div>
{/* Inline Search Bar */}
{findOpen && (
<div className="border-b border-line bg-surface-2 px-4 py-2 flex items-center gap-2 flex-shrink-0">
<Search className="w-3.5 h-3.5 text-ink-3" aria-hidden="true" />
<label htmlFor="editor-find-input" className="sr-only">
Tìm trong tệp hiện tại
</label>
<input
id="editor-find-input"
autoFocus
type="text"
value={findQuery}
onChange={(e) => setFindQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
jumpToNextMatch();
} else if (e.key === 'Escape') {
setFindOpen(false);
}
}}
placeholder="Tìm chuỗi trong mã nguồn (Enter để nhảy tới kết quả)..."
className="flex-1 bg-surface-1 border border-line rounded-lg px-2.5 py-1 text-xs font-mono text-ink-1 outline-none focus:border-accent"
/>
<span className="text-[11px] font-mono tabular-nums text-ink-3">
{matchCount} kết quả
</span>
<Button size="sm" variant="secondary" onClick={jumpToNextMatch} className="min-h-[30px]">
Tìm tiếp
</Button>
<button
type="button"
onClick={() => setFindOpen(false)}
aria-label="Đóng tìm kiếm"
className="p-1 text-ink-3 hover:text-ink-1"
>
<X className="w-3.5 h-3.5" aria-hidden="true" />
</button>
</div>
)}
{/* Editor Body */}
{activeBuffer?.loading ? (
<div className="flex-1 flex items-center justify-center text-xs font-mono text-ink-3">
Đang đọc {activeEditorPath}...
</div>
) : activeBuffer?.error ? (
<div className="flex-1 flex flex-col items-center justify-center p-6 text-center space-y-2">
<p className="text-xs text-rose-500">{activeBuffer.error}</p>
<Button size="sm" variant="secondary" onClick={() => void loadBuffer(activeEditorPath, true)}>
Thử lại
</Button>
</div>
) : (
<div className="flex-1 flex overflow-hidden console-dark">
<div
ref={gutterRef}
aria-hidden="true"
style={{ fontSize: `${fontSize}px`, lineHeight: 1.6 }}
className="w-12 py-3 pr-2.5 text-right font-mono select-none text-zinc-500 border-r border-zinc-800/80 overflow-hidden flex-shrink-0"
>
{Array.from({ length: linesCount }, (_, i) => (
<div key={i}>{i + 1}</div>
))}
</div>
<label htmlFor="code-editor-textarea" className="sr-only">
Nội dung tệp {activeEditorPath}
</label>
<textarea
id="code-editor-textarea"
ref={textareaRef}
spellCheck={false}
value={activeBuffer?.content || ''}
onChange={(e) => {
const next = e.target.value;
setBuffers((prev) => ({
...prev,
[activeKey]: { ...prev[activeKey], content: next },
}));
updateCursorStats(e.currentTarget);
}}
onClick={(e) => updateCursorStats(e.currentTarget)}
onKeyUp={(e) => updateCursorStats(e.currentTarget)}
onKeyDown={handleTextareaKeyDown}
onScroll={(e) => {
if (gutterRef.current) gutterRef.current.scrollTop = e.currentTarget.scrollTop;
}}
style={{ fontSize: `${fontSize}px`, lineHeight: 1.6 }}
className={`flex-1 bg-transparent text-zinc-100 p-3 font-mono outline-none resize-none ${
wordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre overflow-x-auto'
}`}
/>
</div>
)}
{/* Status Bar */}
<div className="h-7 border-t border-line bg-surface-1 px-4 flex items-center justify-between text-[11px] font-mono tabular-nums text-ink-3 flex-shrink-0">
<span className="truncate">{activeEditorPath}</span>
<div className="flex items-center gap-4 flex-shrink-0">
<span>
Ln {cursorPos.line}, Col {cursorPos.col}
</span>
<span>{linesCount} dòng</span>
<span>{formatBytes(byteSize)}</span>
<span>UTF-8</span>
</div>
</div>
</div>
);
}