utils.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import { useEffect, useState } from "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 readFromFile() {
  39. return new Promise<string>((res, rej) => {
  40. const fileInput = document.createElement("input");
  41. fileInput.type = "file";
  42. fileInput.accept = "application/json";
  43. fileInput.onchange = (event: any) => {
  44. const file = event.target.files[0];
  45. const fileReader = new FileReader();
  46. fileReader.onload = (e: any) => {
  47. res(e.target.result);
  48. };
  49. fileReader.onerror = (e) => rej(e);
  50. fileReader.readAsText(file);
  51. };
  52. fileInput.click();
  53. });
  54. }
  55. export function isIOS() {
  56. const userAgent = navigator.userAgent.toLowerCase();
  57. return /iphone|ipad|ipod/.test(userAgent);
  58. }
  59. export function useWindowSize() {
  60. const [size, setSize] = useState({
  61. width: window.innerWidth,
  62. height: window.innerHeight,
  63. });
  64. useEffect(() => {
  65. const onResize = () => {
  66. setSize({
  67. width: window.innerWidth,
  68. height: window.innerHeight,
  69. });
  70. };
  71. window.addEventListener("resize", onResize);
  72. return () => {
  73. window.removeEventListener("resize", onResize);
  74. };
  75. }, []);
  76. return size;
  77. }
  78. export const MOBILE_MAX_WIDTH = 600;
  79. export function useMobileScreen() {
  80. const { width } = useWindowSize();
  81. return width <= MOBILE_MAX_WIDTH;
  82. }
  83. export function isFirefox() {
  84. return (
  85. typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
  86. );
  87. }
  88. export function selectOrCopy(el: HTMLElement, content: string) {
  89. const currentSelection = window.getSelection();
  90. if (currentSelection?.type === "Range") {
  91. return false;
  92. }
  93. copyToClipboard(content);
  94. return true;
  95. }
  96. function getDomContentWidth(dom: HTMLElement) {
  97. const style = window.getComputedStyle(dom);
  98. const paddingWidth =
  99. parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
  100. const width = dom.clientWidth - paddingWidth;
  101. return width;
  102. }
  103. function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) {
  104. let dom = document.getElementById(id);
  105. if (!dom) {
  106. dom = document.createElement("span");
  107. dom.style.position = "absolute";
  108. dom.style.wordBreak = "break-word";
  109. dom.style.fontSize = "14px";
  110. dom.style.transform = "translateY(-200vh)";
  111. dom.style.pointerEvents = "none";
  112. dom.style.opacity = "0";
  113. dom.id = id;
  114. document.body.appendChild(dom);
  115. init?.(dom);
  116. }
  117. return dom!;
  118. }
  119. export function autoGrowTextArea(dom: HTMLTextAreaElement) {
  120. const measureDom = getOrCreateMeasureDom("__measure");
  121. const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => {
  122. dom.innerText = "TEXT_FOR_MEASURE";
  123. });
  124. const width = getDomContentWidth(dom);
  125. measureDom.style.width = width + "px";
  126. measureDom.innerText = dom.value !== "" ? dom.value : "1";
  127. measureDom.style.fontSize = dom.style.fontSize;
  128. const endWithEmptyLine = dom.value.endsWith("\n");
  129. const height = parseFloat(window.getComputedStyle(measureDom).height);
  130. const singleLineHeight = parseFloat(
  131. window.getComputedStyle(singleLineDom).height,
  132. );
  133. const rows =
  134. Math.round(height / singleLineHeight) + (endWithEmptyLine ? 1 : 0);
  135. return rows;
  136. }
  137. export function getCSSVar(varName: string) {
  138. return getComputedStyle(document.body).getPropertyValue(varName).trim();
  139. }