Files
image-workbench-desktop/src/ui-confirm.js
T

69 lines
2.9 KiB
JavaScript
Raw 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.
/* ui-confirm.js —— 页内确认框(桌面端替代 window.confirm)
*
* 为什么需要:Tauri(WKWebView)里 window.confirm 会弹 macOS 原生框并**阻塞 WebView 主线程**,
* 用户点了按钮界面像死机(实测复现)。这里用 DOM 覆盖层实现同样的"确认/取消",
* 用 Promise 返回结果,调用方 await 即可。
*
* 网页端仍然用 window.confirm(行为零变化)。
*/
;(function (global) {
'use strict'
function ask (opts) {
const o = opts || {}
if (typeof document === 'undefined' || !document.body) return Promise.resolve(false)
return new Promise(function (resolve) {
const overlay = document.createElement('div')
overlay.className = 'iwb-confirm-overlay'
const box = document.createElement('div')
box.className = 'iwb-confirm-box'
const title = document.createElement('div')
title.className = 'iwb-confirm-title'
title.textContent = o.title || '确认'
const text = document.createElement('div')
text.className = 'iwb-confirm-text'
text.textContent = String(o.text || '')
const row = document.createElement('div')
row.className = 'iwb-confirm-actions'
const cancel = document.createElement('button')
cancel.className = 'iwb-btn iwb-btn-sm'
cancel.textContent = o.cancelText || '取消'
const ok = document.createElement('button')
ok.className = 'iwb-btn iwb-btn-sm iwb-btn-primary'
ok.textContent = o.okText || '确定'
let settled = false
function done (value) {
if (settled) return
settled = true
try { overlay.remove() } catch (e) { /* ignore */ }
resolve(value)
}
cancel.addEventListener('click', function () { done(false) })
ok.addEventListener('click', function () { done(true) })
overlay.addEventListener('click', function (e) { if (e.target === overlay) done(false) })
overlay.addEventListener('keydown', function (e) {
if (e.key === 'Escape') done(false)
if (e.key === 'Enter') done(true)
})
row.appendChild(cancel)
row.appendChild(ok)
box.appendChild(title)
box.appendChild(text)
box.appendChild(row)
overlay.appendChild(box)
document.body.appendChild(overlay)
setTimeout(function () { try { ok.focus() } catch (e) { /* ignore */ } }, 0)
})
}
// 统一入口:桌面端走页内确认;网页端保持原生 confirm(行为不变)
function askOrNative (text, opts) {
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
const native = !!(D && D.isTauri && D.isTauri())
if (native) return ask(Object.assign({ text: text }, opts || {}))
return Promise.resolve(typeof window !== 'undefined' ? window.confirm(String(text)) : false)
}
global.IWBUIConfirm = { ask: ask, askOrNative: askOrNative }
})(typeof window !== 'undefined' ? window : globalThis)