utils.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 function copyToClipboard(text: string) {
  7. navigator.clipboard
  8. .writeText(text)
  9. .then((res) => {
  10. showToast(Locale.Copy.Success);
  11. })
  12. .catch((err) => {
  13. showToast(Locale.Copy.Failed);
  14. });
  15. }
  16. export function downloadAs(text: string, filename: string) {
  17. const element = document.createElement("a");
  18. element.setAttribute(
  19. "href",
  20. "data:text/plain;charset=utf-8," + encodeURIComponent(text),
  21. );
  22. element.setAttribute("download", filename);
  23. element.style.display = "none";
  24. document.body.appendChild(element);
  25. element.click();
  26. document.body.removeChild(element);
  27. }
  28. export function isIOS() {
  29. const userAgent = navigator.userAgent.toLowerCase();
  30. return /iphone|ipad|ipod/.test(userAgent);
  31. }
  32. export function isMobileScreen() {
  33. return window.innerWidth <= 600;
  34. }
  35. export function selectOrCopy(el: HTMLElement, content: string) {
  36. const currentSelection = window.getSelection();
  37. if (currentSelection?.type === "Range") {
  38. return false;
  39. }
  40. copyToClipboard(content);
  41. return true;
  42. }
  43. export function queryMeta(key: string, defaultValue?: string): string {
  44. let ret: string;
  45. if (document) {
  46. const meta = document.head.querySelector(
  47. `meta[name='${key}']`,
  48. ) as HTMLMetaElement;
  49. ret = meta?.content ?? "";
  50. } else {
  51. ret = defaultValue ?? "";
  52. }
  53. return ret;
  54. }
  55. let currentId: string;
  56. export function getCurrentVersion() {
  57. if (currentId) {
  58. return currentId;
  59. }
  60. currentId = queryMeta("version");
  61. return currentId;
  62. }