feat: editor file attachments (#194)

* fix current slider value

* WIP

* changes to extension attributes

* update command title
This commit is contained in:
Philip Okugbe
2024-08-26 12:38:47 +01:00
committed by GitHub
parent 7e80797e3f
commit 7dc37b933f
19 changed files with 450 additions and 16 deletions

View File

@ -10,5 +10,5 @@ export * from "./lib/callout";
export * from "./lib/media-utils";
export * from "./lib/link";
export * from "./lib/selection";
export * from "./lib/attachment";
export * from "./lib/custom-code-block"

View File

@ -0,0 +1,119 @@
import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import { MediaUploadOptions, UploadFn } from "../media-utils";
import { IAttachment } from "../types";
const uploadKey = new PluginKey("attachment-upload");
export const AttachmentUploadPlugin = ({
placeholderClass,
}: {
placeholderClass: string;
}) =>
new Plugin({
key: uploadKey,
state: {
init() {
return DecorationSet.empty;
},
apply(tr, set) {
set = set.map(tr.mapping, tr.doc);
// See if the transaction adds or removes any placeholders
//@-ts-expect-error - not yet sure what the type I need here
const action = tr.getMeta(this);
if (action?.add) {
const { id, pos, fileName } = action.add;
const placeholder = document.createElement("div");
placeholder.setAttribute("class", placeholderClass);
const uploadingText = document.createElement("span");
uploadingText.setAttribute("class", "uploading-text");
uploadingText.textContent = `Uploading ${fileName}`;
placeholder.appendChild(uploadingText);
const deco = Decoration.widget(pos + 1, placeholder, {
id,
});
set = set.add(tr.doc, [deco]);
} else if (action?.remove) {
set = set.remove(
set.find(
undefined,
undefined,
(spec) => spec.id == action.remove.id,
),
);
}
return set;
},
},
props: {
decorations(state) {
return this.getState(state);
},
},
});
function findPlaceholder(state: EditorState, id: {}) {
const decos = uploadKey.getState(state) as DecorationSet;
const found = decos.find(undefined, undefined, (spec) => spec.id == id);
return found.length ? found[0]?.from : null;
}
export const handleAttachmentUpload =
({ validateFn, onUpload }: MediaUploadOptions): UploadFn =>
async (file, view, pos, pageId) => {
const validated = validateFn?.(file);
// @ts-ignore
if (!validated) return;
// A fresh object to act as the ID for this upload
const id = {};
// Replace the selection with a placeholder
const tr = view.state.tr;
if (!tr.selection.empty) tr.deleteSelection();
tr.setMeta(uploadKey, {
add: {
id,
pos,
fileName: file.name,
},
});
view.dispatch(tr);
await onUpload(file, pageId).then(
(attachment: IAttachment) => {
const { schema } = view.state;
const pos = findPlaceholder(view.state, id);
if (pos == null) return;
if (!attachment) return;
const node = schema.nodes.attachment?.create({
url: `/files/${attachment.id}/${attachment.fileName}`,
name: attachment.fileName,
mime: attachment.mimeType,
size: attachment.fileSize,
attachmentId: attachment.id,
});
if (!node) return;
const transaction = view.state.tr
.replaceWith(pos, pos, node)
.setMeta(uploadKey, { remove: { id } });
view.dispatch(transaction);
},
() => {
// Deletes the placeholder on error
const transaction = view.state.tr
.delete(pos, pos)
.setMeta(uploadKey, { remove: { id } });
view.dispatch(transaction);
},
);
};

View File

@ -0,0 +1,123 @@
import { Node, mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { AttachmentUploadPlugin } from "./attachment-upload";
export interface AttachmentOptions {
HTMLAttributes: Record<string, any>;
view: any;
}
export interface AttachmentAttributes {
url?: string;
name?: string;
mime?: string; // mime type e.g. application/zip
size?: number;
attachmentId?: string;
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
attachment: {
setAttachment: (attributes: AttachmentAttributes) => ReturnType;
};
}
}
export const Attachment = Node.create<AttachmentOptions>({
name: "attachment",
inline: false,
group: "block",
isolating: true,
atom: true,
defining: true,
draggable: true,
addOptions() {
return {
HTMLAttributes: {},
view: null,
};
},
addAttributes() {
return {
url: {
default: "",
parseHTML: (element) => element.getAttribute("data-attachment-url"),
renderHTML: (attributes) => ({
"data-attachment-url": attributes.url,
}),
},
name: {
default: undefined,
parseHTML: (element) => element.getAttribute("data-attachment-name"),
renderHTML: (attributes: AttachmentAttributes) => ({
"data-attachment-name": attributes.name,
}),
},
extension: {
default: undefined,
parseHTML: (element) => element.getAttribute("data-attachment-mime"),
renderHTML: (attributes: AttachmentAttributes) => ({
"data-attachment-mime": attributes.mime,
}),
},
size: {
default: null,
parseHTML: (element) => element.getAttribute("data-attachment-size"),
renderHTML: (attributes: AttachmentAttributes) => ({
"data-attachment-size": attributes.size,
}),
},
attachmentId: {
default: undefined,
parseHTML: (element) => element.getAttribute("data-attachment-id"),
renderHTML: (attributes: AttachmentAttributes) => ({
"data-attachment-id": attributes.attachmentId,
}),
},
};
},
parseHTML() {
return [
{
tag: `div[data-type="${this.name}"]`,
},
];
},
renderHTML({ HTMLAttributes }) {
return [
"div",
mergeAttributes(
{ "data-type": this.name },
this.options.HTMLAttributes,
HTMLAttributes,
),
];
},
addCommands() {
return {
setAttachment:
(attrs: AttachmentAttributes) =>
({ commands }) => {
return commands.insertContent({
type: "attachment",
attrs: attrs,
});
},
};
},
addNodeView() {
return ReactNodeViewRenderer(this.options.view);
},
addProseMirrorPlugins() {
return [
AttachmentUploadPlugin({
placeholderClass: "attachment-placeholder",
}),
];
},
});

View File

@ -0,0 +1,2 @@
export { Attachment } from "./attachment";
export * from "./attachment-upload";