utils.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 { DEFAULT_MODELS } 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 topic
  11. // fix for gemini
  12. .replace(/^["“”*]+|["“”*]+$/g, "")
  13. .replace(/[,。!?”“"、,.!?*]*$/, "");
  14. }
  15. export async function copyToClipboard(text: string) {
  16. try {
  17. if (window.__TAURI__) {
  18. window.__TAURI__.writeText(text);
  19. } else {
  20. await navigator.clipboard.writeText(text);
  21. }
  22. showToast(Locale.Copy.Success);
  23. } catch (error) {
  24. const textArea = document.createElement("textarea");
  25. textArea.value = text;
  26. document.body.appendChild(textArea);
  27. textArea.focus();
  28. textArea.select();
  29. try {
  30. document.execCommand("copy");
  31. showToast(Locale.Copy.Success);
  32. } catch (error) {
  33. showToast(Locale.Copy.Failed);
  34. }
  35. document.body.removeChild(textArea);
  36. }
  37. }
  38. export async function downloadAs(text: string, filename: string) {
  39. if (window.__TAURI__) {
  40. const result = await window.__TAURI__.dialog.save({
  41. defaultPath: `${filename}`,
  42. filters: [
  43. {
  44. name: `${filename.split(".").pop()} files`,
  45. extensions: [`${filename.split(".").pop()}`],
  46. },
  47. {
  48. name: "All Files",
  49. extensions: ["*"],
  50. },
  51. ],
  52. });
  53. if (result !== null) {
  54. try {
  55. await window.__TAURI__.fs.writeBinaryFile(
  56. result,
  57. new Uint8Array([...text].map((c) => c.charCodeAt(0))),
  58. );
  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 compressImage(file: File, maxSize: number): Promise<string> {
  80. return new Promise((resolve, reject) => {
  81. const reader = new FileReader();
  82. reader.onload = (readerEvent: any) => {
  83. const image = new Image();
  84. image.onload = () => {
  85. let canvas = document.createElement("canvas");
  86. let ctx = canvas.getContext("2d");
  87. let width = image.width;
  88. let height = image.height;
  89. let quality = 0.9;
  90. let dataUrl;
  91. do {
  92. canvas.width = width;
  93. canvas.height = height;
  94. ctx?.clearRect(0, 0, canvas.width, canvas.height);
  95. ctx?.drawImage(image, 0, 0, width, height);
  96. dataUrl = canvas.toDataURL("image/jpeg", quality);
  97. if (dataUrl.length < maxSize) break;
  98. if (quality > 0.5) {
  99. // Prioritize quality reduction
  100. quality -= 0.1;
  101. } else {
  102. // Then reduce the size
  103. width *= 0.9;
  104. height *= 0.9;
  105. }
  106. } while (dataUrl.length > maxSize);
  107. resolve(dataUrl);
  108. };
  109. image.onerror = reject;
  110. image.src = readerEvent.target.result;
  111. };
  112. reader.onerror = reject;
  113. reader.readAsDataURL(file);
  114. });
  115. }
  116. export function readFromFile() {
  117. return new Promise<string>((res, rej) => {
  118. const fileInput = document.createElement("input");
  119. fileInput.type = "file";
  120. fileInput.accept = "application/json";
  121. fileInput.onchange = (event: any) => {
  122. const file = event.target.files[0];
  123. const fileReader = new FileReader();
  124. fileReader.onload = (e: any) => {
  125. res(e.target.result);
  126. };
  127. fileReader.onerror = (e) => rej(e);
  128. fileReader.readAsText(file);
  129. };
  130. fileInput.click();
  131. });
  132. }
  133. export function isIOS() {
  134. const userAgent = navigator.userAgent.toLowerCase();
  135. return /iphone|ipad|ipod/.test(userAgent);
  136. }
  137. export function useWindowSize() {
  138. const [size, setSize] = useState({
  139. width: window.innerWidth,
  140. height: window.innerHeight,
  141. });
  142. useEffect(() => {
  143. const onResize = () => {
  144. setSize({
  145. width: window.innerWidth,
  146. height: window.innerHeight,
  147. });
  148. };
  149. window.addEventListener("resize", onResize);
  150. return () => {
  151. window.removeEventListener("resize", onResize);
  152. };
  153. }, []);
  154. return size;
  155. }
  156. export const MOBILE_MAX_WIDTH = 600;
  157. export function useMobileScreen() {
  158. const { width } = useWindowSize();
  159. return width <= MOBILE_MAX_WIDTH;
  160. }
  161. export function isFirefox() {
  162. return (
  163. typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
  164. );
  165. }
  166. export function selectOrCopy(el: HTMLElement, content: string) {
  167. const currentSelection = window.getSelection();
  168. if (currentSelection?.type === "Range") {
  169. return false;
  170. }
  171. copyToClipboard(content);
  172. return true;
  173. }
  174. function getDomContentWidth(dom: HTMLElement) {
  175. const style = window.getComputedStyle(dom);
  176. const paddingWidth =
  177. parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
  178. const width = dom.clientWidth - paddingWidth;
  179. return width;
  180. }
  181. function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) {
  182. let dom = document.getElementById(id);
  183. if (!dom) {
  184. dom = document.createElement("span");
  185. dom.style.position = "absolute";
  186. dom.style.wordBreak = "break-word";
  187. dom.style.fontSize = "14px";
  188. dom.style.transform = "translateY(-200vh)";
  189. dom.style.pointerEvents = "none";
  190. dom.style.opacity = "0";
  191. dom.id = id;
  192. document.body.appendChild(dom);
  193. init?.(dom);
  194. }
  195. return dom!;
  196. }
  197. export function autoGrowTextArea(dom: HTMLTextAreaElement) {
  198. const measureDom = getOrCreateMeasureDom("__measure");
  199. const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => {
  200. dom.innerText = "TEXT_FOR_MEASURE";
  201. });
  202. const width = getDomContentWidth(dom);
  203. measureDom.style.width = width + "px";
  204. measureDom.innerText = dom.value !== "" ? dom.value : "1";
  205. measureDom.style.fontSize = dom.style.fontSize;
  206. const endWithEmptyLine = dom.value.endsWith("\n");
  207. const height = parseFloat(window.getComputedStyle(measureDom).height);
  208. const singleLineHeight = parseFloat(
  209. window.getComputedStyle(singleLineDom).height,
  210. );
  211. const rows =
  212. Math.round(height / singleLineHeight) + (endWithEmptyLine ? 1 : 0);
  213. return rows;
  214. }
  215. export function getCSSVar(varName: string) {
  216. return getComputedStyle(document.body).getPropertyValue(varName).trim();
  217. }
  218. /**
  219. * Detects Macintosh
  220. */
  221. export function isMacOS(): boolean {
  222. if (typeof window !== "undefined") {
  223. let userAgent = window.navigator.userAgent.toLocaleLowerCase();
  224. const macintosh = /iphone|ipad|ipod|macintosh/.test(userAgent);
  225. return !!macintosh;
  226. }
  227. return false;
  228. }
  229. export function getMessageTextContent(message: RequestMessage) {
  230. if (typeof message.content === "string") {
  231. return message.content;
  232. }
  233. for (const c of message.content) {
  234. if (c.type === "text") {
  235. return c.text ?? "";
  236. }
  237. }
  238. return "";
  239. }
  240. export function getMessageImages(message: RequestMessage): string[] {
  241. if (typeof message.content === "string") {
  242. return [];
  243. }
  244. const urls: string[] = [];
  245. for (const c of message.content) {
  246. if (c.type === "image_url") {
  247. urls.push(c.image_url?.url ?? "");
  248. }
  249. }
  250. return urls;
  251. }
  252. export function isVisionModel(model: string) {
  253. return (
  254. model.startsWith("gpt-4-vision") ||
  255. model.startsWith("gemini-pro-vision") ||
  256. !DEFAULT_MODELS.find((m) => m.name == model)
  257. );
  258. }