utils.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 } from "./utils/stream";
  7. export function trimTopic(topic: string) {
  8. // Fix an issue where double quotes still show in the Indonesian language
  9. // This will remove the specified punctuation from the end of the string
  10. // and also trim quotes from both the start and end if they exist.
  11. return (
  12. topic
  13. // fix for gemini
  14. .replace(/^["“”*]+|["“”*]+$/g, "")
  15. .replace(/[,。!?”“"、,.!?*]*$/, "")
  16. );
  17. }
  18. export async function copyToClipboard(text: string) {
  19. try {
  20. if (window.__TAURI__) {
  21. window.__TAURI__.writeText(text);
  22. } else {
  23. await navigator.clipboard.writeText(text);
  24. }
  25. showToast(Locale.Copy.Success);
  26. } catch (error) {
  27. const textArea = document.createElement("textarea");
  28. textArea.value = text;
  29. document.body.appendChild(textArea);
  30. textArea.focus();
  31. textArea.select();
  32. try {
  33. document.execCommand("copy");
  34. showToast(Locale.Copy.Success);
  35. } catch (error) {
  36. showToast(Locale.Copy.Failed);
  37. }
  38. document.body.removeChild(textArea);
  39. }
  40. }
  41. export async function downloadAs(text: string, filename: string) {
  42. if (window.__TAURI__) {
  43. const result = await window.__TAURI__.dialog.save({
  44. defaultPath: `${filename}`,
  45. filters: [
  46. {
  47. name: `${filename.split(".").pop()} files`,
  48. extensions: [`${filename.split(".").pop()}`],
  49. },
  50. {
  51. name: "All Files",
  52. extensions: ["*"],
  53. },
  54. ],
  55. });
  56. if (result !== null) {
  57. try {
  58. await window.__TAURI__.fs.writeTextFile(result, text);
  59. showToast(Locale.Download.Success);
  60. } catch (error) {
  61. showToast(Locale.Download.Failed);
  62. }
  63. } else {
  64. showToast(Locale.Download.Failed);
  65. }
  66. } else {
  67. const element = document.createElement("a");
  68. element.setAttribute(
  69. "href",
  70. "data:text/plain;charset=utf-8," + encodeURIComponent(text),
  71. );
  72. element.setAttribute("download", filename);
  73. element.style.display = "none";
  74. document.body.appendChild(element);
  75. element.click();
  76. document.body.removeChild(element);
  77. }
  78. }
  79. export function readFromFile() {
  80. return new Promise<string>((res, rej) => {
  81. const fileInput = document.createElement("input");
  82. fileInput.type = "file";
  83. fileInput.accept = "application/json";
  84. fileInput.onchange = (event: any) => {
  85. const file = event.target.files[0];
  86. const fileReader = new FileReader();
  87. fileReader.onload = (e: any) => {
  88. res(e.target.result);
  89. };
  90. fileReader.onerror = (e) => rej(e);
  91. fileReader.readAsText(file);
  92. };
  93. fileInput.click();
  94. });
  95. }
  96. export function isIOS() {
  97. const userAgent = navigator.userAgent.toLowerCase();
  98. return /iphone|ipad|ipod/.test(userAgent);
  99. }
  100. export function useWindowSize() {
  101. const [size, setSize] = useState({
  102. width: window.innerWidth,
  103. height: window.innerHeight,
  104. });
  105. useEffect(() => {
  106. const onResize = () => {
  107. setSize({
  108. width: window.innerWidth,
  109. height: window.innerHeight,
  110. });
  111. };
  112. window.addEventListener("resize", onResize);
  113. return () => {
  114. window.removeEventListener("resize", onResize);
  115. };
  116. }, []);
  117. return size;
  118. }
  119. export const MOBILE_MAX_WIDTH = 600;
  120. export function useMobileScreen() {
  121. const { width } = useWindowSize();
  122. return width <= MOBILE_MAX_WIDTH;
  123. }
  124. export function isFirefox() {
  125. return (
  126. typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
  127. );
  128. }
  129. export function selectOrCopy(el: HTMLElement, content: string) {
  130. const currentSelection = window.getSelection();
  131. if (currentSelection?.type === "Range") {
  132. return false;
  133. }
  134. copyToClipboard(content);
  135. return true;
  136. }
  137. function getDomContentWidth(dom: HTMLElement) {
  138. const style = window.getComputedStyle(dom);
  139. const paddingWidth =
  140. parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
  141. const width = dom.clientWidth - paddingWidth;
  142. return width;
  143. }
  144. function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) {
  145. let dom = document.getElementById(id);
  146. if (!dom) {
  147. dom = document.createElement("span");
  148. dom.style.position = "absolute";
  149. dom.style.wordBreak = "break-word";
  150. dom.style.fontSize = "14px";
  151. dom.style.transform = "translateY(-200vh)";
  152. dom.style.pointerEvents = "none";
  153. dom.style.opacity = "0";
  154. dom.id = id;
  155. document.body.appendChild(dom);
  156. init?.(dom);
  157. }
  158. return dom!;
  159. }
  160. export function autoGrowTextArea(dom: HTMLTextAreaElement) {
  161. const measureDom = getOrCreateMeasureDom("__measure");
  162. const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => {
  163. dom.innerText = "TEXT_FOR_MEASURE";
  164. });
  165. const width = getDomContentWidth(dom);
  166. measureDom.style.width = width + "px";
  167. measureDom.innerText = dom.value !== "" ? dom.value : "1";
  168. measureDom.style.fontSize = dom.style.fontSize;
  169. measureDom.style.fontFamily = dom.style.fontFamily;
  170. const endWithEmptyLine = dom.value.endsWith("\n");
  171. const height = parseFloat(window.getComputedStyle(measureDom).height);
  172. const singleLineHeight = parseFloat(
  173. window.getComputedStyle(singleLineDom).height,
  174. );
  175. const rows =
  176. Math.round(height / singleLineHeight) + (endWithEmptyLine ? 1 : 0);
  177. return rows;
  178. }
  179. export function getCSSVar(varName: string) {
  180. return getComputedStyle(document.body).getPropertyValue(varName).trim();
  181. }
  182. /**
  183. * Detects Macintosh
  184. */
  185. export function isMacOS(): boolean {
  186. if (typeof window !== "undefined") {
  187. let userAgent = window.navigator.userAgent.toLocaleLowerCase();
  188. const macintosh = /iphone|ipad|ipod|macintosh/.test(userAgent);
  189. return !!macintosh;
  190. }
  191. return false;
  192. }
  193. export function getMessageTextContent(message: RequestMessage) {
  194. if (typeof message.content === "string") {
  195. return message.content;
  196. }
  197. for (const c of message.content) {
  198. if (c.type === "text") {
  199. return c.text ?? "";
  200. }
  201. }
  202. return "";
  203. }
  204. export function getMessageImages(message: RequestMessage): string[] {
  205. if (typeof message.content === "string") {
  206. return [];
  207. }
  208. const urls: string[] = [];
  209. for (const c of message.content) {
  210. if (c.type === "image_url") {
  211. urls.push(c.image_url?.url ?? "");
  212. }
  213. }
  214. return urls;
  215. }
  216. export function isVisionModel(model: string) {
  217. // Note: This is a better way using the TypeScript feature instead of `&&` or `||` (ts v5.5.0-dev.20240314 I've been using)
  218. const visionKeywords = [
  219. "vision",
  220. "claude-3",
  221. "gemini-1.5-pro",
  222. "gemini-1.5-flash",
  223. "gpt-4o",
  224. "gpt-4o-mini",
  225. ];
  226. const isGpt4Turbo =
  227. model.includes("gpt-4-turbo") && !model.includes("preview");
  228. return (
  229. visionKeywords.some((keyword) => model.includes(keyword)) || isGpt4Turbo
  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. ) {
  241. return true;
  242. }
  243. if (provider == ServiceProvider.Anthropic && !model.includes("claude-2")) {
  244. return true;
  245. }
  246. return false;
  247. }
  248. export function adapter(config: Record<string, unknown>) {
  249. const { baseURL, url, params, ...rest } = config;
  250. const path = baseURL ? `${baseURL}${url}` : url;
  251. const fetchUrl = params
  252. ? `${path}?${new URLSearchParams(params as any).toString()}`
  253. : path;
  254. return fetch(fetchUrl as string, rest)
  255. .then((res) => res.text())
  256. .then((data) => ({ data }));
  257. }
  258. export function safeLocalStorage(): {
  259. getItem: (key: string) => string | null;
  260. setItem: (key: string, value: string) => void;
  261. removeItem: (key: string) => void;
  262. clear: () => void;
  263. } {
  264. let storage: Storage | null;
  265. try {
  266. if (typeof window !== "undefined" && window.localStorage) {
  267. storage = window.localStorage;
  268. } else {
  269. storage = null;
  270. }
  271. } catch (e) {
  272. console.error("localStorage is not available:", e);
  273. storage = null;
  274. }
  275. return {
  276. getItem(key: string): string | null {
  277. if (storage) {
  278. return storage.getItem(key);
  279. } else {
  280. console.warn(
  281. `Attempted to get item "${key}" from localStorage, but localStorage is not available.`,
  282. );
  283. return null;
  284. }
  285. },
  286. setItem(key: string, value: string): void {
  287. if (storage) {
  288. storage.setItem(key, value);
  289. } else {
  290. console.warn(
  291. `Attempted to set item "${key}" in localStorage, but localStorage is not available.`,
  292. );
  293. }
  294. },
  295. removeItem(key: string): void {
  296. if (storage) {
  297. storage.removeItem(key);
  298. } else {
  299. console.warn(
  300. `Attempted to remove item "${key}" from localStorage, but localStorage is not available.`,
  301. );
  302. }
  303. },
  304. clear(): void {
  305. if (storage) {
  306. storage.clear();
  307. } else {
  308. console.warn(
  309. "Attempted to clear localStorage, but localStorage is not available.",
  310. );
  311. }
  312. },
  313. };
  314. }