utils.ts 2.2 KB

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