fix: replace native user action dialogs
parent
cea9e41f7f
commit
ca73a2d657
@ -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
|
||||
});
|
||||
}());
|
||||
@ -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'}
|
||||
|
||||
@ -0,0 +1,22 @@
|
||||
<dialog class="panel-user-dialog" id="panel-user-dialog" aria-modal="true" aria-labelledby="panel-user-dialog-title" aria-describedby="panel-user-dialog-message panel-user-dialog-verification-hint">
|
||||
<form class="panel-user-dialog-card" id="panel-user-dialog-form" method="dialog" novalidate>
|
||||
<div class="panel-user-dialog-header">
|
||||
<span class="panel-user-dialog-mark" aria-hidden="true"><i class="mdi mdi-shield-alert-outline"></i></span>
|
||||
<div class="panel-user-dialog-heading">
|
||||
<span class="panel-user-dialog-kicker">操作确认</span>
|
||||
<h2 id="panel-user-dialog-title">确认操作</h2>
|
||||
<p id="panel-user-dialog-message"></p>
|
||||
</div>
|
||||
<button class="panel-user-dialog-close" id="panel-user-dialog-close" type="button" aria-label="关闭弹窗"><i class="mdi mdi-close" aria-hidden="true"></i></button>
|
||||
</div>
|
||||
<div class="panel-user-dialog-verification" id="panel-user-dialog-verification" hidden>
|
||||
<label id="panel-user-dialog-verification-label" for="panel-user-dialog-verification-input">输入完整名称以确认</label>
|
||||
<input id="panel-user-dialog-verification-input" type="text" autocomplete="off" spellcheck="false" aria-describedby="panel-user-dialog-verification-hint"/>
|
||||
<small id="panel-user-dialog-verification-hint" aria-live="polite"></small>
|
||||
</div>
|
||||
<div class="panel-user-dialog-actions">
|
||||
<button class="button button-outline" id="panel-user-dialog-cancel" type="button">取消</button>
|
||||
<button class="button button-primary" id="panel-user-dialog-confirm" type="submit">确认</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
@ -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 = '<img src=x onerror=alert(1)> 删除实例';
|
||||
const unsafeMessage = '<script>window.pwned=1</script> 请输入完整实例名称。';
|
||||
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.');
|
||||
@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
// Ordinary user pages must keep confirmations and notices inside the product UI.
|
||||
// Administrator scripts and third-party assets are intentionally outside this scope.
|
||||
$root = dirname(__DIR__);
|
||||
$public = $root . '/public';
|
||||
$views = $root . '/resources/views/venix';
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$files = glob($public . '/cloud/*.js') ?: [];
|
||||
$files = array_values(array_filter(
|
||||
$files,
|
||||
static fn (string $path): bool => !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*\(/',
|
||||
'/(?<![A-Za-z0-9_$.])\b(?:alert|confirm|prompt)\s*\(/',
|
||||
'/\bonbeforeunload\b/',
|
||||
'/addEventListener\s*\(\s*[\'\"]beforeunload[\'\"]/',
|
||||
];
|
||||
|
||||
foreach (array_unique($files) as $path) {
|
||||
$source = file_get_contents($path);
|
||||
if (!is_string($source)) {
|
||||
throw new RuntimeException('Unable to read ' . $path);
|
||||
}
|
||||
|
||||
foreach ($patterns as $pattern) {
|
||||
if (preg_match_all($pattern, $source, $matches, PREG_OFFSET_CAPTURE) !== false) {
|
||||
foreach ($matches[0] as [$match, $offset]) {
|
||||
$line = substr_count(substr($source, 0, $offset), "\n") + 1;
|
||||
$violations[$path . ':' . $line] = trim($match);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($violations !== []) {
|
||||
$details = [];
|
||||
foreach ($violations as $location => $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";
|
||||
Loading…
Reference in New Issue