A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
feat: download pasted images
thecodrr2e944b6d700b
diff --git a/packages/editor/src/extensions/image/component.tsx b/packages/editor/src/extensions/image/component.tsxindex e2e1a5c7a..f09dd7493 100644--- a/packages/editor/src/extensions/image/component.tsx+++ b/packages/editor/src/extensions/image/component.tsx@@ -1,7 +1,7 @@-import { Box, Flex, Image } from "rebass";+import { Box, Button, Flex, Image, Text } from "rebass";import { ImageAlignmentOptions, ImageAttributes } from "./image";import { Resizable } from "re-resizable";-import { useEffect, useRef } from "react";+import React, { useEffect, useRef, useState } from "react";import { SelectionBasedReactNodeViewProps } from "../react";import { DesktopOnly } from "../../components/responsive";import { Icon } from "../../toolbar/components/icon";@@ -9,21 +9,44 @@ import { Icons } from "../../toolbar/icons";import { ToolbarGroup } from "../../toolbar/components/toolbar-group";import { useIsMobile } from "../../toolbar/stores/toolbar-store";import { Resizer } from "../../components/resizer";+import { Editor } from "../../types";+import {+ downloadImage,+ isDataUrl,+ toBlobURL,+ toDataURL,+} from "../../utils/downloader";export function ImageComponent(props: SelectionBasedReactNodeViewProps<ImageAttributes & ImageAlignmentOptions>) {- const { editor, updateAttributes, node, selected } = props;+ const { editor, node, selected } = props;const isMobile = useIsMobile();let { src, alt, title, width, height, align, float } = node.attrs;const imageRef = useRef<HTMLImageElement>();+ const [error, setError] = useState<string>();+ const [source, setSource] = useState<string>();useEffect(() => {(async () => {- if (!imageRef.current || !src) return;- imageRef.current.src = await dataUriToBlobURL(src);+ if (!src) return;+ try {+ if (isDataUrl(src)) setSource(await toBlobURL(src));+ else {+ const { url, size, blob, type } = await downloadImage(src);+ setSource(url);+ console.log(url, size, blob, type);+ editor.current?.commands.updateImage(+ { src },+ { src: await toDataURL(blob), size, type }+ );+ }+ } catch (e) {+ console.error(e);+ if (e instanceof Error) setError(e.message);+ }})();}, [src, imageRef]);@@ -33,7 +56,10 @@ export function ImageComponent(<><Boxsx={{- display: float ? "block" : "flex",+ display: float ? "inline" : "flex",+ ml: float ? (align === "right" ? 2 : 0) : 0,+ mr: float ? (align === "left" ? 2 : 0) : 0,+ float: float ? (align as "left" | "right") : "none",justifyContent: float? "stretch": align === "center"@@ -46,92 +72,193 @@ export function ImageComponent(},}}>- <Resizer- editor={editor}- selected={selected}- width={width}- height={height}- onResize={(width, height) => {- updateAttributes(- {- width,- height,- },- { addToHistory: true, preventUpdate: false }- );- }}- >- <DesktopOnly>- {selected && (- <Flex sx={{ position: "relative", justifyContent: "end" }}>- <Flex- sx={{- position: "absolute",- top: -40,- mb: 2,- alignItems: "end",- }}- >- <ToolbarGroup- editor={editor}- tools={[- "imageAlignLeft",- "imageAlignCenter",- "imageAlignRight",- "imageProperties",- ]}- sx={{- boxShadow: "menu",- borderRadius: "default",- bg: "background",- }}- />- </Flex>- </Flex>- )}- </DesktopOnly>- {selected && (- <Icon- className="drag-handle"- data-drag-handle- draggable- path={Icons.dragHandle}- sx={{- cursor: "grab",- position: "absolute",- top: 2,- left: 2,- zIndex: 999,- }}- />- )}- <Image- data-drag-image- ref={imageRef}- alt={alt}- src="/placeholder.svg"- title={title}- width={"100%"}- height={"100%"}+ {!source || error ? (+ <Flex+ width={width}+ maxWidth="100%"+ minWidth={135}sx={{bg: "bgSecondary",border: selected? "2px solid var(--primary)": "2px solid transparent",borderRadius: "default",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ py: 50,+ }}+ >+ <Icon+ path={+ error+ ? Icons.imageFailed+ : !source && !isDataUrl(src)+ ? Icons.imageDownload+ : Icons.image+ }+ size={72}+ color="gray"+ />++ <Text+ as="span"+ variant={"subBody"}+ sx={{+ display: "inline-block",+ textDecoration: "none",+ textAlign: "center",+ mx: 2,+ mt: 2,+ }}+ >+ {error+ ? `There was an error loading the image: ${error}`+ : !source+ ? `Downloading image from ${new URL(src).hostname}`+ : ""}+ </Text>+ {error ? (+ <Button+ variant="secondary"+ sx={{ mt: 1 }}+ onClick={() => {+ setSource(src);+ setError(undefined);+ }}+ >+ Skip downloading (unsafe)+ </Button>+ ) : null}+ </Flex>+ ) : (+ <Resizer+ editor={editor}+ selected={selected}+ width={width}+ height={height}+ onResize={(width, height) => {+ editor.commands.setImageSize({ width, height });}}- {...props}- />- </Resizer>+ >+ <DesktopOnly>+ {selected && (+ <Flex sx={{ position: "relative", justifyContent: "end" }}>+ <Flex+ sx={{+ position: "absolute",+ top: -40,+ mb: 2,+ alignItems: "end",+ }}+ >+ <ToolbarGroup+ editor={editor}+ tools={+ float+ ? [+ "imageAlignLeft",+ "imageAlignRight",+ "imageProperties",+ ]+ : [+ "imageAlignLeft",+ "imageAlignCenter",+ "imageAlignRight",+ "imageProperties",+ ]+ }+ sx={{+ boxShadow: "menu",+ borderRadius: "default",+ bg: "background",+ }}+ />+ </Flex>+ </Flex>+ )}+ </DesktopOnly>+ {selected && (+ <Icon+ className="drag-handle"+ data-drag-handle+ draggable+ path={Icons.dragHandle}+ sx={{+ cursor: "grab",+ position: "absolute",+ top: 2,+ left: 2,+ zIndex: 999,+ }}+ />+ )}+ <Image+ data-drag-image+ ref={imageRef}+ alt={alt}+ src={source}+ title={title}+ width={"100%"}+ height={"100%"}+ sx={{+ bg: "bgSecondary",+ border: selected+ ? "2px solid var(--primary)"+ : "2px solid transparent",+ borderRadius: "default",+ }}+ {...props}+ />+ </Resizer>+ )}</Box></>);}-async function dataUriToBlobURL(dataurl: string) {- if (!dataurl.startsWith("data:image")) return dataurl;+type ImageHeaderToolbarProps = {+ editor: Editor;+ float?: boolean;+ selected: boolean;+};+function _ImageHeaderToolbar(props: ImageHeaderToolbarProps) {+ const { editor, float, selected } = props;- const response = await fetch(dataurl);- const blob = await response.blob();- return URL.createObjectURL(blob);+ if (!selected) return null;+ return (+ <Flex sx={{ position: "relative", justifyContent: "end" }}>+ <Flex+ sx={{+ position: "absolute",+ top: -40,+ mb: 2,+ alignItems: "end",+ }}+ >+ <ToolbarGroup+ editor={editor}+ tools={+ float+ ? ["imageAlignLeft", "imageAlignRight", "imageProperties"]+ : [+ "imageAlignLeft",+ "imageAlignCenter",+ "imageAlignRight",+ "imageProperties",+ ]+ }+ sx={{+ boxShadow: "menu",+ borderRadius: "default",+ bg: "background",+ }}+ />+ </Flex>+ </Flex>+ );}++const ImageHeaderToolbar = React.memo(_ImageHeaderToolbar, (prev, next) => {+ return prev.float === next.float && prev.selected === next.selected;+});diff --git a/packages/editor/src/toolbar/icons.ts b/packages/editor/src/toolbar/icons.tsindex f4d74f786..86ac0d05c 100644--- a/packages/editor/src/toolbar/icons.ts+++ b/packages/editor/src/toolbar/icons.ts@@ -84,7 +84,10 @@ import {mdiFormatHeaderPound,mdiFormatIndentIncrease,mdiFormatIndentDecrease,- mdiResizeBottomRight+ mdiResizeBottomRight,+ mdiImageOutline,+ mdiProgressDownload,+ mdiProgressAlert,} from "@mdi/js";export const Icons = {@@ -119,7 +122,9 @@ export const Icons = {"M7 7h4v2H7c-1.6568542 0-3 1.343146-3 3s1.3431458 3 3 3h4v2H7c-2.7614237 0-5-2.238576-5-5 0-2.7614237 2.2385763-5 5-5m10 0c2.761424 0 5 2.2385763 5 5h-2c0-1.656854-1.343146-3-3-3h-4V7h4m-9 4h8v2H8v-2m15.119777 8.323608-1.07-.82c.02-.17.04-.33.04-.5 0-.17-.01-.33-.04-.5l1.06-.82c.09258-.07939.117526-.212463.06-.32l-1-1.73c-.06-.13-.19-.13-.33-.13l-1.22.5c-.28-.18-.54-.35-.85-.47l-.19-1.32c-.01-.12-.12-.21-.24-.21h-2c-.12 0-.23.09-.25.21l-.19 1.32c-.3.13-.59.29-.85.47l-1.24-.5c-.11 0-.24 0-.31.13l-1 1.73c-.06.11-.04.24.06.32l1.06.82c-.03989.33214-.03989.66786 0 1l-1.06.82c-.09258.07939-.117526.212462-.06.32l1 1.73c.06.13.19.13.31.13l1.24-.5c.26.18.54.35.85.47l.19 1.32c.02.12.12.21.25.21h2c.12 0 .23-.09.25-.21l.19-1.32c.3-.13.56-.29.84-.47l1.22.5c.14 0 .27 0 .34-.13l1-1.73c.05753-.107538.03258-.240607-.06-.32m-4.78.18c-.83 0-1.5-.67-1.5-1.5s.68-1.5 1.5-1.5 1.5.67 1.5 1.5-.66 1.5-1.5 1.5z",url: mdiLink,- image: mdiImage,+ image: mdiImageOutline,+ imageDownload: mdiProgressDownload,+ imageFailed: mdiProgressAlert,imageSettings: mdiImageEditOutline,colorClear: mdiInvertColorsOff,check: mdiCheck,@@ -193,7 +198,7 @@ export const Icons = {circle: mdiCircle,arrowLeft: mdiArrowLeft,resize: mdiResizeBottomRight,- none: ""+ none: "",};export type IconNames = keyof typeof Icons;diff --git a/packages/editor/src/toolbar/popups/image-upload.tsx b/packages/editor/src/toolbar/popups/image-upload.tsxindex 7cb6cf9c8..138d774a0 100644--- a/packages/editor/src/toolbar/popups/image-upload.tsx+++ b/packages/editor/src/toolbar/popups/image-upload.tsx@@ -2,8 +2,8 @@ import { Input } from "@rebass/forms";import { useState } from "react";import { Flex, Text } from "rebass";import { ImageAttributes } from "../../extensions/image";-import { Button } from "../../components/button";import { Popup } from "../components/popup";+import { downloadImage, toDataURL } from "../../utils/downloader";export type ImageUploadPopupProps = {onInsert: (image: ImageAttributes) => void;@@ -28,24 +28,8 @@ export function ImageUploadPopup(props: ImageUploadPopupProps) {setError(undefined);try {- const response = await fetch(url);- if (!response.ok)- return setError(`invalid status code ${response.status}`);-- const contentType = response.headers.get("Content-Type");- const contentLength = response.headers.get("Content-Length");-- if (- !contentType ||- !contentLength ||- contentLength === "0" ||- !contentType.startsWith("image/")- )- return setError("not an image");-- const size = parseInt(contentLength);- const dataurl = await toDataURL(await response.blob());- onInsert({ src: dataurl, type: contentType, size });+ const { blob, size, type } = await downloadImage(url);+ onInsert({ src: await toDataURL(blob), size, type });} catch (e) {if (e instanceof Error) setError(e.message);} finally {@@ -97,27 +81,3 @@ export function ImageUploadPopup(props: ImageUploadPopupProps) {</Popup>);}--function toDataURL(blob: Blob): Promise<string> {- return new Promise<string>((resolve, reject) => {- const reader = new FileReader();- reader.onload = (_e) => resolve(reader.result as string);- reader.onerror = (_e) => reject(reader.error);- reader.onabort = (_e) => reject(new Error("Read aborted"));- reader.readAsDataURL(blob);- });-}--// async function validateURL(url: string): Promise<boolean> {-// try {-// const response = await fetch(url, { method: "HEAD" });--// return (-// response.ok &&-// !!response.headers.get("Content-Type")?.startsWith("image/") &&-// response.headers.get("Content-Length") !== "0"-// );-// } catch {-// return false;-// }-// }diff --git a/packages/editor/src/utils/downloader.ts b/packages/editor/src/utils/downloader.tsnew file mode 100644index 000000000..82cfcb1d0--- /dev/null+++ b/packages/editor/src/utils/downloader.ts@@ -0,0 +1,46 @@+export async function downloadImage(url: string) {+ const response = await fetch(url);+ if (!response.ok) throw new Error(`invalid status code ${response.status}`);++ const contentType = response.headers.get("Content-Type");+ const contentLength = response.headers.get("Content-Length");++ if (+ !contentType ||+ !contentLength ||+ contentLength === "0" ||+ !contentType.startsWith("image/")+ )+ throw new Error("not an image");++ const size = parseInt(contentLength);+ const blob = await response.blob();+ return {+ blob,+ url: URL.createObjectURL(blob),+ type: contentType,+ size,+ };+}++export function toDataURL(blob: Blob): Promise<string> {+ return new Promise<string>((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = (_e) => resolve(reader.result as string);+ reader.onerror = (_e) => reject(reader.error);+ reader.onabort = (_e) => reject(new Error("Read aborted"));+ reader.readAsDataURL(blob);+ });+}++export function isDataUrl(url: string): boolean {+ return url.startsWith("data:");+}++export async function toBlobURL(dataurl: string) {+ if (!isDataUrl(dataurl)) return dataurl;++ const response = await fetch(dataurl);+ const blob = await response.blob();+ return URL.createObjectURL(blob);+}