NextChat-U/app/utils.ts

77 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-03-21 23:56:27 +09:00
import { showToast } from "./components/ui-lib";
import Locale from "./locales";
2023-03-21 01:17:45 +09:00
2023-03-11 03:25:33 +09:00
export function trimTopic(topic: string) {
2023-03-20 01:29:09 +09:00
const s = topic.split("");
2023-03-11 03:25:33 +09:00
let lastChar = s.at(-1); // 获取 s 的最后一个字符
let pattern = /[,。!?、]/; // 定义匹配中文标点符号的正则表达式
while (lastChar && pattern.test(lastChar!)) {
s.pop();
lastChar = s.at(-1);
}
return s.join("");
}
2023-03-16 02:24:03 +09:00
export function copyToClipboard(text: string) {
2023-03-21 23:56:27 +09:00
navigator.clipboard
.writeText(text)
.then((res) => {
showToast(Locale.Copy.Success);
})
.catch((err) => {
showToast(Locale.Copy.Failed);
});
2023-03-16 02:24:03 +09:00
}
export function downloadAs(text: string, filename: string) {
2023-03-21 23:56:27 +09:00
const element = document.createElement("a");
element.setAttribute(
"href",
"data:text/plain;charset=utf-8," + encodeURIComponent(text)
);
element.setAttribute("download", filename);
element.style.display = "none";
2023-03-16 02:24:03 +09:00
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
export function isIOS() {
const userAgent = navigator.userAgent.toLowerCase();
return /iphone|ipad|ipod/.test(userAgent);
2023-03-21 23:56:27 +09:00
}
export function selectOrCopy(el: HTMLElement, content: string) {
const currentSelection = window.getSelection();
if (currentSelection?.type === "Range") {
return false;
}
copyToClipboard(content);
return true;
}
2023-03-24 01:01:00 +09:00
let currentId: string;
export function getCurrentCommitId() {
if (currentId) {
return currentId;
}
if (document) {
const meta = document.head.querySelector(
"meta[name='version']"
) as HTMLMetaElement;
currentId = meta?.content ?? "";
} else {
currentId = process.env.COMMIT_ID ?? "";
}
return currentId;
}