Преглед на файлове

feat: close #887 import masks

Yidadaa преди 1 година
родител
ревизия
596c9b1d27
променени са 2 файла, в които са добавени 41 реда и са изтрити 3 реда
  1. 21 3
      app/components/mask.tsx
  2. 20 0
      app/utils.ts

+ 21 - 3
app/components/mask.tsx

@@ -21,7 +21,7 @@ import { useNavigate } from "react-router-dom";
 
 import chatStyle from "./chat.module.scss";
 import { useEffect, useState } from "react";
-import { downloadAs } from "../utils";
+import { downloadAs, readFromFile } from "../utils";
 import { Updater } from "../api/openai/typing";
 import { ModelConfigList } from "./model-config";
 import { FileName, Path } from "../constant";
@@ -222,6 +222,21 @@ export function MaskPage() {
     downloadAs(JSON.stringify(masks), FileName.Masks);
   };
 
+  const importFromFile = () => {
+    readFromFile().then((content) => {
+      try {
+        const importMasks = JSON.parse(content);
+        if (Array.isArray(importMasks)) {
+          for (const mask of importMasks) {
+            if (mask.name) {
+              maskStore.create(mask);
+            }
+          }
+        }
+      } catch {}
+    });
+  };
+
   return (
     <ErrorBoundary>
       <div className={styles["mask-page"]}>
@@ -247,7 +262,7 @@ export function MaskPage() {
               <IconButton
                 icon={<UploadIcon />}
                 bordered
-                onClick={() => showToast(Locale.WIP)}
+                onClick={() => importFromFile()}
               />
             </div>
             <div className="window-action-button">
@@ -371,7 +386,10 @@ export function MaskPage() {
                 key="export"
                 bordered
                 onClick={() =>
-                  downloadAs(JSON.stringify(editingMask), "mask.json")
+                  downloadAs(
+                    JSON.stringify(editingMask),
+                    `${editingMask.name}.json`,
+                  )
                 }
               />,
               <IconButton

+ 20 - 0
app/utils.ts

@@ -42,6 +42,26 @@ export function downloadAs(text: string, filename: string) {
   document.body.removeChild(element);
 }
 
+export function readFromFile() {
+  return new Promise<string>((res, rej) => {
+    const fileInput = document.createElement("input");
+    fileInput.type = "file";
+    fileInput.accept = "application/json";
+
+    fileInput.onchange = (event: any) => {
+      const file = event.target.files[0];
+      const fileReader = new FileReader();
+      fileReader.onload = (e: any) => {
+        res(e.target.result);
+      };
+      fileReader.onerror = (e) => rej(e);
+      fileReader.readAsText(file);
+    };
+
+    fileInput.click();
+  });
+}
+
 export function isIOS() {
   const userAgent = navigator.userAgent.toLowerCase();
   return /iphone|ipad|ipod/.test(userAgent);