Files
workspace/code/email/Email-Vue/src/utils/common.ts
T
2025-06-10 21:27:20 +08:00

78 lines
1.8 KiB
TypeScript
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.
import { Message } from "@arco-design/web-vue";
/**
* 复制文本到剪切板
* @param text 复制内容
* @returns 是否复制成功
*/
export function copyText(text: string) {
if (navigator.clipboard && window.isSecureContext) {
// 现代浏览器和安全环境下,直接用 Clipboard API
return navigator.clipboard
.writeText(text)
.then(() => {
Message.success("复制成功");
})
.catch((err) => {
Message.error("复制失败:" + err);
});
} else {
// 退回到传统方式
fallbackCopyText(text);
}
}
/**
* 复制文本到剪切板的传统方式
* @param text 复制内容
*/
function fallbackCopyText(text: string) {
const textArea = document.createElement("textarea");
textArea.value = text;
// 避免滚动到页面底部
textArea.style.position = "fixed";
textArea.style.top = "0";
textArea.style.left = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const successful = document.execCommand("copy");
if (successful) {
console.log("复制成功(fallback)");
} else {
console.log("复制失败(fallback)");
}
} catch (err) {
console.error("复制失败(fallback)", err);
}
document.body.removeChild(textArea);
}
export function formatFileSizeToString(size: number): string {
if (size < 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
let sizeD = size;
let unitIndex = 0;
while (sizeD >= 1024 && unitIndex < units.length - 1) {
sizeD /= 1024;
unitIndex++;
}
let formatted: string;
if (sizeD < 10) {
formatted = sizeD.toFixed(2);
} else if (sizeD < 100) {
formatted = sizeD.toFixed(1);
} else {
formatted = sizeD.toFixed(0);
}
return `${formatted} ${units[unitIndex]}`;
}