utils.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 {
  6. REQUEST_TIMEOUT_MS,
  7. REQUEST_TIMEOUT_MS_FOR_THINKING,
  8. ServiceProvider,
  9. } from "./constant";
  10. // import { fetch as tauriFetch, ResponseType } from "@tauri-apps/api/http";
  11. import { fetch as tauriStreamFetch } from "./utils/stream";
  12. import { VISION_MODEL_REGEXES, EXCLUDE_VISION_MODEL_REGEXES } from "./constant";
  13. import { useAccessStore } from "./store";
  14. import { ModelSize } from "./typing";
  15. export function trimTopic(topic: string) {
  16. // Fix an issue where double quotes still show in the Indonesian language
  17. // This will remove the specified punctuation from the end of the string
  18. // and also trim quotes from both the start and end if they exist.
  19. return (
  20. topic
  21. // fix for gemini
  22. .replace(/^["“”*]+|["“”*]+$/g, "")
  23. .replace(/[,。!?”“"、,.!?*]*$/, "")
  24. );
  25. }
  26. export async function copyToClipboard(text: string) {
  27. try {
  28. if (window.__TAURI__) {
  29. window.__TAURI__.writeText(text);
  30. } else {
  31. await navigator.clipboard.writeText(text);
  32. }
  33. showToast(Locale.Copy.Success);
  34. } catch (error) {
  35. const textArea = document.createElement("textarea");
  36. textArea.value = text;
  37. document.body.appendChild(textArea);
  38. textArea.focus();
  39. textArea.select();
  40. try {
  41. document.execCommand("copy");
  42. showToast(Locale.Copy.Success);
  43. } catch (error) {
  44. showToast(Locale.Copy.Failed);
  45. }
  46. document.body.removeChild(textArea);
  47. }
  48. }
  49. export async function downloadAs(text: string, filename: string) {
  50. if (window.__TAURI__) {
  51. const result = await window.__TAURI__.dialog.save({
  52. defaultPath: `${filename}`,
  53. filters: [
  54. {
  55. name: `${filename.split(".").pop()} files`,
  56. extensions: [`${filename.split(".").pop()}`],
  57. },
  58. {
  59. name: "All Files",
  60. extensions: ["*"],
  61. },
  62. ],
  63. });
  64. if (result !== null) {
  65. try {
  66. await window.__TAURI__.fs.writeTextFile(result, text);
  67. showToast(Locale.Download.Success);
  68. } catch (error) {
  69. showToast(Locale.Download.Failed);
  70. }
  71. } else {
  72. showToast(Locale.Download.Failed);
  73. }
  74. } else {
  75. const element = document.createElement("a");
  76. element.setAttribute(
  77. "href",
  78. "data:text/plain;charset=utf-8," + encodeURIComponent(text),
  79. );
  80. element.setAttribute("download", filename);
  81. element.style.display = "none";
  82. document.body.appendChild(element);
  83. element.click();
  84. document.body.removeChild(element);
  85. }
  86. }
  87. export function readFromFile() {
  88. return new Promise<string>((res, rej) => {
  89. const fileInput = document.createElement("input");
  90. fileInput.type = "file";
  91. fileInput.accept = "application/json";
  92. fileInput.onchange = (event: any) => {
  93. const file = event.target.files[0];
  94. const fileReader = new FileReader();
  95. fileReader.onload = (e: any) => {
  96. res(e.target.result);
  97. };
  98. fileReader.onerror = (e) => rej(e);
  99. fileReader.readAsText(file);
  100. };
  101. fileInput.click();
  102. });
  103. }
  104. export function isIOS() {
  105. const userAgent = navigator.userAgent.toLowerCase();
  106. return /iphone|ipad|ipod/.test(userAgent);
  107. }
  108. export function useWindowSize() {
  109. const [size, setSize] = useState({
  110. width: window.innerWidth,
  111. height: window.innerHeight,
  112. });
  113. useEffect(() => {
  114. const onResize = () => {
  115. setSize({
  116. width: window.innerWidth,
  117. height: window.innerHeight,
  118. });
  119. };
  120. window.addEventListener("resize", onResize);
  121. return () => {
  122. window.removeEventListener("resize", onResize);
  123. };
  124. }, []);
  125. return size;
  126. }
  127. export const MOBILE_MAX_WIDTH = 600;
  128. export function useMobileScreen() {
  129. const { width } = useWindowSize();
  130. return width <= MOBILE_MAX_WIDTH;
  131. }
  132. export function isFirefox() {
  133. return (
  134. typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
  135. );
  136. }
  137. export function selectOrCopy(el: HTMLElement, content: string) {
  138. const currentSelection = window.getSelection();
  139. if (currentSelection?.type === "Range") {
  140. return false;
  141. }
  142. copyToClipboard(content);
  143. return true;
  144. }
  145. function getDomContentWidth(dom: HTMLElement) {
  146. const style = window.getComputedStyle(dom);
  147. const paddingWidth =
  148. parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
  149. const width = dom.clientWidth - paddingWidth;
  150. return width;
  151. }
  152. function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) {
  153. let dom = document.getElementById(id);
  154. if (!dom) {
  155. dom = document.createElement("span");
  156. dom.style.position = "absolute";
  157. dom.style.wordBreak = "break-word";
  158. dom.style.fontSize = "14px";
  159. dom.style.transform = "translateY(-200vh)";
  160. dom.style.pointerEvents = "none";
  161. dom.style.opacity = "0";
  162. dom.id = id;
  163. document.body.appendChild(dom);
  164. init?.(dom);
  165. }
  166. return dom!;
  167. }
  168. export function autoGrowTextArea(dom: HTMLTextAreaElement) {
  169. const measureDom = getOrCreateMeasureDom("__measure");
  170. const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => {
  171. dom.innerText = "TEXT_FOR_MEASURE";
  172. });
  173. const width = getDomContentWidth(dom);
  174. measureDom.style.width = width + "px";
  175. measureDom.innerText = dom.value !== "" ? dom.value : "1";
  176. measureDom.style.fontSize = dom.style.fontSize;
  177. measureDom.style.fontFamily = dom.style.fontFamily;
  178. const endWithEmptyLine = dom.value.endsWith("\n");
  179. const height = parseFloat(window.getComputedStyle(measureDom).height);
  180. const singleLineHeight = parseFloat(
  181. window.getComputedStyle(singleLineDom).height,
  182. );
  183. const rows =
  184. Math.round(height / singleLineHeight) + (endWithEmptyLine ? 1 : 0);
  185. return rows;
  186. }
  187. export function getCSSVar(varName: string) {
  188. return getComputedStyle(document.body).getPropertyValue(varName).trim();
  189. }
  190. /**
  191. * Detects Macintosh
  192. */
  193. export function isMacOS(): boolean {
  194. if (typeof window !== "undefined") {
  195. let userAgent = window.navigator.userAgent.toLocaleLowerCase();
  196. const macintosh = /iphone|ipad|ipod|macintosh/.test(userAgent);
  197. return !!macintosh;
  198. }
  199. return false;
  200. }
  201. export function getMessageTextContent(message: RequestMessage) {
  202. if (typeof message.content === "string") {
  203. return message.content;
  204. }
  205. for (const c of message.content) {
  206. if (c.type === "text") {
  207. return c.text ?? "";
  208. }
  209. }
  210. return "";
  211. }
  212. export function getMessageTextContentWithoutThinking(message: RequestMessage) {
  213. let content = "";
  214. if (typeof message.content === "string") {
  215. content = message.content;
  216. } else {
  217. for (const c of message.content) {
  218. if (c.type === "text") {
  219. content = c.text ?? "";
  220. break;
  221. }
  222. }
  223. }
  224. // Filter out thinking lines (starting with "> ")
  225. return content
  226. .split("\n")
  227. .filter((line) => !line.startsWith("> ") && line.trim() !== "")
  228. .join("\n")
  229. .trim();
  230. }
  231. export function getMessageImages(message: RequestMessage): string[] {
  232. if (typeof message.content === "string") {
  233. return [];
  234. }
  235. const urls: string[] = [];
  236. for (const c of message.content) {
  237. if (c.type === "image_url") {
  238. urls.push(c.image_url?.url ?? "");
  239. }
  240. }
  241. return urls;
  242. }
  243. export function isVisionModel(model: string) {
  244. const visionModels = useAccessStore.getState().visionModels;
  245. const envVisionModels = visionModels?.split(",").map((m) => m.trim());
  246. if (envVisionModels?.includes(model)) {
  247. return true;
  248. }
  249. return (
  250. !EXCLUDE_VISION_MODEL_REGEXES.some((regex) => regex.test(model)) &&
  251. VISION_MODEL_REGEXES.some((regex) => regex.test(model))
  252. );
  253. }
  254. export function isDalle3(model: string) {
  255. return "dall-e-3" === model;
  256. }
  257. export function getTimeoutMSByModel(model: string) {
  258. model = model.toLowerCase();
  259. if (
  260. model.startsWith("dall-e") ||
  261. model.startsWith("dalle") ||
  262. model.startsWith("o1") ||
  263. model.startsWith("o3") ||
  264. model.includes("deepseek-r") ||
  265. model.includes("-thinking")
  266. )
  267. return REQUEST_TIMEOUT_MS_FOR_THINKING;
  268. return REQUEST_TIMEOUT_MS;
  269. }
  270. export function getModelSizes(model: string): ModelSize[] {
  271. if (isDalle3(model)) {
  272. return ["1024x1024", "1792x1024", "1024x1792"];
  273. }
  274. if (model.toLowerCase().includes("cogview")) {
  275. return [
  276. "1024x1024",
  277. "768x1344",
  278. "864x1152",
  279. "1344x768",
  280. "1152x864",
  281. "1440x720",
  282. "720x1440",
  283. ];
  284. }
  285. return [];
  286. }
  287. export function supportsCustomSize(model: string): boolean {
  288. return getModelSizes(model).length > 0;
  289. }
  290. export function showPlugins(provider: ServiceProvider, model: string) {
  291. if (
  292. provider == ServiceProvider.OpenAI ||
  293. provider == ServiceProvider.Azure ||
  294. provider == ServiceProvider.Moonshot ||
  295. provider == ServiceProvider.ChatGLM
  296. ) {
  297. return true;
  298. }
  299. if (provider == ServiceProvider.Anthropic && !model.includes("claude-2")) {
  300. return true;
  301. }
  302. if (provider == ServiceProvider.Google && !model.includes("vision")) {
  303. return true;
  304. }
  305. return false;
  306. }
  307. export function fetch(
  308. url: string,
  309. options?: Record<string, unknown>,
  310. ): Promise<any> {
  311. if (window.__TAURI__) {
  312. return tauriStreamFetch(url, options);
  313. }
  314. return window.fetch(url, options);
  315. }
  316. export function adapter(config: Record<string, unknown>) {
  317. const { baseURL, url, params, data: body, ...rest } = config;
  318. const path = baseURL ? `${baseURL}${url}` : url;
  319. const fetchUrl = params
  320. ? `${path}?${new URLSearchParams(params as any).toString()}`
  321. : path;
  322. return fetch(fetchUrl as string, { ...rest, body }).then((res) => {
  323. const { status, headers, statusText } = res;
  324. return res
  325. .text()
  326. .then((data: string) => ({ status, statusText, headers, data }));
  327. });
  328. }
  329. export function safeLocalStorage(): {
  330. getItem: (key: string) => string | null;
  331. setItem: (key: string, value: string) => void;
  332. removeItem: (key: string) => void;
  333. clear: () => void;
  334. } {
  335. let storage: Storage | null;
  336. try {
  337. if (typeof window !== "undefined" && window.localStorage) {
  338. storage = window.localStorage;
  339. } else {
  340. storage = null;
  341. }
  342. } catch (e) {
  343. console.error("localStorage is not available:", e);
  344. storage = null;
  345. }
  346. return {
  347. getItem(key: string): string | null {
  348. if (storage) {
  349. return storage.getItem(key);
  350. } else {
  351. console.warn(
  352. `Attempted to get item "${key}" from localStorage, but localStorage is not available.`,
  353. );
  354. return null;
  355. }
  356. },
  357. setItem(key: string, value: string): void {
  358. if (storage) {
  359. storage.setItem(key, value);
  360. } else {
  361. console.warn(
  362. `Attempted to set item "${key}" in localStorage, but localStorage is not available.`,
  363. );
  364. }
  365. },
  366. removeItem(key: string): void {
  367. if (storage) {
  368. storage.removeItem(key);
  369. } else {
  370. console.warn(
  371. `Attempted to remove item "${key}" from localStorage, but localStorage is not available.`,
  372. );
  373. }
  374. },
  375. clear(): void {
  376. if (storage) {
  377. storage.clear();
  378. } else {
  379. console.warn(
  380. "Attempted to clear localStorage, but localStorage is not available.",
  381. );
  382. }
  383. },
  384. };
  385. }
  386. export function getOperationId(operation: {
  387. operationId?: string;
  388. method: string;
  389. path: string;
  390. }) {
  391. // pattern '^[a-zA-Z0-9_-]+$'
  392. return (
  393. operation?.operationId ||
  394. `${operation.method.toUpperCase()}${operation.path.replaceAll("/", "_")}`
  395. );
  396. }
  397. export function clientUpdate() {
  398. // Version update functionality removed
  399. console.log("Version update functionality has been removed");
  400. return Promise.resolve();
  401. }
  402. // https://gist.github.com/iwill/a83038623ba4fef6abb9efca87ae9ccb
  403. export function semverCompare(a: string, b: string) {
  404. if (a.startsWith(b + "-")) return -1;
  405. if (b.startsWith(a + "-")) return 1;
  406. return a.localeCompare(b, undefined, {
  407. numeric: true,
  408. sensitivity: "case",
  409. caseFirst: "upper",
  410. });
  411. }