Files
2026-11-02 16:01:16 +08:00

266 lines
7.2 KiB
JavaScript

/* ============================================================
功能工具箱 · 共享脚本
主题同步 / Toast / 剪贴板 / 格式化工具
============================================================ */
(function () {
"use strict";
var THEME_KEY = "toolbox-theme";
var root = document.documentElement;
function readStoredTheme() {
try {
var value = localStorage.getItem(THEME_KEY);
return value === "light" || value === "dark" ? value : null;
} catch (error) {
return null;
}
}
function systemTheme() {
return window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
function applyTheme(theme, persist) {
if (theme !== "light" && theme !== "dark") return;
root.dataset.theme = theme;
root.style.colorScheme = theme;
if (persist) {
try {
localStorage.setItem(THEME_KEY, theme);
} catch (error) {
/* 忽略隐私模式下的写入失败 */
}
}
window.dispatchEvent(
new CustomEvent("toolbox:themechange", { detail: { theme: theme } }),
);
}
function currentTheme() {
return root.dataset.theme === "dark" ? "dark" : "light";
}
function toggleTheme() {
var next = currentTheme() === "dark" ? "light" : "dark";
applyTheme(next, true);
return next;
}
// 首次渲染前应用主题,避免闪烁
applyTheme(readStoredTheme() || systemTheme(), false);
// 跟随系统主题(用户未手动选择时)
if (window.matchMedia) {
var media = window.matchMedia("(prefers-color-scheme: dark)");
var onSystemChange = function (event) {
if (!readStoredTheme()) {
applyTheme(event.matches ? "dark" : "light", false);
}
};
if (media.addEventListener) {
media.addEventListener("change", onSystemChange);
} else if (media.addListener) {
media.addListener(onSystemChange);
}
}
// 同一个页面内(父页面 / iframe)的主题同步
window.addEventListener("storage", function (event) {
if (event.key === THEME_KEY && event.newValue) {
applyTheme(event.newValue, false);
}
});
/* ---------- Toast ---------- */
function toastContainer() {
var el = document.querySelector(".toast-wrap");
if (!el) {
el = document.createElement("div");
el.className = "toast-wrap";
document.body.appendChild(el);
}
return el;
}
function toast(message, type) {
if (!document.body) return;
type = type || "info";
var el = document.createElement("div");
el.className = "toast toast--" + type;
el.setAttribute("role", "status");
el.setAttribute("aria-live", "polite");
var icon = document.createElement("span");
icon.className = "toast-icon";
icon.textContent = type === "success" ? "✓" : type === "error" ? "!" : "i";
var text = document.createElement("span");
text.textContent = message;
el.appendChild(icon);
el.appendChild(text);
toastContainer().appendChild(el);
requestAnimationFrame(function () {
el.classList.add("show");
});
setTimeout(function () {
el.classList.remove("show");
setTimeout(function () {
el.remove();
}, 220);
}, 2400);
}
/* ---------- 剪贴板 ---------- */
function legacyCopy(text) {
return new Promise(function (resolve, reject) {
try {
var area = document.createElement("textarea");
area.value = text;
area.style.position = "fixed";
area.style.top = "-9999px";
area.style.opacity = "0";
document.body.appendChild(area);
area.focus();
area.select();
var ok = document.execCommand("copy");
document.body.removeChild(area);
ok ? resolve() : reject(new Error("copy failed"));
} catch (error) {
reject(error);
}
});
}
function copyText(text) {
text = String(text == null ? "" : text);
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text).catch(function () {
// iframe 或权限受限时回退到 execCommand
return legacyCopy(text);
});
}
return legacyCopy(text);
}
function copyWithToast(text, message) {
return copyText(text)
.then(function () {
toast(message || "已复制到剪贴板", "success");
return true;
})
.catch(function () {
toast("复制失败,请手动选择复制", "error");
return false;
});
}
/* ---------- 格式化工具 ---------- */
function formatBytes(bytes, decimals) {
bytes = Number(bytes) || 0;
if (bytes <= 0) return "0 B";
var k = 1024;
var sizes = ["B", "KB", "MB", "GB", "TB"];
var i = Math.min(
Math.floor(Math.log(bytes) / Math.log(k)),
sizes.length - 1,
);
var value = bytes / Math.pow(k, i);
return (
parseFloat(value.toFixed(decimals == null ? 1 : decimals)) +
" " +
sizes[i]
);
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, function (char) {
return {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
}[char];
});
}
function debounce(fn, wait) {
var timer = null;
return function () {
var args = arguments;
var context = this;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, wait);
};
}
/* ---------- 初始化 ---------- */
function initThemeButtons() {
var buttons = document.querySelectorAll("[data-theme-toggle]");
Array.prototype.forEach.call(buttons, function (button) {
if (button.dataset.themeBound === "1") return;
button.dataset.themeBound = "1";
button.addEventListener("click", function () {
toggleTheme();
});
});
}
// 声明式复制按钮:
// data-copy-text="要复制的文本"
// data-copy-target="#elementId" (复制该元素 textContent)
function initCopyButtons() {
if (document.body.dataset.copyBound === "1") return;
document.body.dataset.copyBound = "1";
document.addEventListener("click", function (event) {
var button = event.target.closest("[data-copy-text],[data-copy-target]");
if (!button) return;
var text = button.dataset.copyText;
if (text == null && button.dataset.copyTarget) {
var target = document.querySelector(button.dataset.copyTarget);
text = target ? target.textContent : "";
}
if (!text) return;
event.preventDefault();
copyWithToast(text, button.dataset.copyMessage);
});
}
document.addEventListener("DOMContentLoaded", function () {
initThemeButtons();
initCopyButtons();
});
window.Toolbox = {
theme: currentTheme,
setTheme: function (theme) {
applyTheme(theme, true);
},
toggleTheme: toggleTheme,
onThemeChange: function (callback) {
window.addEventListener("toolbox:themechange", function (event) {
callback(event.detail.theme);
});
},
toast: toast,
copy: copyText,
copyWithToast: copyWithToast,
formatBytes: formatBytes,
escapeHtml: escapeHtml,
debounce: debounce,
};
})();