feat: separate user navigation from focused host management

This commit is contained in:
canglan committed 2026-10-30 15:53:07 +08:00
1 parent d7c007adc4
commit 5a83583101
13 files changed
+153 -46

No files matched your search

+6
View File
@@ -8,6 +8,12 @@
待安装列表仅采用宝塔 Python 项目的 `sdk.streamline` 常用版本。Sea vHost 使用带官方 SHA-256 校验的源码构建,未修改宝塔 `btpyvm.py`;宝塔原生 XML 目录解析异常仍属于面板自身问题。本次实装仅覆盖 3.14.9,不代表全部 Python 分支已逐一安装。 待安装列表仅采用宝塔 Python 项目的 `sdk.streamline` 常用版本。Sea vHost 使用带官方 SHA-256 校验的源码构建,未修改宝塔 `btpyvm.py`;宝塔原生 XML 目录解析异常仍属于面板自身问题。本次实装仅覆盖 3.14.9,不代表全部 Python 分支已逐一安装。
## 用户导航与小屏补充验收(rc.3)
用户侧边栏保留“总览、域名、DNS API、操作日志”,用户计划任务入口移至总览工具区。总览每行仅保留“进入主机”,也可双击行进入;主机管理显示当前主机并可返回用户总览。主机内文件、数据库、FTP、图表和日志限定到当前主机,独立主机账号仍只管理自身。
前端 95 项回归通过。内置浏览器在 1280×900 与 390×844 检查列表及主机操作区;小屏操作列保留可达入口,表格操作按钮保持横向排列,主机详情按钮采用双列。36 线上双主机账号已验证进入指定主机、数据库与文件范围;本轮前端更新未修改账号、主机归属或后端程序。
## 直接开始使用 ## 直接开始使用
- 控制台:<https://host.ser888.cn/>。 - 控制台:<https://host.ser888.cn/>。
+1 -1
View File
@@ -39,7 +39,7 @@
## 网站、文件、环境与日志 ## 网站、文件、环境与日志
用户登录后,在“虚拟主机”的“选择虚拟主机”下拉框选择,选项为“主机名 · 显示名称”,再点击“网站管理”;选择同时决定本页的资源配置、运行目录、凭据和启停操作目标。“文件管理”和“资源图表”有各自的主机选择器,“操作日志”可按主机筛选;域名、FTP、数据库页面汇总该用户名下资源,并标明归属。独立主机账号只可管理自身,只有一台主机时不显示主机切换框。每个网站独立选择运行目录,主站默认 `/`,也可改为 `/public` 或其他主机内目录。目录必须位于主机根目录内。 用户侧边栏仅保留“总览、域名、DNS API、操作日志”。在总览主机列表点击“进入主机”,或双击主机行,进入该主机管理;页头显示目前主机,可“返回用户总览”后选择另一台。主机管理中提供资源配置、网站、文件、数据库、FTP、资源图表及该主机日志,均限定当前主机。账号权限不因进入主机而改变;独立主机账号直接进入自身管理,不提供返回用户总览。用户级计划任务入口保留在用户总览工具区,独立主机账号不可用。用户视图的域名与日志可查看名下主机汇总。每个网站独立选择运行目录,主站默认 `/`,也可改为 `/public` 或其他主机内目录。目录必须位于主机根目录内。
在网站的“运行环境”中可切换同语言的已安装版本;管理员对该主机开启“允许切换运行环境”后,才可跨语言切换。系统先停站并保留文件、数据库,完成后由使用者检查兼容性并手动启动或部署。运行环境的安装与组件补丁更新在管理员“环境配置”页提交,不同任务可排队、同节点串行,重复任务拒绝。 在网站的“运行环境”中可切换同语言的已安装版本;管理员对该主机开启“允许切换运行环境”后,才可跨语言切换。系统先停站并保留文件、数据库,完成后由使用者检查兼容性并手动启动或部署。运行环境的安装与组件补丁更新在管理员“环境配置”页提交,不同任务可排队、同节点串行,重复任务拒绝。
+26 -12
View File
@@ -1,5 +1,5 @@
import '@testing-library/jest-dom/vitest'; import '@testing-library/jest-dom/vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
import {DNSCredentials} from './components/DNSCredentials'; import {DNSCredentials} from './components/DNSCredentials';
import { App } from './App'; import { App } from './App';
@@ -20,6 +20,8 @@ afterEach(() => {
vi.restoreAllMocks(); vi.restoreAllMocks();
}); });
function enterFirstHost(){fireEvent.click(screen.getByRole('button',{name:'进入主机 '+initialProjects[0].hostName}))}
describe('Sea vHost', () => { describe('Sea vHost', () => {
it('opens the create project workflow', () => { it('opens the create project workflow', () => {
render(<App />); render(<App />);
@@ -34,7 +36,8 @@ describe('Sea vHost', () => {
it('lets a tenant configure a host-relative run directory', () => { it('lets a tenant configure a host-relative run directory', () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '主站目录' })[0]); enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: '设置运行目录' }));
expect(screen.getByRole('dialog', { name: '设置运行目录' })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: '设置运行目录' })).toBeInTheDocument();
const input = screen.getByDisplayValue('/public'); const input = screen.getByDisplayValue('/public');
fireEvent.change(input, { target: { value: '/../etc' } }); fireEvent.change(input, { target: { value: '/../etc' } });
@@ -43,14 +46,16 @@ describe('Sea vHost', () => {
it('opens file management for a selected project', async () => { it('opens file management for a selected project', async () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '文件' })[0]); enterFirstHost();
fireEvent.click(within(screen.getByLabelText('主导航')).getByRole('button',{name:'文件管理'}));
expect(screen.getByRole('heading', { name: '文件管理' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '文件管理' })).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '选择虚拟主机' })).toHaveValue('1'); expect(screen.getByRole('combobox', { name: '选择虚拟主机' })).toHaveValue('1');
}); });
it('adds another website with an independent runtime and directory', () => { it('adds another website with an independent runtime and directory', () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
expect(screen.getByRole('dialog', { name: '主机网站' })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: '主机网站' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '新增网站' })); fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
fireEvent.change(screen.getByLabelText('网站名称'), { target: { value: 'docs-site' } }); fireEvent.change(screen.getByLabelText('网站名称'), { target: { value: 'docs-site' } });
@@ -64,7 +69,8 @@ describe('Sea vHost', () => {
it('checks and deploys an uploaded language project before reporting it running', async () => { it('checks and deploys an uploaded language project before reporting it running', async () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
fireEvent.click(screen.getByRole('button', { name: '新增网站' })); fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } }); fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } });
fireEvent.click(screen.getByRole('button', { name: '创建网站' })); fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
@@ -80,7 +86,8 @@ describe('Sea vHost', () => {
it('installs a manual certificate without retaining the private key form', async () => { it('installs a manual certificate without retaining the private key form', async () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
fireEvent.click(screen.getByRole('button', { name: '安装证书 main-site' })); fireEvent.click(screen.getByRole('button', { name: '安装证书 main-site' }));
expect(screen.getByText(/私钥仅用于本次请求/)).toBeInTheDocument(); expect(screen.getByText(/私钥仅用于本次请求/)).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('证书链(PEM)'), { target: { value: '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----' } }); fireEvent.change(screen.getByLabelText('证书链(PEM)'), { target: { value: '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----' } });
@@ -91,7 +98,8 @@ describe('Sea vHost', () => {
it('lets a tenant retry automatic certificate issuance for a managed site', async () => { it('lets a tenant retry automatic certificate issuance for a managed site', async () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument(); expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'HTTP-01 申请证书 main-site' })); fireEvent.click(screen.getByRole('button', { name: 'HTTP-01 申请证书 main-site' }));
await waitFor(() => expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument()); await waitFor(() => expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument());
@@ -99,7 +107,8 @@ describe('Sea vHost', () => {
it('lets a tenant explicitly disable SSL and automatic renewal', async () => { it('lets a tenant explicitly disable SSL and automatic renewal', async () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
fireEvent.click(screen.getByRole('button', { name: '关闭 SSL main-site' })); fireEvent.click(screen.getByRole('button', { name: '关闭 SSL main-site' }));
fireEvent.click(screen.getByRole('button', { name: '确认继续' })); fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
await waitFor(() => expect(screen.getByText(/SSL 未启用/)).toBeInTheDocument()); await waitFor(() => expect(screen.getByText(/SSL 未启用/)).toBeInTheDocument());
@@ -108,7 +117,8 @@ describe('Sea vHost', () => {
it('shows reusable FTP and database credentials', () => { it('shows reusable FTP and database credentials', () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]); enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: '访问凭据' }));
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).not.toHaveTextContent('FTP 与数据库密码已加密保存'); expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).not.toHaveTextContent('FTP 与数据库密码已加密保存');
expect(screen.getByText('demo-ftp-password')).toBeInTheDocument(); expect(screen.getByText('demo-ftp-password')).toBeInTheDocument();
expect(screen.getByText('demo-database-password')).toBeInTheDocument(); expect(screen.getByText('demo-database-password')).toBeInTheDocument();
@@ -116,7 +126,8 @@ describe('Sea vHost', () => {
it('resets the independent host login password', async () => { it('resets the independent host login password', async () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]); enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: '访问凭据' }));
fireEvent.click(screen.getByRole('button', { name: '重置主机密码' })); fireEvent.click(screen.getByRole('button', { name: '重置主机密码' }));
fireEvent.click(screen.getByRole('button', { name: '确认继续' })); fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
expect(await screen.findByText('demo-host-password-reset')).toBeInTheDocument(); expect(await screen.findByText('demo-host-password-reset')).toBeInTheDocument();
@@ -124,7 +135,8 @@ describe('Sea vHost', () => {
it('stops and deletes an additional website without deleting host files', async () => { it('stops and deletes an additional website without deleting host files', async () => {
render(<App />); render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
fireEvent.click(screen.getByRole('button', { name: '新增网站' })); fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
fireEvent.click(screen.getByRole('button', { name: '创建网站' })); fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
fireEvent.click(await screen.findByRole('button', { name: '停止 site-two' })); fireEvent.click(await screen.findByRole('button', { name: '停止 site-two' }));
@@ -147,6 +159,7 @@ describe('Sea vHost', () => {
it('opens encrypted credentials from the FTP resource page', () => { it('opens encrypted credentials from the FTP resource page', () => {
render(<App />); render(<App />);
enterFirstHost();
fireEvent.click(screen.getByRole('button', { name: 'FTP' })); fireEvent.click(screen.getByRole('button', { name: 'FTP' }));
fireEvent.click(screen.getByRole('button', { name: /查看 FTP 凭据 sv8c0a6d2f91/ })); fireEvent.click(screen.getByRole('button', { name: /查看 FTP 凭据 sv8c0a6d2f91/ }));
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).toHaveTextContent('demo-ftp-password'); expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).toHaveTextContent('demo-ftp-password');
@@ -154,6 +167,7 @@ describe('Sea vHost', () => {
it('opens the mobile navigation and navigates to a resource page', () => { it('opens the mobile navigation and navigates to a resource page', () => {
render(<App />); render(<App />);
enterFirstHost();
const menu = screen.getByRole('button', { name: '打开导航' }); const menu = screen.getByRole('button', { name: '打开导航' });
fireEvent.click(menu); fireEvent.click(menu);
expect(menu).toHaveAttribute('aria-expanded', 'true'); expect(menu).toHaveAttribute('aria-expanded', 'true');
@@ -302,7 +316,7 @@ describe('宝塔站点迁移', () => {
describe('主机账号边界', () => { describe('主机账号边界', () => {
it('不显示用户级聚合用量和创建主机入口', () => { it('不显示用户级聚合用量和创建主机入口', () => {
const noop = () => undefined; const noop = () => undefined;
render(<Overview projects={[initialProjects[0]]} plan={demoPlan} usage={demoUsage} activities={[]} hostScoped canCreate={false} onCreate={noop} onToggle={noop} onFiles={noop} onRunPath={noop} onSites={noop} onCredentials={noop} />); render(<Overview projects={[initialProjects[0]]} plan={demoPlan} usage={demoUsage} activities={[]} hostScoped canCreate={false} onCreate={noop} onEnterHost={noop} />);
expect(screen.queryByText('存储空间')).not.toBeInTheDocument(); expect(screen.queryByText('存储空间')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /创建虚拟主机/ })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: /创建虚拟主机/ })).not.toBeInTheDocument();
expect(screen.queryByText('管理当前虚拟主机的网站、文件与访问凭据。')).not.toBeInTheDocument(); expect(screen.queryByText('管理当前虚拟主机的网站、文件与访问凭据。')).not.toBeInTheDocument();
+19 -6
View File
@@ -29,6 +29,8 @@ export function App() {
const adminPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('admin') === '1'; const adminPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('admin') === '1';
const [page, setPage] = useState('overview'); const [page, setPage] = useState('overview');
const [projects, setProjects] = useState<Project[]>(initialProjects); const [projects, setProjects] = useState<Project[]>(initialProjects);
const [managedProjectID, setManagedProjectID] = useState<number>();
useEffect(()=>{document.documentElement.scrollTop=0;document.body.scrollTop=0},[page,managedProjectID]);
const changingProjects=useRef(new Set<number>()),dashboardRevision=useRef(0);const [pendingProjectIDs,setPendingProjectIDs]=useState<number[]>([]); const changingProjects=useRef(new Set<number>()),dashboardRevision=useRef(0);const [pendingProjectIDs,setPendingProjectIDs]=useState<number[]>([]);
const [fileProjectID, setFileProjectID] = useState<number>(); const [fileProjectID, setFileProjectID] = useState<number>();
const [runPathProject, setRunPathProject] = useState<Project>(); const [runPathProject, setRunPathProject] = useState<Project>();
@@ -53,6 +55,11 @@ export function App() {
const [bootError, setBootError] = useState('');const [bootStatus,setBootStatus]=useState<number>(); const [bootError, setBootError] = useState('');const [bootStatus,setBootStatus]=useState<number>();
const [bootAttempt, setBootAttempt] = useState(0); const [bootAttempt, setBootAttempt] = useState(0);
const [showSecurity, setShowSecurity] = useState(false); const [showSecurity, setShowSecurity] = useState(false);
useEffect(()=>{
if(managedProjectID && !projects.some(project=>project.id===managedProjectID)){
setManagedProjectID(undefined);setPage('overview');setSitesProject(undefined);setRunPathProject(undefined);setCredentials(null);
}
},[managedProjectID,projects]);
const applyDashboard=useCallback((dashboard:Dashboard)=>{ const applyDashboard=useCallback((dashboard:Dashboard)=>{
setProjects(dashboard.projects.map(normalizeProject));setPlan(dashboard.plan);setUsage(dashboard.usage);setActivities(dashboard.activities);setHostScoped(dashboard.hostScoped);setDomainApproval(dashboard.domainApproval);setRootDomain(dashboard.rootDomain);setProjectRoot(dashboard.projectRoot); setProjects(dashboard.projects.map(normalizeProject));setPlan(dashboard.plan);setUsage(dashboard.usage);setActivities(dashboard.activities);setHostScoped(dashboard.hostScoped);setDomainApproval(dashboard.domainApproval);setRootDomain(dashboard.rootDomain);setProjectRoot(dashboard.projectRoot);
@@ -203,6 +210,12 @@ export function App() {
if (apiMode) void api.runtimeCatalog(project.id).then(result => setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason => notify(reason instanceof Error ? reason.message : '节点环境读取失败')); if (apiMode) void api.runtimeCatalog(project.id).then(result => setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason => notify(reason instanceof Error ? reason.message : '节点环境读取失败'));
} }
const managedProject = hostScoped ? projects[0] : projects.find(project=>project.id===managedProjectID);
const hostView = hostScoped || !!managedProject;
const visibleProjects = hostView ? (managedProject ? [managedProject] : []) : projects;
function enterHost(project:Project){setManagedProjectID(project.id);setFileProjectID(project.id);setPage('projects')}
function leaveHost(){setManagedProjectID(undefined);setPage('overview');setSitesProject(undefined);setRunPathProject(undefined);setCredentials(null)}
if (adminPreview) return <AdminConsole user={{ id: 1, email: 'admin@ser888.cn', loginName: 'admin@ser888.cn', displayName: '平台管理员', role: 'admin', mfaEnabled: true }} tenants={[{ id: 1, slug: 'sea-demo', name: '示例用户', status: 'active', lifecycleState: 'active', planName: '标准套餐', userCount: 1, projectCount: 3, expiresAt: '2026-12-31T16:00:00Z', createdAt: '2026-10-01T08:00:00Z' }]} plans={[demoPlan]} pendingDomains={[{ id: 9, projectId: 1, siteId: 1, tenantName: '示例用户', hostName: 'sv8c0a6d2f91', projectName: '企业官网', siteName: '主站', domain: 'www.customer.example', kind: 'custom', status: 'pending', resolutionMode: 'cname', cnameTarget: 'sv8c0a6d2f91.vhost.ser888.cn', filingStatus: 'pending', sslStatus: 'pending', createdAt: '2026-10-22T08:00:00Z' }]} approval onApproval={async () => undefined} onReviewDomain={async () => undefined} onCreate={async () => undefined} onCreatePlan={async () => undefined} onSecurity={() => undefined} onLogout={() => undefined} />; if (adminPreview) return <AdminConsole user={{ id: 1, email: 'admin@ser888.cn', loginName: 'admin@ser888.cn', displayName: '平台管理员', role: 'admin', mfaEnabled: true }} tenants={[{ id: 1, slug: 'sea-demo', name: '示例用户', status: 'active', lifecycleState: 'active', planName: '标准套餐', userCount: 1, projectCount: 3, expiresAt: '2026-12-31T16:00:00Z', createdAt: '2026-10-01T08:00:00Z' }]} plans={[demoPlan]} pendingDomains={[{ id: 9, projectId: 1, siteId: 1, tenantName: '示例用户', hostName: 'sv8c0a6d2f91', projectName: '企业官网', siteName: '主站', domain: 'www.customer.example', kind: 'custom', status: 'pending', resolutionMode: 'cname', cnameTarget: 'sv8c0a6d2f91.vhost.ser888.cn', filingStatus: 'pending', sslStatus: 'pending', createdAt: '2026-10-22T08:00:00Z' }]} approval onApproval={async () => undefined} onReviewDomain={async () => undefined} onCreate={async () => undefined} onCreatePlan={async () => undefined} onSecurity={() => undefined} onLogout={() => undefined} />;
if (setupPreview) return <InstallWizard preview />; if (setupPreview) return <InstallWizard preview />;
if (apiMode && setupRequired === true) return <InstallWizard />; if (apiMode && setupRequired === true) return <InstallWizard />;
@@ -212,17 +225,17 @@ export function App() {
if (apiMode && user?.role === 'admin') return <><AdminConsole onPlansChanged={async()=>{setPlans((await api.plans()).plans)}} onImpersonate={async input=>{await api.startImpersonation(input);window.location.reload()}} user={user} tenants={tenants} plans={plans} pendingDomains={pendingDomains} approval={domainApproval} onApproval={async (enabled) => { await api.setDomainApproval(enabled); setDomainApproval(enabled); }} onReviewDomain={async (id, approved) => { await api.reviewDomain(id, approved); setPendingDomains((current) => current.filter((item) => item.id !== id)); }} onCreate={async (input) => { await api.createTenant(input); setTenants((await api.tenants()).tenants); }} onCreatePlan={async (input: PlanInput) => { await api.createPlan(input); setPlans((await api.plans()).plans); }} onSecurity={() => setShowSecurity(true)} onLogout={async () => { await api.logout(); window.location.reload(); }} />{showSecurity ? <SecurityModal onClose={() => setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null}</>; if (apiMode && user?.role === 'admin') return <><AdminConsole onPlansChanged={async()=>{setPlans((await api.plans()).plans)}} onImpersonate={async input=>{await api.startImpersonation(input);window.location.reload()}} user={user} tenants={tenants} plans={plans} pendingDomains={pendingDomains} approval={domainApproval} onApproval={async (enabled) => { await api.setDomainApproval(enabled); setDomainApproval(enabled); }} onReviewDomain={async (id, approved) => { await api.reviewDomain(id, approved); setPendingDomains((current) => current.filter((item) => item.id !== id)); }} onCreate={async (input) => { await api.createTenant(input); setTenants((await api.tenants()).tenants); }} onCreatePlan={async (input: PlanInput) => { await api.createPlan(input); setPlans((await api.plans()).plans); }} onSecurity={() => setShowSecurity(true)} onLogout={async () => { await api.logout(); window.location.reload(); }} />{showSecurity ? <SecurityModal onClose={() => setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null}</>;
return ( return (
<AppShell page={page === 'create' ? 'projects' : page} tenantName={user?.tenantName ?? '示例科技有限公司'} displayName={user?.displayName ?? '张三'} hostScoped={hostScoped} onNavigate={setPage} onLogout={()=>{void api.logout().then(()=>window.location.reload()).catch(reason=>notify(reason instanceof Error?reason.message:'退出失败'))}} onSecurity={() => user?.impersonating?notify('请先返回管理员后操作账号安全'):setShowSecurity(true)}> <AppShell page={page === 'create'||page==='schedules' ? 'overview' : page} tenantName={user?.tenantName ?? '示例科技有限公司'} displayName={user?.displayName ?? '张三'} hostScoped={hostScoped} hostView={hostView} hostName={managedProject?.hostName} onBack={hostView&&!hostScoped?leaveHost:undefined} onNavigate={setPage} onLogout={()=>{void api.logout().then(()=>window.location.reload()).catch(reason=>notify(reason instanceof Error?reason.message:'退出失败'))}} onSecurity={() => user?.impersonating?notify('请先返回管理员后操作账号安全'):setShowSecurity(true)}>
{user?.impersonating?<ImpersonationBanner user={user}/>:null} {user?.impersonating?<ImpersonationBanner user={user}/>:null}
{dashboardSync.error?<p className="resource-error" role="alert">状态刷新失败:{dashboardSync.error}。<button className="secondary" onClick={dashboardSync.refresh}>重新读取状态</button></p>:null} {dashboardSync.error?<p className="resource-error" role="alert">状态刷新失败:{dashboardSync.error}。<button className="secondary" onClick={dashboardSync.refresh}>重新读取状态</button></p>:null}
{page === 'overview' ? <Overview onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} pendingProjectIDs={pendingProjectIDs} onLogs={() => setPage('logs')} projects={projects} plan={plan} usage={usage} activities={activities} hostScoped={hostScoped} canCreate={!apiMode} onCreate={() => setPage('create')} onToggle={toggleProject} onFiles={(id) => { setFileProjectID(id); setPage('files'); }} onRunPath={(project) => setRunPathProject(project)} onSites={(project)=>{setRuntimeVersions(normalizeCatalog({}));setSitesProject(project);if(apiMode) void api.runtimeCatalog(project.id).then(result=>setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason=>notify(reason instanceof Error?reason.message:"节点环境读取失败"));else setRuntimeVersions(demoRuntimeVersions);}} onCredentials={(project) => void showCredentials(project)} /> : null} {page === 'overview' ? <Overview onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onLogs={() => setPage('logs')} onSchedules={!hostScoped?()=>setPage('schedules'):undefined} projects={projects} plan={plan} usage={usage} activities={activities} hostScoped={hostScoped} canCreate={!apiMode} onCreate={() => setPage('create')} onEnterHost={enterHost} /> : null}
{page === 'create' ? <CreateProject runtimeVersions={runtimeVersions} rootDomain={rootDomain} projectRoot={projectRoot} plan={plan} domainApproval={domainApproval} onCancel={() => setPage('overview')} onSubmit={createProject} /> : null} {page === 'create' ? <CreateProject runtimeVersions={runtimeVersions} rootDomain={rootDomain} projectRoot={projectRoot} plan={plan} domainApproval={domainApproval} onCancel={() => setPage('overview')} onSubmit={createProject} /> : null}
{page==='schedules'&&!hostScoped?<UserSchedules projects={projects} live={apiMode}/>:null} {page==='schedules'&&!hostScoped?<UserSchedules projects={projects} live={apiMode}/>:null}
{page==='metrics'?<ResourceCharts projects={projects} live={apiMode}/>:null} {page==='metrics'?<ResourceCharts key={managedProject?.id} projects={visibleProjects} live={apiMode}/>:null}
{page === 'files' ? <FileManager projects={projects} initialProjectID={fileProjectID} live={apiMode} /> : null} {page === 'files' ? <FileManager key={managedProject?.id} projects={visibleProjects} initialProjectID={fileProjectID} live={apiMode} /> : null}
{page === 'projects' ? <HostDetails onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onToggle={toggleProject} pendingProjectIDs={pendingProjectIDs} hostScoped={hostScoped} projects={projects} plan={plan} usage={usage} live={apiMode} onRunPath={setRunPathProject} onSites={showSites} onCredentials={project => void showCredentials(project)} onFiles={id => { setFileProjectID(id); setPage('files'); }} /> : null} {page === 'projects' ? <HostDetails key={managedProject?.id} onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onToggle={toggleProject} pendingProjectIDs={pendingProjectIDs} hostScoped={hostScoped} projects={visibleProjects} plan={plan} usage={usage} live={apiMode} onRunPath={setRunPathProject} onSites={showSites} onCredentials={project => void showCredentials(project)} onFiles={id => { setFileProjectID(id); setPage('files'); }} /> : null}
{page === 'dns' && !hostScoped ? <DNSCredentials live={apiMode} /> : null} {page === 'dns' && !hostScoped ? <DNSCredentials live={apiMode} /> : null}
{['domains', 'databases', 'ftp', 'logs'].includes(page) ? <ResourceCenter page={page} projects={projects} activities={activities} hostScoped={hostScoped} domainApproval={domainApproval} live={apiMode} onCredentials={showCredentialsByID} onNotify={notify} /> : null} {['domains', 'databases', 'ftp', 'logs'].includes(page) ? <ResourceCenter key={`${managedProject?.id}:${page}`} page={page} projects={visibleProjects} projectID={managedProject?.id} activities={activities} hostScoped={hostView} domainApproval={domainApproval} live={apiMode} onCredentials={showCredentialsByID} onNotify={notify} /> : null}
{toast ? <div className="toast" role="status"><CheckIcon />{toast}</div> : null} {toast ? <div className="toast" role="status"><CheckIcon />{toast}</div> : null}
{credentials ? <CredentialsModal credentials={credentials} onReset={user?.role !== 'host' ? resetHostPassword : undefined} onClose={() => { setCredentials(null); setCredentialProjectID(undefined); }} /> : null} {credentials ? <CredentialsModal credentials={credentials} onReset={user?.role !== 'host' ? resetHostPassword : undefined} onClose={() => { setCredentials(null); setCredentialProjectID(undefined); }} /> : null}
{runPathProject ? <RunPathModal project={runPathProject} onClose={() => setRunPathProject(undefined)} onSubmit={updateRunPath} /> : null} {runPathProject ? <RunPathModal project={runPathProject} onClose={() => setRunPathProject(undefined)} onSubmit={updateRunPath} /> : null}
+7
View File
@@ -32,6 +32,13 @@ it('does not show a host switcher for a single-host login',()=>{
expect(screen.queryByRole('combobox',{name:'选择虚拟主机'})).not.toBeInTheDocument(); expect(screen.queryByRole('combobox',{name:'选择虚拟主机'})).not.toBeInTheDocument();
expect(screen.getByRole('heading',{name:initialProjects[0].hostName})).toBeInTheDocument(); expect(screen.getByRole('heading',{name:initialProjects[0].hostName})).toBeInTheDocument();
}); });
it('shows only the entered host databases even when the account resource response includes other hosts',async()=>{
const first=initialProjects[0],target=initialProjects[1];
vi.spyOn(api,'resources').mockResolvedValue({sites:[],domains:[],ftpAccounts:[],databases:[first,target].map(p=>({id:p.id,projectId:p.id,hostName:p.hostName,projectName:p.name,name:'db-'+p.hostName,username:p.hostName,sizeBytes:0,status:'active',createdAt:'2026-10-30T00:00:00Z'}))});
render(<ResourceCenter page="databases" projectID={target.id} projects={[target]} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
expect(await screen.findByText('db-'+target.hostName)).toBeInTheDocument();
expect(screen.queryByText('db-'+first.hostName)).not.toBeInTheDocument();
});
it('loads and refreshes logs scoped to the signed-in host',async()=>{ it('loads and refreshes logs scoped to the signed-in host',async()=>{
const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[{id:91,projectId:initialProjects[0].id,actor:'用户',action:'update',resourceType:'run_path',detail:'用户更新当前主机目录',success:true,createdAt:'2026-10-26T00:00:00Z'}]}); const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[{id:91,projectId:initialProjects[0].id,actor:'用户',action:'update',resourceType:'run_path',detail:'用户更新当前主机目录',success:true,createdAt:'2026-10-26T00:00:00Z'}]});
render(<ResourceCenter page="logs" projects={initialProjects.slice(0,1)} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>); render(<ResourceCenter page="logs" projects={initialProjects.slice(0,1)} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
+1 -1
View File
@@ -11,7 +11,7 @@ it('submits one state change during rapid clicks and shows the requested final s
vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});vi.spyOn(api,'me').mockResolvedValue({user:{id:4,role:'tenant',displayName:'测试用户',tenantName:'测试账号'} as User}); vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});vi.spyOn(api,'me').mockResolvedValue({user:{id:4,role:'tenant',displayName:'测试用户',tenantName:'测试账号'} as User});
vi.spyOn(api,'dashboard').mockResolvedValue({plan:demoPlan,usage:demoUsage,activities:[],hostScoped:false,domainApproval:true,rootDomain:'vhost.ser888.cn',projectRoot:'/www/wwwroot/seavHost/vHost',projects:[{id:9,hostName:'sv9999999999',name:'主机',domain:'qa.vhost.ser888.cn',path:'/www/wwwroot/seavHost/vHost/sv9999999999',runPath:'/public',runtime:'PHP',version:'8.4',status:'stopped',sslStatus:'off',autoSSL:false,processLimit:10,createdAt:'2026-10-29T00:00:00Z'}]} as Dashboard); vi.spyOn(api,'dashboard').mockResolvedValue({plan:demoPlan,usage:demoUsage,activities:[],hostScoped:false,domainApproval:true,rootDomain:'vhost.ser888.cn',projectRoot:'/www/wwwroot/seavHost/vHost',projects:[{id:9,hostName:'sv9999999999',name:'主机',domain:'qa.vhost.ser888.cn',path:'/www/wwwroot/seavHost/vHost/sv9999999999',runPath:'/public',runtime:'PHP',version:'8.4',status:'stopped',sslStatus:'off',autoSSL:false,processLimit:10,createdAt:'2026-10-29T00:00:00Z'}]} as Dashboard);
let finish!:()=>void;const pending=new Promise<void>(resolve=>{finish=resolve});const update=vi.spyOn(api,'setProjectState').mockReturnValue(pending); let finish!:()=>void;const pending=new Promise<void>(resolve=>{finish=resolve});const update=vi.spyOn(api,'setProjectState').mockReturnValue(pending);
render(<App/>);const start=await screen.findByRole('button',{name:'启动'});fireEvent.click(start);fireEvent.click(start);expect(update).toHaveBeenCalledTimes(1);expect(screen.getByRole('button',{name:'处理中…'})).toBeDisabled();finish();await waitFor(()=>expect(screen.getByRole('button',{name:'停止'})).toBeEnabled());expect(update).toHaveBeenCalledWith(9,true); render(<App/>);fireEvent.click(await screen.findByRole('button',{name:'进入主机 sv9999999999'}));const start=await screen.findByRole('button',{name:'启动主站'});fireEvent.click(start);fireEvent.click(start);expect(update).toHaveBeenCalledTimes(1);expect(screen.getByRole('button',{name:'处理中…'})).toBeDisabled();finish();await waitFor(()=>expect(screen.getByRole('button',{name:'停止主站'})).toBeEnabled());expect(update).toHaveBeenCalledWith(9,true);
}); });
it('keeps a rejected run directory visible with an inline reason',async()=>{ it('keeps a rejected run directory visible with an inline reason',async()=>{
render(<RunPathModal project={initialProjects[0]} onClose={vi.fn()} onSubmit={vi.fn().mockRejectedValue(new Error('目标目录不存在'))}/>);fireEvent.click(screen.getByRole('button',{name:'保存'}));expect(await screen.findByRole('alert')).toHaveTextContent('目标目录不存在');expect(screen.getByRole('button',{name:'保存'})).toBeEnabled(); render(<RunPathModal project={initialProjects[0]} onClose={vi.fn()} onSubmit={vi.fn().mockRejectedValue(new Error('目标目录不存在'))}/>);fireEvent.click(screen.getByRole('button',{name:'保存'}));expect(await screen.findByRole('alert')).toHaveTextContent('目标目录不存在');expect(screen.getByRole('button',{name:'保存'})).toBeEnabled();
+33
View File
@@ -0,0 +1,33 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,within} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {App} from './App';
import {initialProjects} from './data';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
it('keeps only account navigation and preserves user schedules in the overview',()=>{
render(<App/>);
expect(within(screen.getByLabelText('主导航')).getAllByRole('button').map(item=>item.textContent)).toEqual(['总览','域名','DNS API','操作日志']);
expect(screen.getByRole('button',{name:'计划任务'})).toBeInTheDocument();
expect(screen.queryByRole('button',{name:'文件管理'})).not.toBeInTheDocument();
});
it('enters the selected host, scopes its tools, and returns to the user overview',()=>{
render(<App/>);const host=initialProjects[1];
fireEvent.click(screen.getByRole('button',{name:'进入主机 '+host.hostName}));
expect(screen.getByRole('heading',{name:host.hostName})).toBeInTheDocument();
fireEvent.click(within(screen.getByLabelText('主导航')).getByRole('button',{name:'数据库'}));
expect(screen.getAllByText(host.hostName).length).toBeGreaterThan(0);
expect(screen.queryByText(initialProjects[0].hostName)).not.toBeInTheDocument();
fireEvent.click(within(screen.getByLabelText('主导航')).getByRole('button',{name:'文件管理'}));
expect(screen.getByRole('combobox',{name:'选择虚拟主机'}).querySelectorAll('option')).toHaveLength(1);
expect(screen.getByRole('combobox',{name:'选择虚拟主机'})).toHaveValue(String(host.id));
fireEvent.click(screen.getByRole('button',{name:'返回用户总览'}));
expect(screen.getAllByRole('button',{name:/^进入主机 /})).toHaveLength(initialProjects.length);
expect(screen.getByRole('heading',{name:'总览'})).toBeInTheDocument();
});
it('supports double-clicking a host row without changing account identity',()=>{
render(<App/>);const host=initialProjects[2];
fireEvent.doubleClick(screen.getByRole('button',{name:'进入主机 '+host.hostName}).closest('tr')!);
expect(screen.getByRole('heading',{name:host.hostName})).toBeInTheDocument();
expect(screen.getByRole('button',{name:'返回用户总览'})).toBeInTheDocument();
expect(screen.queryByRole('button',{name:'返回管理视图'})).not.toBeInTheDocument();
});
+5 -5
View File
@@ -1,10 +1,10 @@
import { Building2, ChevronDown, Menu, UserRound,LogOut } from 'lucide-react'; import { ArrowLeft, Building2, ChevronDown, Menu, UserRound,LogOut } from 'lucide-react';
import { useState, type ReactNode } from 'react'; import { useState, type ReactNode } from 'react';
import { Brand } from './Brand'; import { Brand } from './Brand';
import { Sidebar } from './Sidebar'; import { Sidebar } from './Sidebar';
import {useNavigationOverlay} from './overlay'; import {useNavigationOverlay} from './overlay';
export function AppShell({ page, tenantName, displayName, hostScoped = false, onNavigate, onSecurity,onLogout, children }: { page: string; tenantName: string; displayName: string; hostScoped?: boolean; onNavigate: (page: string) => void; onSecurity: () => void;onLogout?:()=>void; children: ReactNode }) { export function AppShell({ page, tenantName, displayName, hostScoped = false, hostView = false, hostName, onBack, onNavigate, onSecurity,onLogout, children }: { page: string; tenantName: string; displayName: string; hostScoped?: boolean; hostView?: boolean; hostName?:string; onBack?:()=>void; onNavigate: (page: string) => void; onSecurity: () => void;onLogout?:()=>void; children: ReactNode }) {
const [mobileNavOpen, setMobileNavOpen] = useState(false); const [mobileNavOpen, setMobileNavOpen] = useState(false);
useNavigationOverlay(mobileNavOpen,setMobileNavOpen); useNavigationOverlay(mobileNavOpen,setMobileNavOpen);
function navigate(pageName: string) { function navigate(pageName: string) {
@@ -16,15 +16,15 @@ export function AppShell({ page, tenantName, displayName, hostScoped = false, on
<header className="topbar"> <header className="topbar">
<button className="mobile-menu" aria-label={mobileNavOpen ? '关闭导航' : '打开导航'} aria-expanded={mobileNavOpen} onClick={() => setMobileNavOpen((value) => !value)}><Menu size={21} /></button> <button className="mobile-menu" aria-label={mobileNavOpen ? '关闭导航' : '打开导航'} aria-expanded={mobileNavOpen} onClick={() => setMobileNavOpen((value) => !value)}><Menu size={21} /></button>
<Brand /> <Brand />
<div className="tenant-switch"><Building2 size={17} /><span>{tenantName}</span></div> <div className="tenant-switch"><Building2 size={17} /><span>{hostView || hostScoped ? hostName : tenantName}</span></div>
<div className="top-actions"> <div className="top-actions">
{onLogout?<button className="icon-button" aria-label="退出登录" onClick={onLogout}><LogOut size={18}/></button>:null} {onLogout?<button className="icon-button" aria-label="退出登录" onClick={onLogout}><LogOut size={18}/></button>:null}
<button className="user-menu" onClick={onSecurity} aria-label="账号安全"><span className="avatar"><UserRound size={17} /></span><span>{displayName}</span><ChevronDown size={15} /></button> <button className="user-menu" onClick={onSecurity} aria-label="账号安全"><span className="avatar"><UserRound size={17} /></span><span>{displayName}</span><ChevronDown size={15} /></button>
</div> </div>
</header> </header>
{mobileNavOpen ? <button className="mobile-nav-backdrop" aria-label="关闭导航" onClick={() => setMobileNavOpen(false)} /> : null} {mobileNavOpen ? <button className="mobile-nav-backdrop" aria-label="关闭导航" onClick={() => setMobileNavOpen(false)} /> : null}
<div className={mobileNavOpen ? 'mobile-sidebar open' : 'mobile-sidebar'}><Sidebar page={page} hostScoped={hostScoped} onNavigate={navigate} /></div> <div className={mobileNavOpen ? 'mobile-sidebar open' : 'mobile-sidebar'}><Sidebar page={page} hostScoped={hostScoped} hostView={hostView} onNavigate={navigate} /></div>
<main className="main-content">{children}</main> <main className="main-content">{onBack ? <div className="host-context-bar"><span>目前主机 <b>{hostName}</b></span><button className="secondary" onClick={()=>{setMobileNavOpen(false);onBack()}}><ArrowLeft size={15}/>返回用户总览</button></div> : null}{children}</main>
</div> </div>
); );
} }
+5 -9
View File
@@ -9,23 +9,19 @@ const resourceLabels: Record<string, string> = { file: '文件管理', database:
interface OverviewProps { interface OverviewProps {
onRefresh?:()=>void;refreshing?:boolean; onRefresh?:()=>void;refreshing?:boolean;
pendingProjectIDs?:number[]; onEnterHost:(project:Project)=>void;
onSchedules?:()=>void;
projects: Project[]; projects: Project[];
plan: Plan; plan: Plan;
usage: Usage; usage: Usage;
activities: ActivityEntry[]; activities: ActivityEntry[];
hostScoped: boolean; hostScoped: boolean;
onCreate: () => void; onCreate: () => void;
onToggle: (id: number) => void;
onFiles: (id: number) => void;
onRunPath: (project: Project) => void;
onSites: (project: Project) => void;
onCredentials: (project: Project) => void;
canCreate: boolean; canCreate: boolean;
onLogs?: () => void; onLogs?: () => void;
} }
export function Overview({ onRefresh,refreshing,pendingProjectIDs,projects, plan, usage, activities, hostScoped, onCreate, onToggle, onFiles, onRunPath, onSites, onCredentials, canCreate, onLogs }: OverviewProps) { export function Overview({ onRefresh,refreshing,projects, plan, usage, activities, hostScoped, onCreate, onEnterHost, onSchedules, canCreate, onLogs }: OverviewProps) {
const resources = [ const resources = [
{ label: '存储空间', value: usage.storageBytes, limit: plan.storageBytes }, { label: '存储空间', value: usage.storageBytes, limit: plan.storageBytes },
{ label: '本月流量', value: usage.bandwidthBytes, limit: plan.bandwidthBytes }, { label: '本月流量', value: usage.bandwidthBytes, limit: plan.bandwidthBytes },
@@ -34,14 +30,14 @@ export function Overview({ onRefresh,refreshing,pendingProjectIDs,projects, plan
]; ];
return ( return (
<div className="page"> <div className="page">
<PageHeader title="总览" description={hostScoped ? '管理当前虚拟主机的网站、文件与访问凭据。' : '查看当前账号下的资源使用情况和业务概览。'} actions={onRefresh?<button className="secondary" disabled={refreshing} onClick={onRefresh}><RefreshCw size={15}/>{refreshing?'正在刷新…':'刷新状态'}</button>:null}/> <PageHeader title="总览" actions={<div className="overview-actions">{onSchedules?<button className="secondary" onClick={onSchedules}>计划任务</button>:null}{onRefresh?<button className="secondary" disabled={refreshing} onClick={onRefresh}><RefreshCw size={15}/>{refreshing?'正在刷新…':'刷新状态'}</button>:null}</div>}/>
{!hostScoped ? <div className="metrics-grid"> {!hostScoped ? <div className="metrics-grid">
<MetricCard icon={HardDrive} label="存储空间" value={formatBytes(usage.storageBytes)} limit={formatBytes(plan.storageBytes)} percent={usagePercent(usage.storageBytes, plan.storageBytes)} /> <MetricCard icon={HardDrive} label="存储空间" value={formatBytes(usage.storageBytes)} limit={formatBytes(plan.storageBytes)} percent={usagePercent(usage.storageBytes, plan.storageBytes)} />
<MetricCard icon={Network} label="本月流量" value={formatBytes(usage.bandwidthBytes)} limit={formatBytes(plan.bandwidthBytes)} percent={usagePercent(usage.bandwidthBytes, plan.bandwidthBytes)} /> <MetricCard icon={Network} label="本月流量" value={formatBytes(usage.bandwidthBytes)} limit={formatBytes(plan.bandwidthBytes)} percent={usagePercent(usage.bandwidthBytes, plan.bandwidthBytes)} />
<MetricCard icon={Cpu} label="进程数量" value={String(usage.processCount)} limit={String(plan.processLimit)} percent={usagePercent(usage.processCount, plan.processLimit)} /> <MetricCard icon={Cpu} label="进程数量" value={String(usage.processCount)} limit={String(plan.processLimit)} percent={usagePercent(usage.processCount, plan.processLimit)} />
<MetricCard icon={Database} label="数据库大小" value={formatBytes(usage.databaseBytes)} limit={formatBytes(plan.databaseBytes)} percent={usagePercent(usage.databaseBytes, plan.databaseBytes)} /> <MetricCard icon={Database} label="数据库大小" value={formatBytes(usage.databaseBytes)} limit={formatBytes(plan.databaseBytes)} percent={usagePercent(usage.databaseBytes, plan.databaseBytes)} />
</div> : null} </div> : null}
<ProjectTable pendingProjectIDs={pendingProjectIDs} projects={projects} canCreate={canCreate} onCreate={onCreate} onToggle={onToggle} onFiles={onFiles} onRunPath={onRunPath} onSites={onSites} onCredentials={onCredentials} /> <ProjectTable projects={projects} canCreate={canCreate} onCreate={onCreate} onEnterHost={onEnterHost} />
{!hostScoped ? <div className="lower-grid"> {!hostScoped ? <div className="lower-grid">
<section className="activity-panel"> <section className="activity-panel">
<div className="section-title"><h2>最近操作日志</h2>{onLogs?<button onClick={onLogs}>查看全部 <ArrowRight size={15} /></button>:null}</div> <div className="section-title"><h2>最近操作日志</h2>{onLogs?<button onClick={onLogs}>查看全部 <ArrowRight size={15} /></button>:null}</div>
+6 -6
View File
@@ -5,7 +5,7 @@ import {formatBytes} from '../format';
import {RuntimeMark} from './UI'; import {RuntimeMark} from './UI';
const statusLabels: Record<Project['status'], string> = { running: '运行中', stopped: '已停止', provisioning: '创建中', awaiting_upload: '待上传', failed: '创建失败', quota_suspended: '配额暂停' }; const statusLabels: Record<Project['status'], string> = { running: '运行中', stopped: '已停止', provisioning: '创建中', awaiting_upload: '待上传', failed: '创建失败', quota_suspended: '配额暂停' };
export function ProjectTable({pendingProjectIDs=[], projects, canCreate, onCreate, onToggle, onFiles, onRunPath, onSites, onCredentials }: {pendingProjectIDs?:number[]; projects: Project[]; canCreate: boolean; onCreate: () => void; onToggle: (id: number) => void; onFiles: (id: number) => void; onRunPath: (project: Project) => void; onSites: (project: Project) => void; onCredentials: (project: Project) => void }) { export function ProjectTable({ projects, canCreate, onCreate, onEnterHost }: { projects: Project[]; canCreate: boolean; onCreate: () => void; onEnterHost: (project:Project)=>void }) {
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query); const deferredQuery = useDeferredValue(query);
const filtered = useMemo(() => { const filtered = useMemo(() => {
@@ -23,19 +23,19 @@ export function ProjectTable({pendingProjectIDs=[], projects, canCreate, onCreat
</div> </div>
</div> </div>
<div className="table-scroll"> <div className="table-scroll">
<table> <table className="user-host-table">
<thead><tr><th>#</th><th>域名(主机名 / 目录)</th><th>运行环境</th><th>状态</th><th>SSL 证书</th><th>本月流量</th><th>创建时间</th><th>操作</th></tr></thead> <thead><tr><th>#</th><th>域名 / 主机</th><th>运行环境</th><th>状态</th><th>SSL 证书</th><th>本月流量</th><th>创建时间</th><th>操作</th></tr></thead>
<tbody> <tbody>
{filtered.map((project, index) => ( {filtered.map((project, index) => (
<tr key={project.id}> <tr key={project.id} title="双击进入主机管理" onDoubleClick={event=>{if(!(event.target as HTMLElement).closest('button,a,input,select'))onEnterHost(project)}}>
<td className="muted">{index + 1}</td> <td className="muted">{index + 1}</td>
<td><b>{project.domain}</b><small>{project.name} · {project.hostName} · {project.path} · 发布 {project.runPath}</small></td> <td><b>{project.domain}</b><small>{project.hostName} · {project.name}</small></td>
<td><RuntimeMark runtime={project.runtime}/>{project.runtime} {project.version}</td> <td><RuntimeMark runtime={project.runtime}/>{project.runtime} {project.version}</td>
<td><span className={`status ${project.status}`}>{statusLabels[project.status]}</span></td> <td><span className={`status ${project.status}`}>{statusLabels[project.status]}</span></td>
<td className={project.ssl ? 'success' : 'muted'}><LockKeyhole size={14} /> {project.ssl ? '已部署' : '未部署'}</td> <td className={project.ssl ? 'success' : 'muted'}><LockKeyhole size={14} /> {project.ssl ? '已部署' : '未部署'}</td>
<td>{formatBytes(project.trafficGB*1024**3)}</td> <td>{formatBytes(project.trafficGB*1024**3)}</td>
<td className="muted">{project.createdAt}</td> <td className="muted">{project.createdAt}</td>
<td className="row-actions"><button title={pendingProjectIDs.includes(project.id)?'正在应用主站状态':!['running','stopped'].includes(project.status)?'主站尚未完成部署或已受配额限制':undefined} disabled={pendingProjectIDs.includes(project.id)||!['running', 'stopped'].includes(project.status)} onClick={() => onToggle(project.id)}>{pendingProjectIDs.includes(project.id)?'处理中…':project.status === 'running' ? '停止' : '启动'}</button><button onClick={() => onSites(project)}>网站</button><button onClick={() => onFiles(project.id)}>文件</button><button onClick={() => onCredentials(project)}>凭据</button><button disabled={['failed', 'provisioning'].includes(project.status)} onClick={() => onRunPath(project)}>主站目录</button></td> <td><button className="host-enter-button" aria-label={'进入主机 '+project.hostName} onClick={() => onEnterHost(project)}>进入主机</button></td>
</tr> </tr>
))} ))}
{filtered.length === 0 ? <tr><td colSpan={8} className="empty-row">没有匹配的虚拟主机</td></tr> : null} {filtered.length === 0 ? <tr><td colSpan={8} className="empty-row">没有匹配的虚拟主机</td></tr> : null}
+11 -4
View File
@@ -8,6 +8,7 @@ import type { ActivityEntry, Project, Site } from '../types';
interface ResourceCenterProps { interface ResourceCenterProps {
page: string; page: string;
projectID?:number;
projects: Project[]; projects: Project[];
activities: ActivityEntry[]; activities: ActivityEntry[];
hostScoped: boolean; hostScoped: boolean;
@@ -17,7 +18,7 @@ interface ResourceCenterProps {
onNotify: (message: string) => void; onNotify: (message: string) => void;
} }
export function ResourceCenter({ page, projects, activities, hostScoped, domainApproval, live, onCredentials, onNotify }: ResourceCenterProps) { export function ResourceCenter({ page, projectID, projects, activities, hostScoped, domainApproval, live, onCredentials, onNotify }: ResourceCenterProps) {
const demoInventory = useMemo(() => inventoryFromProjects(projects), [projects]); const demoInventory = useMemo(() => inventoryFromProjects(projects), [projects]);
const [inventory, setInventory] = useState<ResourceInventory>(()=>live?{sites:[],domains:[],ftpAccounts:[],databases:[]}:demoInventory); const [inventory, setInventory] = useState<ResourceInventory>(()=>live?{sites:[],domains:[],ftpAccounts:[],databases:[]}:demoInventory);
const [busy, setBusy] = useState(live); const [busy, setBusy] = useState(live);
@@ -40,9 +41,15 @@ export function ResourceCenter({ page, projects, activities, hostScoped, domainA
return () => { active = false; }; return () => { active = false; };
}, [demoInventory, live, page,epoch]); }, [demoInventory, live, page,epoch]);
if (page === 'domains') return <DomainPage onRefresh={reload} inventory={inventory} setInventory={setInventory} approval={domainApproval} live={live} busy={busy} error={error} onNotify={onNotify} />; const visibleInventory = projectID ? {
if (page === 'databases') return <DatabasePage onRefresh={reload} items={inventory.databases} busy={busy} error={error} onCredentials={onCredentials} />; sites:inventory.sites.filter(item=>item.projectId===projectID),
if (page === 'ftp') return <FTPPage pausedProjectIDs={projects.filter(p=>p.status==='quota_suspended').map(p=>p.id)} onRefresh={reload} items={inventory.ftpAccounts} busy={busy} error={error} onCredentials={onCredentials} live={live} onNotify={onNotify} onChanged={async()=>setInventory(await api.resources())}/>; domains:inventory.domains.filter(item=>item.projectId===projectID),
databases:inventory.databases.filter(item=>item.projectId===projectID),
ftpAccounts:inventory.ftpAccounts.filter(item=>item.projectId===projectID),
} : inventory;
if (page === 'domains') return <DomainPage onRefresh={reload} inventory={visibleInventory} setInventory={setInventory} approval={domainApproval} live={live} busy={busy} error={error} onNotify={onNotify} />;
if (page === 'databases') return <DatabasePage onRefresh={reload} items={visibleInventory.databases} busy={busy} error={error} onCredentials={onCredentials} />;
if (page === 'ftp') return <FTPPage pausedProjectIDs={projects.filter(p=>p.status==='quota_suspended').map(p=>p.id)} onRefresh={reload} items={visibleInventory.ftpAccounts} busy={busy} error={error} onCredentials={onCredentials} live={live} onNotify={onNotify} onChanged={async()=>setInventory(await api.resources())}/>;
return <ActivityPage activities={activities} hostScoped={hostScoped} projects={projects} live={live} />; return <ActivityPage activities={activities} hostScoped={hostScoped} projects={projects} live={live} />;
} }
+3 -2
View File
@@ -13,11 +13,12 @@ const items = [
['logs', '操作日志', ScrollText], ['logs', '操作日志', ScrollText],
] as const; ] as const;
export function Sidebar({ page, onNavigate, hostScoped = false }: { page: string; onNavigate: (page: string) => void; hostScoped?: boolean }) { export function Sidebar({ page, onNavigate, hostScoped = false, hostView = false }: { page: string; onNavigate: (page: string) => void; hostScoped?: boolean; hostView?: boolean }) {
const hostNavigation = hostScoped || hostView;
return ( return (
<aside className="sidebar" aria-label="主导航"> <aside className="sidebar" aria-label="主导航">
<nav> <nav>
{items.filter(([key]) => !(hostScoped && (key === 'overview'||key === 'dns'||key==='schedules'))).map(([key, label, Icon]) => ( {items.filter(([key]) => hostNavigation ? !['overview','dns','schedules'].includes(key) : ['overview','domains','dns','logs'].includes(key)).map(([key, label, Icon]) => (
<button key={key} aria-current={page === key ? "page" : undefined} className={page === key ? 'nav-item active' : 'nav-item'} onClick={() => onNavigate(key)}> <button key={key} aria-current={page === key ? "page" : undefined} className={page === key ? 'nav-item active' : 'nav-item'} onClick={() => onNavigate(key)}>
<Icon size={19} aria-hidden="true" /> <Icon size={19} aria-hidden="true" />
<span>{label}</span> <span>{label}</span>
+30
View File
@@ -34,6 +34,36 @@
.sso-identity small { color: var(--muted); overflow-wrap: anywhere; } .sso-identity small { color: var(--muted); overflow-wrap: anywhere; }
.sso-create-actions { display: grid; gap: 14px; margin-top: 14px; } .sso-create-actions { display: grid; gap: 14px; margin-top: 14px; }
.sso-create-actions .text-button { background: none; border: none; color: var(--muted); } .sso-create-actions .text-button { background: none; border: none; color: var(--muted); }
.host-context-bar { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:14px 32px; border-bottom:1px solid var(--line); background:var(--surface,#fff); color:var(--muted); font-size:13px; }
.host-context-bar > span { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.host-context-bar b { color:var(--ink); font-weight:600; }
.host-context-bar button { flex:0 0 auto; min-height:34px; white-space:nowrap; display:inline-flex; align-items:center; gap:6px; }
.overview-actions { display:flex; flex-wrap:nowrap; gap:10px; }
.overview-actions > button { white-space:nowrap; flex:0 0 auto; }
.table-panel .user-host-table { min-width:960px; }
.user-host-table td:nth-child(2) { max-width:300px; }
.user-host-table td:nth-child(2) :is(b,small) { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.user-host-table td:last-child,.user-host-table th:last-child { position:sticky; right:0; width:116px; background:var(--surface,#fff); box-shadow:-8px 0 12px -12px #526580; z-index:1; white-space:nowrap; }
.user-host-table tbody tr:hover td:last-child { background:var(--surface-subtle,#fafcff); }
.host-enter-button { display:inline-flex; align-items:center; min-height:32px; padding:5px 10px; color:var(--blue-strong); border:1px solid var(--line); border-radius:6px; background:var(--surface,#fff); white-space:nowrap; }
.host-enter-button:hover { background:var(--blue-soft); border-color:var(--blue); }
.table-scroll td > .row-actions,.admin-table-v2 td > .row-actions { flex-wrap:nowrap; width:max-content; max-width:none; }
td.row-actions { display:table-cell; white-space:nowrap; }
.row-actions > button { flex-shrink:0; white-space:nowrap; }
.host-row-actions { display:flex; flex-wrap:nowrap; gap:12px; min-width:max-content; }
.host-row-actions .danger-text { border-left:1px solid var(--line); padding-left:12px; }
.sites-row .site-actions { flex-wrap:nowrap; min-width:0; max-width:100%; overflow-x:auto; overscroll-behavior-x:contain; scrollbar-width:thin; padding-bottom:5px; }
@media (max-width:700px) {
.host-context-bar { padding:12px 16px; gap:8px; }
.host-context-bar button { padding:6px 9px; font-size:12px; }
.host-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:9px; }
.host-actions button { width:auto; justify-content:center; min-width:0; padding:9px 6px; white-space:nowrap; }
.host-info-card > header { flex-wrap:nowrap; gap:8px; }
.host-info-card > header > div { gap:7px; min-width:0; }
.host-info-card > header > div h2 { font-size:14px; overflow-wrap:anywhere; }
.host-info-card > header > button { flex-shrink:0; padding:7px 9px; white-space:nowrap; }
.table-panel .panel-toolbar { align-items:flex-start; }
}
@media (min-width: 980px) { @media (min-width: 980px) {
.dns-credential-row { grid-template-columns: minmax(160px,1.2fr) 110px minmax(150px,1fr) 140px minmax(258px,auto); gap: 16px; } .dns-credential-row { grid-template-columns: minmax(160px,1.2fr) 110px minmax(150px,1fr) 140px minmax(258px,auto); gap: 16px; }
} }