utils.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { showToast } from "./components/ui-lib";
  2. import Locale from "./locales";
  3. export function trimTopic(topic: string) {
  4. return topic.replace(/[,。!?、,.!?]*$/, "");
  5. }
  6. export async function copyToClipboard(text: string) {
  7. try {
  8. await navigator.clipboard.writeText(text);
  9. } catch (error) {
  10. const textarea = document.createElement("textarea");
  11. textarea.value = text;
  12. document.body.appendChild(textarea);
  13. textarea.select();
  14. document.execCommand("copy");
  15. document.body.removeChild(textarea);
  16. } finally {
  17. showToast(Locale.Copy.Success);
  18. }
  19. }
  20. export function downloadAs(text: string, filename: string) {
  21. const element = document.createElement("a");
  22. element.setAttribute(
  23. "href",
  24. "data:text/plain;charset=utf-8," + encodeURIComponent(text),
  25. );
  26. element.setAttribute("download", filename);
  27. element.style.display = "none";
  28. document.body.appendChild(element);
  29. element.click();
  30. document.body.removeChild(element);
  31. }
  32. export function isIOS() {
  33. const userAgent = navigator.userAgent.toLowerCase();
  34. return /iphone|ipad|ipod/.test(userAgent);
  35. }
  36. export function isMobileScreen() {
  37. return window.innerWidth <= 600;
  38. }
  39. export function selectOrCopy(el: HTMLElement, content: string) {
  40. const currentSelection = window.getSelection();
  41. if (currentSelection?.type === "Range") {
  42. return false;
  43. }
  44. copyToClipboard(content);
  45. return true;
  46. }
  47. export function queryMeta(key: string, defaultValue?: string): string {
  48. let ret: string;
  49. if (document) {
  50. const meta = document.head.querySelector(
  51. `meta[name='${key}']`,
  52. ) as HTMLMetaElement;
  53. ret = meta?.content ?? "";
  54. } else {
  55. ret = defaultValue ?? "";
  56. }
  57. return ret;
  58. }
  59. let currentId: string;
  60. export function getCurrentVersion() {
  61. if (currentId) {
  62. return currentId;
  63. }
  64. currentId = queryMeta("version");
  65. return currentId;
  66. }