utils.ts 7.7 KB

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