Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

feat: finalize attachments

thecodrrccac8dc6c4a7
diff --git a/packages/editor/dist/extensions/attachment/attachment.d.ts b/packages/editor/dist/extensions/attachment/attachment.d.ts
index be965cb5e..6ed6db8aa 100644
--- a/packages/editor/dist/extensions/attachment/attachment.d.ts
+++ b/packages/editor/dist/extensions/attachment/attachment.d.ts
@@ -1,11 +1,13 @@
-import { Node } from "@tiptap/core";
+import { Node, Editor } from "@tiptap/core";
+import { Attribute } from "@tiptap/core";
export declare type AttachmentType = "image" | "file";
export interface AttachmentOptions {
HTMLAttributes: Record<string, any>;
- onDownloadAttachment: (attachment: Attachment) => boolean;
- onOpenAttachmentPicker: (type: AttachmentType) => boolean;
+ onDownloadAttachment: (editor: Editor, attachment: Attachment) => boolean;
+ onOpenAttachmentPicker: (editor: Editor, type: AttachmentType) => boolean;
}
-export declare type Attachment = AttachmentProgress & {
+export declare type AttachmentWithProgress = AttachmentProgress & Attachment;
+export declare type Attachment = {
hash: string;
filename: string;
type: string;
@@ -13,7 +15,7 @@ export declare type Attachment = AttachmentProgress & {
};
export declare type AttachmentProgress = {
progress: number;
- type: "upload" | "download";
+ type: "upload" | "download" | "encrypt";
hash: string;
};
declare module "@tiptap/core" {
@@ -22,8 +24,9 @@ declare module "@tiptap/core" {
openAttachmentPicker: (type: AttachmentType) => ReturnType;
insertAttachment: (attachment: Attachment) => ReturnType;
downloadAttachment: (attachment: Attachment) => ReturnType;
- setProgress: (progress: AttachmentProgress) => ReturnType;
+ setAttachmentProgress: (progress: AttachmentProgress) => ReturnType;
};
}
}
export declare const AttachmentNode: Node<AttachmentOptions, any>;
+export declare function getDataAttribute(name: string, def?: any | null): Partial<Attribute>;
diff --git a/packages/editor/dist/extensions/attachment/attachment.js b/packages/editor/dist/extensions/attachment/attachment.js
index 52b7e9878..aaf0d909c 100644
--- a/packages/editor/dist/extensions/attachment/attachment.js
+++ b/packages/editor/dist/extensions/attachment/attachment.js
@@ -1,3 +1,14 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
@@ -10,7 +21,7 @@ var __values = (this && this.__values) || function(o) {
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { Node, mergeAttributes, findChildren } from "@tiptap/core";
-import { createNodeView } from "../react";
+import { createSelectionBasedNodeView } from "../react";
import { AttachmentComponent } from "./component";
export var AttachmentNode = Node.create({
name: "attachment",
@@ -31,6 +42,10 @@ export var AttachmentNode = Node.create({
draggable: true,
addAttributes: function () {
return {
+ progress: {
+ default: 0,
+ rendered: false,
+ },
hash: getDataAttribute("hash"),
filename: getDataAttribute("filename"),
type: getDataAttribute("type"),
@@ -52,7 +67,13 @@ export var AttachmentNode = Node.create({
];
},
addNodeView: function () {
- return createNodeView(AttachmentComponent);
+ return createSelectionBasedNodeView(AttachmentComponent, {
+ shouldUpdate: function (_a, _b) {
+ var prev = _a.attrs;
+ var next = _b.attrs;
+ return prev.progress !== next.progress;
+ },
+ });
},
addCommands: function () {
var _this = this;
@@ -60,6 +81,7 @@ export var AttachmentNode = Node.create({
insertAttachment: function (attachment) {
return function (_a) {
var commands = _a.commands;
+ console.log("HI!", attachment);
return commands.insertContent({
type: _this.name,
attrs: attachment,
@@ -68,28 +90,30 @@ export var AttachmentNode = Node.create({
},
downloadAttachment: function (attachment) {
return function (_a) {
- return _this.options.onDownloadAttachment(attachment);
+ var editor = _a.editor;
+ return _this.options.onDownloadAttachment(editor, attachment);
+ };
+ },
+ openAttachmentPicker: function (type) {
+ return function (_a) {
+ var editor = _a.editor;
+ return _this.options.onOpenAttachmentPicker(editor, type);
};
},
- openAttachmentPicker: function (type) { return function () {
- return _this.options.onOpenAttachmentPicker(type);
- }; },
- setProgress: function (options) {
+ setAttachmentProgress: function (options) {
return function (_a) {
var e_1, _b;
var state = _a.state, tr = _a.tr, dispatch = _a.dispatch;
var hash = options.hash, progress = options.progress, type = options.type;
var attachments = findChildren(state.doc, function (node) {
- return (node.type.name === "attachment" || node.type.name === "image") &&
+ return (node.type.name === _this.name || node.type.name === "image") &&
node.attrs.hash === hash;
});
try {
for (var attachments_1 = __values(attachments), attachments_1_1 = attachments_1.next(); !attachments_1_1.done; attachments_1_1 = attachments_1.next()) {
var attachment = attachments_1_1.value;
- tr.setNodeMarkup(attachment.pos, attachment.node.type, {
- progress: progress,
- type: type,
- });
+ console.log(attachment.node.attrs);
+ tr.setNodeMarkup(attachment.pos, attachment.node.type, __assign(__assign({}, attachment.node.attrs), { progress: progress }));
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -99,6 +123,7 @@ export var AttachmentNode = Node.create({
}
finally { if (e_1) throw e_1.error; }
}
+ tr.skipUpdate = true;
if (dispatch)
dispatch(tr);
return true;
@@ -119,9 +144,9 @@ export var AttachmentNode = Node.create({
// ];
// },
});
-function getDataAttribute(name) {
+export function getDataAttribute(name, def) {
return {
- default: null,
+ default: def,
parseHTML: function (element) { return element.dataset[name]; },
renderHTML: function (attributes) {
var _a;
diff --git a/packages/editor/dist/extensions/attachment/component.d.ts b/packages/editor/dist/extensions/attachment/component.d.ts
index 64ba9b1d8..ea57c55f9 100644
--- a/packages/editor/dist/extensions/attachment/component.d.ts
+++ b/packages/editor/dist/extensions/attachment/component.d.ts
@@ -1,4 +1,4 @@
/// <reference types="react" />
-import { Attachment } from "./attachment";
-import { ReactNodeViewProps } from "../react";
-export declare function AttachmentComponent(props: ReactNodeViewProps<Attachment>): JSX.Element;
+import { AttachmentWithProgress } from "./attachment";
+import { SelectionBasedReactNodeViewProps } from "../react";
+export declare function AttachmentComponent(props: SelectionBasedReactNodeViewProps<AttachmentWithProgress>): JSX.Element;
diff --git a/packages/editor/dist/extensions/attachment/component.js b/packages/editor/dist/extensions/attachment/component.js
index 16aef78e4..50179910c 100644
--- a/packages/editor/dist/extensions/attachment/component.js
+++ b/packages/editor/dist/extensions/attachment/component.js
@@ -16,44 +16,53 @@ import { useRef } from "react";
// import { MenuPresenter } from "../../components/menu/menu";
import { Icon } from "../../toolbar/components/icon";
import { Icons } from "../../toolbar/icons";
+import { PopupPresenter } from "../../components/popup-presenter";
export function AttachmentComponent(props) {
- var _a = props.node.attrs, hash = _a.hash, filename = _a.filename, size = _a.size;
- var editor = props.editor;
+ var editor = props.editor, node = props.node, selected = props.selected;
+ var _a = node.attrs, hash = _a.hash, filename = _a.filename, size = _a.size, progress = _a.progress;
var elementRef = useRef();
- var isActive = editor.isActive("attachment", { hash: hash });
+ // const isActive = editor.isActive("attachment", { hash });
// const [isToolbarVisible, setIsToolbarVisible] = useState<boolean>();
// useEffect(() => {
// setIsToolbarVisible(isActive);
// }, [isActive]);
- return (_jsx(_Fragment, { children: _jsxs(Box, __assign({ ref: elementRef, as: "span", contentEditable: false, variant: "body", sx: {
- display: "inline-flex",
- overflow: "hidden",
- position: "relative",
- zIndex: 1,
- userSelect: "none",
- alignItems: "center",
- backgroundColor: "bgSecondary",
- px: 1,
- borderRadius: "default",
- border: "1px solid var(--border)",
- cursor: "pointer",
- maxWidth: 250,
- borderColor: isActive ? "primary" : "border",
- ":hover": {
- bg: "hover",
- },
- }, title: filename }, { children: [_jsx(Icon, { path: Icons.attachment, size: 14 }), _jsx(Text, __assign({ as: "span", sx: {
- ml: "small",
- fontSize: "0.85rem",
- whiteSpace: "nowrap",
- textOverflow: "ellipsis",
- overflow: "hidden",
- }, className: "filename" }, { children: filename })), _jsx(Text, __assign({ as: "span", className: "size", sx: {
- ml: 1,
- fontSize: "subBody",
- color: "fontTertiary",
- flexShrink: 0,
- } }, { children: formatBytes(size) }))] })) }));
+ console.log(progress);
+ return (_jsxs(_Fragment, { children: [_jsxs(Box, __assign({ ref: elementRef, as: "span", contentEditable: false, variant: "body", sx: {
+ display: "inline-flex",
+ overflow: "hidden",
+ position: "relative",
+ justifyContent: "center",
+ zIndex: 1,
+ userSelect: "none",
+ alignItems: "center",
+ backgroundColor: "bgSecondary",
+ px: 1,
+ borderRadius: "default",
+ border: "1px solid var(--border)",
+ cursor: "pointer",
+ maxWidth: 250,
+ borderColor: selected ? "primary" : "border",
+ ":hover": {
+ bg: "hover",
+ },
+ }, title: filename }, { children: [_jsx(Icon, { path: Icons.attachment, size: 14 }), _jsx(Text, __assign({ as: "span", sx: {
+ ml: "small",
+ fontSize: "body",
+ whiteSpace: "nowrap",
+ textOverflow: "ellipsis",
+ overflow: "hidden",
+ } }, { children: filename })), _jsx(Text, __assign({ as: "span", sx: {
+ ml: 1,
+ fontSize: "0.65rem",
+ color: "fontTertiary",
+ flexShrink: 0,
+ } }, { children: progress ? "".concat(progress, "%") : formatBytes(size) }))] })), _jsx(PopupPresenter, __assign({ isOpen: selected, onClose: function () { }, blocking: false, focusOnRender: false, position: {
+ target: elementRef.current || undefined,
+ align: "center",
+ location: "top",
+ yOffset: 5,
+ isTargetAbsolute: true,
+ } }, { children: _jsx(AttachmentToolbar, { editor: editor }) }))] }));
}
function formatBytes(bytes, decimals) {
if (decimals === void 0) { decimals = 1; }
@@ -68,18 +77,10 @@ function formatBytes(bytes, decimals) {
// TODO make this functional
function AttachmentToolbar(props) {
var editor = props.editor;
- return (_jsx(Flex, __assign({ sx: {
- flexDirection: "column",
- // position: "absolute",
- // top: 0,
- mb: 2,
- zIndex: 9999,
- alignItems: "end",
- } }, { children: _jsxs(Flex, __assign({ sx: {
- bg: "background",
- boxShadow: "menu",
- flexWrap: "nowrap",
- borderRadius: "default",
- mb: 2,
- } }, { children: [_jsx(ToolButton, { toggled: false, title: "Download", id: "download", icon: "download", onClick: function () { }, variant: "small", sx: { mr: 1 } }), _jsx(ToolButton, { toggled: false, title: "delete", id: "delete", icon: "delete", onClick: function () { }, variant: "small", sx: { mr: 0 } })] })) })));
+ return (_jsxs(Flex, __assign({ sx: {
+ bg: "background",
+ boxShadow: "menu",
+ flexWrap: "nowrap",
+ borderRadius: "default",
+ } }, { children: [_jsx(ToolButton, { toggled: false, title: "Download", id: "download", icon: "download", onClick: function () { }, sx: { mr: 1 } }), _jsx(ToolButton, { toggled: false, title: "delete", id: "delete", icon: "delete", onClick: function () { }, sx: { mr: 0 } })] })));
}
diff --git a/packages/editor/dist/extensions/codeblock/highlighter.d.ts b/packages/editor/dist/extensions/codeblock/highlighter.d.ts
index 6d35d2729..e42464534 100644
--- a/packages/editor/dist/extensions/codeblock/highlighter.d.ts
+++ b/packages/editor/dist/extensions/codeblock/highlighter.d.ts
@@ -1,5 +1,7 @@
import { Plugin } from "prosemirror-state";
import { DecorationSet } from "prosemirror-view";
+import { AddMarkStep, RemoveMarkStep, ReplaceAroundStep, ReplaceStep } from "prosemirror-transform";
+export declare type MergedStep = AddMarkStep | RemoveMarkStep | ReplaceAroundStep | ReplaceStep;
export declare function HighlighterPlugin({ name, defaultLanguage, }: {
name: string;
defaultLanguage: string | null | undefined;
diff --git a/packages/editor/dist/extensions/embed/embed.js b/packages/editor/dist/extensions/embed/embed.js
index b2c6e7c3a..3d7beff7b 100644
--- a/packages/editor/dist/extensions/embed/embed.js
+++ b/packages/editor/dist/extensions/embed/embed.js
@@ -10,7 +10,7 @@ var __assign = (this && this.__assign) || function () {
return __assign.apply(this, arguments);
};
import { Node, mergeAttributes } from "@tiptap/core";
-import { createSelectionBasedNodeView, NodeViewSelectionNotifierPlugin, } from "../react";
+import { createSelectionBasedNodeView, } from "../react";
import { EmbedComponent } from "./component";
export var EmbedNode = Node.create({
name: "embed",
@@ -49,9 +49,6 @@ export var EmbedNode = Node.create({
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
];
},
- addProseMirrorPlugins: function () {
- return [NodeViewSelectionNotifierPlugin];
- },
addNodeView: function () {
return createSelectionBasedNodeView(EmbedComponent);
},
diff --git a/packages/editor/dist/extensions/image/component.js b/packages/editor/dist/extensions/image/component.js
index d5151a082..317926924 100644
--- a/packages/editor/dist/extensions/image/component.js
+++ b/packages/editor/dist/extensions/image/component.js
@@ -9,6 +9,42 @@ var __assign = (this && this.__assign) || function () {
};
return __assign.apply(this, arguments);
};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+var __generator = (this && this.__generator) || function (thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (_) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
@@ -29,15 +65,36 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
import { Box, Flex, Image } from "rebass";
import { Resizable } from "re-resizable";
import { ToolButton } from "../../toolbar/components/tool-button";
-import { useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { ResponsivePresenter } from "../../components/responsive";
import { ImageProperties } from "../../toolbar/popups/image-properties";
import { Popup } from "../../toolbar/components/popup";
+import { Icon } from "../../toolbar/components/icon";
+import { Icons } from "../../toolbar/icons";
export function ImageComponent(props) {
+ var _this = this;
var editor = props.editor, updateAttributes = props.updateAttributes, node = props.node, selected = props.selected;
var _a = node.attrs, src = _a.src, alt = _a.alt, title = _a.title, width = _a.width, height = _a.height, align = _a.align, float = _a.float;
var imageRef = useRef();
- return (_jsx(_Fragment, { children: _jsx(Box, __assign({ sx: {
+ useEffect(function () {
+ (function () { return __awaiter(_this, void 0, void 0, function () {
+ var _a;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ if (!imageRef.current)
+ return [2 /*return*/];
+ _a = imageRef.current;
+ return [4 /*yield*/, dataUriToBlobURL(src)];
+ case 1:
+ _a.src = _b.sent();
+ return [2 /*return*/];
+ }
+ });
+ }); })();
+ }, [src, imageRef]);
+ return (_jsx(_Fragment, { children: _jsxs(Box, __assign({ sx: {
+ position: "relative",
display: float ? "block" : "flex",
justifyContent: float
? "stretch"
@@ -46,22 +103,32 @@ export function ImageComponent(props) {
: align === "left"
? "start"
: "end",
- } }, { children: _jsxs(Resizable, __assign({ style: {
- float: float ? (align === "left" ? "left" : "right") : "none",
- }, size: {
- height: height || "auto",
- width: width || "auto",
- }, maxWidth: "100%", onResizeStop: function (e, direction, ref, d) {
- updateAttributes({
- width: ref.clientWidth,
- height: ref.clientHeight,
- });
- }, lockAspectRatio: true }, { children: [selected && (_jsx(Flex, __assign({ sx: { position: "relative", justifyContent: "end" } }, { children: _jsx(ImageToolbar, { editor: editor, float: float, align: align, height: height || 0, width: width || 0 }) }))), _jsx(Image, __assign({ ref: imageRef, src: src, alt: alt, title: title, width: "100%", height: "100%", sx: {
- border: selected
- ? "2px solid var(--primary)"
- : "2px solid transparent",
- borderRadius: "default",
- } }, props))] })) })) }));
+ ":hover .drag-handle, :active .drag-handle": {
+ opacity: 1,
+ },
+ }, draggable: false }, { children: [_jsx(Icon, { className: "drag-handle", "data-drag-handle": true, draggable: true, path: Icons.dragHandle, sx: {
+ cursor: "grab",
+ position: "absolute",
+ top: 2,
+ left: 2,
+ zIndex: 999,
+ opacity: 0,
+ } }), _jsxs(Resizable, __assign({ style: {
+ float: float ? (align === "left" ? "left" : "right") : "none",
+ }, size: {
+ height: height || "auto",
+ width: width || "auto",
+ }, maxWidth: "100%", onResizeStop: function (e, direction, ref, d) {
+ updateAttributes({
+ width: ref.clientWidth,
+ height: ref.clientHeight,
+ });
+ }, lockAspectRatio: true }, { children: [selected && (_jsx(Flex, __assign({ sx: { position: "relative", justifyContent: "end" } }, { children: _jsx(ImageToolbar, { editor: editor, float: float, align: align, height: height || 0, width: width || 0 }) }))), _jsx(Image, __assign({ "data-drag-image": true, ref: imageRef, alt: alt, title: title, width: "100%", height: "100%", sx: {
+ border: selected
+ ? "2px solid var(--primary)"
+ : "2px solid transparent",
+ borderRadius: "default",
+ } }, props))] }))] })) }));
}
function ImageToolbar(props) {
var editor = props.editor, float = props.float, height = props.height, width = props.width;
@@ -110,3 +177,22 @@ function ImageToolbar(props) {
setIsOpen(false);
} }, { children: _jsx(ImageProperties, __assign({}, props)) })) }))] })));
}
+function dataUriToBlobURL(dataurl) {
+ return __awaiter(this, void 0, void 0, function () {
+ var response, blob;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ if (!dataurl.startsWith("data:image"))
+ return [2 /*return*/, dataurl];
+ return [4 /*yield*/, fetch(dataurl)];
+ case 1:
+ response = _a.sent();
+ return [4 /*yield*/, response.blob()];
+ case 2:
+ blob = _a.sent();
+ return [2 /*return*/, URL.createObjectURL(blob)];
+ }
+ });
+ });
+}
diff --git a/packages/editor/dist/extensions/image/image.d.ts b/packages/editor/dist/extensions/image/image.d.ts
index 7423a7ac4..eb963ae33 100644
--- a/packages/editor/dist/extensions/image/image.d.ts
+++ b/packages/editor/dist/extensions/image/image.d.ts
@@ -1,10 +1,11 @@
import { Node } from "@tiptap/core";
+import { Attachment } from "../attachment";
export interface ImageOptions {
inline: boolean;
allowBase64: boolean;
HTMLAttributes: Record<string, any>;
}
-export declare type ImageAttributes = Partial<ImageSizeOptions> & {
+export declare type ImageAttributes = Partial<ImageSizeOptions> & Partial<Attachment> & {
src: string;
alt?: string;
title?: string;
@@ -23,7 +24,8 @@ declare module "@tiptap/core" {
/**
* Add an image
*/
- setImage: (options: ImageAttributes) => ReturnType;
+ insertImage: (options: ImageAttributes) => ReturnType;
+ updateImage: (options: ImageAttributes) => ReturnType;
setImageAlignment: (options: ImageAlignmentOptions) => ReturnType;
setImageSize: (options: ImageSizeOptions) => ReturnType;
};
diff --git a/packages/editor/dist/extensions/image/image.js b/packages/editor/dist/extensions/image/image.js
index f072fea9f..a610afec9 100644
--- a/packages/editor/dist/extensions/image/image.js
+++ b/packages/editor/dist/extensions/image/image.js
@@ -9,6 +9,17 @@ var __assign = (this && this.__assign) || function () {
};
return __assign.apply(this, arguments);
};
+var __values = (this && this.__values) || function(o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
@@ -25,8 +36,9 @@ var __read = (this && this.__read) || function (o, n) {
}
return ar;
};
-import { Node, nodeInputRule, mergeAttributes } from "@tiptap/core";
-import { createSelectionBasedNodeView, NodeViewSelectionNotifierPlugin, } from "../react";
+import { Node, nodeInputRule, mergeAttributes, findChildren, } from "@tiptap/core";
+import { getDataAttribute } from "../attachment";
+import { createSelectionBasedNodeView, } from "../react";
import { ImageComponent } from "./component";
export var inputRegex = /(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/;
export var ImageNode = Node.create({
@@ -58,10 +70,12 @@ export var ImageNode = Node.create({
},
width: { default: null },
height: { default: null },
- float: {
- default: false,
- },
- align: { default: "left" },
+ float: getDataAttribute("float", false),
+ align: getDataAttribute("align", "left"),
+ hash: getDataAttribute("hash"),
+ filename: getDataAttribute("filename"),
+ type: getDataAttribute("type"),
+ size: getDataAttribute("size"),
};
},
parseHTML: function () {
@@ -83,13 +97,10 @@ export var ImageNode = Node.create({
addNodeView: function () {
return createSelectionBasedNodeView(ImageComponent);
},
- addProseMirrorPlugins: function () {
- return [NodeViewSelectionNotifierPlugin];
- },
addCommands: function () {
var _this = this;
return {
- setImage: function (options) {
+ insertImage: function (options) {
return function (_a) {
var commands = _a.commands;
return commands.insertContent({
@@ -110,6 +121,39 @@ export var ImageNode = Node.create({
return commands.updateAttributes(_this.name, __assign({}, options));
};
},
+ updateImage: function (options) {
+ return function (_a) {
+ var e_1, _b;
+ var state = _a.state, tr = _a.tr, dispatch = _a.dispatch;
+ var query = options.hash
+ ? { key: "hash", value: options.hash }
+ : options.src
+ ? { key: "src", value: options.src }
+ : null;
+ if (!query)
+ return false;
+ var images = findChildren(state.doc, function (node) {
+ return node.type.name === _this.name &&
+ node.attrs[query.key] === query.value;
+ });
+ try {
+ for (var images_1 = __values(images), images_1_1 = images_1.next(); !images_1_1.done; images_1_1 = images_1.next()) {
+ var image = images_1_1.value;
+ tr.setNodeMarkup(image.pos, image.node.type, __assign(__assign({}, image.node.attrs), options));
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (images_1_1 && !images_1_1.done && (_b = images_1.return)) _b.call(images_1);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ if (dispatch)
+ dispatch(tr);
+ return true;
+ };
+ },
};
},
addInputRules: function () {
diff --git a/packages/editor/dist/extensions/react/plugin.d.ts b/packages/editor/dist/extensions/react/plugin.d.ts
index 6fcf944a9..032e5008b 100644
--- a/packages/editor/dist/extensions/react/plugin.d.ts
+++ b/packages/editor/dist/extensions/react/plugin.d.ts
@@ -1,4 +1,5 @@
import { Plugin, PluginKey } from "prosemirror-state";
+import { Extension } from "@tiptap/core";
export declare type StateChangeHandler = (fromPos: number, toPos: number) => any;
export declare class ReactNodeViewState {
private changeHandlers;
@@ -9,3 +10,4 @@ export declare class ReactNodeViewState {
}
export declare const stateKey: PluginKey<any>;
export declare const NodeViewSelectionNotifierPlugin: Plugin<ReactNodeViewState>;
+export declare const NodeViewSelectionNotifier: Extension<any, any>;
diff --git a/packages/editor/dist/extensions/react/plugin.js b/packages/editor/dist/extensions/react/plugin.js
index 3559110ac..7a737165e 100644
--- a/packages/editor/dist/extensions/react/plugin.js
+++ b/packages/editor/dist/extensions/react/plugin.js
@@ -1,4 +1,5 @@
import { Plugin, PluginKey } from "prosemirror-state";
+import { Extension } from "@tiptap/core";
var ReactNodeViewState = /** @class */ (function () {
function ReactNodeViewState() {
this.changeHandlers = [];
@@ -37,3 +38,8 @@ export var NodeViewSelectionNotifierPlugin = new Plugin({
};
},
});
+export var NodeViewSelectionNotifier = Extension.create({
+ addProseMirrorPlugins: function () {
+ return [NodeViewSelectionNotifierPlugin];
+ },
+});
diff --git a/packages/editor/dist/extensions/react/reactnodeview.d.ts b/packages/editor/dist/extensions/react/reactnodeview.d.ts
index b4ca5a585..fa7b419c7 100644
--- a/packages/editor/dist/extensions/react/reactnodeview.d.ts
+++ b/packages/editor/dist/extensions/react/reactnodeview.d.ts
@@ -15,6 +15,7 @@ export declare class ReactNodeView<P extends ReactNodeViewProps> implements Node
private contentDOMWrapper?;
contentDOM: HTMLElement | undefined;
node: PMNode;
+ isDragging: boolean;
constructor(node: PMNode, editor: Editor, getPos: GetPosNode, portalProviderAPI: PortalProviderAPI, eventDispatcher: EventDispatcher, options: ReactNodeViewOptions<P>);
/**
* This method exists to move initialization logic out of the constructor,
@@ -34,6 +35,8 @@ export declare class ReactNodeView<P extends ReactNodeViewProps> implements Node
render(props?: P, forwardRef?: ForwardRef): React.ReactElement<any> | null;
updateAttributes(attributes: any, pos: number): void;
update(node: PMNode, _decorations: readonly Decoration[], _innerDecorations: DecorationSource): boolean;
+ onDragStart(event: DragEvent): void;
+ stopEvent(event: Event): boolean;
ignoreMutation(mutation: MutationRecord | {
type: "selection";
target: Element;
diff --git a/packages/editor/dist/extensions/react/reactnodeview.js b/packages/editor/dist/extensions/react/reactnodeview.js
index a32e5c447..5abca4f57 100644
--- a/packages/editor/dist/extensions/react/reactnodeview.js
+++ b/packages/editor/dist/extensions/react/reactnodeview.js
@@ -35,6 +35,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
return to.concat(ar || Array.prototype.slice.call(from));
};
import { jsx as _jsx } from "react/jsx-runtime";
+import { NodeSelection } from "prosemirror-state";
import { ThemeProvider } from "emotion-theming";
var ReactNodeView = /** @class */ (function () {
function ReactNodeView(node, editor, getPos, portalProviderAPI, eventDispatcher, options) {
@@ -44,6 +45,7 @@ var ReactNodeView = /** @class */ (function () {
this.portalProviderAPI = portalProviderAPI;
this.eventDispatcher = eventDispatcher;
this.options = options;
+ this.isDragging = false;
this.handleRef = function (node) { return _this._handleRef(node); };
this.node = node;
}
@@ -59,6 +61,7 @@ var ReactNodeView = /** @class */ (function () {
ReactNodeView.prototype.init = function () {
var _this = this;
this.domRef = this.createDomRef();
+ this.domRef.ondragstart = function (ev) { return _this.onDragStart(ev); };
// this.setDomAttrs(this.node, this.domRef);
var _a = this.getContentDOM() || {
dom: undefined,
@@ -157,6 +160,105 @@ var ReactNodeView = /** @class */ (function () {
});
return true;
};
+ ReactNodeView.prototype.onDragStart = function (event) {
+ var _a, _b, _c, _d, _e, _f, _g;
+ var view = this.editor.view;
+ var target = event.target;
+ // get the drag handle element
+ // `closest` is not available for text nodes so we may have to use its parent
+ var dragHandle = target.nodeType === 3
+ ? (_a = target.parentElement) === null || _a === void 0 ? void 0 : _a.closest("[data-drag-handle]")
+ : target.closest("[data-drag-handle]");
+ if (!this.dom || ((_b = this.contentDOM) === null || _b === void 0 ? void 0 : _b.contains(target)) || !dragHandle) {
+ return;
+ }
+ var dragImage = this.dom.querySelector("[data-drag-image]") || this.dom;
+ var x = 0;
+ var y = 0;
+ // calculate offset for drag element if we use a different drag handle element
+ if (dragImage !== dragHandle) {
+ var domBox = dragImage.getBoundingClientRect();
+ var handleBox = dragHandle.getBoundingClientRect();
+ // In React, we have to go through nativeEvent to reach offsetX/offsetY.
+ var offsetX = (_c = event.offsetX) !== null && _c !== void 0 ? _c : (_d = event.nativeEvent) === null || _d === void 0 ? void 0 : _d.offsetX;
+ var offsetY = (_e = event.offsetY) !== null && _e !== void 0 ? _e : (_f = event.nativeEvent) === null || _f === void 0 ? void 0 : _f.offsetY;
+ x = handleBox.x - domBox.x + offsetX;
+ y = handleBox.y - domBox.y + offsetY;
+ }
+ (_g = event.dataTransfer) === null || _g === void 0 ? void 0 : _g.setDragImage(dragImage, x, y);
+ // we need to tell ProseMirror that we want to move the whole node
+ // so we create a NodeSelection
+ var selection = NodeSelection.create(view.state.doc, this.getPos());
+ var transaction = view.state.tr.setSelection(selection);
+ view.dispatch(transaction);
+ };
+ ReactNodeView.prototype.stopEvent = function (event) {
+ var _this = this;
+ var _a;
+ if (!this.dom) {
+ return false;
+ }
+ // if (typeof this.options.stopEvent === 'function') {
+ // return this.options.stopEvent({ event })
+ // }
+ var target = event.target;
+ var isInElement = this.dom.contains(target) && !((_a = this.contentDOM) === null || _a === void 0 ? void 0 : _a.contains(target));
+ // any event from child nodes should be handled by ProseMirror
+ if (!isInElement) {
+ return false;
+ }
+ var isDropEvent = event.type === "drop";
+ var isInput = ["INPUT", "BUTTON", "SELECT", "TEXTAREA"].includes(target.tagName) ||
+ target.isContentEditable;
+ // any input event within node views should be ignored by ProseMirror
+ if (isInput && !isDropEvent) {
+ return true;
+ }
+ var isEditable = this.editor.isEditable;
+ var isDragging = this.isDragging;
+ var isDraggable = !!this.node.type.spec.draggable;
+ var isSelectable = NodeSelection.isSelectable(this.node);
+ var isCopyEvent = event.type === "copy";
+ var isPasteEvent = event.type === "paste";
+ var isCutEvent = event.type === "cut";
+ var isClickEvent = event.type === "mousedown";
+ var isDragEvent = event.type.startsWith("drag");
+ // ProseMirror tries to drag selectable nodes
+ // even if `draggable` is set to `false`
+ // this fix prevents that
+ if (!isDraggable && isSelectable && isDragEvent) {
+ event.preventDefault();
+ }
+ if (isDraggable && isDragEvent && !isDragging) {
+ event.preventDefault();
+ return false;
+ }
+ // we have to store that dragging started
+ if (isDraggable && isEditable && !isDragging && isClickEvent) {
+ var dragHandle = target.closest("[data-drag-handle]");
+ var isValidDragHandle = dragHandle &&
+ (this.dom === dragHandle || this.dom.contains(dragHandle));
+ if (isValidDragHandle) {
+ this.isDragging = true;
+ document.addEventListener("dragend", function () {
+ _this.isDragging = false;
+ }, { once: true });
+ document.addEventListener("mouseup", function () {
+ _this.isDragging = false;
+ }, { once: true });
+ }
+ }
+ // these events are handled by prosemirror
+ if (isDragging ||
+ isDropEvent ||
+ isCopyEvent ||
+ isPasteEvent ||
+ isCutEvent ||
+ (isClickEvent && isSelectable)) {
+ return false;
+ }
+ return true;
+ };
ReactNodeView.prototype.ignoreMutation = function (mutation) {
if (!this.dom || !this.contentDOM) {
return true;
diff --git a/packages/editor/dist/extensions/react/reactportalprovider.d.ts b/packages/editor/dist/extensions/react/reactportalprovider.d.ts
index 62e1d0f5c..b3df1ee34 100644
--- a/packages/editor/dist/extensions/react/reactportalprovider.d.ts
+++ b/packages/editor/dist/extensions/react/reactportalprovider.d.ts
@@ -23,7 +23,7 @@ export declare class PortalProvider extends React.Component<BasePortalProviderPr
static displayName: string;
portalProviderAPI: PortalProviderAPI;
constructor(props: BasePortalProviderProps);
- render(): JSX.Element | React.ReactChild | null;
+ render(): React.ReactChild | JSX.Element | null;
componentDidUpdate(): void;
}
export declare class PortalRenderer extends React.Component<{
diff --git a/packages/editor/dist/extensions/react/selectionbasedreactnodeview.d.ts b/packages/editor/dist/extensions/react/selectionbasedreactnodeview.d.ts
index 0a84a0b06..6fb983b66 100644
--- a/packages/editor/dist/extensions/react/selectionbasedreactnodeview.d.ts
+++ b/packages/editor/dist/extensions/react/selectionbasedreactnodeview.d.ts
@@ -48,7 +48,7 @@ export declare class SelectionBasedNodeView<P extends SelectionBasedReactNodeVie
private isSelectedNode;
insideSelection: () => boolean;
nodeInsideSelection: () => boolean;
- viewShouldUpdate(_nextNode: PMNode): boolean;
+ viewShouldUpdate(nextNode: PMNode): boolean;
destroy(): void;
private onSelectionChange;
}
diff --git a/packages/editor/dist/extensions/react/selectionbasedreactnodeview.js b/packages/editor/dist/extensions/react/selectionbasedreactnodeview.js
index 209d14fd0..7c4c0c7e8 100644
--- a/packages/editor/dist/extensions/react/selectionbasedreactnodeview.js
+++ b/packages/editor/dist/extensions/react/selectionbasedreactnodeview.js
@@ -132,7 +132,9 @@ var SelectionBasedNodeView = /** @class */ (function (_super) {
posEnd: typeof posEnd !== "number" ? this.posEnd : posEnd,
};
};
- SelectionBasedNodeView.prototype.viewShouldUpdate = function (_nextNode) {
+ SelectionBasedNodeView.prototype.viewShouldUpdate = function (nextNode) {
+ if (_super.prototype.viewShouldUpdate.call(this, nextNode))
+ return true;
var selection = this.editor.view.state.selection;
// update selection
var oldSelection = this.oldSelection;
diff --git a/packages/editor/dist/index.js b/packages/editor/dist/index.js
index 2610cc0c4..14bf83d46 100644
--- a/packages/editor/dist/index.js
+++ b/packages/editor/dist/index.js
@@ -53,7 +53,7 @@ import { EmbedNode } from "./extensions/embed";
import { CodeBlock } from "./extensions/code-block";
import { ListItem } from "./extensions/list-item";
import { Link } from "./extensions/link";
-import { EventDispatcher } from "./extensions/react";
+import { EventDispatcher, NodeViewSelectionNotifier, } from "./extensions/react";
import { OutlineList } from "./extensions/outline-list";
import { OutlineListItem } from "./extensions/outline-list-item";
EditorView.prototype.updateState = function updateState(state) {
@@ -63,10 +63,11 @@ EditorView.prototype.updateState = function updateState(state) {
};
var useTiptap = function (options, deps) {
if (options === void 0) { options = {}; }
- var theme = options.theme, onCreate = options.onCreate, onDownloadAttachment = options.onDownloadAttachment, onOpenAttachmentPicker = options.onOpenAttachmentPicker, portalProviderAPI = options.portalProviderAPI, restOptions = __rest(options, ["theme", "onCreate", "onDownloadAttachment", "onOpenAttachmentPicker", "portalProviderAPI"]);
+ var theme = options.theme, onCreate = options.onCreate, onUpdate = options.onUpdate, onDownloadAttachment = options.onDownloadAttachment, onOpenAttachmentPicker = options.onOpenAttachmentPicker, portalProviderAPI = options.portalProviderAPI, restOptions = __rest(options, ["theme", "onCreate", "onUpdate", "onDownloadAttachment", "onOpenAttachmentPicker", "portalProviderAPI"]);
var eventDispatcher = useMemo(function () { return new EventDispatcher(); }, []);
var defaultOptions = useMemo(function () { return ({
extensions: [
+ NodeViewSelectionNotifier,
SearchReplace,
TextStyle,
StarterKit.configure({
@@ -133,10 +134,19 @@ var useTiptap = function (options, deps) {
if (onCreate)
onCreate({ editor: editor });
},
+ onUpdate: function (_a) {
+ var editor = _a.editor, transaction = _a.transaction;
+ // a custom extension to transaction that indicates whether
+ // this is an actual update or not.
+ if (transaction.skipUpdate)
+ return;
+ onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate({ editor: editor, transaction: transaction });
+ },
injectCSS: false,
}); }, [
theme,
onCreate,
+ onUpdate,
onDownloadAttachment,
onOpenAttachmentPicker,
portalProviderAPI,
diff --git a/packages/editor/dist/toolbar/tools/block.js b/packages/editor/dist/toolbar/tools/block.js
index 26a762b6f..bf94303ab 100644
--- a/packages/editor/dist/toolbar/tools/block.js
+++ b/packages/editor/dist/toolbar/tools/block.js
@@ -107,7 +107,9 @@ var image = function (editor) { return ({
type: "button",
title: "Upload from disk",
icon: "upload",
- onClick: function () { },
+ onClick: function () {
+ return editor === null || editor === void 0 ? void 0 : editor.chain().focus().openAttachmentPicker("image").run();
+ },
},
{
key: "upload-from-url",
diff --git a/packages/editor/src/extensions/attachment/attachment.ts b/packages/editor/src/extensions/attachment/attachment.ts
index 7161dd380..544e7d3f8 100644
--- a/packages/editor/src/extensions/attachment/attachment.ts
+++ b/packages/editor/src/extensions/attachment/attachment.ts
@@ -1,16 +1,18 @@
-import { Node, mergeAttributes, findChildren } from "@tiptap/core";
+import { Node, mergeAttributes, findChildren, Editor } from "@tiptap/core";
import { Attribute } from "@tiptap/core";
-import { createNodeView } from "../react";
+import { createNodeView, createSelectionBasedNodeView } from "../react";
import { AttachmentComponent } from "./component";
export type AttachmentType = "image" | "file";
export interface AttachmentOptions {
HTMLAttributes: Record<string, any>;
- onDownloadAttachment: (attachment: Attachment) => boolean;
- onOpenAttachmentPicker: (type: AttachmentType) => boolean;
+ onDownloadAttachment: (editor: Editor, attachment: Attachment) => boolean;
+ onOpenAttachmentPicker: (editor: Editor, type: AttachmentType) => boolean;
}
-export type Attachment = AttachmentProgress & {
+export type AttachmentWithProgress = AttachmentProgress & Attachment;
+
+export type Attachment = {
hash: string;
filename: string;
type: string;
@@ -19,7 +21,7 @@ export type Attachment = AttachmentProgress & {
export type AttachmentProgress = {
progress: number;
- type: "upload" | "download";
+ type: "upload" | "download" | "encrypt";
hash: string;
};
@@ -29,7 +31,7 @@ declare module "@tiptap/core" {
openAttachmentPicker: (type: AttachmentType) => ReturnType;
insertAttachment: (attachment: Attachment) => ReturnType;
downloadAttachment: (attachment: Attachment) => ReturnType;
- setProgress: (progress: AttachmentProgress) => ReturnType;
+ setAttachmentProgress: (progress: AttachmentProgress) => ReturnType;
};
}
}
@@ -57,6 +59,10 @@ export const AttachmentNode = Node.create<AttachmentOptions>({
addAttributes() {
return {
+ progress: {
+ default: 0,
+ rendered: false,
+ },
hash: getDataAttribute("hash"),
filename: getDataAttribute("filename"),
type: getDataAttribute("type"),
@@ -80,7 +86,11 @@ export const AttachmentNode = Node.create<AttachmentOptions>({
},
addNodeView() {
- return createNodeView(AttachmentComponent);
+ return createSelectionBasedNodeView(AttachmentComponent, {
+ shouldUpdate: ({ attrs: prev }, { attrs: next }) => {
+ return prev.progress !== next.progress;
+ },
+ });
},
addCommands() {
@@ -88,6 +98,7 @@ export const AttachmentNode = Node.create<AttachmentOptions>({
insertAttachment:
(attachment) =>
({ commands }) => {
+ console.log("HI!", attachment);
return commands.insertContent({
type: this.name,
attrs: attachment,
@@ -95,28 +106,32 @@ export const AttachmentNode = Node.create<AttachmentOptions>({
},
downloadAttachment:
(attachment) =>
- ({}) => {
- return this.options.onDownloadAttachment(attachment);
+ ({ editor }) => {
+ return this.options.onDownloadAttachment(editor, attachment);
},
- openAttachmentPicker: (type: AttachmentType) => () => {
- return this.options.onOpenAttachmentPicker(type);
- },
- setProgress:
+ openAttachmentPicker:
+ (type: AttachmentType) =>
+ ({ editor }) => {
+ return this.options.onOpenAttachmentPicker(editor, type);
+ },
+ setAttachmentProgress:
(options) =>
({ state, tr, dispatch }) => {
const { hash, progress, type } = options;
const attachments = findChildren(
state.doc,
(node) =>
- (node.type.name === "attachment" || node.type.name === "image") &&
+ (node.type.name === this.name || node.type.name === "image") &&
node.attrs.hash === hash
);
for (const attachment of attachments) {
+ console.log(attachment.node.attrs);
tr.setNodeMarkup(attachment.pos, attachment.node.type, {
+ ...attachment.node.attrs,
progress,
- type,
});
}
+ (tr as any).skipUpdate = true;
if (dispatch) dispatch(tr);
return true;
},
@@ -138,9 +153,12 @@ export const AttachmentNode = Node.create<AttachmentOptions>({
// },
});
-function getDataAttribute(name: keyof Attachment): Partial<Attribute> {
+export function getDataAttribute(
+ name: string,
+ def?: any | null
+): Partial<Attribute> {
return {
- default: null,
+ default: def,
parseHTML: (element) => element.dataset[name],
renderHTML: (attributes) => {
if (!attributes[name]) {
diff --git a/packages/editor/src/extensions/attachment/component.tsx b/packages/editor/src/extensions/attachment/component.tsx
index 0b246e978..ac558a9b8 100644
--- a/packages/editor/src/extensions/attachment/component.tsx
+++ b/packages/editor/src/extensions/attachment/component.tsx
@@ -1,25 +1,27 @@
import { Box, Flex, Text } from "rebass";
-import { Attachment } from "./attachment";
+import { AttachmentWithProgress } from "./attachment";
import { ToolButton } from "../../toolbar/components/tool-button";
import { Editor } from "@tiptap/core";
import { useRef } from "react";
// import { MenuPresenter } from "../../components/menu/menu";
import { Icon } from "../../toolbar/components/icon";
import { Icons } from "../../toolbar/icons";
-import { ReactNodeViewProps } from "../react";
+import { SelectionBasedReactNodeViewProps } from "../react";
+import { PopupPresenter } from "../../components/popup-presenter";
-export function AttachmentComponent(props: ReactNodeViewProps<Attachment>) {
- const { hash, filename, size } = props.node.attrs;
-
- const { editor } = props;
+export function AttachmentComponent(
+ props: SelectionBasedReactNodeViewProps<AttachmentWithProgress>
+) {
+ const { editor, node, selected } = props;
+ const { hash, filename, size, progress } = node.attrs;
const elementRef = useRef<HTMLSpanElement>();
- const isActive = editor.isActive("attachment", { hash });
+ // const isActive = editor.isActive("attachment", { hash });
// const [isToolbarVisible, setIsToolbarVisible] = useState<boolean>();
// useEffect(() => {
// setIsToolbarVisible(isActive);
// }, [isActive]);
-
+ console.log(progress);
return (
<>
<Box
@@ -31,6 +33,7 @@ export function AttachmentComponent(props: ReactNodeViewProps<Attachment>) {
display: "inline-flex",
overflow: "hidden",
position: "relative",
+ justifyContent: "center",
zIndex: 1,
userSelect: "none",
alignItems: "center",
@@ -40,7 +43,7 @@ export function AttachmentComponent(props: ReactNodeViewProps<Attachment>) {
border: "1px solid var(--border)",
cursor: "pointer",
maxWidth: 250,
- borderColor: isActive ? "primary" : "border",
+ borderColor: selected ? "primary" : "border",
":hover": {
bg: "hover",
},
@@ -52,45 +55,41 @@ export function AttachmentComponent(props: ReactNodeViewProps<Attachment>) {
as="span"
sx={{
ml: "small",
- fontSize: "0.85rem",
+ fontSize: "body",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
overflow: "hidden",
}}
- className="filename"
>
{filename}
</Text>
<Text
as="span"
- className="size"
sx={{
ml: 1,
- fontSize: "subBody",
+ fontSize: "0.65rem",
color: "fontTertiary",
flexShrink: 0,
}}
>
- {formatBytes(size)}
+ {progress ? `${progress}%` : formatBytes(size)}
</Text>
</Box>
- {/* <MenuPresenter
- isOpen={isActive}
+ <PopupPresenter
+ isOpen={selected}
onClose={() => {}}
- items={[]}
- options={{
- type: "autocomplete",
- position: {
- target: elementRef.current || undefined,
- location: "top",
- yOffset: -5,
- isTargetAbsolute: true,
- align: "end",
- },
+ blocking={false}
+ focusOnRender={false}
+ position={{
+ target: elementRef.current || undefined,
+ align: "center",
+ location: "top",
+ yOffset: 5,
+ isTargetAbsolute: true,
}}
>
<AttachmentToolbar editor={editor} />
- </MenuPresenter> */}
+ </PopupPresenter>
</>
);
}
@@ -118,42 +117,28 @@ function AttachmentToolbar(props: AttachmentToolbarProps) {
return (
<Flex
sx={{
- flexDirection: "column",
- // position: "absolute",
- // top: 0,
- mb: 2,
- zIndex: 9999,
- alignItems: "end",
+ bg: "background",
+ boxShadow: "menu",
+ flexWrap: "nowrap",
+ borderRadius: "default",
}}
>
- <Flex
- sx={{
- bg: "background",
- boxShadow: "menu",
- flexWrap: "nowrap",
- borderRadius: "default",
- mb: 2,
- }}
- >
- <ToolButton
- toggled={false}
- title="Download"
- id="download"
- icon="download"
- onClick={() => {}}
- variant="small"
- sx={{ mr: 1 }}
- />
- <ToolButton
- toggled={false}
- title="delete"
- id="delete"
- icon="delete"
- onClick={() => {}}
- variant="small"
- sx={{ mr: 0 }}
- />
- </Flex>
+ <ToolButton
+ toggled={false}
+ title="Download"
+ id="download"
+ icon="download"
+ onClick={() => {}}
+ sx={{ mr: 1 }}
+ />
+ <ToolButton
+ toggled={false}
+ title="delete"
+ id="delete"
+ icon="delete"
+ onClick={() => {}}
+ sx={{ mr: 0 }}
+ />
</Flex>
);
}
diff --git a/packages/editor/src/extensions/code-block/highlighter.ts b/packages/editor/src/extensions/code-block/highlighter.ts
index 9222701ca..734659399 100644
--- a/packages/editor/src/extensions/code-block/highlighter.ts
+++ b/packages/editor/src/extensions/code-block/highlighter.ts
@@ -18,7 +18,7 @@ import {
toCodeLines,
} from "./code-block";
-type MergedStep =
+export type MergedStep =
| AddMarkStep
| RemoveMarkStep
| ReplaceAroundStep
diff --git a/packages/editor/src/extensions/embed/embed.ts b/packages/editor/src/extensions/embed/embed.ts
index e50ad998e..1e44423c5 100644
--- a/packages/editor/src/extensions/embed/embed.ts
+++ b/packages/editor/src/extensions/embed/embed.ts
@@ -78,10 +78,6 @@ export const EmbedNode = Node.create<EmbedOptions>({
];
},
- addProseMirrorPlugins() {
- return [NodeViewSelectionNotifierPlugin];
- },
-
addNodeView() {
return createSelectionBasedNodeView(EmbedComponent);
},
diff --git a/packages/editor/src/extensions/image/component.tsx b/packages/editor/src/extensions/image/component.tsx
index 5f035ce64..b315f98a0 100644
--- a/packages/editor/src/extensions/image/component.tsx
+++ b/packages/editor/src/extensions/image/component.tsx
@@ -13,6 +13,8 @@ import { ReactNodeViewProps, SelectionBasedReactNodeViewProps } from "../react";
import { ResponsivePresenter } from "../../components/responsive";
import { ImageProperties } from "../../toolbar/popups/image-properties";
import { Popup } from "../../toolbar/components/popup";
+import { Icon } from "../../toolbar/components/icon";
+import { Icons } from "../../toolbar/icons";
export function ImageComponent(
props: SelectionBasedReactNodeViewProps<
@@ -23,10 +25,18 @@ export function ImageComponent(
const { src, alt, title, width, height, align, float } = node.attrs;
const imageRef = useRef<HTMLImageElement>();
+ useEffect(() => {
+ (async () => {
+ if (!imageRef.current) return;
+ imageRef.current.src = await dataUriToBlobURL(src);
+ })();
+ }, [src, imageRef]);
+
return (
<>
<Box
sx={{
+ position: "relative",
display: float ? "block" : "flex",
justifyContent: float
? "stretch"
@@ -35,8 +45,27 @@ export function ImageComponent(
: align === "left"
? "start"
: "end",
+ ":hover .drag-handle, :active .drag-handle": {
+ opacity: 1,
+ },
}}
+ draggable={false}
>
+ <Icon
+ className="drag-handle"
+ data-drag-handle
+ draggable
+ path={Icons.dragHandle}
+ sx={{
+ cursor: "grab",
+ position: "absolute",
+ top: 2,
+ left: 2,
+ zIndex: 999,
+ opacity: 0,
+ }}
+ />
+
<Resizable
style={{
float: float ? (align === "left" ? "left" : "right") : "none",
@@ -66,8 +95,8 @@ export function ImageComponent(
</Flex>
)}
<Image
+ data-drag-image
ref={imageRef}
- src={src}
alt={alt}
title={title}
width={"100%"}
@@ -206,3 +235,11 @@ function ImageToolbar(props: ImageToolbarProps) {
</Flex>
);
}
+
+async function dataUriToBlobURL(dataurl: string) {
+ if (!dataurl.startsWith("data:image")) return dataurl;
+
+ const response = await fetch(dataurl);
+ const blob = await response.blob();
+ return URL.createObjectURL(blob);
+}
diff --git a/packages/editor/src/extensions/image/image.ts b/packages/editor/src/extensions/image/image.ts
index 03749f48a..7996126d0 100644
--- a/packages/editor/src/extensions/image/image.ts
+++ b/packages/editor/src/extensions/image/image.ts
@@ -1,4 +1,10 @@
-import { Node, nodeInputRule, mergeAttributes } from "@tiptap/core";
+import {
+ Node,
+ nodeInputRule,
+ mergeAttributes,
+ findChildren,
+} from "@tiptap/core";
+import { Attachment, getDataAttribute } from "../attachment";
import {
createNodeView,
createSelectionBasedNodeView,
@@ -12,11 +18,12 @@ export interface ImageOptions {
HTMLAttributes: Record<string, any>;
}
-export type ImageAttributes = Partial<ImageSizeOptions> & {
- src: string;
- alt?: string;
- title?: string;
-};
+export type ImageAttributes = Partial<ImageSizeOptions> &
+ Partial<Attachment> & {
+ src: string;
+ alt?: string;
+ title?: string;
+ };
export type ImageAlignmentOptions = {
float?: boolean;
@@ -34,7 +41,8 @@ declare module "@tiptap/core" {
/**
* Add an image
*/
- setImage: (options: ImageAttributes) => ReturnType;
+ insertImage: (options: ImageAttributes) => ReturnType;
+ updateImage: (options: ImageAttributes) => ReturnType;
setImageAlignment: (options: ImageAlignmentOptions) => ReturnType;
setImageSize: (options: ImageSizeOptions) => ReturnType;
};
@@ -77,10 +85,13 @@ export const ImageNode = Node.create<ImageOptions>({
},
width: { default: null },
height: { default: null },
- float: {
- default: false,
- },
- align: { default: "left" },
+
+ float: getDataAttribute("float", false),
+ align: getDataAttribute("align", "left"),
+ hash: getDataAttribute("hash"),
+ filename: getDataAttribute("filename"),
+ type: getDataAttribute("type"),
+ size: getDataAttribute("size"),
};
},
@@ -105,13 +116,9 @@ export const ImageNode = Node.create<ImageOptions>({
return createSelectionBasedNodeView(ImageComponent);
},
- addProseMirrorPlugins() {
- return [NodeViewSelectionNotifierPlugin];
- },
-
addCommands() {
return {
- setImage:
+ insertImage:
(options) =>
({ commands }) => {
return commands.insertContent({
@@ -129,6 +136,31 @@ export const ImageNode = Node.create<ImageOptions>({
({ commands }) => {
return commands.updateAttributes(this.name, { ...options });
},
+ updateImage:
+ (options) =>
+ ({ state, tr, dispatch }) => {
+ const query = options.hash
+ ? { key: "hash", value: options.hash }
+ : options.src
+ ? { key: "src", value: options.src }
+ : null;
+ if (!query) return false;
+
+ const images = findChildren(
+ state.doc,
+ (node) =>
+ node.type.name === this.name &&
+ node.attrs[query.key] === query.value
+ );
+ for (const image of images) {
+ tr.setNodeMarkup(image.pos, image.node.type, {
+ ...image.node.attrs,
+ ...options,
+ });
+ }
+ if (dispatch) dispatch(tr);
+ return true;
+ },
};
},
diff --git a/packages/editor/src/extensions/react/plugin.ts b/packages/editor/src/extensions/react/plugin.ts
index 9592bfafa..e75da6b37 100644
--- a/packages/editor/src/extensions/react/plugin.ts
+++ b/packages/editor/src/extensions/react/plugin.ts
@@ -1,5 +1,6 @@
import { Plugin, PluginKey } from "prosemirror-state";
import { EditorView } from "prosemirror-view";
+import { Extension } from "@tiptap/core";
export type StateChangeHandler = (fromPos: number, toPos: number) => any;
@@ -46,3 +47,9 @@ export const NodeViewSelectionNotifierPlugin = new Plugin({
};
},
});
+
+export const NodeViewSelectionNotifier = Extension.create({
+ addProseMirrorPlugins() {
+ return [NodeViewSelectionNotifierPlugin];
+ },
+});
diff --git a/packages/editor/src/extensions/react/react-node-view.tsx b/packages/editor/src/extensions/react/react-node-view.tsx
index c365c3d91..a431be0e3 100644
--- a/packages/editor/src/extensions/react/react-node-view.tsx
+++ b/packages/editor/src/extensions/react/react-node-view.tsx
@@ -1,7 +1,7 @@
import React from "react";
import { NodeView, Decoration, DecorationSource } from "prosemirror-view";
import { Node as PMNode } from "prosemirror-model";
-
+import { NodeSelection } from "prosemirror-state";
import { PortalProviderAPI } from "./react-portal-provider";
import { EventDispatcher } from "./event-dispatcher";
import {
@@ -21,6 +21,7 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {
contentDOM: HTMLElement | undefined;
node: PMNode;
+ isDragging = false;
constructor(
node: PMNode,
@@ -44,6 +45,7 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {
*/
init() {
this.domRef = this.createDomRef();
+ this.domRef.ondragstart = (ev) => this.onDragStart(ev);
// this.setDomAttrs(this.node, this.domRef);
const { dom: contentDOMWrapper, contentDOM } = this.getContentDOM() || {
@@ -182,6 +184,142 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {
return true;
}
+ onDragStart(event: DragEvent) {
+ const { view } = this.editor;
+ const target = event.target as HTMLElement;
+
+ // get the drag handle element
+ // `closest` is not available for text nodes so we may have to use its parent
+ const dragHandle =
+ target.nodeType === 3
+ ? target.parentElement?.closest("[data-drag-handle]")
+ : target.closest("[data-drag-handle]");
+
+ if (!this.dom || this.contentDOM?.contains(target) || !dragHandle) {
+ return;
+ }
+
+ const dragImage = this.dom.querySelector("[data-drag-image]") || this.dom;
+
+ let x = 0;
+ let y = 0;
+
+ // calculate offset for drag element if we use a different drag handle element
+ if (dragImage !== dragHandle) {
+ const domBox = dragImage.getBoundingClientRect();
+ const handleBox = dragHandle.getBoundingClientRect();
+
+ // In React, we have to go through nativeEvent to reach offsetX/offsetY.
+ const offsetX = event.offsetX ?? (event as any).nativeEvent?.offsetX;
+ const offsetY = event.offsetY ?? (event as any).nativeEvent?.offsetY;
+
+ x = handleBox.x - domBox.x + offsetX;
+ y = handleBox.y - domBox.y + offsetY;
+ }
+
+ event.dataTransfer?.setDragImage(dragImage, x, y);
+
+ // we need to tell ProseMirror that we want to move the whole node
+ // so we create a NodeSelection
+ const selection = NodeSelection.create(view.state.doc, this.getPos());
+ const transaction = view.state.tr.setSelection(selection);
+
+ view.dispatch(transaction);
+ }
+
+ stopEvent(event: Event): boolean {
+ if (!this.dom) {
+ return false;
+ }
+
+ // if (typeof this.options.stopEvent === 'function') {
+ // return this.options.stopEvent({ event })
+ // }
+
+ const target = event.target as HTMLElement;
+ const isInElement =
+ this.dom.contains(target) && !this.contentDOM?.contains(target);
+
+ // any event from child nodes should be handled by ProseMirror
+ if (!isInElement) {
+ return false;
+ }
+
+ const isDropEvent = event.type === "drop";
+ const isInput =
+ ["INPUT", "BUTTON", "SELECT", "TEXTAREA"].includes(target.tagName) ||
+ target.isContentEditable;
+
+ // any input event within node views should be ignored by ProseMirror
+ if (isInput && !isDropEvent) {
+ return true;
+ }
+
+ const { isEditable } = this.editor;
+ const { isDragging } = this;
+ const isDraggable = !!this.node.type.spec.draggable;
+ const isSelectable = NodeSelection.isSelectable(this.node);
+ const isCopyEvent = event.type === "copy";
+ const isPasteEvent = event.type === "paste";
+ const isCutEvent = event.type === "cut";
+ const isClickEvent = event.type === "mousedown";
+ const isDragEvent = event.type.startsWith("drag");
+
+ // ProseMirror tries to drag selectable nodes
+ // even if `draggable` is set to `false`
+ // this fix prevents that
+ if (!isDraggable && isSelectable && isDragEvent) {
+ event.preventDefault();
+ }
+
+ if (isDraggable && isDragEvent && !isDragging) {
+ event.preventDefault();
+ return false;
+ }
+
+ // we have to store that dragging started
+ if (isDraggable && isEditable && !isDragging && isClickEvent) {
+ const dragHandle = target.closest("[data-drag-handle]");
+ const isValidDragHandle =
+ dragHandle &&
+ (this.dom === dragHandle || this.dom.contains(dragHandle));
+
+ if (isValidDragHandle) {
+ this.isDragging = true;
+
+ document.addEventListener(
+ "dragend",
+ () => {
+ this.isDragging = false;
+ },
+ { once: true }
+ );
+
+ document.addEventListener(
+ "mouseup",
+ () => {
+ this.isDragging = false;
+ },
+ { once: true }
+ );
+ }
+ }
+
+ // these events are handled by prosemirror
+ if (
+ isDragging ||
+ isDropEvent ||
+ isCopyEvent ||
+ isPasteEvent ||
+ isCutEvent ||
+ (isClickEvent && isSelectable)
+ ) {
+ return false;
+ }
+
+ return true;
+ }
+
ignoreMutation(
mutation: MutationRecord | { type: "selection"; target: Element }
) {
diff --git a/packages/editor/src/extensions/react/selection-based-react-node-view.tsx b/packages/editor/src/extensions/react/selection-based-react-node-view.tsx
index b5ed9329c..6f61bb42f 100644
--- a/packages/editor/src/extensions/react/selection-based-react-node-view.tsx
+++ b/packages/editor/src/extensions/react/selection-based-react-node-view.tsx
@@ -182,7 +182,9 @@ export class SelectionBasedNodeView<
);
};
- viewShouldUpdate(_nextNode: PMNode) {
+ viewShouldUpdate(nextNode: PMNode) {
+ if (super.viewShouldUpdate(nextNode)) return true;
+
const {
state: { selection },
} = this.editor.view;
diff --git a/packages/editor/src/index.ts b/packages/editor/src/index.ts
index a002d1d65..681a55070 100644
--- a/packages/editor/src/index.ts
+++ b/packages/editor/src/index.ts
@@ -32,7 +32,11 @@ import { EmbedNode } from "./extensions/embed";
import { CodeBlock } from "./extensions/code-block";
import { ListItem } from "./extensions/list-item";
import { Link } from "./extensions/link";
-import { PortalProviderAPI, EventDispatcher } from "./extensions/react";
+import {
+ PortalProviderAPI,
+ EventDispatcher,
+ NodeViewSelectionNotifier,
+} from "./extensions/react";
import { OutlineList } from "./extensions/outline-list";
import { OutlineListItem } from "./extensions/outline-list-item";
@@ -51,6 +55,7 @@ const useTiptap = (
const {
theme,
onCreate,
+ onUpdate,
onDownloadAttachment,
onOpenAttachmentPicker,
portalProviderAPI,
@@ -61,6 +66,7 @@ const useTiptap = (
const defaultOptions = useMemo<Partial<EditorOptions>>(
() => ({
extensions: [
+ NodeViewSelectionNotifier,
SearchReplace,
TextStyle,
StarterKit.configure({
@@ -126,11 +132,19 @@ const useTiptap = (
if (onCreate) onCreate({ editor });
},
+ onUpdate: ({ editor, transaction }) => {
+ // a custom extension to transaction that indicates whether
+ // this is an actual update or not.
+ if ((transaction as any).skipUpdate) return;
+
+ onUpdate?.({ editor, transaction });
+ },
injectCSS: false,
}),
[
theme,
onCreate,
+ onUpdate,
onDownloadAttachment,
onOpenAttachmentPicker,
portalProviderAPI,
diff --git a/packages/editor/src/toolbar/tools/block.tsx b/packages/editor/src/toolbar/tools/block.tsx
index a8a00b072..e70d3cdb0 100644
--- a/packages/editor/src/toolbar/tools/block.tsx
+++ b/packages/editor/src/toolbar/tools/block.tsx
@@ -120,7 +120,8 @@ const image = (editor: Editor | null): MenuItem => ({
type: "button",
title: "Upload from disk",
icon: "upload",
- onClick: () => {},
+ onClick: () =>
+ editor?.chain().focus().openAttachmentPicker("image").run(),
},
{
key: "upload-from-url",