utils.ts 11 KB

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