utils.ts 7.7 KB

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