utils.ts 2.0 KB

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