diff --git a/web/public/cloud/app.js b/web/public/cloud/app.js index 0f098996..87d1da75 100644 --- a/web/public/cloud/app.js +++ b/web/public/cloud/app.js @@ -1,4 +1,4 @@ -import { initializeTaskCenter } from './task-center.js?v=2026102003'; +import { initializeTaskCenter } from './task-center.js?v=2026102004'; const pageModules = Object.freeze({ instances: '/cloud/instances.js', diff --git a/web/public/cloud/client.css b/web/public/cloud/client.css index fdc32e46..d6a2f553 100644 --- a/web/public/cloud/client.css +++ b/web/public/cloud/client.css @@ -30,6 +30,44 @@ .panel-topbar { position: sticky; top: 0; z-index: 25; } .main-area > .content .template-catalog { isolation: isolate; } .panel-topbar-logout { text-decoration: none; } +html.panel-user-dialog-open { overflow: hidden; overscroll-behavior: none; } +.panel-user-dialog { width: min(468px, calc(100% - 32px)); max-width: none; max-height: min(88vh, 680px); margin: auto; padding: 0; border: 0; border-radius: 16px; background: transparent; color: #25384e; box-shadow: 0 28px 80px rgba(13, 35, 53, .24); overflow: visible; } +.panel-user-dialog:not([open]) { display: none; } +.panel-user-dialog::backdrop { background: rgba(11, 25, 40, .58); backdrop-filter: blur(3px); animation: panel-user-dialog-backdrop-in .18s ease-out both; } +.panel-user-dialog[open]:not(.is-dialog-fallback) { animation: panel-user-dialog-in .2s cubic-bezier(.22, 1, .36, 1) both; } +.panel-user-dialog-card { width: 100%; max-height: min(88vh, 680px); overflow-y: auto; border: 1px solid rgba(220, 231, 237, .9); border-radius: 16px; background: #fff; box-shadow: inherit; } +.panel-user-dialog-header { display: grid; grid-template-columns: 46px minmax(0,1fr) 36px; align-items: start; gap: 14px; padding: 25px 25px 21px; } +.panel-user-dialog-mark { display: grid; width: 46px; height: 46px; place-items: center; border-radius: 13px; background: #fff4df; color: #a46c18; font-size: 24px; } +.panel-user-dialog[data-tone="danger"] .panel-user-dialog-mark { background: #fff0f1; color: #c03f4c; } +.panel-user-dialog[data-tone="info"] .panel-user-dialog-mark { background: #eaf7f8; color: #148c98; } +.panel-user-dialog[data-tone="success"] .panel-user-dialog-mark { background: #eaf7ef; color: #25875d; } +.panel-user-dialog-heading { min-width: 0; } +.panel-user-dialog-kicker { display: block; margin: 0 0 5px; color: #657789; font-size: 10px; font-weight: 800; letter-spacing: .1em; } +.panel-user-dialog-heading h2 { margin: 0; color: #20364c; font-size: 19px; font-weight: 800; line-height: 1.45; letter-spacing: -.25px; overflow-wrap: anywhere; } +.panel-user-dialog-heading p { margin: 9px 0 0; color: #607486; font-size: 12px; line-height: 1.8; white-space: pre-line; overflow-wrap: anywhere; } +.panel-user-dialog-close { display: grid; width: 36px; height: 36px; place-items: center; padding: 0; border: 0; border-radius: 9px; background: transparent; color: #7d8f9f; font-size: 20px; cursor: pointer; } +.panel-user-dialog-close:hover { background: #f0f5f7; color: #30485c; } +.panel-user-dialog-close:focus-visible { outline: 3px solid rgba(18, 166, 176, .2); outline-offset: 1px; } +.panel-user-dialog-verification { margin: 0 25px 2px; padding: 16px; border: 1px solid #efd7da; border-radius: 11px; background: #fff8f8; } +.panel-user-dialog-verification[hidden] { display: none; } +.panel-user-dialog-verification label { display: block; margin-bottom: 9px; color: #71444b; font-size: 12px; font-weight: 800; } +.panel-user-dialog-verification input { width: 100%; height: 43px; padding: 0 12px; border: 1px solid #ddc1c5; border-radius: 8px; background: #fff; color: #263b50; font: 13px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; } +.panel-user-dialog-verification input:focus { border-color: #cf5964; outline: 0; box-shadow: 0 0 0 4px rgba(207, 89, 100, .11); } +.panel-user-dialog-verification small { display: block; margin-top: 8px; color: #93636a; font-size: 10px; line-height: 1.6; overflow-wrap: anywhere; } +.panel-user-dialog-verification small.is-mismatch { color: #bd3f4c; } +.panel-user-dialog-verification.is-matched { border-color: #c9e5d7; background: #f3fbf7; } +.panel-user-dialog-verification.is-matched label, +.panel-user-dialog-verification.is-matched small { color: #287859; } +.panel-user-dialog-verification.is-matched input { border-color: #76b99a; } +.panel-user-dialog-verification.is-matched input:focus { border-color: #42916d; box-shadow: 0 0 0 4px rgba(66, 145, 109, .11); } +.panel-user-dialog-actions { display: flex; justify-content: flex-end; gap: 9px; margin-top: 22px; padding: 17px 25px 21px; border-top: 1px solid #e8eef2; background: #fbfcfd; border-radius: 0 0 16px 16px; } +.panel-user-dialog-actions .button { min-width: 92px; } +.panel-user-dialog-actions .button:focus-visible { outline: 3px solid rgba(18, 166, 176, .2); outline-offset: 2px; } +.panel-user-dialog-actions .button-danger:focus-visible { outline-color: rgba(217, 67, 80, .22); } +.panel-user-dialog.is-dialog-fallback { position: fixed; inset: 0; z-index: 1000; display: grid; width: 100%; height: 100%; max-height: none; margin: 0; padding: 16px; place-items: center; border-radius: 0; background: rgba(11, 25, 40, .58); box-shadow: none; backdrop-filter: blur(3px); } +.panel-user-dialog.is-dialog-fallback .panel-user-dialog-card { width: min(468px, 100%); } +@keyframes panel-user-dialog-in { from { opacity: 0; transform: translateY(10px) scale(.985); } to { opacity: 1; transform: none; } } +@keyframes panel-user-dialog-backdrop-in { from { background: rgba(11, 25, 40, 0); } to { background: rgba(11, 25, 40, .58); } } /* Announcements share the user shell without loading administrator styles. */ .panel-announcements-close.button { flex: 0 0 44px; width: 44px; height: 44px; min-height: 44px; padding: 0; font-size: 22px; } .panel-announcements-trigger.button, @@ -191,6 +229,13 @@ body.vu-embedded .dashboard > .main-area > .vu-main > .vu-topbar { margin: 0; } .panel-user-menu .topbar-user .avatar { display: inline-flex; } .panel-user-menu .topbar-user > span:nth-child(2) { display: none; } .panel-user-menu .topbar-user #current-username { display: block; max-width: 90px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .panel-user-dialog { width: calc(100% - 20px); max-width: 468px; } + .panel-user-dialog-header { grid-template-columns: 40px minmax(0,1fr) 34px; gap: 11px; padding: 20px 17px 17px; } + .panel-user-dialog-mark { width: 40px; height: 40px; border-radius: 11px; font-size: 21px; } + .panel-user-dialog-heading h2 { font-size: 17px; } + .panel-user-dialog-verification { margin-inline: 17px; padding: 14px; } + .panel-user-dialog-actions { padding: 15px 17px max(17px, env(safe-area-inset-bottom)); } + .panel-user-dialog-actions .button { flex: 1 1 0; min-width: 0; } } @media (prefers-reduced-motion: reduce) { .panel-announcements-drawer, @@ -199,6 +244,8 @@ body.vu-embedded .dashboard > .main-area > .vu-main > .vu-topbar { margin: 0; } .panel-announcements-drawer::backdrop, .panel-task-drawer::backdrop, .panel-account-drawer::backdrop { transition: none; } + .panel-user-dialog[open], + .panel-user-dialog::backdrop { animation: none; } } .admin-menu-options { max-height: min(70vh, 520px); overflow-y: auto; } .admin-menu-options a { min-height: 34px; display: flex; align-items: center; padding: 7px 10px; border-radius: 7px; color: #536b7e; font-size: 12px; font-weight: 700; text-decoration: none; } diff --git a/web/public/cloud/detail.js b/web/public/cloud/detail.js index e64cada7..e31698b4 100644 --- a/web/public/cloud/detail.js +++ b/web/public/cloud/detail.js @@ -11,6 +11,7 @@ const { selectedVm, setVmDetailTab, showError, state, stopVmMetrics, stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp, } = await import(runtimeUrl.href); +const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); const VM_METADATA_FIELDS = Object.freeze([ 'region', 'location', 'created_at', 'os_source', 'os_name', @@ -1262,7 +1263,13 @@ async function restoreVmSnapshot(vmId, snapshot) { const key = snapshotKey(snapshot); if (!key || snapshotMutation || snapshotEffectLocked) return; const name = snapshotName(snapshot); - if (!window.confirm(`确认恢复到“${name}”?系统盘会回到快照创建时;账单、服务周期和公网 IP 不会回滚。`)) return; + const confirmed = await requestUserConfirmation({ + title: '恢复系统盘快照', + message: `实例系统盘将恢复到快照“${name}”创建时的状态。账单、服务周期和公网 IP 不会回滚。`, + confirmText: '恢复快照', + tone: 'danger', + }); + if (!confirmed) return; const confirmationName = String(selectedVm()?.name || ''); await startSnapshotMutation( vmId, 'restore', @@ -1275,7 +1282,13 @@ async function deleteVmSnapshot(vmId, snapshot) { const key = snapshotKey(snapshot); if (!key || snapshotMutation || snapshotEffectLocked) return; const name = snapshotName(snapshot); - if (!window.confirm(`确认删除快照“${name}”?删除后无法使用它恢复系统盘。`)) return; + const confirmed = await requestUserConfirmation({ + title: '永久删除快照', + message: `快照“${name}”将被永久删除,之后无法再用它恢复系统盘。`, + confirmText: '删除快照', + tone: 'danger', + }); + if (!confirmed) return; const confirmationName = String(selectedVm()?.name || ''); await startSnapshotMutation( vmId, 'delete', diff --git a/web/public/cloud/iso-images.js b/web/public/cloud/iso-images.js index 9106410d..34972603 100644 --- a/web/public/cloud/iso-images.js +++ b/web/public/cloud/iso-images.js @@ -6,6 +6,7 @@ if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion); const { api, bindPageCleanup, byId, initializeSession, showError, state, toast, } = await import(runtimeUrl.href); +const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); const pageState = { isos: [], canImport: true, busy: false, stopped: false, @@ -70,7 +71,14 @@ function renderIsos() { } remove.addEventListener('click', async () => { if (!canDelete) return; - if (!confirm(`删除 ISO“${record.name || record.id}”?未完成账单或仍在安装的实例会阻止删除。`)) return; + const isoName = record.name || record.id; + const confirmed = await requestUserConfirmation({ + title: '删除个人 ISO', + message: `确定从个人镜像库删除“${isoName}”?存在未完成账单或仍在安装的实例时,服务端会阻止删除。`, + confirmText: '删除 ISO', + tone: 'danger', + }); + if (!confirmed) return; remove.disabled = true; try { const result = await api(`/api/v1/user-isos/${encodeURIComponent(record.id)}`, { diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 5ed1bc30..5f15aa80 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -4,6 +4,7 @@ import { announceTaskAccepted, observeTask, taskUrl } from './task-observer.js?v // PHP owns authentication, authorisation, ownership and purchasing. No Agent // address, token, host credential or unrestricted create API exists in this UI. const byId = (id) => document.getElementById(id); +const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, powerMutation: null, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false }; let vmStatusRequest = null; let vmStatusGeneration = 0; @@ -413,7 +414,18 @@ async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); if (state.mutationBusy || state.powerMutation) return; - if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; + if (dangerous) { + const resetting = action === 'reset'; + const confirmed = await requestUserConfirmation({ + title: resetting ? '强制重置实例' : '强制断电', + message: resetting + ? `实例“${vm.name}”将立即断电并重新启动,未写入磁盘的数据可能丢失。` + : `实例“${vm.name}”将立即断电,未保存的数据可能丢失。`, + confirmText: resetting ? '强制重置' : '强制断电', + tone: 'danger', + }); + if (!confirmed) return; + } const mutation = { vmId: vm.api_id, action }; state.powerMutation = mutation; renderVmDetail(vm); @@ -439,7 +451,36 @@ async function powerAction(action, dangerous = false) { if (selectedVm()) renderVmDetail(selectedVm()); } } -async function deleteVm() { const vm = selectedVm(); if (!vm?.can_delete) return toast('当前账户无权删除该实例。', 'error'); if (state.mutationBusy || state.powerMutation) return; const confirmation = prompt(`永久删除“${vm.name}”及面板管理的虚拟磁盘,此操作不可恢复。请输入完整虚拟机名称确认:`); if (confirmation === null) return; if (confirmation !== vm.name) return toast('虚拟机名称不匹配,未执行删除。', 'error'); state.mutationBusy = true; setDetailBusy(true); try { const result = await api(vmPath(vm), { method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true }, expectedStatus: 202, requireTaskReceipt: true }); announceTaskAccepted(result, { title: '删除实例' }); toast('任务已接收,可在任务中心查看结果。', 'success', '删除实例'); navigate(CLOUD_PATHS.instances); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } +async function deleteVm() { + const vm = selectedVm(); + if (!vm?.can_delete) return toast('当前账户无权删除该实例。', 'error'); + if (state.mutationBusy || state.powerMutation) return; + const confirmed = await requestUserConfirmation({ + title: '永久删除实例', + message: `实例“${vm.name}”及面板管理的虚拟磁盘将被永久删除,此操作无法恢复。`, + confirmText: '永久删除', + tone: 'danger', + requiredText: vm.name, + requiredLabel: '输入完整实例名称以确认永久删除', + }); + if (!confirmed) return; + state.mutationBusy = true; + setDetailBusy(true); + try { + const result = await api(vmPath(vm), { + method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true }, + expectedStatus: 202, requireTaskReceipt: true, + }); + announceTaskAccepted(result, { title: '删除实例' }); + toast('任务已接收,可在任务中心查看结果。', 'success', '删除实例'); + navigate(CLOUD_PATHS.instances); + } catch (error) { + toast(error.message, 'error'); + } finally { + state.mutationBusy = false; + setDetailBusy(false); + } +} function setDetailBusy(busy) { if (!busy && selectedVm()) renderVmDetail(selectedVm()); else if (busy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); } async function credential(copy = false) { const vm = selectedVm(); if (!vm?.can_view_credential || !vm.password_available) return; @@ -456,7 +497,7 @@ async function loadKeys() { function renderKeys() { const container = byId('ssh-keys-list'); container.replaceChildren(); if (!state.sshKeys.length) return container.append(makeElement('p', 'muted', '还没有公钥。')); - for (const key of state.sshKeys) { const row = makeElement('div', 'ssh-key-row'); const details = makeElement('div', 'ssh-key-details'); details.append(makeElement('strong', '', key.name), makeElement('small', '', key.fingerprint || '')); const actions = makeElement('div', 'ssh-key-actions'); const button = actionButton('删除', async () => { if (!confirm(`删除公钥“${key.name}”?已创建的虚拟机不受影响。`)) return; try { await api(`/api/v1/ssh-keys/${encodeURIComponent(key.id)}`, { method: 'DELETE' }); await loadKeys(); } catch (error) { toast(error.message, 'error'); } }); button.classList.add('ssh-key-delete'); actions.append(button); row.append(details, actions); container.append(row); } + for (const key of state.sshKeys) { const row = makeElement('div', 'ssh-key-row'); const details = makeElement('div', 'ssh-key-details'); details.append(makeElement('strong', '', key.name), makeElement('small', '', key.fingerprint || '')); const actions = makeElement('div', 'ssh-key-actions'); const button = actionButton('删除', async () => { const confirmed = await requestUserConfirmation({ title: '删除 SSH 公钥', message: `确定删除“${key.name}”?已经创建的实例不会受到影响。`, confirmText: '删除公钥', tone: 'danger' }); if (!confirmed) return; try { await api(`/api/v1/ssh-keys/${encodeURIComponent(key.id)}`, { method: 'DELETE' }); await loadKeys(); } catch (error) { toast(error.message, 'error'); } }); button.classList.add('ssh-key-delete'); actions.append(button); row.append(details, actions); container.append(row); } } function renderKeyCards(kind) { const id = kind === 'create' ? 'vm-guest-ssh-key-cards' : 'reinstall-ssh-key-cards'; const container = byId(id); if (!container) return; container.replaceChildren(); @@ -1050,7 +1091,15 @@ function renderRescueStatus(status) { state.rescueActive = status.active === tru async function rescueAction(action) { const vm = selectedVm(); if (!vm || state.mutationBusy) return; if (byId('rescue-confirm-name').value !== vm.name) return showError('rescue-error', '请输入完整虚拟机名称确认。'); if (action === 'load' && !byId('rescue-template-id').value) return showError('rescue-error', '请选择救援模板。'); - if (action === 'force-start' && !confirm('正常关机未成功。强制断电并冷启动进入已挂载的救援环境可能丢失数据,确认继续?')) return; + if (action === 'force-start') { + const confirmed = await requestUserConfirmation({ + title: '强制进入救援环境', + message: `实例“${vm.name}”正常关机未成功。继续会强制断电并冷启动进入已挂载的救援环境,未保存的数据可能丢失。`, + confirmText: '强制进入救援', + tone: 'danger', + }); + if (!confirmed) return; + } state.mutationBusy = true; showError('rescue-error', ''); try { const body = { confirmation_name: vm.name }; if (action === 'load') { body.template_id = byId('rescue-template-id').value; body.ack_data_loss = true; } if (action === 'force-start') body.ack_data_loss = true; const result = await api(`${vmPath(vm)}/rescue${action === 'load' ? '' : '/' + action}`, { method: 'POST', body, expectedStatus: 202, requireTaskReceipt: true }); const rescueLabels = { load: '救援', 'force-start': '强制进入救援', exit: '退出救援' }; const title = rescueLabels[action] || '救援'; const observer = observeAcceptedTask(result, { title }, { onTerminal: task => { if (task.status === 'failed') showError('rescue-error', taskFailureMessage(task, `${title}任务失败。`)); void api(`${vmPath(vm)}/rescue`).then(renderRescueStatus).catch(error => showError('rescue-error', error.message)); } }); if (observer) { toast('任务已接收,可在任务中心查看结果。', 'success', title); text('rescue-status', '任务已接收,正在后台执行;你可以离开当前页面。'); } else { showError('rescue-error', '请求已送达,但任务回执协议无效。请勿再次提交,并联系管理员核查。'); } } catch (error) { showError('rescue-error', error.message); } diff --git a/web/public/cloud/ssh-keys.js b/web/public/cloud/ssh-keys.js index 314146b3..f9f10fcf 100644 --- a/web/public/cloud/ssh-keys.js +++ b/web/public/cloud/ssh-keys.js @@ -4,6 +4,7 @@ import { toast } from './toast.js?v=2026100102'; // first HTML response. This module owns only the add/delete interactions and // deliberately does not load the all-feature VM runtime or a session endpoint. const byId = id => document.getElementById(id); +const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); const state = { csrfToken: '', keys: [], mutationBusy: false }; function showError(id, message = '') { @@ -151,7 +152,14 @@ async function deleteKey(button) { if (state.mutationBusy) return; const id = String(button.dataset.sshKeyDelete || ''); const key = state.keys.find(item => item.id === id); - if (!key || !confirm(`删除公钥“${key.name}”?已创建的虚拟机不受影响。`)) return; + if (!key) return; + const confirmed = await requestUserConfirmation({ + title: '删除 SSH 公钥', + message: `确定删除“${key.name}”?已经创建的实例不会受到影响。`, + confirmText: '删除公钥', + tone: 'danger', + }); + if (!confirmed) return; setMutationBusy(true); showError('ssh-keys-list-error'); try { diff --git a/web/public/cloud/user-dialog.js b/web/public/cloud/user-dialog.js new file mode 100644 index 00000000..15884e29 --- /dev/null +++ b/web/public/cloud/user-dialog.js @@ -0,0 +1,197 @@ +(function () { + 'use strict'; + + var dialog = document.getElementById('panel-user-dialog'); + var form = document.getElementById('panel-user-dialog-form'); + var title = document.getElementById('panel-user-dialog-title'); + var message = document.getElementById('panel-user-dialog-message'); + var kicker = dialog ? dialog.querySelector('.panel-user-dialog-kicker') : null; + var closeButton = document.getElementById('panel-user-dialog-close'); + var cancelButton = document.getElementById('panel-user-dialog-cancel'); + var confirmButton = document.getElementById('panel-user-dialog-confirm'); + var verification = document.getElementById('panel-user-dialog-verification'); + var verificationInput = document.getElementById('panel-user-dialog-verification-input'); + var verificationLabel = document.getElementById('panel-user-dialog-verification-label'); + var verificationHint = document.getElementById('panel-user-dialog-verification-hint'); + var activeRequest = null; + var fallbackMode = false; + var ignoredCloseEvents = 0; + + function stringValue(value, fallback) { + if (value === null || value === undefined || String(value).trim() === '') return fallback; + return String(value); + } + + function safeTone(value) { + return ['info', 'success', 'warning', 'danger'].includes(value) ? value : 'warning'; + } + + function canOpen() { + return dialog && form && title && message && kicker && closeButton && cancelButton && confirmButton + && verification && verificationInput && verificationLabel && verificationHint; + } + + function matchesRequiredText() { + return activeRequest && activeRequest.requiredText !== null + && verificationInput.value === activeRequest.requiredText; + } + + function updateVerification() { + if (!activeRequest || activeRequest.requiredText === null) { + confirmButton.disabled = false; + verificationInput.removeAttribute('aria-invalid'); + verification.classList.remove('is-matched'); + verificationHint.classList.remove('is-mismatch'); + return; + } + var matched = matchesRequiredText(); + var hasValue = verificationInput.value.length > 0; + confirmButton.disabled = !matched; + verificationInput.setAttribute('aria-invalid', hasValue && !matched ? 'true' : 'false'); + verification.classList.toggle('is-matched', matched); + verificationHint.classList.toggle('is-mismatch', hasValue && !matched); + verificationHint.textContent = matched ? '名称已匹配,可以继续。' + : (hasValue ? '名称不匹配,请完整输入:' : '请输入:') + activeRequest.requiredText; + } + + function restoreFocus(node) { + if (!node || typeof node.focus !== 'function' || node.isConnected === false) return; + try { + node.focus({ preventScroll: true }); + } catch (error) { + node.focus(); + } + } + + function closeDialog() { + document.documentElement.classList.remove('panel-user-dialog-open'); + dialog.classList.remove('is-dialog-fallback'); + if (dialog.open && typeof dialog.close === 'function') { + ignoredCloseEvents += 1; + dialog.close(); + } + else dialog.removeAttribute('open'); + fallbackMode = false; + } + + function settle(value) { + if (!activeRequest) return; + var request = activeRequest; + activeRequest = null; + closeDialog(); + verificationInput.value = ''; + restoreFocus(request.opener); + request.resolve(value); + } + + function show(options, mode) { + if (!canOpen() || activeRequest) return Promise.resolve(false); + var config = options && typeof options === 'object' ? options : {}; + var requiredText = mode === 'confirm' && typeof config.requiredText === 'string' + && config.requiredText.length > 0 ? config.requiredText : null; + var tone = safeTone(config.tone); + + return new Promise(function (resolve) { + activeRequest = { + mode: mode, + opener: document.activeElement, + requiredText: requiredText, + resolve: resolve + }; + + dialog.dataset.tone = tone; + dialog.setAttribute('role', mode === 'alert' && tone !== 'danger' ? 'dialog' : 'alertdialog'); + kicker.textContent = mode === 'alert' ? '操作提示' : requiredText === null ? '操作确认' : '高风险操作'; + title.textContent = stringValue(config.title, mode === 'alert' ? '提示' : '确认操作'); + message.textContent = stringValue(config.message, '请确认是否继续。'); + cancelButton.textContent = stringValue(config.cancelText, '取消'); + confirmButton.textContent = stringValue(config.confirmText, mode === 'alert' ? '知道了' : '确认'); + cancelButton.hidden = mode === 'alert'; + verification.hidden = requiredText === null; + verificationInput.value = ''; + if (requiredText === null) verificationInput.removeAttribute('required'); + else verificationInput.setAttribute('required', 'required'); + verificationInput.setAttribute('aria-required', requiredText === null ? 'false' : 'true'); + verificationLabel.textContent = stringValue(config.requiredLabel, '输入完整名称以确认'); + verificationHint.textContent = ''; + confirmButton.className = 'button ' + (tone === 'danger' ? 'button-danger' : 'button-primary'); + updateVerification(); + + document.documentElement.classList.add('panel-user-dialog-open'); + if (typeof dialog.showModal === 'function') { + dialog.showModal(); + } else { + fallbackMode = true; + dialog.classList.add('is-dialog-fallback'); + dialog.setAttribute('open', 'open'); + } + + if (requiredText !== null) verificationInput.focus(); + else if (mode === 'confirm') cancelButton.focus(); + else confirmButton.focus(); + }); + } + + function requestConfirmation(options) { + return show(options, 'confirm'); + } + + function showAlert(options) { + return show(options, 'alert').then(function () { return undefined; }); + } + + function focusableControls() { + return [closeButton, verification.hidden ? null : verificationInput, + cancelButton.hidden ? null : cancelButton, confirmButton] + .filter(function (control) { return control && !control.disabled && !control.hidden; }); + } + + if (canOpen()) { + closeButton.addEventListener('click', function () { settle(false); }); + cancelButton.addEventListener('click', function () { settle(false); }); + verificationInput.addEventListener('input', updateVerification); + form.addEventListener('submit', function (event) { + event.preventDefault(); + if (activeRequest && activeRequest.requiredText !== null && !matchesRequiredText()) return; + settle(true); + }); + dialog.addEventListener('cancel', function (event) { + event.preventDefault(); + settle(false); + }); + dialog.addEventListener('close', function () { + if (ignoredCloseEvents > 0) { + ignoredCloseEvents -= 1; + return; + } + settle(false); + }); + dialog.addEventListener('click', function (event) { + if (event.target === dialog) settle(false); + }); + dialog.addEventListener('keydown', function (event) { + if (event.key === 'Escape') { + event.preventDefault(); + settle(false); + return; + } + if (!fallbackMode || event.key !== 'Tab') return; + var controls = focusableControls(); + if (controls.length === 0) return; + var first = controls[0]; + var last = controls[controls.length - 1]; + if (event.shiftKey && document.activeElement === first) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } + }); + } + + window.VenixDialog = Object.freeze({ + confirm: requestConfirmation, + alert: showAlert + }); +}()); diff --git a/web/public/theme/venix/js/fuck.js b/web/public/theme/venix/js/fuck.js index 1d232937..442a2eca 100644 --- a/web/public/theme/venix/js/fuck.js +++ b/web/public/theme/venix/js/fuck.js @@ -98,6 +98,27 @@ })); // 判断 360 浏览器跳转 if (new Browser().browser == '360' || new Browser().browser == '360EE' || new Browser().browser == '360SE') { - window.alert('我们禁止您使用 360 浏览器访问本站,我们要求您通过 Chrome 或 Firefox 浏览器访问本站。\n点击确定后将会跳转至 Chrome 浏览器下载'); - window.location.href='https://chrome-dl.com'; + var blockedBrowserMessage = '本站不支持 360 浏览器,请改用 Chrome 或 Firefox。关闭提示后将跳转至 Chrome 浏览器下载页面。'; + var redirectToChrome = function () { + window.location.href = 'https://chrome-dl.com'; + }; + var showBlockedBrowserNotice = function () { + if (window.VenixDialog && window.VenixDialog.alert) { + window.VenixDialog.alert({ + title: '浏览器不受支持', + message: blockedBrowserMessage, + confirmText: '前往下载', + tone: 'warning' + }).then(redirectToChrome, redirectToChrome); + return; + } + var notice = document.createElement('div'); + notice.setAttribute('role', 'alert'); + notice.textContent = blockedBrowserMessage; + notice.style.cssText = 'position:fixed;left:50%;top:24px;z-index:10000;max-width:520px;transform:translateX(-50%);padding:14px 18px;border:1px solid #efd7a4;border-radius:10px;background:#fff8e8;color:#77531e;box-shadow:0 12px 36px rgba(16,29,44,.18);font:14px/1.7 sans-serif'; + document.body.appendChild(notice); + window.setTimeout(redirectToChrome, 3000); + }; + if (document.body) showBlockedBrowserNotice(); + else document.addEventListener('DOMContentLoaded', showBlockedBrowserNotice, { once: true }); } diff --git a/web/public/theme/venix/js/recharge.js b/web/public/theme/venix/js/recharge.js index 70ab06ab..1da1f731 100644 --- a/web/public/theme/venix/js/recharge.js +++ b/web/public/theme/venix/js/recharge.js @@ -46,7 +46,14 @@ if (window.VuModal && window.VuModal.alert) { return window.VuModal.alert(message, type || "success", title); } - window.alert(message); + var host = topWindow(); + if (host.VenixDialog && host.VenixDialog.alert) { + return host.VenixDialog.alert({ + title: title || (type === "error" ? "操作失败" : "操作提示"), + message: message, + tone: type === "error" ? "danger" : type === "success" ? "success" : "info" + }); + } return Promise.resolve(); } diff --git a/web/public/theme/venix/js/ticket-page.js b/web/public/theme/venix/js/ticket-page.js index 99c9ca23..6f1e4803 100644 --- a/web/public/theme/venix/js/ticket-page.js +++ b/web/public/theme/venix/js/ticket-page.js @@ -70,7 +70,13 @@ if (window.VuModal && window.VuModal.alert) { return window.VuModal.alert(message, type, title); } - window.alert(message); + if (window.VenixDialog && window.VenixDialog.alert) { + return window.VenixDialog.alert({ + title: title || (type === "error" ? "操作失败" : "操作提示"), + message: message, + tone: type === "error" ? "danger" : type === "success" ? "success" : "info" + }); + } return Promise.resolve(); } diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 289dfa3f..ca416d99 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026102003' scope='global'} +{assign var=venix_asset_version value='2026102004' scope='global'} diff --git a/web/resources/views/venix/user/dialog.tpl b/web/resources/views/venix/user/dialog.tpl new file mode 100644 index 00000000..4c463be4 --- /dev/null +++ b/web/resources/views/venix/user/dialog.tpl @@ -0,0 +1,22 @@ + +
+
+ +
+ 操作确认 +

确认操作

+

+
+ +
+ +
+ + +
+
+
diff --git a/web/resources/views/venix/user/panel_topbar.tpl b/web/resources/views/venix/user/panel_topbar.tpl index 5b2ed18d..13e1396b 100644 --- a/web/resources/views/venix/user/panel_topbar.tpl +++ b/web/resources/views/venix/user/panel_topbar.tpl @@ -25,6 +25,8 @@ {/if} +{include file='user/dialog.tpl'} + {if empty($smarty.get.drawer)} {if $panel_cloud_mode}{include file='user/task_center_drawer.tpl'}{/if} diff --git a/web/tests/UserDialogBehaviorTest.mjs b/web/tests/UserDialogBehaviorTest.mjs new file mode 100644 index 00000000..f0334785 --- /dev/null +++ b/web/tests/UserDialogBehaviorTest.mjs @@ -0,0 +1,524 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import vm from 'node:vm'; + +// Exercise the shipped classic script through its public browser API. The +// lightweight DOM keeps this test dependency-free while preserving dialog, +// focus, event and timer behaviour that callers observe. +const source = await readFile( + new URL('../public/cloud/user-dialog.js', import.meta.url), + 'utf8', +); + +class FakeEvent { + constructor(type, fields = {}) { + this.type = type; + this.bubbles = fields.bubbles ?? false; + this.cancelable = fields.cancelable ?? false; + this.defaultPrevented = false; + this.target = fields.target ?? null; + this.currentTarget = null; + Object.assign(this, fields); + } + + preventDefault() { + if (this.cancelable) this.defaultPrevented = true; + } + + stopPropagation() { this.cancelBubble = true; } +} + +class FakeNode { + constructor(tag = 'div', documentRef = null) { + this.tagName = String(tag).toUpperCase(); + this.ownerDocument = documentRef; + this.parentNode = null; + this.children = []; + this.listeners = new Map(); + this.attributes = new Map(); + this.dataset = {}; + this.hidden = false; + this.disabled = false; + this.open = false; + this.value = ''; + this.returnValue = ''; + this.type = ''; + this.name = ''; + this._text = ''; + this._innerHTML = ''; + this.innerHTMLWrites = []; + this.focusCount = 0; + this.style = { + values: new Map(), + setProperty: (name, value) => this.style.values.set(name, String(value)), + removeProperty: name => this.style.values.delete(name), + }; + const classes = new Set(); + this.classList = { + add: (...names) => names.forEach(name => classes.add(name)), + remove: (...names) => names.forEach(name => classes.delete(name)), + contains: name => classes.has(name), + toggle: (name, force) => { + const next = force === undefined ? !classes.has(name) : Boolean(force); + if (next) classes.add(name); else classes.delete(name); + return next; + }, + }; + } + + set id(value) { this.setAttribute('id', value); } + get id() { return this.getAttribute('id') || ''; } + set className(value) { + this.setAttribute('class', value); + for (const name of String(value).split(/\s+/).filter(Boolean)) this.classList.add(name); + } + get className() { return this.getAttribute('class') || ''; } + set textContent(value) { + this._text = String(value ?? ''); + this.children.forEach(child => { child.parentNode = null; }); + this.children = []; + } + get textContent() { + return this._text + this.children.map(child => child.textContent).join(''); + } + set innerHTML(value) { + const next = String(value ?? ''); + this.innerHTMLWrites.push(next); + this._innerHTML = next; + this._text = ''; + this.children.forEach(child => { child.parentNode = null; }); + this.children = []; + } + get innerHTML() { return this._innerHTML; } + get isConnected() { + let current = this; + while (current) { + if (current === this.ownerDocument?.documentElement) return true; + current = current.parentNode; + } + return false; + } + + append(...children) { + children.forEach(child => { + if (child === null || child === undefined) return; + const node = typeof child === 'object' + ? child : this.ownerDocument.createTextNode(String(child)); + node.parentNode = this; + this.children.push(node); + }); + } + + appendChild(child) { this.append(child); return child; } + replaceChildren(...children) { + this._text = ''; + this.children.forEach(child => { child.parentNode = null; }); + this.children = []; + this.append(...children); + } + remove() { + if (!this.parentNode) return; + this.parentNode.children = this.parentNode.children.filter(child => child !== this); + this.parentNode = null; + } + contains(candidate) { + if (candidate === this) return true; + return this.children.some(child => child.contains?.(candidate)); + } + + setAttribute(name, value) { + this.attributes.set(String(name), String(value)); + if (name === 'hidden') this.hidden = true; + if (name === 'disabled') this.disabled = true; + } + getAttribute(name) { return this.attributes.get(String(name)) ?? null; } + hasAttribute(name) { return this.attributes.has(String(name)); } + removeAttribute(name) { + this.attributes.delete(String(name)); + if (name === 'hidden') this.hidden = false; + if (name === 'disabled') this.disabled = false; + } + + addEventListener(type, listener, options = {}) { + const entries = this.listeners.get(type) || []; + entries.push({ listener, once: options === true || options?.once === true }); + this.listeners.set(type, entries); + } + removeEventListener(type, listener) { + this.listeners.set(type, + (this.listeners.get(type) || []).filter(entry => entry.listener !== listener)); + } + dispatchEvent(event) { + if (!(event instanceof FakeEvent)) throw new TypeError('Expected FakeEvent.'); + if (!event.target) event.target = this; + let current = this; + while (current) { + event.currentTarget = current; + const entries = [...(current.listeners.get(event.type) || [])]; + for (const entry of entries) { + entry.listener.call(current, event); + if (entry.once) current.removeEventListener(event.type, entry.listener); + } + if (!event.bubbles || event.cancelBubble) break; + current = current.parentNode; + } + return !event.defaultPrevented; + } + dispatch(type, fields = {}) { + return this.dispatchEvent(new FakeEvent(type, { + bubbles: fields.bubbles ?? true, + cancelable: fields.cancelable ?? true, + ...fields, + })); + } + click() { + if (this.disabled) return; + const allowed = this.dispatch('click'); + if (!allowed || this.tagName !== 'BUTTON' || this.type !== 'submit') return; + const form = this.closest('form'); + if (!form) return; + const submitted = form.dispatch('submit', { target: form, submitter: this }); + if (!submitted || form.getAttribute('method') !== 'dialog') return; + form.closest('dialog')?.close(this.value); + } + + closest(selector) { + let current = this; + while (current) { + if (current.matches(selector)) return current; + current = current.parentNode; + } + return null; + } + matches(selector) { + if (selector.startsWith('#')) return this.id === selector.slice(1); + if (selector.startsWith('.')) return this.classList.contains(selector.slice(1)); + return this.tagName === String(selector).toUpperCase(); + } + querySelector(selector) { + for (const child of this.children) { + if (child.matches?.(selector)) return child; + const nested = child.querySelector?.(selector); + if (nested) return nested; + } + return null; + } + + focus(options) { + this.focusCount += 1; + this.lastFocusOptions = options; + if (this.ownerDocument) this.ownerDocument.activeElement = this; + } + showModal() { this.open = true; this.setAttribute('open', ''); } + close(returnValue = '') { + if (!this.open) return; + this.returnValue = String(returnValue); + this.open = false; + this.removeAttribute('open'); + const notify = () => this.dispatch('close', { bubbles: false, cancelable: false }); + if (typeof this.ownerDocument?.queueTask === 'function') this.ownerDocument.queueTask(notify); + else notify(); + } + reset() { + const resetNode = node => { + if (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA') node.value = ''; + node.children.forEach(resetNode); + }; + resetNode(this); + } + setCustomValidity(message) { this.validationMessage = String(message); } + getBoundingClientRect() { + return { left: 100, top: 100, right: 600, bottom: 500, width: 500, height: 400 }; + } +} + +class FakeDocument extends FakeNode { + constructor() { + super('#document'); + this.ownerDocument = this; + this.readyState = 'complete'; + this.documentElement = new FakeNode('html', this); + this.body = new FakeNode('body', this); + this.documentElement.append(this.body); + this.activeElement = this.body; + } + + createElement(tag) { return new FakeNode(tag, this); } + createTextNode(value) { + const node = new FakeNode('#text', this); + node._text = String(value); + return node; + } + getElementById(id) { + const visit = node => { + if (node.id === id) return node; + for (const child of node.children) { + const match = visit(child); + if (match) return match; + } + return null; + }; + return visit(this.documentElement); + } + querySelector(selector) { + if (selector.startsWith('#')) return this.getElementById(selector.slice(1)); + return null; + } +} + +const flush = async () => { + for (let turn = 0; turn < 16; turn += 1) await Promise.resolve(); +}; + +function appendDialogMarkup(document) { + const element = (tag, id) => { + const node = document.createElement(tag); + node.id = id; + return node; + }; + const dialog = element('dialog', 'panel-user-dialog'); + const form = element('form', 'panel-user-dialog-form'); + const title = element('h2', 'panel-user-dialog-title'); + const message = element('p', 'panel-user-dialog-message'); + const kicker = document.createElement('span'); + kicker.className = 'panel-user-dialog-kicker'; + const close = element('button', 'panel-user-dialog-close'); + const cancel = element('button', 'panel-user-dialog-cancel'); + const confirm = element('button', 'panel-user-dialog-confirm'); + const verification = element('div', 'panel-user-dialog-verification'); + const input = element('input', 'panel-user-dialog-verification-input'); + const label = element('label', 'panel-user-dialog-verification-label'); + const hint = element('p', 'panel-user-dialog-verification-hint'); + + form.setAttribute('method', 'dialog'); + close.type = 'button'; + cancel.type = 'button'; + confirm.type = 'submit'; + verification.hidden = true; + verification.append(label, input, hint); + form.append(close, kicker, title, message, verification, cancel, confirm); + dialog.append(form); + document.body.append(dialog); +} + +function fixture() { + const document = new FakeDocument(); + appendDialogMarkup(document); + let now = 0; + let timerSequence = 0; + const timers = new Map(); + const setTimeout = (callback, delay = 0) => { + const id = ++timerSequence; + timers.set(id, { callback, due: now + Math.max(0, Number(delay) || 0) }); + return id; + }; + const clearTimeout = id => timers.delete(id); + document.queueTask = callback => setTimeout(callback, 0); + const window = new FakeNode('#window', document); + Object.assign(window, { + window, + self: window, + document, + Event: FakeEvent, + CustomEvent: FakeEvent, + Element: FakeNode, + HTMLElement: FakeNode, + HTMLDialogElement: FakeNode, + setTimeout, + clearTimeout, + requestAnimationFrame: callback => setTimeout(callback, 16), + cancelAnimationFrame: clearTimeout, + console, + }); + vm.runInNewContext(source, window, { filename: 'user-dialog.js' }); + document.dispatch('DOMContentLoaded', { bubbles: false, cancelable: false }); + + const byId = id => { + const node = document.getElementById(id); + assert.ok(node, `Missing dialog element #${id}.`); + return node; + }; + return { + window, + document, + byId, + async advance(milliseconds) { + const end = now + milliseconds; + let turns = 0; + while (true) { + const next = [...timers.entries()] + .filter(([, timer]) => timer.due <= end) + .sort((left, right) => left[1].due - right[1].due)[0]; + if (!next) break; + assert.ok(turns++ < 1000, 'Dialog scheduled an unbounded timer loop.'); + now = next[1].due; + timers.delete(next[0]); + next[1].callback(); + await flush(); + } + now = end; + await flush(); + }, + }; +} + +function tracked(promise) { + const outcome = { settled: false, rejected: false, value: undefined }; + promise.then( + value => { outcome.settled = true; outcome.value = value; }, + error => { outcome.settled = true; outcome.rejected = true; outcome.value = error; }, + ); + return outcome; +} + +async function expectResolution(test, promise, expected) { + const outcome = tracked(promise); + await test.advance(1000); + assert.equal(outcome.settled, true, 'Dialog promise did not settle after a user decision.'); + assert.equal(outcome.rejected, false, 'Dialog user decisions must not reject.'); + assert.equal(outcome.value, expected); +} + +// A normal confirmation remains pending until the user decides, starts on the +// safe action, resolves true on confirmation, and restores its opener. +{ + const test = fixture(); + assert.equal(typeof test.window.VenixDialog?.confirm, 'function'); + assert.equal(typeof test.window.VenixDialog?.alert, 'function'); + const opener = test.document.createElement('button'); + test.document.body.append(opener); + opener.focus(); + const promise = test.window.VenixDialog.confirm({ + title: '强制断电', + message: '此操作可能导致未保存的数据丢失。', + confirmText: '继续操作', + cancelText: '取消', + }); + const outcome = tracked(promise); + await test.advance(600_000); + assert.equal(outcome.settled, false, 'A confirmation must not auto-dismiss on a timer.'); + assert.equal(test.byId('panel-user-dialog').open, true); + assert.equal(test.document.activeElement, test.byId('panel-user-dialog-cancel')); + test.byId('panel-user-dialog-confirm').click(); + await expectResolution(test, promise, true); + assert.equal(test.document.activeElement, opener, 'Closing must restore focus to the opener.'); +} + +// Every non-confirming exit fails closed, including Cancel, the close button, +// Escape, and an actual backdrop click. A click inside the panel is inert. +for (const exit of ['cancel', 'close', 'escape', 'backdrop']) { + const test = fixture(); + const opener = test.document.createElement('button'); + test.document.body.append(opener); + opener.focus(); + const promise = test.window.VenixDialog.confirm({ title: '删除快照', message: '删除后无法恢复。' }); + await test.advance(0); + const dialog = test.byId('panel-user-dialog'); + if (exit === 'cancel') test.byId('panel-user-dialog-cancel').click(); + if (exit === 'close') test.byId('panel-user-dialog-close').click(); + if (exit === 'escape') dialog.dispatch('cancel', { bubbles: false, cancelable: true }); + if (exit === 'backdrop') { + dialog.dispatch('click', { target: test.byId('panel-user-dialog-form') }); + await flush(); + assert.equal(dialog.open, true, 'Clicks inside the dialog must not cancel it.'); + dialog.dispatch('click', { target: dialog }); + } + await expectResolution(test, promise, false); + assert.equal(test.document.activeElement, opener, `${exit} must restore focus to the opener.`); +} + +// Typed destructive confirmation is exact and literal. User-controlled copy is +// rendered as text, while the action stays unavailable until a strict match. +{ + const test = fixture(); + const unsafeTitle = ' 删除实例'; + const unsafeMessage = ' 请输入完整实例名称。'; + const expectedName = 'Prod-VM<&>01'; + const promise = test.window.VenixDialog.confirm({ + title: unsafeTitle, + message: unsafeMessage, + requiredText: expectedName, + confirmText: '永久删除', + }); + await test.advance(0); + const title = test.byId('panel-user-dialog-title'); + const message = test.byId('panel-user-dialog-message'); + const verification = test.byId('panel-user-dialog-verification'); + const input = test.byId('panel-user-dialog-verification-input'); + const confirm = test.byId('panel-user-dialog-confirm'); + assert.equal(title.textContent, unsafeTitle); + assert.equal(message.textContent, unsafeMessage); + assert.equal(verification.hidden, false); + assert.equal(input.getAttribute('aria-required'), 'true'); + assert.equal(input.hasAttribute('required'), true); + assert.equal(confirm.disabled, true); + assert.ok(![...title.innerHTMLWrites, ...message.innerHTMLWrites] + .some(value => value.includes(unsafeTitle) || value.includes(unsafeMessage)), + 'Dynamic dialog copy must never be assigned through innerHTML.'); + + for (const mismatch of ['prod-vm<&>01', `${expectedName} `, ` ${expectedName}`]) { + input.value = mismatch; + input.dispatch('input'); + assert.equal(confirm.disabled, true, `Non-exact value ${JSON.stringify(mismatch)} enabled deletion.`); + assert.equal(input.getAttribute('aria-invalid'), 'true'); + assert.match(test.byId('panel-user-dialog-verification-hint').textContent, /名称不匹配/); + } + input.value = expectedName; + input.dispatch('input'); + assert.equal(confirm.disabled, false); + assert.equal(input.getAttribute('aria-invalid'), 'false'); + assert.match(test.byId('panel-user-dialog-verification-hint').textContent, /名称已匹配/); + confirm.click(); + await expectResolution(test, promise, true); +} + +// A second concurrent request must fail closed without replacing or resolving +// the active confirmation. +{ + const test = fixture(); + const first = test.window.VenixDialog.confirm({ title: '第一项操作', message: '保持可见。' }); + await test.advance(0); + const firstOutcome = tracked(first); + const second = test.window.VenixDialog.confirm({ title: '第二项操作', message: '不得覆盖第一项。' }); + await expectResolution(test, second, false); + assert.equal(firstOutcome.settled, false); + assert.equal(test.byId('panel-user-dialog-title').textContent, '第一项操作'); + assert.equal(test.byId('panel-user-dialog').open, true); + test.byId('panel-user-dialog-cancel').click(); + await expectResolution(test, first, false); +} + +// Browsers queue the close event from dialog.close(). A stale close event from +// the previous decision must not cancel a dialog opened immediately afterward. +{ + const test = fixture(); + const first = test.window.VenixDialog.confirm({ title: '第一项操作', message: '立即确认。' }); + const firstOutcome = tracked(first); + test.byId('panel-user-dialog-confirm').click(); + await flush(); + assert.equal(firstOutcome.settled, true); + assert.equal(firstOutcome.value, true); + + const second = test.window.VenixDialog.confirm({ title: '第二项操作', message: '必须保持打开。' }); + const secondOutcome = tracked(second); + await test.advance(0); + assert.equal(secondOutcome.settled, false, 'A stale close event cancelled the next dialog.'); + assert.equal(test.byId('panel-user-dialog').open, true); + assert.equal(test.byId('panel-user-dialog-title').textContent, '第二项操作'); + test.byId('panel-user-dialog-cancel').click(); + await expectResolution(test, second, false); +} + +// Alerts share the in-product surface, resolve with no value, and never invoke +// a browser-native acknowledgement dialog. +{ + const test = fixture(); + const promise = test.window.VenixDialog.alert({ title: '操作完成', message: '任务已提交。' }); + await test.advance(0); + assert.equal(test.byId('panel-user-dialog-title').textContent, '操作完成'); + assert.equal(test.byId('panel-user-dialog-message').textContent, '任务已提交。'); + test.byId('panel-user-dialog-confirm').click(); + await expectResolution(test, promise, undefined); +} + +console.log('User dialog behavior checks passed.'); diff --git a/web/tests/UserNativeDialogContractTest.php b/web/tests/UserNativeDialogContractTest.php new file mode 100644 index 00000000..eaf82991 --- /dev/null +++ b/web/tests/UserNativeDialogContractTest.php @@ -0,0 +1,106 @@ + !str_starts_with(basename($path), 'admin') +)); + +foreach (['auth.js', 'user-home.js', 'ticket-page.js', 'recharge.js', 'fuck.js'] as $script) { + $files[] = $public . '/theme/venix/js/' . $script; +} + +foreach (['auth', 'cloud', 'home', 'password', 'user'] as $viewDirectory) { + $directory = $views . '/' . $viewDirectory; + if (!is_dir($directory)) { + continue; + } + + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS) + ); + foreach ($iterator as $file) { + if ($file->isFile() && $file->getExtension() === 'tpl') { + $files[] = $file->getPathname(); + } + } +} + +$violations = []; +$patterns = [ + '/\b(?:window|globalThis|self|top|parent)\s*\.\s*(?:alert|confirm|prompt)\s*\(/', + '/(? $call) { + $details[] = str_replace($root . '/', '', $location) . ' (' . $call . ')'; + } + throw new RuntimeException( + "Ordinary user pages still invoke browser-native dialogs:\n- " + . implode("\n- ", $details) + ); +} + +$topbar = file_get_contents($views . '/user/panel_topbar.tpl'); +$markup = file_get_contents($views . '/user/dialog.tpl'); +$runtime = file_get_contents($public . '/cloud/user-dialog.js'); +$styles = file_get_contents($public . '/cloud/client.css'); +$assets = file_get_contents($views . '/layout_assets.tpl'); +$entry = file_get_contents($public . '/cloud/app.js'); +foreach (compact('topbar', 'markup', 'runtime', 'styles', 'assets', 'entry') as $name => $source) { + $assert(is_string($source), 'Unable to read user dialog asset: ' . $name); +} + +$assert(str_contains($topbar, "{include file='user/dialog.tpl'}") + && str_contains($topbar, 'src="/cloud/user-dialog.js?v={$venix_asset_version'), + 'The shared user shell must mount the in-product dialog with the common cache key.'); +$assert(str_contains($markup, 'id="panel-user-dialog"') + && str_contains($markup, 'aria-labelledby="panel-user-dialog-title"') + && str_contains($markup, 'aria-describedby="panel-user-dialog-message panel-user-dialog-verification-hint"'), + 'The shared user dialog must expose an accessible name and description.'); +$assert(str_contains($runtime, 'window.VenixDialog = Object.freeze') + && str_contains($runtime, 'textContent =') + && !str_contains($runtime, 'innerHTML'), + 'The dialog API must render dynamic copy as text and expose the shared browser contract.'); +$assert(str_contains($styles, '.panel-user-dialog::backdrop') + && str_contains($styles, '.panel-user-dialog.is-dialog-fallback') + && str_contains($styles, '@media (prefers-reduced-motion: reduce)'), + 'The user dialog must retain a styled fallback and reduced-motion behavior.'); + +$assert(preg_match("/value='([0-9]+)'/", $assets, $assetMatch) === 1 + && preg_match('/task-center\\.js\\?v=([0-9]+)/', $entry, $entryMatch) === 1 + && $assetMatch[1] === $entryMatch[1], + 'The shared asset version and application module cache key must stay synchronized.'); + +echo "Ordinary user native-dialog boundary checks passed.\n";