utils.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 isFirefox() {
  46. return (
  47. typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
  48. );
  49. }
  50. export function selectOrCopy(el: HTMLElement, content: string) {
  51. const currentSelection = window.getSelection();
  52. if (currentSelection?.type === "Range") {
  53. return false;
  54. }
  55. copyToClipboard(content);
  56. return true;
  57. }
  58. export function queryMeta(key: string, defaultValue?: string): string {
  59. let ret: string;
  60. if (document) {
  61. const meta = document.head.querySelector(
  62. `meta[name='${key}']`,
  63. ) as HTMLMetaElement;
  64. ret = meta?.content ?? "";
  65. } else {
  66. ret = defaultValue ?? "";
  67. }
  68. return ret;
  69. }
  70. let currentId: string;
  71. export function getCurrentVersion() {
  72. if (currentId) {
  73. return currentId;
  74. }
  75. currentId = queryMeta("version");
  76. return currentId;
  77. }
  78. export function getEmojiUrl(unified: string, style: EmojiStyle) {
  79. return `https://cdn.staticfile.org/emoji-datasource-apple/14.0.0/img/${style}/64/${unified}.png`;
  80. }