Files
2026-08-08 18:28:49 +08:00

108 lines
3.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* csp_global.js — MES2 全局事件委托脚本
*
* 设计目标:在「无 'unsafe-inline' / 无 'unsafe-eval'」的严格 CSP 下,
* 彻底替代原有的内联事件处理器(onclick / onchange / onsubmit / oninput)。
*
* 两种迁移方式(均不使用 eval,符合严格 CSP):
* 1) 语义类(来自早期批次改造)
* - a.confirm-link[data-confirm] : 点击前 confirm 确认
* - form.confirm-form[data-confirm] : 提交前 confirm 确认
* - .station-card[data-href] : 卡片点击跳转(仅当带 data-href)
* - select.auto-submit : 变更即提交所在表单
* 2) 函数委托(用于动态生成的复杂处理器)
* - [data-action="fnName" data-args='[...]'] : 调用 window.fnName(...args)
* - [data-action-el="fnName" data-args='[...]'] : 调用 window.fnName(el, ...args)
* data-action-el 会把触发元素 el 作为第一个参数传入,
* 便于处理器读取 el.value / el.checked 等动态值)
*
* 注意:所有被调用的函数(addField、updateFieldsConfig、openEditModal …)
* 必须由对应视图 / 辅助文件的「带 nonce 的 <script>」定义为全局函数。
*/
(function () {
'use strict';
// ---------- 1) 语义类处理器 ----------
// 确认型链接
document.addEventListener('click', function (e) {
var a = e.target.closest('a.confirm-link');
if (a) {
var msg = a.getAttribute('data-confirm') || '确定执行该操作?';
if (!window.confirm(msg)) {
e.preventDefault();
}
}
});
// 确认型表单
document.addEventListener('submit', function (e) {
var form = e.target;
if (form && form.classList && form.classList.contains('confirm-form')) {
var msg = form.getAttribute('data-confirm') || '确定执行该操作?';
if (!window.confirm(msg)) {
e.preventDefault();
}
}
});
// 工位卡片导航(仅当卡片带有 data-href 时才拦截跳转,避免影响未改造的普通 <a> 卡片)
document.addEventListener('click', function (e) {
var card = e.target.closest('.station-card[data-href]');
if (card) {
e.preventDefault();
var href = card.getAttribute('data-href');
if (href) {
window.location.href = href;
}
}
});
// 自动提交
document.addEventListener('change', function (e) {
var el = e.target;
if (el && el.classList && el.classList.contains('auto-submit') && el.form) {
el.form.submit();
}
});
// ---------- 2) 函数委托处理器 ----------
function fire(el, attr, withEl) {
var name = el.getAttribute(attr);
if (!name) return;
var fn = window[name];
if (typeof fn !== 'function') {
if (window.console) console.warn('[csp_global] 未找到全局函数: ' + name);
return;
}
var args = [];
var aj = el.getAttribute('data-args');
if (aj) {
try { args = JSON.parse(aj); } catch (_) { args = []; }
}
if (withEl) {
fn.apply(null, [el].concat(args));
} else {
fn.apply(null, args);
}
}
function delegate(evt) {
document.addEventListener(evt, function (e) {
var el = e.target.closest('[data-action],[data-action-el]');
if (!el) return;
if (el.hasAttribute('data-action-el')) {
fire(el, 'data-action-el', true);
} else {
fire(el, 'data-action', false);
}
});
}
delegate('click');
delegate('change');
delegate('submit');
delegate('input');
})();