mirror of
https://github.com/usememos/memos.git
synced 2025-06-05 22:09:59 +02:00
chore: update upload resources button
This commit is contained in:
@ -0,0 +1,84 @@
|
||||
import { IconButton } from "@mui/joy";
|
||||
import { useContext, useRef, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import Icon from "@/components/Icon";
|
||||
import { useResourceStore } from "@/store/v1";
|
||||
import { Resource } from "@/types/proto/api/v1/resource_service";
|
||||
import { MemoEditorContext } from "../types";
|
||||
|
||||
interface State {
|
||||
uploadingFlag: boolean;
|
||||
}
|
||||
|
||||
const UploadResourceButton = () => {
|
||||
const context = useContext(MemoEditorContext);
|
||||
const resourceStore = useResourceStore();
|
||||
const [state, setState] = useState<State>({
|
||||
uploadingFlag: false,
|
||||
});
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleFileInputChange = async () => {
|
||||
if (!fileInputRef.current || !fileInputRef.current.files || fileInputRef.current.files.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (state.uploadingFlag) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState((state) => {
|
||||
return {
|
||||
...state,
|
||||
uploadingFlag: true,
|
||||
};
|
||||
});
|
||||
|
||||
const createdResourceList: Resource[] = [];
|
||||
try {
|
||||
if (!fileInputRef.current || !fileInputRef.current.files) {
|
||||
return;
|
||||
}
|
||||
const filesOnInput = Array.from(fileInputRef.current.files);
|
||||
for (const file of fileInputRef.current.files) {
|
||||
const fileOnInput = filesOnInput.find((fileOnInput) => fileOnInput.name === file.name);
|
||||
if (!fileOnInput) {
|
||||
continue;
|
||||
}
|
||||
const { name: filename, size, type } = file;
|
||||
const buffer = new Uint8Array(await file.arrayBuffer());
|
||||
const resource = await resourceStore.createResource({
|
||||
resource: Resource.fromPartial({
|
||||
filename,
|
||||
size,
|
||||
type,
|
||||
content: buffer,
|
||||
}),
|
||||
});
|
||||
createdResourceList.push(resource);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
toast.error(error.details);
|
||||
}
|
||||
|
||||
context.setResourceList([...context.resourceList, ...createdResourceList]);
|
||||
};
|
||||
|
||||
return (
|
||||
<IconButton size="sm">
|
||||
<Icon.Image className="w-5 h-5 mx-auto" />
|
||||
<input
|
||||
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
|
||||
ref={fileInputRef}
|
||||
disabled={state.uploadingFlag}
|
||||
onChange={handleFileInputChange}
|
||||
type="file"
|
||||
id="files"
|
||||
multiple={true}
|
||||
accept="*"
|
||||
/>
|
||||
</IconButton>
|
||||
);
|
||||
};
|
||||
|
||||
export default UploadResourceButton;
|
Reference in New Issue
Block a user