utils.ts 2.1 KB

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