utils.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 isMobileScreen() {
  84. if (typeof window === "undefined") {
  85. return false;
  86. }
  87. return window.innerWidth <= MOBILE_MAX_WIDTH;
  88. }
  89. export function isFirefox() {
  90. return (
  91. typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
  92. );
  93. }
  94. export function selectOrCopy(el: HTMLElement, content: string) {
  95. const currentSelection = window.getSelection();
  96. if (currentSelection?.type === "Range") {
  97. return false;
  98. }
  99. copyToClipboard(content);
  100. return true;
  101. }
  102. function getDomContentWidth(dom: HTMLElement) {
  103. const style = window.getComputedStyle(dom);
  104. const paddingWidth =
  105. parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
  106. const width = dom.clientWidth - paddingWidth;
  107. return width;
  108. }
  109. function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) {
  110. let dom = document.getElementById(id);
  111. if (!dom) {
  112. dom = document.createElement("span");
  113. dom.style.position = "absolute";
  114. dom.style.wordBreak = "break-word";
  115. dom.style.fontSize = "14px";
  116. dom.style.transform = "translateY(-200vh)";
  117. dom.style.pointerEvents = "none";
  118. dom.style.opacity = "0";
  119. dom.id = id;
  120. document.body.appendChild(dom);
  121. init?.(dom);
  122. }
  123. return dom!;
  124. }
  125. export function autoGrowTextArea(dom: HTMLTextAreaElement) {
  126. const measureDom = getOrCreateMeasureDom("__measure");
  127. const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => {
  128. dom.innerText = "TEXT_FOR_MEASURE";
  129. });
  130. const width = getDomContentWidth(dom);
  131. measureDom.style.width = width + "px";
  132. measureDom.innerText = dom.value !== "" ? dom.value : "1";
  133. const endWithEmptyLine = dom.value.endsWith("\n");
  134. const height = parseFloat(window.getComputedStyle(measureDom).height);
  135. const singleLineHeight = parseFloat(
  136. window.getComputedStyle(singleLineDom).height,
  137. );
  138. const rows =
  139. Math.round(height / singleLineHeight) + (endWithEmptyLine ? 1 : 0);
  140. return rows;
  141. }
  142. export function getCSSVar(varName: string) {
  143. return getComputedStyle(document.body).getPropertyValue(varName).trim();
  144. }