ChatGPT-Next-Web/app/utils.ts

95 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-04-05 07:48:44 +00:00
import { EmojiStyle } from "emoji-picker-react";
2023-03-21 14:56:27 +00:00
import { showToast } from "./components/ui-lib";
import Locale from "./locales";
2023-03-20 16:17:45 +00:00
2023-03-10 18:25:33 +00:00
export function trimTopic(topic: string) {
2023-04-05 17:22:29 +00:00
return topic.replace(/[,。!?”“"、,.!?]*$/, "");
2023-03-10 18:25:33 +00:00
}
2023-03-15 17:24:03 +00:00
2023-04-03 03:16:56 +00:00
export async function copyToClipboard(text: string) {
2023-04-04 18:49:44 +00:00
if (navigator.clipboard) {
navigator.clipboard.writeText(text).catch(err => {
console.error('Failed to copy: ', err);
});
} else {
const textArea = document.createElement('textarea');
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
console.log('Text copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
document.body.removeChild(textArea);
2023-04-03 03:16:56 +00:00
}
2023-03-15 17:24:03 +00:00
}
export function downloadAs(text: string, filename: string) {
2023-03-21 14:56:27 +00:00
const element = document.createElement("a");
element.setAttribute(
"href",
2023-03-30 09:55:19 +00:00
"data:text/plain;charset=utf-8," + encodeURIComponent(text),
2023-03-21 14:56:27 +00:00
);
element.setAttribute("download", filename);
element.style.display = "none";
2023-03-15 17:24:03 +00: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 14:56:27 +00:00
}
2023-03-30 16:20:47 +00:00
export function isMobileScreen() {
return window.innerWidth <= 600;
}
2023-03-21 14:56:27 +00:00
export function selectOrCopy(el: HTMLElement, content: string) {
const currentSelection = window.getSelection();
if (currentSelection?.type === "Range") {
return false;
}
copyToClipboard(content);
return true;
}
2023-03-23 16:01:00 +00:00
export function queryMeta(key: string, defaultValue?: string): string {
let ret: string;
if (document) {
const meta = document.head.querySelector(
2023-03-30 09:55:19 +00:00
`meta[name='${key}']`,
) as HTMLMetaElement;
ret = meta?.content ?? "";
} else {
ret = defaultValue ?? "";
}
return ret;
}
2023-03-23 16:01:00 +00:00
let currentId: string;
2023-03-30 16:46:17 +00:00
export function getCurrentVersion() {
2023-03-23 16:01:00 +00:00
if (currentId) {
return currentId;
}
currentId = queryMeta("version");
2023-03-23 16:01:00 +00:00
return currentId;
}
2023-04-05 07:48:44 +00:00
export function getEmojiUrl(unified: string, style: EmojiStyle) {
return `https://cdn.staticfile.org/emoji-datasource-apple/14.0.0/img/${style}/64/${unified}.png`;
}