Spaces:
Running
Running
File size: 21,447 Bytes
7e79d39 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | 'use client';
import React, { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import {
BRAND_NAME,
ROUTES,
WORKSPACE_TABS,
} from '@/shared/constants';
import { normalizePath } from '@/shared/lib/format';
import { useToast } from '@/shared/hooks/useToast';
import { BrandLogoMark, EmptyZoneGlyph } from '@/shared/components/BrandGlyphs';
import { Button } from '@/shared/components/Button';
import { Input, Select } from '@/shared/components/Input';
import { ConfirmModal, Modal } from '@/shared/components/Modal';
import { ThemeSelector } from '@/shared/components/ThemeSelector';
import { AuthDialog, useAuthSession } from '@/features/auth';
import {
FileCode,
Folder,
Layers,
LogOut,
Menu,
Plus,
Radio,
Search,
Shield,
Terminal,
Trash2,
X,
} from 'lucide-react';
import { validateZoneInput } from '../schemas/workspaceSchema';
import { workspaceService } from '../services/workspaceService';
import { useWorkspaceStore } from '../hooks/useWorkspaceStore';
import { WorkspaceOwnerOption, Zone } from '../types/workspaceTypes';
const TAB_ICONS = {
files: Folder,
editor: FileCode,
terminal: Terminal,
ports: Radio,
} as const;
export function WorkspaceShell({ children }: { children: React.ReactNode }) {
const pathname = usePathname() || ROUTES.PANEL_FILES;
const activePath = normalizePath(pathname);
const router = useRouter();
const { pushToast } = useToast();
const { user, authLoading, publicConfig, motdDismissed, dismissMotd, logout } = useAuthSession();
const {
zones,
activeZone,
selectZone,
createZone,
deleteZone,
sidebarOpen,
setSidebarOpen,
editorTabs,
openPalette,
} = useWorkspaceStore();
const [zoneSearch, setZoneSearch] = useState('');
const [createOpen, setCreateOpen] = useState(false);
const [newName, setNewName] = useState('');
const [newDesc, setNewDesc] = useState('');
const [ownerId, setOwnerId] = useState('');
const [owners, setOwners] = useState<WorkspaceOwnerOption[]>([]);
const [createError, setCreateError] = useState('');
const [creating, setCreating] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const isAdmin = user?.role === 'admin';
const isAdminRoute = activePath.startsWith('/panel/admin');
const maxZones = publicConfig.max_zones || 0;
useEffect(() => {
if (!createOpen || !isAdmin) return;
workspaceService
.listOwnerOptions()
.then((list) => setOwners(list || []))
.catch(() => {});
}, [createOpen, isAdmin]);
const filteredZones = useMemo(() => {
const q = zoneSearch.trim().toLowerCase();
if (!q) return zones;
return zones.filter(
(z) =>
z.name.toLowerCase().includes(q) ||
(z.description && z.description.toLowerCase().includes(q)) ||
(z.owner_name && z.owner_name.toLowerCase().includes(q)),
);
}, [zones, zoneSearch]);
const groupedZones = useMemo(() => {
const map = new Map<string, { label: string; items: Zone[] }>();
for (const z of filteredZones) {
const key = z.owner_id || 'self';
const label = z.owner_name || user?.username || 'Cá nhân';
const existing = map.get(key);
if (existing) existing.items.push(z);
else map.set(key, { label, items: [z] });
}
return Array.from(map.values());
}, [filteredZones, user?.username]);
const openCreateModal = () => {
setNewName('');
setNewDesc('');
setOwnerId(user?.id || '');
setCreateError('');
setCreateOpen(true);
};
const handleCreateSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setCreateError('');
const check = validateZoneInput(newName, newDesc);
if (!check.ok || !check.data) {
setCreateError(check.error || 'Tên zone không hợp lệ.');
return;
}
setCreating(true);
try {
await createZone(check.data.name, check.data.description, isAdmin ? ownerId : undefined);
setCreateOpen(false);
pushToast(`Đã tạo zone "${check.data.name}"`, 'success');
if (isAdminRoute) router.push(ROUTES.PANEL_FILES);
} catch (err: unknown) {
setCreateError(err instanceof Error ? err.message : 'Không thể tạo zone');
} finally {
setCreating(false);
}
};
const handleConfirmDelete = async () => {
if (!deleteTarget) return;
setDeleting(true);
try {
await deleteZone(deleteTarget);
pushToast(`Đã xoá zone "${deleteTarget}"`, 'success');
setDeleteTarget(null);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Không thể xoá zone', 'error');
} finally {
setDeleting(false);
}
};
if (authLoading) {
return (
<div className="h-screen w-screen flex items-center justify-center bg-canvas">
<div
role="status"
aria-label="Đang xác thực phiên làm việc"
className="w-9 h-9 border-2 border-accent border-t-transparent rounded-full animate-spin"
/>
</div>
);
}
if (!user) {
return (
<div className="h-screen w-screen bg-canvas">
<AuthDialog standaloneOpen onStandaloneClose={() => router.push(ROUTES.HOME)} />
</div>
);
}
const motdText = publicConfig.motd && !motdDismissed ? publicConfig.motd : '';
return (
<div className="h-screen w-screen flex flex-col bg-canvas text-ink-1 overflow-hidden">
{motdText && (
<div className="bg-accent px-4 py-1.5 text-xs text-on-accent flex items-center justify-between gap-2 z-30 flex-shrink-0">
<div className="flex-1 text-center font-medium truncate">{motdText}</div>
<button
type="button"
onClick={dismissMotd}
aria-label="Đóng thông báo hệ thống"
className="p-1 min-h-[32px] min-w-[32px] flex items-center justify-center rounded-lg hover:bg-black/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-on-accent"
>
<X className="w-3.5 h-3.5" aria-hidden="true" />
</button>
</div>
)}
<div className="flex-1 flex overflow-hidden">
{sidebarOpen && (
<div
onClick={() => setSidebarOpen(false)}
className="fixed inset-0 z-40 bg-black/65 backdrop-blur-sm lg:hidden"
aria-hidden="true"
/>
)}
<aside
aria-label="Danh sách Zone"
className={`fixed inset-y-0 left-0 z-50 w-72 bg-surface-1 border-r border-line flex flex-col transition-transform duration-200 lg:static lg:translate-x-0 ${
sidebarOpen ? 'translate-x-0' : '-translate-x-full'
}`}
>
<div className="h-14 px-4 border-b border-line flex items-center justify-between gap-2 flex-shrink-0">
<Link
href={ROUTES.HOME}
className="flex items-center gap-2.5 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<span className="w-8 h-8 rounded-lg bg-accent/15 border border-accent/35 text-accent flex items-center justify-center">
<BrandLogoMark className="w-4 h-4" />
</span>
<span className="font-bold text-sm tracking-tight text-ink-1 truncate">
{BRAND_NAME}
</span>
</Link>
<button
type="button"
onClick={() => setSidebarOpen(false)}
aria-label="Đóng thanh bên"
className="p-2 min-h-[40px] min-w-[40px] flex items-center justify-center rounded-lg text-ink-3 hover:text-ink-1 hover:bg-surface-2 lg:hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<X className="w-4 h-4" aria-hidden="true" />
</button>
</div>
<div className="p-3 border-b border-line space-y-2.5 flex-shrink-0">
<div className="flex items-center justify-between text-[11px] font-mono text-ink-3">
<span>ZONES ({zones.length}{maxZones > 0 && !isAdmin ? `/${maxZones}` : ''})</span>
<Button size="sm" variant="primary" onClick={openCreateModal} className="min-h-[32px] px-2.5 py-1">
<Plus className="w-3.5 h-3.5" aria-hidden="true" />
<span>Tạo Zone</span>
</Button>
</div>
<Input
aria-label="Tìm kiếm zone"
placeholder="Tìm nhanh zone..."
value={zoneSearch}
onChange={(e) => setZoneSearch(e.target.value)}
leftIcon={<Search className="w-3.5 h-3.5" />}
className="min-h-[36px] text-xs"
/>
</div>
<div className="flex-1 overflow-y-auto p-2.5 space-y-4">
{filteredZones.length === 0 ? (
<div className="py-10 px-3 text-center space-y-2 text-ink-3">
<EmptyZoneGlyph className="w-12 h-12 mx-auto" />
<p className="text-xs">
{zones.length === 0 ? 'Chưa có zone nào.' : 'Không tìm thấy zone phù hợp.'}
</p>
</div>
) : (
groupedZones.map((group) => (
<div key={group.label} className="space-y-1">
{isAdmin && groupedZones.length > 1 && (
<div className="px-2 py-1 text-[10px] font-mono uppercase tracking-wider text-ink-3">
{group.label} ({group.items.length})
</div>
)}
{group.items.map((z) => {
const selected = z.name === activeZone;
return (
<div
key={z.name}
className={`group flex items-center justify-between gap-2 rounded-xl border px-2.5 py-2 ${
selected
? 'bg-accent/10 border-accent/40 text-ink-1'
: 'border-transparent hover:bg-surface-2 text-ink-2'
}`}
>
<button
type="button"
onClick={() => {
selectZone(z.name);
if (isAdminRoute) router.push(ROUTES.PANEL_FILES);
}}
className="flex-1 min-w-0 flex items-center gap-2 text-left min-h-[32px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent rounded-lg"
>
<span
className={`w-2 h-2 rounded-full flex-shrink-0 ${
selected ? 'bg-accent' : 'bg-ink-3/50'
}`}
aria-hidden="true"
/>
<span className="min-w-0 flex-1">
<span className="block font-mono text-xs font-semibold text-ink-1 truncate">
{z.name}
</span>
{(z.description || z.has_autostart || (z.ports_count || 0) > 0) && (
<span className="block text-[10px] text-ink-3 truncate">
{z.has_autostart ? 'Autostart · ' : ''}
{(z.ports_count || 0) > 0 ? `${z.ports_count} port · ` : ''}
{z.description || 'Workspace'}
</span>
)}
</span>
</button>
<button
type="button"
onClick={() => setDeleteTarget(z.name)}
aria-label={`Xoá zone ${z.name}`}
className="p-1.5 min-h-[32px] min-w-[32px] flex items-center justify-center rounded-lg text-ink-3 hover:text-rose-500 hover:bg-rose-500/10 opacity-70 group-hover:opacity-100 transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
</button>
</div>
);
})}
</div>
))
)}
</div>
<div className="p-3 border-t border-line bg-surface-2/40 flex items-center justify-between gap-2 flex-shrink-0">
<div className="min-w-0">
<div className="text-xs font-semibold text-ink-1 truncate">{user.username}</div>
<div className="text-[10px] font-mono uppercase tracking-wider text-accent">
{user.role}
</div>
</div>
<button
type="button"
onClick={logout}
aria-label="Đăng xuất tài khoản"
className="p-2 min-h-[40px] min-w-[40px] flex items-center justify-center rounded-xl border border-line bg-surface-1 hover:bg-surface-2 text-ink-2 hover:text-rose-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<LogOut className="w-4 h-4" aria-hidden="true" />
</button>
</div>
</aside>
<main className="flex-1 flex flex-col min-w-0 bg-canvas">
<header className="h-14 border-b border-line px-3 sm:px-5 flex items-center justify-between gap-2 bg-surface-1/85 backdrop-blur-md flex-shrink-0">
<div className="flex items-center gap-2.5 min-w-0">
<button
type="button"
onClick={() => setSidebarOpen(true)}
aria-label="Mở menu thanh bên"
className="p-2 min-h-[42px] min-w-[42px] flex items-center justify-center rounded-xl border border-line bg-surface-2 text-ink-2 hover:text-ink-1 lg:hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Menu className="w-4 h-4" aria-hidden="true" />
</button>
{activeZone ? (
<div className="inline-flex items-center gap-2 px-2.5 py-1 rounded-lg bg-surface-2 border border-line min-w-0">
<span className="w-2 h-2 rounded-full bg-accent animate-pulse flex-shrink-0" />
<span className="font-mono text-xs font-semibold text-ink-1 truncate max-w-[120px] sm:max-w-xs">
{activeZone}
</span>
</div>
) : (
<span className="text-xs text-ink-3 italic">Chưa chọn zone</span>
)}
</div>
<div className="flex items-center gap-2">
{(activeZone || isAdmin) && (
<nav
aria-label="Điều hướng Workspace"
className="flex items-center gap-1 bg-surface-2 border border-line p-1 rounded-xl overflow-x-auto"
>
{activeZone &&
WORKSPACE_TABS.map((tab) => {
const Icon = TAB_ICONS[tab.id];
const isRoot = activePath === '/panel' && tab.id === 'files';
const active = isRoot || activePath === normalizePath(tab.href);
return (
<Link
key={tab.id}
href={tab.href}
className={`inline-flex items-center gap-1.5 px-2.5 sm:px-3 min-h-[34px] rounded-lg text-xs font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
active
? 'bg-accent text-on-accent shadow-sm'
: 'text-ink-2 hover:text-ink-1 hover:bg-surface-3'
}`}
>
<Icon className="w-3.5 h-3.5" aria-hidden="true" />
<span className="hidden md:inline">{tab.label}</span>
{tab.id === 'editor' && editorTabs.length > 0 && (
<span
className={`px-1.5 py-0.2 rounded-full text-[10px] font-mono tabular-nums ${
active ? 'bg-black/15 text-on-accent' : 'bg-accent/15 text-accent'
}`}
>
{editorTabs.length}
</span>
)}
</Link>
);
})}
{isAdmin && (
<Link
href={ROUTES.PANEL_ADMIN}
className={`inline-flex items-center gap-1.5 px-2.5 sm:px-3 min-h-[34px] rounded-lg text-xs font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
isAdminRoute
? 'bg-amber-500 text-zinc-950 shadow-sm'
: 'text-amber-500 hover:bg-surface-3'
}`}
>
<Shield className="w-3.5 h-3.5" aria-hidden="true" />
<span className="hidden md:inline">Admin</span>
</Link>
)}
</nav>
)}
<button
type="button"
onClick={openPalette}
aria-label="Mở bảng lệnh nhanh Ctrl+K"
className="hidden sm:inline-flex items-center gap-1.5 min-h-[38px] px-2.5 rounded-xl border border-line bg-surface-2 hover:bg-surface-3 text-ink-2 text-xs font-mono focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Search className="w-3.5 h-3.5" aria-hidden="true" />
<span>Ctrl+K</span>
</button>
<ThemeSelector compact />
</div>
</header>
<div className="flex-1 overflow-hidden flex flex-col">
{!activeZone && !isAdminRoute ? (
<div className="flex-1 flex flex-col items-center justify-center p-6 text-center space-y-4">
<EmptyZoneGlyph className="w-16 h-16 text-ink-3" />
<div className="space-y-1 max-w-sm">
<h2 className="text-base font-bold text-ink-1">Chưa có Zone nào được chọn</h2>
<p className="text-xs text-ink-2 leading-relaxed">
Tạo một Zone mới để bắt đầu quản lý tệp, chỉnh sửa mã nguồn, chạy Terminal PTY và mở cổng Reverse Proxy.
</p>
</div>
<Button onClick={openCreateModal}>
<Layers className="w-4 h-4" aria-hidden="true" />
<span>Tạo Zone đầu tiên</span>
</Button>
</div>
) : (
children
)}
</div>
</main>
</div>
<Modal open={createOpen} onClose={() => setCreateOpen(false)} title="Tạo Zone làm việc mới">
<form onSubmit={handleCreateSubmit} className="space-y-4">
{createError && (
<p role="alert" className="text-xs text-rose-500 bg-rose-500/10 border border-rose-500/30 rounded-xl p-3">
{createError}
</p>
)}
<Input
label="Tên Zone"
required
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder="vd: web-api, discord-bot"
helperText="Chỉ gồm chữ, số, _ hoặc - (1–50 ký tự)"
/>
<Input
label="Mô tả (tùy chọn)"
value={newDesc}
onChange={(e) => setNewDesc(e.target.value)}
placeholder="Dự án Node.js / Python / Go..."
/>
{isAdmin && owners.length > 0 && (
<Select
label="Chủ sở hữu Zone"
value={ownerId}
onChange={(e) => setOwnerId(e.target.value)}
>
{owners.map((u) => (
<option key={u.id} value={u.id}>
{u.username} ({u.role})
</option>
))}
</Select>
)}
<div className="flex items-center justify-end gap-2 pt-2">
<Button variant="secondary" size="sm" onClick={() => setCreateOpen(false)}>
Huỷ
</Button>
<Button type="submit" size="sm" loading={creating}>
{creating ? 'Đang tạo...' : 'Khởi tạo Zone'}
</Button>
</div>
</form>
</Modal>
<ConfirmModal
open={Boolean(deleteTarget)}
onClose={() => setDeleteTarget(null)}
onConfirm={handleConfirmDelete}
title="Xoá Zone"
description={`Toàn bộ mã nguồn, cấu hình cổng và log trong zone "${deleteTarget}" sẽ bị xoá vĩnh viễn.`}
confirmLabel="Xoá vĩnh viễn"
danger
loading={deleting}
/>
</div>
);
}
|