utils.ts 11 KB

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