utils.ts 2.2 KB

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