utils.ts 2.3 KB

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