utils.ts 7.2 KB

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