utils.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. if (window.__TAURI__) {
  10. window.__TAURI__.writeText(text);
  11. } else {
  12. await navigator.clipboard.writeText(text);
  13. }
  14. showToast(Locale.Copy.Success);
  15. } catch (error) {
  16. const textArea = document.createElement("textarea");
  17. textArea.value = text;
  18. document.body.appendChild(textArea);
  19. textArea.focus();
  20. textArea.select();
  21. try {
  22. document.execCommand("copy");
  23. showToast(Locale.Copy.Success);
  24. } catch (error) {
  25. showToast(Locale.Copy.Failed);
  26. }
  27. document.body.removeChild(textArea);
  28. }
  29. }
  30. export async function downloadAs(text: string, filename: string) {
  31. if (window.__TAURI__) {
  32. const result = await window.__TAURI__.dialog.save({
  33. defaultPath: `${filename}`,
  34. filters: [
  35. {
  36. name: `${filename.split('.').pop()} files`,
  37. extensions: [`${filename.split('.').pop()}`],
  38. },
  39. {
  40. name: "All Files",
  41. extensions: ["*"],
  42. },
  43. ],
  44. });
  45. if (result !== null) {
  46. try {
  47. await window.__TAURI__.fs.writeBinaryFile(
  48. result,
  49. new Uint8Array([...text].map((c) => c.charCodeAt(0)))
  50. );
  51. showToast(Locale.Download.Success);
  52. } catch (error) {
  53. showToast(Locale.Download.Failed);
  54. }
  55. } else {
  56. showToast(Locale.Download.Failed);
  57. }
  58. } else {
  59. const element = document.createElement("a");
  60. element.setAttribute(
  61. "href",
  62. "data:text/plain;charset=utf-8," + encodeURIComponent(text),
  63. );
  64. element.setAttribute("download", filename);
  65. element.style.display = "none";
  66. document.body.appendChild(element);
  67. element.click();
  68. document.body.removeChild(element);
  69. }
  70. }
  71. export function readFromFile() {
  72. return new Promise<string>((res, rej) => {
  73. const fileInput = document.createElement("input");
  74. fileInput.type = "file";
  75. fileInput.accept = "application/json";
  76. fileInput.onchange = (event: any) => {
  77. const file = event.target.files[0];
  78. const fileReader = new FileReader();
  79. fileReader.onload = (e: any) => {
  80. res(e.target.result);
  81. };
  82. fileReader.onerror = (e) => rej(e);
  83. fileReader.readAsText(file);
  84. };
  85. fileInput.click();
  86. });
  87. }
  88. export function isIOS() {
  89. const userAgent = navigator.userAgent.toLowerCase();
  90. return /iphone|ipad|ipod/.test(userAgent);
  91. }
  92. export function useWindowSize() {
  93. const [size, setSize] = useState({
  94. width: window.innerWidth,
  95. height: window.innerHeight,
  96. });
  97. useEffect(() => {
  98. const onResize = () => {
  99. setSize({
  100. width: window.innerWidth,
  101. height: window.innerHeight,
  102. });
  103. };
  104. window.addEventListener("resize", onResize);
  105. return () => {
  106. window.removeEventListener("resize", onResize);
  107. };
  108. }, []);
  109. return size;
  110. }
  111. export const MOBILE_MAX_WIDTH = 600;
  112. export function useMobileScreen() {
  113. const { width } = useWindowSize();
  114. return width <= MOBILE_MAX_WIDTH;
  115. }
  116. export function isFirefox() {
  117. return (
  118. typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
  119. );
  120. }
  121. export function selectOrCopy(el: HTMLElement, content: string) {
  122. const currentSelection = window.getSelection();
  123. if (currentSelection?.type === "Range") {
  124. return false;
  125. }
  126. copyToClipboard(content);
  127. return true;
  128. }
  129. function getDomContentWidth(dom: HTMLElement) {
  130. const style = window.getComputedStyle(dom);
  131. const paddingWidth =
  132. parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
  133. const width = dom.clientWidth - paddingWidth;
  134. return width;
  135. }
  136. function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) {
  137. let dom = document.getElementById(id);
  138. if (!dom) {
  139. dom = document.createElement("span");
  140. dom.style.position = "absolute";
  141. dom.style.wordBreak = "break-word";
  142. dom.style.fontSize = "14px";
  143. dom.style.transform = "translateY(-200vh)";
  144. dom.style.pointerEvents = "none";
  145. dom.style.opacity = "0";
  146. dom.id = id;
  147. document.body.appendChild(dom);
  148. init?.(dom);
  149. }
  150. return dom!;
  151. }
  152. export function autoGrowTextArea(dom: HTMLTextAreaElement) {
  153. const measureDom = getOrCreateMeasureDom("__measure");
  154. const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => {
  155. dom.innerText = "TEXT_FOR_MEASURE";
  156. });
  157. const width = getDomContentWidth(dom);
  158. measureDom.style.width = width + "px";
  159. measureDom.innerText = dom.value !== "" ? dom.value : "1";
  160. measureDom.style.fontSize = dom.style.fontSize;
  161. const endWithEmptyLine = dom.value.endsWith("\n");
  162. const height = parseFloat(window.getComputedStyle(measureDom).height);
  163. const singleLineHeight = parseFloat(
  164. window.getComputedStyle(singleLineDom).height,
  165. );
  166. const rows =
  167. Math.round(height / singleLineHeight) + (endWithEmptyLine ? 1 : 0);
  168. return rows;
  169. }
  170. export function getCSSVar(varName: string) {
  171. return getComputedStyle(document.body).getPropertyValue(varName).trim();
  172. }
  173. /**
  174. * Detects Macintosh
  175. */
  176. export function isMacOS(): boolean {
  177. if (typeof window !== "undefined") {
  178. let userAgent = window.navigator.userAgent.toLocaleLowerCase();
  179. const macintosh = /iphone|ipad|ipod|macintosh/.test(userAgent)
  180. return !!macintosh
  181. }
  182. return false
  183. }