Merge pull request #510 from vivganes/patch-502

add ability to paste image from clipboard
This commit is contained in:
Kieran 2023-04-13 18:02:15 +01:00 committed by GitHub
commit c3c1e02ad8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 58 additions and 18 deletions

View File

@ -27,6 +27,8 @@ import type { RootState } from "State/Store";
import { LNURL } from "LNURL";
import messages from "./messages";
import { ClipboardEventHandler, useState } from "react";
import Spinner from "Icons/Spinner";
interface NotePreviewProps {
note: TaggedRawEvent;
@ -58,6 +60,7 @@ export function NoteCreator() {
const zapForward = useSelector((s: RootState) => s.noteCreator.zapForward);
const sensitive = useSelector((s: RootState) => s.noteCreator.sensitive);
const pollOptions = useSelector((s: RootState) => s.noteCreator.pollOptions);
const [uploadInProgress, setUploadInProgress] = useState(false);
const dispatch = useDispatch();
async function sendNote() {
@ -99,6 +102,19 @@ export function NoteCreator() {
async function attachFile() {
try {
const file = await openFile();
if (file) {
uploadFile(file);
}
} catch (error: unknown) {
if (error instanceof Error) {
dispatch(setError(error?.message));
}
}
}
async function uploadFile(file: File | Blob) {
setUploadInProgress(true);
try {
if (file) {
const rx = await uploader.upload(file, file.name);
if (rx.url) {
@ -111,6 +127,8 @@ export function NoteCreator() {
if (error instanceof Error) {
dispatch(setError(error?.message));
}
} finally {
setUploadInProgress(false);
}
}
@ -205,6 +223,25 @@ export function NoteCreator() {
}
}
const handlePaste: ClipboardEventHandler<HTMLDivElement> = evt => {
if (evt.clipboardData) {
const clipboardItems = evt.clipboardData.items;
const items: DataTransferItem[] = Array.from(clipboardItems).filter(function (item: DataTransferItem) {
// Filter the image items only
return /^image\//.test(item.type);
});
if (items.length === 0) {
return;
}
const item = items[0];
const blob = item.getAsFile();
if (blob) {
uploadFile(blob);
}
}
};
return (
<>
{show && (
@ -212,7 +249,9 @@ export function NoteCreator() {
{replyTo && <NotePreview note={replyTo} />}
{preview && getPreviewNote()}
{!preview && (
<div className={`flex note-creator${replyTo ? " note-reply" : ""}${pollOptions ? " poll" : ""}`}>
<div
onPaste={handlePaste}
className={`flex note-creator${replyTo ? " note-reply" : ""}${pollOptions ? " poll" : ""}`}>
<div className="flex f-col f-grow">
<Textarea
autoFocus
@ -242,6 +281,7 @@ export function NoteCreator() {
</div>
)}
<div className="note-creator-actions">
{uploadInProgress && <Spinner />}
<button className="secondary" type="button" onClick={() => dispatch(setShowAdvanced(!showAdvanced))}>
<FormattedMessage defaultMessage="Advanced" />
</button>