diff --git a/README.md b/README.md index 200c5e7b..d3207120 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ SELECT id, username, email FROM users WHERE id = 1; 宿主机私钥、已填写的私钥口令和配置加密保存在 MariaDB。数据库备份与 `data/master.key` 同时泄露时,这些凭据可以被解密,因此须分别严密保护;运行中的 root 面板进程同样能使用它们。OpenSSH 连接时需要读取私钥文件,Linux 上面板会将其临时还原到权限为 `0700` 的 `/dev/shm` 内存文件系统目录;面板关闭时清除。`data/runtime-wrappers/` 只包含不带密钥的启动包装器。若 SSH agent 异常退出,后台采样会限频尝试使用已保存口令恢复连接;若保存的口令错误,仍需管理员检查并重新保存。面板仅支持单个 Uvicorn worker。 -虚拟机列表只展示状态、地区、系统或安装镜像、IP、规格和磁盘;点击虚拟机名称进入该机管理页,控制台、电源、重装和删除等操作都在管理页。地区取自当前宿主机设置。新建或重装的云镜像 VM 会记录所选模板名称及配置的公网 IP/CIDR;这个 IP 是**配置记录**,不是连通性探测。详情页的公网 IP 不显示 `/24` 等掩码后缀,可点击旁边的按钮复制;磁盘信息只显示总容量,不再显示磁盘块数。ISO 安装 VM 只记录安装镜像文件名,不能据此确认客体最终安装的系统;旧 VM 或面板外创建的 VM 若无可靠记录,会显示“未识别”或“未获取”,不会猜测客体系统与 IP。 +虚拟机列表只展示状态、地区、系统或安装镜像、IP、规格和磁盘;点击虚拟机名称进入该机管理页,控制台、电源、重装和删除等操作都在管理页。“创建虚拟机”从列表进入独立页面,“重装系统”从虚拟机详情进入独立页面,表单和任务进度不再使用弹窗。地区取自当前宿主机设置。新建或重装的云镜像 VM 会记录所选模板名称及配置的公网 IP/CIDR;这个 IP 是**配置记录**,不是连通性探测。详情页的公网 IP 不显示 `/24` 等掩码后缀,可点击旁边的按钮复制;磁盘信息只显示总容量,不再显示磁盘块数。ISO 安装 VM 只记录安装镜像文件名,不能据此确认客体最终安装的系统;旧 VM 或面板外创建的 VM 若无可靠记录,会显示“未识别”或“未获取”,不会猜测客体系统与 IP。 云镜像 VM 的详情页显示 SSH 登录名 `root`。面板保存了初始 root 密码时,默认以星号遮盖;管理员或该 VM 的所属用户可按需点击图标查看、复制,不会在虚拟机列表或普通详情数据中直接返回密码。新建云镜像 VM 无论是否选择 SSH 公钥,都会设置并加密保存可查看的初始密码;重装时若只选公钥而不填写密码,则保持仅公钥登录,不保存新密码。ISO 安装和面板外创建的 VM 的客体密码不由面板管理。旧 VM 曾使用但面板未保存的密码无法从密码哈希或虚拟机系统中还原。客体内修改 root 密码后,详情页保存的**初始**密码不会自动更新,可能已无法用于登录;请妥善保护数据库备份和面板主密钥。 @@ -87,13 +87,13 @@ SELECT id, username, email FROM users WHERE id = 1; ## 公网云镜像模板创建(无需手动安装) -面板的“创建虚拟机”现在有独立的“公网云镜像”方式。先在宿主机设置中选择已工作的 Linux 网桥,例如 `bridge:br0`;打开创建弹窗的“导入新的云镜像模板”,填写 [AlmaLinux 10 官方 Generic Cloud qcow2 镜像](https://wiki.almalinux.org/cloud/Generic-cloud)在 `https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/` 下的下载地址、发布方 SHA-256 和模板显示名。地址必须是官方 HTTPS 直链,面板不会跟随重定向。面板服务器 A 需要能访问该地址。导入在后台运行,一次只允许一个任务,面板下载、校验 SHA-256 后通过当前 libvirt SSH 连接把模板镜像上传到 B 的磁盘池;无需登录 B 手工复制。模板目录记录加密保存在 MariaDB,绑定当前宿主机身份和磁盘池。不要在导入期间关闭面板进程;若进程异常退出,运行中的导入任务记录不会恢复,可能需要检查项目 `data/` 中的 `.cloud-image-*` 临时文件和 B 磁盘池中 `panel-template-*` 卷,不要未经核对就删除。 +面板的“创建虚拟机”现在有独立的“公网云镜像”方式。先在宿主机设置中选择已工作的 Linux 网桥,例如 `bridge:br0`;进入创建虚拟机页面,展开“导入新的云镜像模板”,填写 [AlmaLinux 10 官方 Generic Cloud qcow2 镜像](https://wiki.almalinux.org/cloud/Generic-cloud)在 `https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/` 下的下载地址、发布方 SHA-256 和模板显示名。地址必须是官方 HTTPS 直链,面板不会跟随重定向。面板服务器 A 需要能访问该地址。导入在后台运行,一次只允许一个任务,面板下载、校验 SHA-256 后通过当前 libvirt SSH 连接把模板镜像上传到 B 的磁盘池;无需登录 B 手工复制。模板目录记录加密保存在 MariaDB,绑定当前宿主机身份和磁盘池。不要在导入期间关闭面板进程;若进程异常退出,运行中的导入任务记录不会恢复,可能需要检查项目 `data/` 中的 `.cloud-image-*` 临时文件和 B 磁盘池中 `panel-template-*` 卷,不要未经核对就删除。 选择模板后填写 VM 资源和 root 登录方式。宿主机公网地址池支持实际获配的 `/24` 至 `/30` 前缀。例如服务商分配 `123.123.123.112/28`、宿主机网关为 `123.123.123.113` 时,在宿主机设置填写该 `/28` 网段(填写 `123.123.123.113/28` 也会规范化为 `123.123.123.112/28`),网关填 `123.123.123.113`,DNS 按服务商要求填写。自动分配只考虑此 `/28` 的有效主机地址;扣除网关后是 `123.123.123.114` 至 `123.123.123.126`,还会跳过保留、已用及池内 DNS 地址。**不要填写 `123.123.123.114/24` 或 `123.123.123.0/24`,除非服务商确实分配了整个 `/24`。**设置页会预览输入前缀换算出的实际网段和主机地址范围。 “虚拟机网卡前缀”与可分配地址池是独立设置:留空时客体使用地址池前缀;如果现场确认服务商要求 VM 内配置 `/24`,而实际只获配上述 `/28`,这里填 `24`,新建 VM 将获得例如 `123.123.123.114/24`,但面板仍只会从 `123.123.123.112/28` 挑选地址。可填写的客体前缀范围为 `/24` 到地址池前缀,以确保整个地址池中的 IP 与网关处于同一客体子网。修改此项不会自动改写已创建 VM;云镜像重装会保留该 VM 首次创建时的网络前缀。若使用 `/28` 不通,其具体原因仍需结合宿主机路由、网桥及服务商网络确认;仅改变面板掩码无法替代上游放行或路由配置。 -配置地址池后,创建时会自动选择一个尚未使用的地址,并沿用宿主机设置的网关和 DNS;用户不能在创建请求中另填 IP、网关或 DNS 来绕过地址池。面板会跳过网络地址、广播地址、网关、保留地址、宿主机自身的字面 IPv4,以及 libvirt 可见虚拟机元数据中的已用 IP,并防止面板并发创建分到相同地址。地址池用尽时创建会报错,不会复用仍占用的地址;面板删除 VM 后会释放其地址占用记录。旧宿主机若未配置地址池,仍可按原方式手填已分配给你的**具体公网 IPv4/CIDR**(如 `/24` 或 `/28`)、同网段网关和 1–4 个 DNS 地址。在创建窗口中可选一个已保存的 SSH 公钥,同时设置初始 root 密码,登录时可用对应私钥或密码;不选择公钥也可以只用密码。手动密码须为 12–128 个字符,包含大写字母、小写字母和符号;密码留空时面板自动生成并加密保存初始密码,**即使已经选择公钥**。客体登录密钥与连接宿主机的 root 私钥是两套独立凭据。面板无法探测面板及 libvirt 元数据之外的设备是否占用地址,也无法替服务商分配或路由公网 IP。当前版本只支持网关与 VM IP 同一子网的桥接 IPv4;服务商给出 `/32` 或异网段网关时不要强填,需另做路由网络模式。上游网络还必须允许 VM 使用额外 MAC,`br0` 本身不能保证公网可达。 +配置地址池后,创建时会自动选择一个尚未使用的地址,并沿用宿主机设置的网关和 DNS;用户不能在创建请求中另填 IP、网关或 DNS 来绕过地址池。面板会跳过网络地址、广播地址、网关、保留地址、宿主机自身的字面 IPv4,以及 libvirt 可见虚拟机元数据中的已用 IP,并防止面板并发创建分到相同地址。地址池用尽时创建会报错,不会复用仍占用的地址;面板删除 VM 后会释放其地址占用记录。旧宿主机若未配置地址池,仍可按原方式手填已分配给你的**具体公网 IPv4/CIDR**(如 `/24` 或 `/28`)、同网段网关和 1–4 个 DNS 地址。在创建页面中可选一个已保存的 SSH 公钥,同时设置初始 root 密码,登录时可用对应私钥或密码;不选择公钥也可以只用密码。手动密码须为 12–128 个字符,包含大写字母、小写字母和符号;密码留空时面板自动生成并加密保存初始密码,**即使已经选择公钥**。客体登录密钥与连接宿主机的 root 私钥是两套独立凭据。面板无法探测面板及 libvirt 元数据之外的设备是否占用地址,也无法替服务商分配或路由公网 IP。当前版本只支持网关与 VM IP 同一子网的桥接 IPv4;服务商给出 `/32` 或异网段网关时不要强填,需另做路由网络模式。上游网络还必须允许 VM 使用额外 MAC,`br0` 本身不能保证公网可达。 若 DNS 本身位于该地址池中,它的地址也会自动跳过。面板创建成功后会保留 IP 占用记录,只有通过面板删除 VM 才自动释放;如果直接在宿主机或其他工具中删除 VM,旧占用记录会保守保留,避免误将该 IP 分给新 VM,需核查真实占用情况后再处理。 diff --git a/static/app.js b/static/app.js index b218a7f1..a832be9a 100644 --- a/static/app.js +++ b/static/app.js @@ -27,6 +27,7 @@ const state = { resources: null, sshKeys: [], sshKeysLoad: null, + sshKeysReturnView: null, templateLoad: null, templateImportJobId: null, loadingVMs: false, @@ -206,6 +207,8 @@ function showLogin() { stopPolling(); stopVmMetrics(); closeModal(); + resetCreatePage(); + resetReinstallPage(); clearVmCredential(); state.updatePollToken += 1; state.updateJobId = null; @@ -221,6 +224,7 @@ function showLogin() { state.vms = []; state.sshKeys = []; state.sshKeysLoad = null; + state.sshKeysReturnView = null; state.resources = null; state.hostConfig = null; state.templateLoad = null; @@ -503,18 +507,76 @@ async function initialize() { } } -function showVmWorkspace() { +function resetCreatePage() { + byId("create-form").reset(); + clearSshKeyPicker("vm-guest-ssh-key-cards"); + byId("vm-root-password").value = ""; + updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); + showError("create-error", ""); +} + +function resetReinstallPage() { + state.reinstallPollToken += 1; + state.reinstallTarget = null; + state.reinstallJobId = null; + state.reinstallInProgress = false; + state.reinstallExpectGeneratedPassword = false; + state.reinstallPasswordPendingAck = false; + byId("reinstall-form").reset(); + clearSshKeyPicker("reinstall-ssh-key-cards"); + byId("reinstall-root-password").value = ""; + updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); + byId("reinstall-generated-password").textContent = ""; + showError("reinstall-error", ""); +} + +function canLeaveReinstallPage() { + if (byId("dashboard-view").hidden || byId("vm-workspace").hidden || byId("reinstall-view").hidden) return true; + if (state.reinstallPasswordPendingAck) { + toast("请先保存 root 密码,再点击“已保存密码,完成”确认清除。", "error"); + return false; + } + if (state.reinstallInProgress) { + toast("重装正在进行,请保持此页面打开,以免错过一次性显示的 root 密码。", "error"); + return false; + } + return true; +} + +function discardVmSubpageDrafts() { + if (!byId("create-view").hidden) resetCreatePage(); + if (!byId("reinstall-view").hidden) resetReinstallPage(); + state.sshKeysReturnView = null; +} + +function showVmSubpage(view) { + stopVmMetrics(); + clearVmCredential(); + byId("vm-list-view").hidden = true; + byId("vm-detail-view").hidden = true; + byId("create-view").hidden = view !== "create"; + byId("reinstall-view").hidden = view !== "reinstall"; + text("breadcrumb-current", view === "create" ? "创建虚拟机" : "重装系统"); + window.scrollTo({ top: 0, behavior: "auto" }); + byId(view === "create" ? "create-title" : "reinstall-title").focus(); +} + +function showVmWorkspace({ preserveDraft = false } = {}) { if (!state.admin && (!state.approved || !state.hostReady)) { showAccessWait(state.approved ? "host" : "approval"); - return; + return false; } + if (!canLeaveReinstallPage()) return false; byId("admin-menu").open = false; stopVmMetrics(); clearVmCredential(); + if (!preserveDraft) discardVmSubpageDrafts(); state.selectedVmId = null; byId("vm-workspace").hidden = false; byId("vm-list-view").hidden = false; byId("vm-detail-view").hidden = true; + byId("create-view").hidden = true; + byId("reinstall-view").hidden = true; byId("ssh-keys-workspace").hidden = true; byId("update-workspace").hidden = true; byId("smtp-workspace").hidden = true; @@ -528,17 +590,30 @@ function showVmWorkspace() { byId("smtp-settings-button").classList.remove("active"); byId("smtp-settings-button").removeAttribute("aria-current"); text("breadcrumb-current", "虚拟机"); + window.scrollTo({ top: 0, behavior: "auto" }); + return true; } -async function showSshKeysWorkspace() { +async function showSshKeysWorkspace(returnView = null) { if (!state.csrfToken) return; + if (!canLeaveReinstallPage()) return; + if (returnView === "create" || returnView === "reinstall") { + const passwordId = returnView === "create" ? "vm-root-password" : "reinstall-root-password"; + const hintId = returnView === "create" ? "vm-root-password-hint" : "reinstall-root-password-hint"; + if (byId(passwordId).value) { + byId(passwordId).value = ""; + updateRootPasswordHint(passwordId, hintId); + toast("已清空未提交的 root 密码;返回后请重新填写。", "info"); + } + } else discardVmSubpageDrafts(); + state.sshKeysReturnView = returnView; byId("access-wait-view").hidden = true; byId("dashboard-view").hidden = false; byId("admin-menu").open = false; state.updateReturnView = null; stopVmMetrics(); clearVmCredential(); - state.selectedVmId = null; + if (returnView !== "reinstall") state.selectedVmId = null; byId("vm-workspace").hidden = true; byId("update-workspace").hidden = true; byId("smtp-workspace").hidden = true; @@ -561,6 +636,19 @@ async function showSshKeysWorkspace() { } } +function returnFromSshKeysWorkspace() { + const returnView = state.sshKeysReturnView; + if (!returnView) { + showVmWorkspace(); + return; + } + state.sshKeysReturnView = null; + if (!showVmWorkspace({ preserveDraft: true })) return; + showVmSubpage(returnView); + if (returnView === "create") updateCreateSource(); + else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); +} + function selectedSshKeyId(containerId) { return byId(containerId).querySelector('.ssh-key-option[aria-pressed="true"]')?.dataset.keyId || ""; } @@ -706,6 +794,8 @@ function leaveUpdateWorkspace() { async function showUpdateWorkspace() { if (!state.admin) return; + if (!canLeaveReinstallPage()) return; + discardVmSubpageDrafts(); byId("admin-menu").open = false; stopVmMetrics(); clearVmCredential(); @@ -797,6 +887,8 @@ async function loadPendingUsers() { async function showSmtpWorkspace() { if (!state.admin) return; + if (!canLeaveReinstallPage()) return; + discardVmSubpageDrafts(); byId("admin-menu").open = false; stopVmMetrics(); clearVmCredential(); @@ -1405,6 +1497,8 @@ function openVmDetail(uuid) { state.selectedVmId = uuid; byId("vm-list-view").hidden = true; byId("vm-detail-view").hidden = false; + byId("create-view").hidden = true; + byId("reinstall-view").hidden = true; renderVmDetail(vm); clearVmMetrics("正在加载监控数据…"); startVmMetrics(); @@ -1802,7 +1896,7 @@ function fillTemplateSelect(items, preferredId = "") { reinstallSelect.replaceChildren(); const reinstallPlaceholder = document.createElement("option"); reinstallPlaceholder.value = ""; - reinstallPlaceholder.textContent = items.length ? "选择重装模板" : "暂无模板,请先在创建虚拟机窗口导入"; + reinstallPlaceholder.textContent = items.length ? "选择重装模板" : "暂无模板,请先在创建虚拟机页面导入"; reinstallSelect.append(reinstallPlaceholder); for (const item of items) { const id = String(item?.id || ""); @@ -1850,10 +1944,10 @@ async function waitForTemplateImport(jobId) { if (job?.status !== "running") throw new Error("模板导入状态未知,请稍后重新查看。"); if (attempt % 6 === 5) { const seconds = (attempt + 1) * 5; - showTemplateImportStatus(`宿主机正在后台导入镜像,已等待约 ${seconds < 60 ? `${seconds} 秒` : `${Math.floor(seconds / 60)} 分钟`}。关闭弹窗不会取消任务。`); + showTemplateImportStatus(`宿主机正在后台导入镜像,已等待约 ${seconds < 60 ? `${seconds} 秒` : `${Math.floor(seconds / 60)} 分钟`}。离开页面不会取消任务。`); } } - throw new Error("模板仍在后台导入。稍后重新打开创建窗口并查看导入状态。"); + throw new Error("模板仍在后台导入。稍后返回创建虚拟机页面查看导入状态。"); } function selectedCreateSource() { @@ -1956,23 +2050,6 @@ function closeModal() { if (!state.activeModal) return; const returnFocus = state.lastFocus; if (state.activeModal.id === "console-modal") disconnectConsole(); - if (state.activeModal.id === "create-modal") { - byId("create-form").reset(); - byId("vm-root-password").value = ""; - updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); - } - if (state.activeModal.id === "reinstall-modal") { - state.reinstallPollToken += 1; - state.reinstallTarget = null; - state.reinstallJobId = null; - state.reinstallInProgress = false; - state.reinstallExpectGeneratedPassword = false; - state.reinstallPasswordPendingAck = false; - byId("reinstall-form").reset(); - byId("reinstall-root-password").value = ""; - updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); - byId("reinstall-generated-password").textContent = ""; - } state.activeModal.hidden = true; state.activeModal = null; state.deleteTarget = null; @@ -1990,16 +2067,16 @@ function closeModal() { function openCreate() { if (!state.admin && (!state.approved || !state.hostReady)) return; - byId("create-form").reset(); + if (!showVmWorkspace()) return; + resetCreatePage(); fillSshKeyCards(state.sshKeys); clearSshKeyPicker("vm-guest-ssh-key-cards"); - byId("vm-root-password").value = ""; byId("template-import").open = !!state.templateImportJobId; showTemplateImportStatus(state.templateImportJobId ? "宿主机仍在后台导入模板。查询会自动更新;若中断,可点击“导入模板”继续查看。" : ""); showError("template-import-error", ""); showError("create-error", ""); updateCreateSource(); - openModal("create-modal"); + showVmSubpage("create"); if (!state.resources) { void loadResources().catch((error) => showError("create-error", `无法加载宿主机资源:${error.message}`)); } @@ -2021,7 +2098,7 @@ function openReinstall(vm) { toast("此标签页已有重装任务,已恢复任务状态;请不要重复提交。", "info"); return; } - byId("reinstall-form").reset(); + resetReinstallPage(); fillSshKeyCards(state.sshKeys); clearSshKeyPicker("reinstall-ssh-key-cards"); updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); @@ -2037,21 +2114,33 @@ function openReinstall(vm) { byId("reinstall-retry").hidden = true; byId("reinstall-done").hidden = true; text("reinstall-done", "完成"); - byId("reinstall-close-top").disabled = false; + byId("reinstall-back").disabled = false; showError("reinstall-error", ""); text("reinstall-subtitle", `${vm.name || vm.uuid} · 保留公网网络参数,重新创建系统盘。`); text("reinstall-public-ip", String(vm.public_ip_cidr || "未知")); text("reinstall-confirm-hint", `请准确输入“${vm.name || ""}”;这也是防止选错虚拟机的最后一道确认。`); byId("reinstall-confirm-name").placeholder = vm.name || "请输入完整的虚拟机名称"; - openModal("reinstall-modal"); state.reinstallTarget = vm; + showVmSubpage("reinstall"); void loadTemplates().catch((error) => showError("reinstall-error", `无法加载重装模板:${error.message}`)); void loadSshKeys().catch((error) => showError("reinstall-error", `无法读取已保存公钥:${error.message}。请稍后重试,或选择密码登录。`)); } +function leaveReinstallPage() { + if (!canLeaveReinstallPage()) return; + const uuid = String(state.reinstallTarget?.uuid || ""); + if (!showVmWorkspace()) return; + if (uuid && state.vms.some((vm) => String(vm.uuid || "") === uuid)) openVmDetail(uuid); + else byId("vm-list-title").focus(); +} + function resumeReinstallJob() { const saved = readSavedReinstallJob(); - if (!saved || state.activeModal) return; + if (!saved) return; + if (state.reinstallJobId === saved.job_id && (state.reinstallInProgress || state.reinstallPasswordPendingAck)) { + showVmSubpage("reinstall"); + return; + } byId("reinstall-form").reset(); byId("reinstall-fields").hidden = true; byId("reinstall-result").hidden = true; @@ -2066,13 +2155,13 @@ function resumeReinstallJob() { showError("reinstall-error", ""); text("reinstall-subtitle", "正在恢复此标签页中尚未确认的重装任务。"); text("reinstall-phase", "正在查询已有重装任务…"); - openModal("reinstall-modal"); state.reinstallTarget = null; state.reinstallJobId = saved.job_id; state.reinstallExpectGeneratedPassword = Boolean(saved.expect_generated_password); state.reinstallPasswordPendingAck = false; state.reinstallInProgress = true; - byId("reinstall-close-top").disabled = true; + byId("reinstall-back").disabled = true; + showVmSubpage("reinstall"); const token = ++state.reinstallPollToken; void pollReinstallJob(saved.job_id, token); } @@ -2109,7 +2198,7 @@ function showReinstallResult(success, message, job = {}, terminal = true) { byId("reinstall-retry").hidden = terminal; byId("reinstall-done").hidden = false; text("reinstall-done", state.reinstallPasswordPendingAck ? "已保存密码,完成" : "完成"); - byId("reinstall-close-top").disabled = state.reinstallPasswordPendingAck; + byId("reinstall-back").disabled = state.reinstallPasswordPendingAck; text("reinstall-result-title", success ? "重装任务已完成" : "重装任务未完成"); text("reinstall-result-message", message); byId("reinstall-result").classList.toggle("failed", !success); @@ -2464,6 +2553,7 @@ byId("smtp-settings-form").addEventListener("submit", async (event) => { }); async function logout(button) { + if (!canLeaveReinstallPage()) return; setButtonBusy(button, true, "退出中…"); try { await api("/api/v1/logout", { method: "POST" }); @@ -2479,8 +2569,13 @@ byId("logout-button").addEventListener("click", () => void logout(byId("logout-b byId("wait-logout-button").addEventListener("click", () => void logout(byId("wait-logout-button"))); byId("host-logout-button").addEventListener("click", () => void logout(byId("host-logout-button"))); byId("unlock-logout-button").addEventListener("click", () => void logout(byId("unlock-logout-button"))); -byId("host-settings-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true })); -byId("host-settings-mobile-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true })); +function openHostSettings() { + if (!canLeaveReinstallPage()) return; + discardVmSubpageDrafts(); + showHostView(state.hostConfig || { configured: true }); +} +byId("host-settings-button").addEventListener("click", openHostSettings); +byId("host-settings-mobile-button").addEventListener("click", openHostSettings); byId("host-update-button").addEventListener("click", () => openUpdateFromGate("host")); byId("unlock-update-button").addEventListener("click", () => openUpdateFromGate("unlock")); byId("vm-navigation-button").addEventListener("click", leaveUpdateWorkspace); @@ -2492,9 +2587,9 @@ byId("update-settings-mobile-button").addEventListener("click", () => void showU byId("smtp-settings-button").addEventListener("click", () => void showSmtpWorkspace()); byId("smtp-settings-mobile-button").addEventListener("click", () => void showSmtpWorkspace()); byId("smtp-back-button").addEventListener("click", showVmWorkspace); -byId("ssh-keys-back-button").addEventListener("click", showVmWorkspace); +byId("ssh-keys-back-button").addEventListener("click", returnFromSshKeysWorkspace); byId("update-back-button").addEventListener("click", leaveUpdateWorkspace); -byId("unlock-settings-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true })); +byId("unlock-settings-button").addEventListener("click", openHostSettings); byId("host-back-button").addEventListener("click", () => { clearHostPrivateKey(); if (state.hostConfig?.key_locked) showUnlockView(state.hostConfig); @@ -2741,6 +2836,11 @@ byId("vm-detail-back-button").addEventListener("click", () => { byId("search-input").addEventListener("input", () => renderVMs()); byId("state-filter").addEventListener("change", () => renderVMs()); byId("create-button").addEventListener("click", openCreate); +byId("create-back").addEventListener("click", () => { + if (showVmWorkspace()) byId("vm-list-title").focus(); +}); +byId("reinstall-back").addEventListener("click", leaveReinstallPage); +byId("reinstall-cancel").addEventListener("click", leaveReinstallPage); byId("ssh-key-file").addEventListener("change", async (event) => { const file = event.currentTarget.files?.[0]; if (!file) return; @@ -2786,8 +2886,7 @@ byId("ssh-key-form").addEventListener("submit", async (event) => { }); for (const id of ["vm-open-ssh-keys", "reinstall-open-ssh-keys"]) { byId(id).addEventListener("click", () => { - closeModal(); - void showSshKeysWorkspace(); + void showSshKeysWorkspace(id === "vm-open-ssh-keys" ? "create" : "reinstall"); }); } for (const [inputId, hintId] of [["vm-root-password", "vm-root-password-hint"], ["reinstall-root-password", "reinstall-root-password-hint"]]) { @@ -2833,7 +2932,7 @@ byId("template-import-button").addEventListener("click", async () => { if (!jobId) throw new Error("面板未返回模板导入任务编号,请刷新模板列表确认结果。"); state.templateImportJobId = jobId; } - showTemplateImportStatus("宿主机正在后台下载并校验云镜像。关闭弹窗不会取消任务,请稍候。"); + showTemplateImportStatus("宿主机正在后台下载并校验云镜像。离开页面不会取消任务,请稍候。"); const completed = await waitForTemplateImport(jobId); state.templateImportJobId = null; showTemplateImportStatus(""); @@ -3019,7 +3118,7 @@ byId("create-form").addEventListener("submit", async (event) => { try { const autoPassword = source === "cloud" && !body.root_password; const createdVm = await api("/api/v1/vms", { method: "POST", body }); - closeModal(); + showVmWorkspace(); const createdIp = String(createdVm?.public_ip_cidr || "").split("/")[0]; toast(autoPassword ? `虚拟机 ${body.name} 创建成功${createdIp ? `,公网 IP:${createdIp}` : ""}。初始 root 密码可在虚拟机详情页查看。` @@ -3046,7 +3145,7 @@ byId("reinstall-form").addEventListener("submit", async (event) => { const rootPassword = byId("reinstall-root-password").value; const confirmationName = byId("reinstall-confirm-name").value; if (!templateId) { - showError("reinstall-error", "请先选择已导入的云镜像模板。若列表为空,请在“创建虚拟机”窗口先导入模板。"); + showError("reinstall-error", "请先选择已导入的云镜像模板。若列表为空,请在“创建虚拟机”页面先导入模板。"); return; } if (selectedKeyId && !state.sshKeys.some((key) => String(key.id) === selectedKeyId)) { @@ -3072,7 +3171,7 @@ byId("reinstall-form").addEventListener("submit", async (event) => { if (rootPassword) body.root_password = rootPassword; state.reinstallInProgress = true; state.reinstallExpectGeneratedPassword = !selectedKeyId && !rootPassword; - byId("reinstall-close-top").disabled = true; + byId("reinstall-back").disabled = true; byId("reinstall-cancel").disabled = true; setButtonBusy(button, true, "正在提交…"); try { @@ -3090,7 +3189,7 @@ byId("reinstall-form").addEventListener("submit", async (event) => { void pollReinstallJob(jobId, token); } catch (error) { state.reinstallInProgress = false; - byId("reinstall-close-top").disabled = false; + byId("reinstall-back").disabled = false; byId("reinstall-cancel").disabled = false; showError("reinstall-error", error.message); } finally { @@ -3113,7 +3212,7 @@ byId("reinstall-copy-password").addEventListener("click", async () => { }); byId("reinstall-done").addEventListener("click", async () => { if (!state.reinstallPasswordPendingAck) { - closeModal(); + leaveReinstallPage(); return; } const jobId = state.reinstallJobId; @@ -3128,9 +3227,9 @@ byId("reinstall-done").addEventListener("click", async () => { if (result?.acknowledged !== true) throw new Error("面板未确认密码已经清除,请稍后重试。"); state.reinstallPasswordPendingAck = false; clearSavedReinstallJob(); - closeModal(); + leaveReinstallPage(); } catch (error) { - showError("reinstall-error", `确认密码失败:${error.message}。密码仍在此窗口中,请先安全保存后重试。`); + showError("reinstall-error", `确认密码失败:${error.message}。密码仍在此页面中,请先安全保存后重试。`); } finally { setButtonBusy(button, false); } @@ -3139,7 +3238,7 @@ byId("reinstall-retry").addEventListener("click", () => { const jobId = state.reinstallJobId; if (!jobId) return; state.reinstallInProgress = true; - byId("reinstall-close-top").disabled = true; + byId("reinstall-back").disabled = true; byId("reinstall-result").hidden = true; byId("reinstall-progress").hidden = false; byId("reinstall-retry").hidden = true; @@ -3151,7 +3250,7 @@ byId("reinstall-retry").addEventListener("click", () => { byId("reinstall-forget").addEventListener("click", () => { if (!window.confirm("请先在宿主机核对虚拟机、新旧系统盘和登录方式。放弃恢复后,本标签页将不再查询此任务,尚未领取的自动 root 密码也可能无法找回。确定放弃吗?")) return; clearSavedReinstallJob(); - closeModal(); + leaveReinstallPage(); }); byId("delete-form").addEventListener("submit", async (event) => { @@ -3210,14 +3309,6 @@ byId("console-password-form").addEventListener("submit", (event) => { }); function requestCloseModal() { - if (state.activeModal?.id === "reinstall-modal" && state.reinstallPasswordPendingAck) { - toast("请先保存 root 密码,再点击“已保存密码,完成”确认清除。", "error"); - return; - } - if (state.activeModal?.id === "reinstall-modal" && state.reinstallInProgress) { - toast("重装正在进行,请保持此窗口打开,以免错过一次性显示的 root 密码。", "error"); - return; - } closeModal(); } diff --git a/static/index.html b/static/index.html index f1bbdcfa..c0ab620b 100644 --- a/static/index.html +++ b/static/index.html @@ -5,8 +5,8 @@ VirtPilot · 虚拟机管理 - - + +
@@ -293,6 +293,66 @@

磁盘 I/O 为每秒读写量,仅统计 libvirt 提供计数的设备;网络收发为虚拟机视角的每秒速率,不代表套餐带宽上限。内存已用量为估算值,取决于虚拟机是否提供气球驱动统计。

+ +
- - - - diff --git a/static/styles.css b/static/styles.css index 646d2122..28ec6e21 100644 --- a/static/styles.css +++ b/static/styles.css @@ -137,19 +137,18 @@ tbody tr:hover{background:#fcfefe} .vm-metrics{margin-top:25px}.vm-metrics-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:14px}.vm-metrics-heading h2{font-size:19px;margin:7px 0 6px}.vm-metrics-heading p{font-size:11px;color:#8191a1;line-height:1.6;margin:0}.vm-metrics-range-control{display:flex;align-items:center;gap:9px;flex:none;color:#64768a;font-size:11px;font-weight:700}.vm-metrics-range-control select{height:37px;padding:0 11px;border:1px solid #dbe6ec;border-radius:8px;color:#344e60;background:#fff;font-size:12px;font-weight:700}.vm-metrics-status{margin:0 0 14px;padding:9px 12px;border-radius:8px;background:#eaf7f7;color:#277b82;font-size:11px;line-height:1.5}.vm-metrics-status.warning{background:#fff6e9;color:#946620}.vm-metrics-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-metric-card{min-width:0;padding:20px 21px 16px;border:1px solid #e7ecf2;border-radius:13px;background:#fff;box-shadow:0 10px 30px rgba(19,42,65,.027)}.vm-metric-card-heading{display:flex;align-items:flex-start;gap:11px;min-height:62px}.vm-metric-card-heading>div{min-width:0}.vm-metric-card-heading h3{margin:1px 0 6px;font-size:13px;color:#32485b}.vm-metric-card-heading p{margin:0;color:#60758a;font-size:12px;line-height:1.45;overflow-wrap:anywhere}.vm-metric-icon{display:flex;align-items:center;justify-content:center;flex:none;width:34px;height:34px;border-radius:9px;font-size:18px;font-weight:700}.vm-metric-icon.cpu{background:#e8f8f8;color:#0f9eaa}.vm-metric-icon.memory{background:#edf3fb;color:#4781cf}.vm-metric-icon.disk{background:#eef3fa;color:#477dc9}.vm-metric-icon.network{background:#eaf8f2;color:#17a685}.vm-metric-plot{display:flex;align-items:center;justify-content:center;height:205px;margin:8px 0 6px;overflow:hidden}.vm-metric-plot svg{display:block;width:100%;height:100%;font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif}.vm-metric-gridline{stroke:#e5edf2;stroke-width:1;stroke-dasharray:3 4}.vm-metric-axis-label{fill:#9aabb9;font-size:10px}.vm-metric-empty{margin:0;padding:15px;text-align:center;color:#94a2af;font-size:11px;line-height:1.6}.vm-metric-legend{display:flex;align-items:center;flex-wrap:wrap;gap:15px;padding-left:7px;color:#728297;font-size:10px;font-weight:700}.vm-metric-legend span{display:inline-flex;align-items:center;gap:6px}.vm-metric-swatch{display:inline-block;width:16px;height:0;border-top:3px solid #0f9eaa;border-radius:2px}.vm-metric-swatch.cpu{border-color:#0f9eaa}.vm-metric-swatch.memory{border-color:#4781cf}.vm-metric-swatch.memory-total{border-color:#a4b7d7;border-top-style:dashed}.vm-metric-swatch.disk-read{border-color:#477dc9}.vm-metric-swatch.disk-write{border-color:#e59c46}.vm-metric-swatch.network-rx{border-color:#17a685}.vm-metric-swatch.network-tx{border-color:#926ed0}.vm-metrics-footnote{margin:12px 1px 0;color:#9ba8b6;font-size:10px;line-height:1.6} .modal-backdrop{position:fixed;inset:0;z-index:30;background:rgba(11,25,40,.58);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(3px)} .modal{width:min(100%,610px);max-height:min(92vh,900px);overflow:auto;border-radius:14px;background:#fff;box-shadow:0 22px 70px rgba(0,0,0,.2)}.narrow-modal{width:min(100%,460px)} -.create-modal{width:min(100%,720px)} .modal-header{display:flex;align-items:flex-start;justify-content:space-between;padding:26px 29px 18px;border-bottom:1px solid #edf1f5}.modal-header h2{font-size:21px;letter-spacing:-.35px;margin:7px 0 5px}.modal-header p{font-size:12px;color:#95a1af;margin:0}.icon-button{border:0;border-radius:8px;background:transparent;color:#8a98a8;width:31px;height:31px;font-size:23px;line-height:1;display:flex;align-items:center;justify-content:center}.icon-button:hover{background:#f1f5f8;color:#30445a} .modal-body{padding:23px 29px 25px}.modal-footer{display:flex;justify-content:flex-end;gap:9px;padding:18px 29px;border-top:1px solid #edf1f5} +.workspace-form-page{width:min(100%,900px);margin:0 auto 48px}.workspace-form-back{padding-left:0;margin-bottom:15px;min-height:34px}.workspace-form-heading{margin-bottom:22px}.workspace-form-heading h1{margin-top:8px}.workspace-form-card{overflow:hidden}.workspace-form-body{padding:28px clamp(22px,3vw,36px) 32px}.workspace-form-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:10px;padding:18px clamp(22px,3vw,36px);border-top:1px solid #edf1f5;background:#fbfdfe}.workspace-form-actions .button{min-width:120px}.workspace-form-body>.form-error{margin:18px 0 0} .form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 17px}.field.full{grid-column:1/-1}.field label{display:block}.field label span{color:#dc5965}.field small{display:block;color:#a1adbb;font-size:10px;margin-top:7px;line-height:1.5}.field select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%2393a1ae' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center;padding-right:35px} .create-source-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;border:0;padding:0;margin:0 0 23px;min-width:0}.create-source-picker legend{color:#34445a;font-size:13px;font-weight:700;padding:0;margin-bottom:10px}.create-source-picker label{position:relative;display:block;cursor:pointer}.create-source-picker input{position:absolute;opacity:0;width:1px;height:1px}.create-source-picker label span{display:block;border:1px solid #dce4eb;border-radius:9px;padding:12px 14px;min-height:65px;background:#fff}.create-source-picker input:checked+span{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.create-source-picker input:focus-visible+span{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.create-source-picker strong{display:block;color:#334a5f;font-size:12px}.create-source-picker small{display:block;color:#8999a8;font-size:10px;margin-top:5px} .template-import{border:1px solid #e0e9ee;border-radius:9px;margin-top:12px;background:#fbfdfd}.template-import summary{cursor:pointer;padding:11px 13px;color:#148c98;font-size:11px;font-weight:700}.template-import-fields{display:grid;gap:13px;padding:2px 13px 14px}.template-import-fields .field input{height:42px}.template-import-fields .form-error{margin:0}.template-import-fields .button{justify-self:start}.template-import-status{margin:0;color:#317c85;font-size:11px;line-height:1.6} -.cloud-fields{grid-column:1/-1;border-top:1px solid #e7edf2;padding-top:18px}.cloud-fields-heading{margin-bottom:17px}.cloud-fields-heading strong{display:block;color:#34445a;font-size:13px}.cloud-fields-heading small{display:block;color:#8798a7;font-size:10px;line-height:1.6;margin-top:6px}.cloud-fields textarea{width:100%;min-height:79px;padding:11px 13px;border:1px solid #dce4eb;border-radius:9px;color:#15243a;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;resize:vertical;background:#fff}.cloud-fields textarea:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none} +.cloud-fields{grid-column:1/-1;border-top:1px solid #e7edf2;padding-top:18px}.cloud-fields-heading{margin-bottom:17px}.cloud-fields-heading strong{display:block;color:#34445a;font-size:13px}.cloud-fields-heading small{display:block;color:#8798a7;font-size:10px;line-height:1.6;margin-top:6px} .vm-auto-public-pool{display:grid;gap:5px;margin:0 0 18px;padding:13px 15px;border:1px solid #cce9e0;border-radius:9px;background:#f0fbf8}.vm-auto-public-pool strong{font-size:12px;color:#217d6e}.vm-auto-public-pool span{font-size:11px;line-height:1.6;color:#5b837a}.vm-cloud-auth-fields{margin-top:18px} .input-suffix{position:relative}.input-suffix input{padding-right:48px}.input-suffix span{position:absolute;right:13px;top:13px;color:#97a4b2;font-size:12px} .form-tip{display:flex;gap:10px;background:#f1f9fa;border:1px solid #e1f2f3;border-radius:9px;padding:12px 14px;color:#318b96;margin-top:22px}.form-tip>span{font-size:16px;line-height:1}.form-tip p{font-size:11px;line-height:1.55;margin:0}.modal-body>.form-error{margin:18px 0 0} .delete-copy{font-size:13px;color:#647388;line-height:1.8;margin:0 0 19px}.delete-copy strong{color:#263c54;overflow-wrap:anywhere}.danger-text{color:#d64753} .reinstall-warning{margin:0 0 15px;padding:14px 16px;border:1px solid #f2cbd0;border-radius:9px;background:#fff4f5;color:#99414d;font-size:12px;line-height:1.7}.reinstall-warning strong{display:block;margin-bottom:4px;color:#a82f3f;font-size:13px}.reinstall-network{margin:0 0 21px;color:#51677c;font-size:12px;line-height:1.7}.reinstall-network strong{color:#174458;overflow-wrap:anywhere} -#reinstall-form .field textarea{width:100%;min-height:80px;padding:11px 13px;border:1px solid #dce4eb;border-radius:9px;color:#15243a;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;resize:vertical;background:#fff}#reinstall-form .field textarea:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none} .reinstall-progress{display:flex;align-items:flex-start;gap:15px;padding:14px 2px;min-height:105px}.reinstall-progress .console-spinner{flex:none;margin-top:2px}.reinstall-progress strong{display:block;color:#274459;font-size:14px}.reinstall-progress p{margin:8px 0;color:#238894;font-size:12px;line-height:1.6}.reinstall-progress small{display:block;color:#8192a4;font-size:11px;line-height:1.6} .reinstall-result{padding:4px 0 10px}.reinstall-result h3{margin:0 0 10px;color:#167f72;font-size:18px}.reinstall-result.failed h3{color:#b1404c}.reinstall-result.unknown h3{color:#916425}.reinstall-result>p{margin:0 0 14px;color:#4f6478;font-size:12px;line-height:1.75;overflow-wrap:anywhere}.reinstall-password-box{border:1px solid #b9e2d5;border-radius:9px;background:#f1fbf7;padding:14px;margin-top:15px}.reinstall-password-box>span{display:block;color:#286f60;font-size:12px;font-weight:700}.reinstall-password-box>div{display:flex;align-items:center;gap:9px;margin:10px 0}.reinstall-password-box code{display:block;flex:1;min-width:0;padding:11px;border-radius:7px;background:#fff;color:#1d4a41;font-size:14px;overflow-wrap:anywhere;user-select:all}.reinstall-password-box small{display:block;color:#617f76;font-size:11px;line-height:1.6}.reinstall-result-warning{padding:10px 12px;border-radius:8px;background:#fff6e7;color:#916425!important} .checkbox-row{border:1px solid #f0dadd;background:#fffafa;border-radius:9px;padding:14px;display:flex;align-items:flex-start;gap:11px;cursor:pointer}.checkbox-row input{margin:3px 0 0;accent-color:#d94350}.checkbox-row strong{display:block;font-size:12px;color:#9e3440}.checkbox-row small{display:block;margin-top:4px;font-size:11px;line-height:1.5;color:#bd7a81} @@ -168,6 +167,7 @@ tbody tr:hover{background:#fcfefe} @media(max-width:510px){.topbar{padding:0 17px}.content{padding:25px 14px}.page-heading{padding:0 3px}.overview-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-card{padding:13px 11px;min-height:112px}.stat-card>strong{font-size:23px}.stat-icon{display:none}.topbar-right{gap:4px}.topbar-user{font-size:11px}.breadcrumb{font-size:11px}.modal-backdrop{padding:10px}.modal-header,.modal-body{padding-left:19px;padding-right:19px}.modal-footer{padding:14px 19px}.form-grid{gap:15px 10px}.console-backdrop{padding:0}.console-modal{height:100vh;max-height:100vh;border-radius:0}.console-stage{flex:1;height:auto}.console-tools .button{display:none}.console-password{flex-wrap:wrap}.console-password input{flex:1;min-width:130px}} @media(max-width:510px){.topbar-right{flex-wrap:nowrap;justify-content:flex-end;gap:5px;min-width:0}.topbar-user{min-width:0}.topbar-user #current-username{display:block;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.topbar-user .avatar{display:none}.topbar-right #logout-button{font-size:10px;padding:5px;min-height:28px}.breadcrumb{white-space:nowrap}.breadcrumb span{padding:0 5px}.update-versions{grid-template-columns:1fr}} @media(max-width:510px){.create-source-picker,.cloud-fields>.form-grid{grid-template-columns:1fr}} +@media(max-width:510px){.workspace-form-body{padding:22px 19px 25px}.workspace-form-actions{padding:15px 19px}.workspace-form-actions .button{flex:1 1 100%}.workspace-form-back{margin-bottom:10px}} @media(max-width:510px){.host-public-pool>.form-grid{grid-template-columns:1fr}} @media(max-width:510px){.register-code-row{flex-wrap:wrap}.register-code-row input{flex-basis:100%}.register-code-row .button{width:100%}.pending-user-row{align-items:flex-start;flex-direction:column}.pending-user-row .button{width:100%}.smtp-card .form-grid{grid-template-columns:1fr}} @media(max-width:510px){.ssh-key-row{align-items:flex-start;flex-direction:column}.ssh-key-actions{width:100%}.ssh-key-actions .button{flex:1}} diff --git a/tests/test_frontend_page_layout.py b/tests/test_frontend_page_layout.py new file mode 100644 index 00000000..73c88051 --- /dev/null +++ b/tests/test_frontend_page_layout.py @@ -0,0 +1,99 @@ +"""Keep VM creation and reinstall in the dashboard, not in modal dialogs.""" + +from __future__ import annotations + +from collections import defaultdict +from dataclasses import dataclass +from html.parser import HTMLParser +from pathlib import Path + +import pytest + + +STATIC_DIR = Path(__file__).resolve().parents[1] / "static" +VOID_TAGS = { + "area", "base", "br", "col", "embed", "hr", "img", "input", + "link", "meta", "param", "source", "track", "wbr", +} + + +@dataclass(frozen=True) +class Element: + tag: str + attrs: dict[str, str | None] + ancestors: tuple[Element, ...] + + @property + def element_id(self) -> str | None: + return self.attrs.get("id") + + +class PageParser(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.stack: list[Element] = [] + self.elements: list[Element] = [] + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + element = Element(tag, dict(attrs), tuple(self.stack)) + self.elements.append(element) + if tag not in VOID_TAGS: + self.stack.append(element) + + def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + self.elements.append(Element(tag, dict(attrs), tuple(self.stack))) + + def handle_endtag(self, tag: str) -> None: + for index in range(len(self.stack) - 1, -1, -1): + if self.stack[index].tag == tag: + del self.stack[index:] + return + + +@pytest.fixture(scope="module") +def page() -> tuple[list[Element], dict[str, list[Element]]]: + parser = PageParser() + parser.feed((STATIC_DIR / "index.html").read_text(encoding="utf-8")) + assert not parser.stack, "Unclosed HTML element in the dashboard page" + by_id: dict[str, list[Element]] = defaultdict(list) + for element in parser.elements: + if element.element_id: + by_id[element.element_id].append(element) + return parser.elements, by_id + + +@pytest.mark.parametrize("prefix", ["create", "reinstall"]) +def test_vm_form_is_a_dashboard_page_not_a_modal(page, prefix: str) -> None: + _, by_id = page + forms = by_id[f"{prefix}-form"] + assert len(forms) == 1 + form = forms[0] + assert form.tag == "form" + ancestor_ids = {ancestor.element_id for ancestor in form.ancestors} + assert {"dashboard-view", "vm-workspace", f"{prefix}-view"} <= ancestor_ids + + for element in (*form.ancestors, form): + assert element.tag != "dialog" + assert element.attrs.get("role") != "dialog" + assert "modal-backdrop" not in (element.attrs.get("class") or "").split() + + back_buttons = by_id[f"{prefix}-back"] + assert len(back_buttons) == 1 + assert back_buttons[0].tag == "button" + assert f"{prefix}-view" in { + ancestor.element_id for ancestor in back_buttons[0].ancestors + } + + +def test_old_vm_modal_elements_and_js_references_are_removed(page) -> None: + _, by_id = page + script = (STATIC_DIR / "app.js").read_text(encoding="utf-8") + for element_id in ("create-modal", "reinstall-modal"): + assert element_id not in by_id + assert element_id not in script + + +def test_every_html_id_is_unique(page) -> None: + _, by_id = page + duplicates = sorted(element_id for element_id, elements in by_id.items() if len(elements) > 1) + assert duplicates == []