utils.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import { useEffect, useState } from "react";
  2. import { showToast } from "./components/ui-lib";
  3. import Locale from "./locales";
  4. import { RequestMessage } from "./client/api";
  5. export function trimTopic(topic: string) {
  6. // Fix an issue where double quotes still show in the Indonesian language
  7. // This will remove the specified punctuation from the end of the string
  8. // and also trim quotes from both the start and end if they exist.
  9. return (
  10. topic
  11. // fix for gemini
  12. .replace(/^["“”*]+|["“”*]+$/g, "")
  13. .replace(/[,。!?”“"、,.!?*]*$/, "")
  14. );
  15. }
  16. export async function copyToClipboard(text: string) {
  17. try {
  18. if (window.__TAURI__) {
  19. window.__TAURI__.writeText(text);
  20. } else {
  21. await navigator.clipboard.writeText(text);
  22. }
  23. showToast(Locale.Copy.Success);
  24. } catch (error) {
  25. const textArea = document.createElement("textarea");
  26. textArea.value = text;
  27. document.body.appendChild(textArea);
  28. textArea.focus();
  29. textArea.select();
  30. try {
  31. document.execCommand("copy");
  32. showToast(Locale.Copy.Success);
  33. } catch (error) {
  34. showToast(Locale.Copy.Failed);
  35. }
  36. document.body.removeChild(textArea);
  37. }
  38. }
  39. export async function downloadAs(text: string, filename: string) {
  40. if (window.__TAURI__) {
  41. const result = await window.__TAURI__.dialog.save({
  42. defaultPath: `${filename}`,
  43. filters: [
  44. {
  45. name: `${filename.split(".").pop()} files`,
  46. extensions: [`${filename.split(".").pop()}`],
  47. },
  48. {
  49. name: "All Files",
  50. extensions: ["*"],
  51. },
  52. ],
  53. });
  54. if (result !== null) {
  55. try {
  56. await window.__TAURI__.fs.writeTextFile(result, text);
  57. showToast(Locale.Download.Success);
  58. } catch (error) {
  59. showToast(Locale.Download.Failed);
  60. }
  61. } else {
  62. showToast(Locale.Download.Failed);
  63. }
  64. } else {
  65. const element = document.createElement("a");
  66. element.setAttribute(
  67. "href",
  68. "data:text/plain;charset=utf-8," + encodeURIComponent(text),
  69. );
  70. element.setAttribute("download", filename);
  71. element.style.display = "none";
  72. document.body.appendChild(element);
  73. element.click();
  74. document.body.removeChild(element);
  75. }
  76. }
  77. export function readFromFile() {
  78. return new Promise<string>((res, rej) => {
  79. const fileInput = document.createElement("input");
  80. fileInput.type = "file";
  81. fileInput.accept = "application/json";
  82. fileInput.onchange = (event: any) => {
  83. const file = event.target.files[0];
  84. const fileReader = new FileReader();
  85. fileReader.onload = (e: any) => {
  86. res(e.target.result);
  87. };
  88. fileReader.onerror = (e) => rej(e);
  89. fileReader.readAsText(file);
  90. };
  91. fileInput.click();
  92. });
  93. }
  94. export function isIOS() {
  95. const userAgent = navigator.userAgent.toLowerCase();
  96. return /iphone|ipad|ipod/.test(userAgent);
  97. }
  98. export function useWindowSize() {
  99. const [size, setSize] = useState({
  100. width: window.innerWidth,
  101. height: window.innerHeight,
  102. });
  103. useEffect(() => {
  104. const onResize = () => {
  105. setSize({
  106. width: window.innerWidth,
  107. height: window.innerHeight,
  108. });
  109. };
  110. window.addEventListener("resize", onResize);
  111. return () => {
  112. window.removeEventListener("resize", onResize);
  113. };
  114. }, []);
  115. return size;
  116. }
  117. export const MOBILE_MAX_WIDTH = 600;
  118. export function useMobileScreen() {
  119. const { width } = useWindowSize();
  120. return width <= MOBILE_MAX_WIDTH;
  121. }
  122. export function isFirefox() {
  123. return (
  124. typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
  125. );
  126. }
  127. export function selectOrCopy(el: HTMLElement, content: string) {
  128. const currentSelection = window.getSelection();
  129. if (currentSelection?.type === "Range") {
  130. return false;
  131. }
  132. copyToClipboard(content);
  133. return true;
  134. }
  135. function getDomContentWidth(dom: HTMLElement) {
  136. const style = window.getComputedStyle(dom);
  137. const paddingWidth =
  138. parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
  139. const width = dom.clientWidth - paddingWidth;
  140. return width;
  141. }
  142. function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) {
  143. let dom = document.getElementById(id);
  144. if (!dom) {
  145. dom = document.createElement("span");
  146. dom.style.position = "absolute";
  147. dom.style.wordBreak = "break-word";
  148. dom.style.fontSize = "14px";
  149. dom.style.transform = "translateY(-200vh)";
  150. dom.style.pointerEvents = "none";
  151. dom.style.opacity = "0";
  152. dom.id = id;
  153. document.body.appendChild(dom);
  154. init?.(dom);
  155. }
  156. return dom!;
  157. }
  158. export function autoGrowTextArea(dom: HTMLTextAreaElement) {
  159. const measureDom = getOrCreateMeasureDom("__measure");
  160. const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => {
  161. dom.innerText = "TEXT_FOR_MEASURE";
  162. });
  163. const width = getDomContentWidth(dom);
  164. measureDom.style.width = width + "px";
  165. measureDom.innerText = dom.value !== "" ? dom.value : "1";
  166. measureDom.style.fontSize = dom.style.fontSize;
  167. measureDom.style.fontFamily = dom.style.fontFamily;
  168. const endWithEmptyLine = dom.value.endsWith("\n");
  169. const height = parseFloat(window.getComputedStyle(measureDom).height);
  170. const singleLineHeight = parseFloat(
  171. window.getComputedStyle(singleLineDom).height,
  172. );
  173. const rows =
  174. Math.round(height / singleLineHeight) + (endWithEmptyLine ? 1 : 0);
  175. return rows;
  176. }
  177. export function getCSSVar(varName: string) {
  178. return getComputedStyle(document.body).getPropertyValue(varName).trim();
  179. }
  180. /**
  181. * Detects Macintosh
  182. */
  183. export function isMacOS(): boolean {
  184. if (typeof window !== "undefined") {
  185. let userAgent = window.navigator.userAgent.toLocaleLowerCase();
  186. const macintosh = /iphone|ipad|ipod|macintosh/.test(userAgent);
  187. return !!macintosh;
  188. }
  189. return false;
  190. }
  191. export function getMessageTextContent(message: RequestMessage) {
  192. if (typeof message.content === "string") {
  193. return message.content;
  194. }
  195. for (const c of message.content) {
  196. if (c.type === "text") {
  197. return c.text ?? "";
  198. }
  199. }
  200. return "";
  201. }
  202. export function getMessageImages(message: RequestMessage): string[] {
  203. if (typeof message.content === "string") {
  204. return [];
  205. }
  206. const urls: string[] = [];
  207. for (const c of message.content) {
  208. if (c.type === "image_url") {
  209. urls.push(c.image_url?.url ?? "");
  210. }
  211. }
  212. return urls;
  213. }
  214. export function isVisionModel(model: string) {
  215. // Note: This is a better way using the TypeScript feature instead of `&&` or `||` (ts v5.5.0-dev.20240314 I've been using)
  216. const visionKeywords = [
  217. "vision",
  218. "claude-3",
  219. "gemini-1.5-pro",
  220. "gemini-1.5-flash",
  221. "gpt-4o",
  222. "gpt-4o-mini",
  223. "qwen-vl",
  224. ];
  225. const isGpt4Turbo =
  226. model.includes("gpt-4-turbo") && !model.includes("preview");
  227. return (
  228. visionKeywords.some((keyword) => model.includes(keyword)) || isGpt4Turbo
  229. );
  230. }
  231. export function isDalle3(model: string) {
  232. return "dall-e-3" === model;
  233. }