mirror of
https://github.com/usememos/memos.git
synced 2025-06-05 22:09:59 +02:00
feat: handle upload image by drop event
This commit is contained in:
@ -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("内容不能为空呀");
|
||||
|
Reference in New Issue
Block a user