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
editor: improve image loading
Abdullah Attae5db3353aec8
diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsxindex 658175529..64797724a 100644--- a/apps/web/src/components/editor/tiptap.tsx+++ b/apps/web/src/components/editor/tiptap.tsx@@ -57,6 +57,7 @@ import { store as editorstore } from "../../stores/editor-store";import { ScopedThemeProvider } from "../theme-provider";import { writeText } from "clipboard-polyfill";import { useStore as useThemeStore } from "../../stores/theme-store";+import { toBlobURL } from "@notesnook/editor/dist/utils/downloader";type OnChangeHandler = (id: string | undefined,@@ -446,7 +447,7 @@ function toIEditor(editor: Editor): IEditor {if (file.dataurl) {editor.current?.commands.insertImage({...file,- dataurl: file.dataurl+ bloburl: toBlobURL(file.dataurl, file.hash)});} else editor.current?.commands.insertAttachment(file);},@@ -455,7 +456,7 @@ function toIEditor(editor: Editor): IEditor {loadImage: (hash, dataurl) =>editor.current?.commands.updateImage({ hash },- { hash, dataurl, preventUpdate: true }+ { hash, bloburl: toBlobURL(dataurl, hash), preventUpdate: true }),sendAttachmentProgress: (hash, type, progress) =>editor.current?.commands.setAttachmentProgress({diff --git a/packages/editor/src/extensions/image/component.tsx b/packages/editor/src/extensions/image/component.tsxindex 2b7e0fa63..8cfc1f889 100644--- a/packages/editor/src/extensions/image/component.tsx+++ b/packages/editor/src/extensions/image/component.tsx@@ -17,9 +17,9 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import { Box, Button, Flex, Image, Text } from "@theme-ui/components";+import { Box, Flex, Image } from "@theme-ui/components";import { ImageAlignmentOptions, ImageAttributes } from "./image";-import { useEffect, useRef, useState } from "react";+import { useRef } from "react";import { SelectionBasedReactNodeViewProps } from "../react";import { DesktopOnly } from "../../components/responsive";import { Icon } from "@notesnook/ui";@@ -31,6 +31,7 @@ import {} from "../../toolbar/stores/toolbar-store";import { Resizer } from "../../components/resizer";import {+ corsify,downloadImage,isDataUrl,toBlobURL,@@ -38,15 +39,8 @@ import {} from "../../utils/downloader";import { motion } from "framer-motion";-const IMAGE_SOURCE_CACHE: Record<string, string | undefined> = {};export const AnimatedImage = motion(Image);-type imageInfo = {- size: number;- blob: Blob;- type: string;-};-export function ImageComponent(props: SelectionBasedReactNodeViewProps<ImageAttributes & ImageAlignmentOptions@@ -55,7 +49,7 @@ export function ImageComponent(const { editor, node, selected } = props;const isMobile = useIsMobile();const {- dataurl,+ bloburl,src,alt,title,@@ -71,42 +65,8 @@ export function ImageComponent(if (!align) align = textDirection ? "right" : "left";const imageRef = useRef<HTMLImageElement>(null);- const imageInfoRef = useRef<imageInfo>();- const [error, setError] = useState<string>();- const [source, setSource] = useState<string>();const downloadOptions = useToolbarStore((store) => store.downloadOptions);const isReadonly = !editor.current?.isEditable;- const hasOrSrc = hash || src;- useEffect(- () => {- (async () => {- if (!src && !dataurl && !IMAGE_SOURCE_CACHE[hasOrSrc]) return;- try {- if (IMAGE_SOURCE_CACHE[hasOrSrc])- setSource(IMAGE_SOURCE_CACHE[hasOrSrc]);- else if (dataurl) setSource(await toBlobURL(dataurl));- else if (isDataUrl(src)) setSource(await toBlobURL(src));- else if (canParse(src)) {- const { url, size, blob, type } = await downloadImage(- src,- downloadOptions- );- setSource(url);- imageInfoRef.current = { size, blob, type };- } else {- setError("Failed to parse source url.");- }- } catch (e) {- console.error(e);- if (e instanceof Error) setError(e.message);- }- })();- },- // eslint-disable-next-line react-hooks/exhaustive-deps- [src, dataurl, imageRef, downloadOptions]- );-- if (source && hasOrSrc) IMAGE_SOURCE_CACHE[hasOrSrc] = source;const relativeHeight = aspectRatio? editor.view.dom.clientWidth / aspectRatio: undefined;@@ -132,176 +92,133 @@ export function ImageComponent(}}}>- {!source || error ? (- <Flex- sx={{- width: width || "100%",- height: height || relativeHeight || "100%",- maxWidth: "100%",- minWidth: 135,- bg: "background",- border: selected- ? "2px solid var(--accent)"- : "2px solid transparent",- borderRadius: "default",- flexDirection: "column",- alignItems: "center",- justifyContent: "center",- mt: 1,- py: 50- }}- >- <Icon- path={- error- ? Icons.imageFailed- : isDownloadable(source, src)- ? Icons.imageDownload- : Icons.image- }- size={width ? width * 0.2 : 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}`- : isDownloadable(source, src)- ? `Downloading image`- : ""}- </Text>- {error ? (- <Button- variant="secondary"- sx={{ mt: 1 }}- onClick={() => {- setSource(src);- setError(undefined);+ <Resizer+ style={{ marginTop: 5 }}+ editor={editor}+ selected={selected}+ width={width}+ height={height || relativeHeight}+ onResize={(width, height) => {+ editor.commands.setImageSize({ width, height });+ }}+ >+ <DesktopOnly>+ {selected && (+ <Flex+ sx={{+ position: "absolute",+ top: -40,+ right: 0,+ mb: 2,+ alignItems: "end"}}>- Skip downloading (unsafe)- </Button>- ) : null}- </Flex>- ) : (- <Resizer- style={{ marginTop: 5 }}- editor={editor}- selected={selected}- width={width}- onResize={(width, height) => {- editor.commands.setImageSize({ width, height });- }}- >- <DesktopOnly>- {selected && (- <Flex+ <ToolbarGroup+ editor={editor}+ tools={+ isReadonly+ ? [+ hash ? "previewAttachment" : "none",+ hash ? "downloadAttachment" : "none"+ ]+ : [+ hash ? "previewAttachment" : "none",+ hash ? "downloadAttachment" : "none",+ "imageAlignLeft",+ float ? "none" : "imageAlignCenter",+ "imageAlignRight",+ "imageProperties"+ ]+ }sx={{- position: "absolute",- top: -40,- right: 0,- mb: 2,- alignItems: "end"+ boxShadow: "menu",+ borderRadius: "default",+ bg: "background"}}- >- <ToolbarGroup- editor={editor}- tools={- isReadonly- ? [- hash ? "previewAttachment" : "none",- hash ? "downloadAttachment" : "none"- ]- : [- hash ? "previewAttachment" : "none",- hash ? "downloadAttachment" : "none",- "imageAlignLeft",- float ? "none" : "imageAlignCenter",- "imageAlignRight",- "imageProperties"- ]- }- sx={{- boxShadow: "menu",- borderRadius: "default",- bg: "background"- }}- />- </Flex>- )}- </DesktopOnly>- {!isReadonly && selected && (- <Icon- className="drag-handle"- data-drag-handle- draggable- path={Icons.dragHandle}- color="black"- sx={{- cursor: "grab",- position: "absolute",- top: 1,- left: 1,- zIndex: 999- }}- />+ />+ </Flex>)}- <AnimatedImage- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- transition={{ duration: 0.5, ease: "easeIn" }}- data-drag-image- ref={imageRef}- alt={alt}- src={source}- title={title}+ </DesktopOnly>+ {!isReadonly && selected && (+ <Icon+ className="drag-handle"+ data-drag-handle+ draggable+ path={Icons.dragHandle}+ color="black"sx={{- width: editor.isEditable ? "100%" : width,- height: editor.isEditable ? "100%" : height,- border: selected- ? "2px solid var(--accent)"- : "2px solid transparent",- borderRadius: "default"- }}- onDoubleClick={() =>- editor.current?.commands.previewAttachment(node.attrs)- }- onLoad={async (e) => {- const { clientHeight, clientWidth } = e.currentTarget;- if (!height && !width && !aspectRatio && imageInfoRef.current) {- editor.current?.commands.updateImage(- { src },- {- src: await toDataURL(imageInfoRef.current.blob),- size: imageInfoRef.current.size,- mime: imageInfoRef.current.type,- aspectRatio: clientWidth / clientHeight- }- );- }+ cursor: "grab",+ position: "absolute",+ top: 1,+ left: 1,+ zIndex: 999}}/>- </Resizer>- )}+ )}+ <AnimatedImage+ initial={{ opacity: 0 }}+ animate={{ opacity: bloburl || src ? 1 : 0 }}+ transition={{ duration: 0.5, ease: "easeIn" }}+ data-drag-image+ ref={imageRef}+ alt={alt}+ crossOrigin="anonymous"+ src={+ toBlobURL("", hash) ||+ bloburl ||+ corsify(src, downloadOptions?.corsHost)+ }+ title={title}+ sx={{+ width: editor.isEditable ? "100%" : width,+ height: editor.isEditable ? "100%" : height,+ border: selected+ ? "2px solid var(--accent) !important"+ : "2px solid transparent !important",+ borderRadius: "default"+ }}+ onDoubleClick={() =>+ editor.current?.commands.previewAttachment(node.attrs)+ }+ onLoad={async () => {+ if (!imageRef.current) return;+ const { clientHeight, clientWidth } = imageRef.current;++ if (!isDataUrl(src) && canParse(src)) {+ const { url, size, blob, mimeType } = await downloadImage(+ src,+ downloadOptions+ );+ editor.current?.commands.updateImage(+ { src, hash },+ {+ src: await toDataURL(blob),+ bloburl: url,+ size: size,+ mime: mimeType,+ aspectRatio:+ !height && !width && !aspectRatio+ ? clientWidth / clientHeight+ : undefined+ }+ );+ } else if (!height && !width && !aspectRatio) {+ editor.current?.commands.updateImage(+ { src, hash },+ {+ aspectRatio: clientWidth / clientHeight+ }+ );+ }+ }}+ />+ </Resizer>+ {/* )} */}</Box></>);}-function isDownloadable(source?: string, src?: string) {- return !source && src && !isDataUrl(src);-}-function canParse(src: string) {try {return !!new URL(src);diff --git a/packages/editor/src/extensions/image/image.ts b/packages/editor/src/extensions/image/image.tsindex 56be3e78f..65605a4fe 100644--- a/packages/editor/src/extensions/image/image.ts+++ b/packages/editor/src/extensions/image/image.ts@@ -61,7 +61,7 @@ export interface ImageOptions {export type ImageAttributes = Partial<ImageSizeOptions> &Attachment & {src: string;- dataurl?: string;+ bloburl?: string;alt?: string;title?: string;textDirection?: TextDirections;@@ -154,8 +154,8 @@ export const ImageNode = Node.create<ImageOptions>({}},- dataurl: {- ...getDataAttribute("dataurl"),+ bloburl: {+ ...getDataAttribute("bloburl"),rendered: false}};@@ -192,11 +192,11 @@ export const ImageNode = Node.create<ImageOptions>({content.content.descendants((node) => {if (node.type.name === this.name &&- typeof node.attrs.dataurl === "string"+ typeof node.attrs.bloburl === "string") {const attrs = node.attrs as Writeable<Attrs>;- attrs.src = attrs.dataurl;- delete attrs.dataurl;+ attrs.src = attrs.bloburl;+ delete attrs.bloburl;}});return content;diff --git a/packages/editor/src/extensions/react/react-node-view.tsx b/packages/editor/src/extensions/react/react-node-view.tsxindex 476f938f4..350eb0344 100644--- a/packages/editor/src/extensions/react/react-node-view.tsx+++ b/packages/editor/src/extensions/react/react-node-view.tsx@@ -243,6 +243,7 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {: target.closest("[data-drag-handle]");if (!this.dom || this.contentDOM?.contains(target) || !dragHandle) {+ event.preventDefault();return;}diff --git a/packages/editor/src/toolbar/popups/image-upload.tsx b/packages/editor/src/toolbar/popups/image-upload.tsxindex 785d188d9..18b9c51fa 100644--- a/packages/editor/src/toolbar/popups/image-upload.tsx+++ b/packages/editor/src/toolbar/popups/image-upload.tsx@@ -49,11 +49,11 @@ export function ImageUploadPopup(props: ImageUploadPopupProps) {setError(undefined);try {- const { blob, size, type } = await downloadImage(+ const { blob, size, mimeType } = await downloadImage(url,downloadOptions);- onInsert({ src: await toDataURL(blob), size, mime: type });+ onInsert({ src: await toDataURL(blob), size, mime: mimeType });} catch (e) {if (e instanceof Error) setError(e.message);} finally {diff --git a/packages/editor/src/utils/downloader.ts b/packages/editor/src/utils/downloader.tsindex 279e152e3..f81c4293f 100644--- a/packages/editor/src/utils/downloader.ts+++ b/packages/editor/src/utils/downloader.ts@@ -58,10 +58,18 @@ const UTITypes: Record<string, string> = {"public.heifs": "image/heif-sequence"};+export function corsify(url: string, host?: string) {+ if (host && !url.startsWith("blob:") && !isDataUrl(url))+ return `${host}/${url}`;+ return url;+}+export async function downloadImage(url: string, options?: DownloadOptions) {- if (options?.corsHost && !url.startsWith("blob:"))- url = `${options.corsHost}/${url}`;- const response = await fetch(url);+ const response = await fetch(corsify(url, options?.corsHost), {+ mode: "cors",+ credentials: "omit",+ cache: "force-cache"+ });if (!response.ok) throw new Error(`invalid status code ${response.status}`);let contentType = response.headers.get("Content-Type");@@ -87,7 +95,7 @@ export async function downloadImage(url: string, options?: DownloadOptions) {return {blob,url: URL.createObjectURL(blob),- type: contentType,+ mimeType: contentType,size};}@@ -106,10 +114,15 @@ export function isDataUrl(url?: string): boolean {return url?.startsWith("data:") || false;}-export async function toBlobURL(dataurl: string) {- if (!isDataUrl(dataurl)) return dataurl;+const OBJECT_URL_CACHE: Record<string, string | undefined> = {};+export function toBlobURL(dataurl: string, id?: string) {+ if (id && OBJECT_URL_CACHE[id]) return OBJECT_URL_CACHE[id];+ if (!isDataUrl(dataurl)) return;++ const objectURL = URL.createObjectURL(+ new Blob([Buffer.from(dataurl.split(",")[1], "base64")])+ );- const response = await fetch(dataurl);- const blob = await response.blob();- return URL.createObjectURL(blob);+ if (id) OBJECT_URL_CACHE[id] = objectURL;+ return objectURL;}