utils.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. 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. provider == ServiceProvider.ChatGLM
  242. ) {
  243. return true;
  244. }
  245. if (provider == ServiceProvider.Anthropic && !model.includes("claude-2")) {
  246. return true;
  247. }
  248. if (provider == ServiceProvider.Google && !model.includes("vision")) {
  249. return true;
  250. }
  251. return false;
  252. }
  253. export function fetch(
  254. url: string,
  255. options?: Record<string, unknown>,
  256. ): Promise<any> {
  257. if (window.__TAURI__) {
  258. return tauriStreamFetch(url, options);
  259. }
  260. return window.fetch(url, options);
  261. }
  262. export function adapter(config: Record<string, unknown>) {
  263. const { baseURL, url, params, data: body, ...rest } = config;
  264. const path = baseURL ? `${baseURL}${url}` : url;
  265. const fetchUrl = params
  266. ? `${path}?${new URLSearchParams(params as any).toString()}`
  267. : path;
  268. return fetch(fetchUrl as string, { ...rest, body }).then((res) => {
  269. const { status, headers, statusText } = res;
  270. return res
  271. .text()
  272. .then((data: string) => ({ status, statusText, headers, data }));
  273. });
  274. }
  275. export function safeLocalStorage(): {
  276. getItem: (key: string) => string | null;
  277. setItem: (key: string, value: string) => void;
  278. removeItem: (key: string) => void;
  279. clear: () => void;
  280. } {
  281. let storage: Storage | null;
  282. try {
  283. if (typeof window !== "undefined" && window.localStorage) {
  284. storage = window.localStorage;
  285. } else {
  286. storage = null;
  287. }
  288. } catch (e) {
  289. console.error("localStorage is not available:", e);
  290. storage = null;
  291. }
  292. return {
  293. getItem(key: string): string | null {
  294. if (storage) {
  295. return storage.getItem(key);
  296. } else {
  297. console.warn(
  298. `Attempted to get item "${key}" from localStorage, but localStorage is not available.`,
  299. );
  300. return null;
  301. }
  302. },
  303. setItem(key: string, value: string): void {
  304. if (storage) {
  305. storage.setItem(key, value);
  306. } else {
  307. console.warn(
  308. `Attempted to set item "${key}" in localStorage, but localStorage is not available.`,
  309. );
  310. }
  311. },
  312. removeItem(key: string): void {
  313. if (storage) {
  314. storage.removeItem(key);
  315. } else {
  316. console.warn(
  317. `Attempted to remove item "${key}" from localStorage, but localStorage is not available.`,
  318. );
  319. }
  320. },
  321. clear(): void {
  322. if (storage) {
  323. storage.clear();
  324. } else {
  325. console.warn(
  326. "Attempted to clear localStorage, but localStorage is not available.",
  327. );
  328. }
  329. },
  330. };
  331. }
  332. export function getOperationId(operation: {
  333. operationId?: string;
  334. method: string;
  335. path: string;
  336. }) {
  337. // pattern '^[a-zA-Z0-9_-]+$'
  338. return (
  339. operation?.operationId ||
  340. `${operation.method.toUpperCase()}${operation.path.replaceAll("/", "_")}`
  341. );
  342. }
  343. export function clientUpdate() {
  344. // this a wild for updating client app
  345. return window.__TAURI__?.updater
  346. .checkUpdate()
  347. .then((updateResult) => {
  348. if (updateResult.shouldUpdate) {
  349. window.__TAURI__?.updater
  350. .installUpdate()
  351. .then((result) => {
  352. showToast(Locale.Settings.Update.Success);
  353. })
  354. .catch((e) => {
  355. console.error("[Install Update Error]", e);
  356. showToast(Locale.Settings.Update.Failed);
  357. });
  358. }
  359. })
  360. .catch((e) => {
  361. console.error("[Check Update Error]", e);
  362. showToast(Locale.Settings.Update.Failed);
  363. });
  364. }
  365. // https://gist.github.com/iwill/a83038623ba4fef6abb9efca87ae9ccb
  366. export function semverCompare(a: string, b: string) {
  367. if (a.startsWith(b + "-")) return -1;
  368. if (b.startsWith(a + "-")) return 1;
  369. return a.localeCompare(b, undefined, {
  370. numeric: true,
  371. sensitivity: "case",
  372. caseFirst: "upper",
  373. });
  374. }