utils.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. import { ServiceProvider, REQUEST_TIMEOUT_MS } from "./constant";
  6. import isObject from "lodash-es/isObject";
  7. import { fetch as tauriFetch, Body, ResponseType } from "@tauri-apps/api/http";
  8. export function trimTopic(topic: string) {
  9. // Fix an issue where double quotes still show in the Indonesian language
  10. // This will remove the specified punctuation from the end of the string
  11. // and also trim quotes from both the start and end if they exist.
  12. return (
  13. topic
  14. // fix for gemini
  15. .replace(/^["“”*]+|["“”*]+$/g, "")
  16. .replace(/[,。!?”“"、,.!?*]*$/, "")
  17. );
  18. }
  19. export async function copyToClipboard(text: string) {
  20. try {
  21. if (window.__TAURI__) {
  22. window.__TAURI__.writeText(text);
  23. } else {
  24. await navigator.clipboard.writeText(text);
  25. }
  26. showToast(Locale.Copy.Success);
  27. } catch (error) {
  28. const textArea = document.createElement("textarea");
  29. textArea.value = text;
  30. document.body.appendChild(textArea);
  31. textArea.focus();
  32. textArea.select();
  33. try {
  34. document.execCommand("copy");
  35. showToast(Locale.Copy.Success);
  36. } catch (error) {
  37. showToast(Locale.Copy.Failed);
  38. }
  39. document.body.removeChild(textArea);
  40. }
  41. }
  42. export async function downloadAs(text: string, filename: string) {
  43. if (window.__TAURI__) {
  44. const result = await window.__TAURI__.dialog.save({
  45. defaultPath: `${filename}`,
  46. filters: [
  47. {
  48. name: `${filename.split(".").pop()} files`,
  49. extensions: [`${filename.split(".").pop()}`],
  50. },
  51. {
  52. name: "All Files",
  53. extensions: ["*"],
  54. },
  55. ],
  56. });
  57. if (result !== null) {
  58. try {
  59. await window.__TAURI__.fs.writeTextFile(result, text);
  60. showToast(Locale.Download.Success);
  61. } catch (error) {
  62. showToast(Locale.Download.Failed);
  63. }
  64. } else {
  65. showToast(Locale.Download.Failed);
  66. }
  67. } else {
  68. const element = document.createElement("a");
  69. element.setAttribute(
  70. "href",
  71. "data:text/plain;charset=utf-8," + encodeURIComponent(text),
  72. );
  73. element.setAttribute("download", filename);
  74. element.style.display = "none";
  75. document.body.appendChild(element);
  76. element.click();
  77. document.body.removeChild(element);
  78. }
  79. }
  80. export function readFromFile() {
  81. return new Promise<string>((res, rej) => {
  82. const fileInput = document.createElement("input");
  83. fileInput.type = "file";
  84. fileInput.accept = "application/json";
  85. fileInput.onchange = (event: any) => {
  86. const file = event.target.files[0];
  87. const fileReader = new FileReader();
  88. fileReader.onload = (e: any) => {
  89. res(e.target.result);
  90. };
  91. fileReader.onerror = (e) => rej(e);
  92. fileReader.readAsText(file);
  93. };
  94. fileInput.click();
  95. });
  96. }
  97. export function isIOS() {
  98. const userAgent = navigator.userAgent.toLowerCase();
  99. return /iphone|ipad|ipod/.test(userAgent);
  100. }
  101. export function useWindowSize() {
  102. const [size, setSize] = useState({
  103. width: window.innerWidth,
  104. height: window.innerHeight,
  105. });
  106. useEffect(() => {
  107. const onResize = () => {
  108. setSize({
  109. width: window.innerWidth,
  110. height: window.innerHeight,
  111. });
  112. };
  113. window.addEventListener("resize", onResize);
  114. return () => {
  115. window.removeEventListener("resize", onResize);
  116. };
  117. }, []);
  118. return size;
  119. }
  120. export const MOBILE_MAX_WIDTH = 600;
  121. export function useMobileScreen() {
  122. const { width } = useWindowSize();
  123. return width <= MOBILE_MAX_WIDTH;
  124. }
  125. export function isFirefox() {
  126. return (
  127. typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
  128. );
  129. }
  130. export function selectOrCopy(el: HTMLElement, content: string) {
  131. const currentSelection = window.getSelection();
  132. if (currentSelection?.type === "Range") {
  133. return false;
  134. }
  135. copyToClipboard(content);
  136. return true;
  137. }
  138. function getDomContentWidth(dom: HTMLElement) {
  139. const style = window.getComputedStyle(dom);
  140. const paddingWidth =
  141. parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
  142. const width = dom.clientWidth - paddingWidth;
  143. return width;
  144. }
  145. function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) {
  146. let dom = document.getElementById(id);
  147. if (!dom) {
  148. dom = document.createElement("span");
  149. dom.style.position = "absolute";
  150. dom.style.wordBreak = "break-word";
  151. dom.style.fontSize = "14px";
  152. dom.style.transform = "translateY(-200vh)";
  153. dom.style.pointerEvents = "none";
  154. dom.style.opacity = "0";
  155. dom.id = id;
  156. document.body.appendChild(dom);
  157. init?.(dom);
  158. }
  159. return dom!;
  160. }
  161. export function autoGrowTextArea(dom: HTMLTextAreaElement) {
  162. const measureDom = getOrCreateMeasureDom("__measure");
  163. const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => {
  164. dom.innerText = "TEXT_FOR_MEASURE";
  165. });
  166. const width = getDomContentWidth(dom);
  167. measureDom.style.width = width + "px";
  168. measureDom.innerText = dom.value !== "" ? dom.value : "1";
  169. measureDom.style.fontSize = dom.style.fontSize;
  170. measureDom.style.fontFamily = dom.style.fontFamily;
  171. const endWithEmptyLine = dom.value.endsWith("\n");
  172. const height = parseFloat(window.getComputedStyle(measureDom).height);
  173. const singleLineHeight = parseFloat(
  174. window.getComputedStyle(singleLineDom).height,
  175. );
  176. const rows =
  177. Math.round(height / singleLineHeight) + (endWithEmptyLine ? 1 : 0);
  178. return rows;
  179. }
  180. export function getCSSVar(varName: string) {
  181. return getComputedStyle(document.body).getPropertyValue(varName).trim();
  182. }
  183. /**
  184. * Detects Macintosh
  185. */
  186. export function isMacOS(): boolean {
  187. if (typeof window !== "undefined") {
  188. let userAgent = window.navigator.userAgent.toLocaleLowerCase();
  189. const macintosh = /iphone|ipad|ipod|macintosh/.test(userAgent);
  190. return !!macintosh;
  191. }
  192. return false;
  193. }
  194. export function getMessageTextContent(message: RequestMessage) {
  195. if (typeof message.content === "string") {
  196. return message.content;
  197. }
  198. for (const c of message.content) {
  199. if (c.type === "text") {
  200. return c.text ?? "";
  201. }
  202. }
  203. return "";
  204. }
  205. export function getMessageImages(message: RequestMessage): string[] {
  206. if (typeof message.content === "string") {
  207. return [];
  208. }
  209. const urls: string[] = [];
  210. for (const c of message.content) {
  211. if (c.type === "image_url") {
  212. urls.push(c.image_url?.url ?? "");
  213. }
  214. }
  215. return urls;
  216. }
  217. export function isVisionModel(model: string) {
  218. // Note: This is a better way using the TypeScript feature instead of `&&` or `||` (ts v5.5.0-dev.20240314 I've been using)
  219. const visionKeywords = [
  220. "vision",
  221. "claude-3",
  222. "gemini-1.5-pro",
  223. "gemini-1.5-flash",
  224. "gpt-4o",
  225. "gpt-4o-mini",
  226. ];
  227. const isGpt4Turbo =
  228. model.includes("gpt-4-turbo") && !model.includes("preview");
  229. return (
  230. visionKeywords.some((keyword) => model.includes(keyword)) || isGpt4Turbo
  231. );
  232. }
  233. export function isDalle3(model: string) {
  234. return "dall-e-3" === model;
  235. }
  236. export function showPlugins(provider: ServiceProvider, model: string) {
  237. if (
  238. provider == ServiceProvider.OpenAI ||
  239. provider == ServiceProvider.Azure ||
  240. provider == ServiceProvider.Moonshot
  241. ) {
  242. return true;
  243. }
  244. if (provider == ServiceProvider.Anthropic && !model.includes("claude-2")) {
  245. return true;
  246. }
  247. return false;
  248. }
  249. export function fetch(
  250. url: string,
  251. options?: Record<string, unknown>,
  252. ): Promise<any> {
  253. if (window.__TAURI__) {
  254. const payload = options?.body || options?.data;
  255. return tauriFetch(url, {
  256. ...options,
  257. body:
  258. payload &&
  259. ({
  260. type: "Text",
  261. payload,
  262. } as any),
  263. timeout: ((options?.timeout as number) || REQUEST_TIMEOUT_MS) / 1000,
  264. responseType:
  265. options?.responseType == "text" ? ResponseType.Text : ResponseType.JSON,
  266. } as any);
  267. }
  268. return window.fetch(url, options);
  269. }
  270. export function adapter(config: Record<string, unknown>) {
  271. const { baseURL, url, params, ...rest } = config;
  272. const path = baseURL ? `${baseURL}${url}` : url;
  273. const fetchUrl = params
  274. ? `${path}?${new URLSearchParams(params as any).toString()}`
  275. : path;
  276. return fetch(fetchUrl as string, { ...rest, responseType: "text" });
  277. }
  278. export function safeLocalStorage(): {
  279. getItem: (key: string) => string | null;
  280. setItem: (key: string, value: string) => void;
  281. removeItem: (key: string) => void;
  282. clear: () => void;
  283. } {
  284. let storage: Storage | null;
  285. try {
  286. if (typeof window !== "undefined" && window.localStorage) {
  287. storage = window.localStorage;
  288. } else {
  289. storage = null;
  290. }
  291. } catch (e) {
  292. console.error("localStorage is not available:", e);
  293. storage = null;
  294. }
  295. return {
  296. getItem(key: string): string | null {
  297. if (storage) {
  298. return storage.getItem(key);
  299. } else {
  300. console.warn(
  301. `Attempted to get item "${key}" from localStorage, but localStorage is not available.`,
  302. );
  303. return null;
  304. }
  305. },
  306. setItem(key: string, value: string): void {
  307. if (storage) {
  308. storage.setItem(key, value);
  309. } else {
  310. console.warn(
  311. `Attempted to set item "${key}" in localStorage, but localStorage is not available.`,
  312. );
  313. }
  314. },
  315. removeItem(key: string): void {
  316. if (storage) {
  317. storage.removeItem(key);
  318. } else {
  319. console.warn(
  320. `Attempted to remove item "${key}" from localStorage, but localStorage is not available.`,
  321. );
  322. }
  323. },
  324. clear(): void {
  325. if (storage) {
  326. storage.clear();
  327. } else {
  328. console.warn(
  329. "Attempted to clear localStorage, but localStorage is not available.",
  330. );
  331. }
  332. },
  333. };
  334. }