utils.ts 5.7 KB

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