feat: handle upload image by drop event

This commit is contained in:
boojack
2021-12-17 08:11:02 +08:00
parent 3fc74490de
commit 494c4f4578
4 changed files with 60 additions and 40 deletions

View File

@ -1,6 +1,6 @@
import { useCallback, useContext, useEffect, useMemo, useRef } from "react";
import appContext from "../stores/appContext";
import { globalStateService, locationService, memoService } from "../services";
import { globalStateService, locationService, memoService, resourceService } from "../services";
import utils from "../helpers/utils";
import { storage } from "../helpers/storage";
import toastHelper from "./Toast";
@ -33,6 +33,57 @@ const MemoEditor: React.FC<Props> = () => {
prevGlobalStateRef.current = globalState;
}, [globalState.markMemoId, globalState.editMemoId]);
useEffect(() => {
if (!editorRef.current) {
return;
}
const handleUploadFile = async (file: File) => {
const { type } = file;
if (!type.startsWith("image")) {
return;
}
try {
if (!editorRef.current) {
return;
}
const image = await resourceService.upload(file);
const url = `/r/${image.id}/${image.filename}`;
editorRef.current.insertText(url);
} catch (error: any) {
toastHelper.error(error);
}
};
const handlePasteEvent = async (event: ClipboardEvent) => {
if (event.clipboardData && event.clipboardData.files.length > 0) {
event.preventDefault();
const file = event.clipboardData.files[0];
handleUploadFile(file);
}
};
const handleDropEvent = async (event: DragEvent) => {
if (event.dataTransfer && event.dataTransfer.files.length > 0) {
event.preventDefault();
const file = event.dataTransfer.files[0];
handleUploadFile(file);
}
};
editorRef.current.element.addEventListener("paste", handlePasteEvent);
editorRef.current.element.addEventListener("drop", handleDropEvent);
return () => {
editorRef.current?.element.removeEventListener("paste", handlePasteEvent);
editorRef.current?.element.removeEventListener("drop", handleDropEvent);
};
}, []);
const handleSaveBtnClick = useCallback(async (content: string) => {
if (content === "") {
toastHelper.error("内容不能为空呀");