utils.ts 2.1 KB

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