utils.ts 12 KB

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