NextChat-U/app/utils.ts

84 lines
1.8 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) {
return topic.replace(/[,。!?、,.!?]*$/, "");
2023-03-11 03:25:33 +09:00
}
2023-03-16 02:24:03 +09:00
2023-04-03 12:16:56 +09:00
export async function copyToClipboard(text: string) {
try {
await navigator.clipboard.writeText(text);
} catch (error) {
const textarea = document.createElement("textarea");
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
} finally {
showToast(Locale.Copy.Success);
}
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",
2023-03-30 18:55:19 +09:00
"data:text/plain;charset=utf-8," + encodeURIComponent(text),
2023-03-21 23:56:27 +09:00
);
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
}
2023-03-31 01:20:47 +09:00
export function isMobileScreen() {
return window.innerWidth <= 600;
}
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
export function queryMeta(key: string, defaultValue?: string): string {
let ret: string;
if (document) {
const meta = document.head.querySelector(
2023-03-30 18:55:19 +09:00
`meta[name='${key}']`,
) as HTMLMetaElement;
ret = meta?.content ?? "";
} else {
ret = defaultValue ?? "";
}
return ret;
}
2023-03-24 01:01:00 +09:00
let currentId: string;
2023-03-31 01:46:17 +09:00
export function getCurrentVersion() {
2023-03-24 01:01:00 +09:00
if (currentId) {
return currentId;
}
currentId = queryMeta("version");
2023-03-24 01:01:00 +09:00
return currentId;
}