utils.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { EmojiStyle } from "emoji-picker-react";
  2. import { showToast } from "./components/ui-lib";
  3. import Locale from "./locales";
  4. export function trimTopic(topic: string) {
  5. return topic.replace(/[,。!?”“"、,.!?]*$/, "");
  6. }
  7. export async function copyToClipboard(text: string) {
  8. try {
  9. await navigator.clipboard.writeText(text);
  10. showToast(Locale.Copy.Success);
  11. } catch (error) {
  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. showToast(Locale.Copy.Success);
  20. } catch (error) {
  21. showToast(Locale.Copy.Failed);
  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. }
  73. export function getEmojiUrl(unified: string, style: EmojiStyle) {
  74. return `https://cdn.staticfile.org/emoji-datasource-apple/14.0.0/img/${style}/64/${unified}.png`;
  75. }