utils.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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 getMessageImages(message: RequestMessage): string[] {
  209. if (typeof message.content === "string") {
  210. return [];
  211. }
  212. const urls: string[] = [];
  213. for (const c of message.content) {
  214. if (c.type === "image_url") {
  215. urls.push(c.image_url?.url ?? "");
  216. }
  217. }
  218. return urls;
  219. }
  220. export function isVisionModel(model: string) {
  221. const visionModels = useAccessStore.getState().visionModels;
  222. const envVisionModels = visionModels
  223. ?.split(",")
  224. .map((m) => m.trim());
  225. if (envVisionModels?.includes(model)) {
  226. return true;
  227. }
  228. return (
  229. !EXCLUDE_VISION_MODEL_REGEXES.some((regex) => regex.test(model)) &&
  230. VISION_MODEL_REGEXES.some((regex) => regex.test(model))
  231. );
  232. }
  233. export function isDalle3(model: string) {
  234. return "dall-e-3" === model;
  235. }
  236. export function getModelSizes(model: string): ModelSize[] {
  237. if (isDalle3(model)) {
  238. return ["1024x1024", "1792x1024", "1024x1792"];
  239. }
  240. if (model.toLowerCase().includes("cogview")) {
  241. return [
  242. "1024x1024",
  243. "768x1344",
  244. "864x1152",
  245. "1344x768",
  246. "1152x864",
  247. "1440x720",
  248. "720x1440",
  249. ];
  250. }
  251. return [];
  252. }
  253. export function supportsCustomSize(model: string): boolean {
  254. return getModelSizes(model).length > 0;
  255. }
  256. export function showPlugins(provider: ServiceProvider, model: string) {
  257. if (
  258. provider == ServiceProvider.OpenAI ||
  259. provider == ServiceProvider.Azure ||
  260. provider == ServiceProvider.Moonshot ||
  261. provider == ServiceProvider.ChatGLM
  262. ) {
  263. return true;
  264. }
  265. if (provider == ServiceProvider.Anthropic && !model.includes("claude-2")) {
  266. return true;
  267. }
  268. if (provider == ServiceProvider.Google && !model.includes("vision")) {
  269. return true;
  270. }
  271. return false;
  272. }
  273. export function fetch(
  274. url: string,
  275. options?: Record<string, unknown>,
  276. ): Promise<any> {
  277. if (window.__TAURI__) {
  278. return tauriStreamFetch(url, options);
  279. }
  280. return window.fetch(url, options);
  281. }
  282. export function adapter(config: Record<string, unknown>) {
  283. const { baseURL, url, params, data: body, ...rest } = config;
  284. const path = baseURL ? `${baseURL}${url}` : url;
  285. const fetchUrl = params
  286. ? `${path}?${new URLSearchParams(params as any).toString()}`
  287. : path;
  288. return fetch(fetchUrl as string, { ...rest, body }).then((res) => {
  289. const { status, headers, statusText } = res;
  290. return res
  291. .text()
  292. .then((data: string) => ({ status, statusText, headers, data }));
  293. });
  294. }
  295. export function safeLocalStorage(): {
  296. getItem: (key: string) => string | null;
  297. setItem: (key: string, value: string) => void;
  298. removeItem: (key: string) => void;
  299. clear: () => void;
  300. } {
  301. let storage: Storage | null;
  302. try {
  303. if (typeof window !== "undefined" && window.localStorage) {
  304. storage = window.localStorage;
  305. } else {
  306. storage = null;
  307. }
  308. } catch (e) {
  309. console.error("localStorage is not available:", e);
  310. storage = null;
  311. }
  312. return {
  313. getItem(key: string): string | null {
  314. if (storage) {
  315. return storage.getItem(key);
  316. } else {
  317. console.warn(
  318. `Attempted to get item "${key}" from localStorage, but localStorage is not available.`,
  319. );
  320. return null;
  321. }
  322. },
  323. setItem(key: string, value: string): void {
  324. if (storage) {
  325. storage.setItem(key, value);
  326. } else {
  327. console.warn(
  328. `Attempted to set item "${key}" in localStorage, but localStorage is not available.`,
  329. );
  330. }
  331. },
  332. removeItem(key: string): void {
  333. if (storage) {
  334. storage.removeItem(key);
  335. } else {
  336. console.warn(
  337. `Attempted to remove item "${key}" from localStorage, but localStorage is not available.`,
  338. );
  339. }
  340. },
  341. clear(): void {
  342. if (storage) {
  343. storage.clear();
  344. } else {
  345. console.warn(
  346. "Attempted to clear localStorage, but localStorage is not available.",
  347. );
  348. }
  349. },
  350. };
  351. }
  352. export function getOperationId(operation: {
  353. operationId?: string;
  354. method: string;
  355. path: string;
  356. }) {
  357. // pattern '^[a-zA-Z0-9_-]+$'
  358. return (
  359. operation?.operationId ||
  360. `${operation.method.toUpperCase()}${operation.path.replaceAll("/", "_")}`
  361. );
  362. }
  363. export function clientUpdate() {
  364. // this a wild for updating client app
  365. return window.__TAURI__?.updater
  366. .checkUpdate()
  367. .then((updateResult) => {
  368. if (updateResult.shouldUpdate) {
  369. window.__TAURI__?.updater
  370. .installUpdate()
  371. .then((result) => {
  372. showToast(Locale.Settings.Update.Success);
  373. })
  374. .catch((e) => {
  375. console.error("[Install Update Error]", e);
  376. showToast(Locale.Settings.Update.Failed);
  377. });
  378. }
  379. })
  380. .catch((e) => {
  381. console.error("[Check Update Error]", e);
  382. showToast(Locale.Settings.Update.Failed);
  383. });
  384. }
  385. // https://gist.github.com/iwill/a83038623ba4fef6abb9efca87ae9ccb
  386. export function semverCompare(a: string, b: string) {
  387. if (a.startsWith(b + "-")) return -1;
  388. if (b.startsWith(a + "-")) return 1;
  389. return a.localeCompare(b, undefined, {
  390. numeric: true,
  391. sensitivity: "case",
  392. caseFirst: "upper",
  393. });
  394. }