upload image option (#64)
This commit is contained in:
@@ -1,49 +1,142 @@
|
||||
import { ReactNodeViewRenderer } from "@tiptap/react";
|
||||
import TipTapImage from "@tiptap/extension-image";
|
||||
import { ResizableImageTemplate } from "../nodes/image-resize";
|
||||
import { PluginKey, Plugin } from "@tiptap/pm/state";
|
||||
import { toast } from "@unsend/ui/src/toaster";
|
||||
|
||||
export const ResizableImageExtension = TipTapImage.extend({
|
||||
addAttributes() {
|
||||
return {
|
||||
...this.parent?.(),
|
||||
width: { renderHTML: ({ width }) => ({ width }), default: "600" },
|
||||
height: { renderHTML: ({ height }) => ({ height }) },
|
||||
borderRadius: {
|
||||
default: "0",
|
||||
},
|
||||
borderWidth: {
|
||||
default: "0",
|
||||
},
|
||||
borderColor: {
|
||||
default: "rgb(0, 0, 0)",
|
||||
},
|
||||
alignment: {
|
||||
default: "center",
|
||||
renderHTML: ({ alignment }) => ({ "data-alignment": alignment }),
|
||||
parseHTML: (element) =>
|
||||
element.getAttribute("data-alignment") || "center",
|
||||
},
|
||||
externalLink: {
|
||||
default: null,
|
||||
renderHTML: ({ externalLink }) => {
|
||||
if (!externalLink) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
"data-external-link": externalLink,
|
||||
};
|
||||
const uploadKey = new PluginKey("upload-image");
|
||||
|
||||
export type UploadFn = (image: File) => Promise<string>;
|
||||
|
||||
interface ResizableImageExtensionOptions {
|
||||
uploadImage?: UploadFn;
|
||||
}
|
||||
|
||||
export const ResizableImageExtension =
|
||||
TipTapImage.extend<ResizableImageExtensionOptions>({
|
||||
addAttributes() {
|
||||
return {
|
||||
...this.parent?.(),
|
||||
width: { renderHTML: ({ width }) => ({ width }), default: "600" },
|
||||
height: { renderHTML: ({ height }) => ({ height }) },
|
||||
borderRadius: {
|
||||
default: "0",
|
||||
},
|
||||
parseHTML: (element) => {
|
||||
const externalLink = element.getAttribute("data-external-link");
|
||||
return externalLink ? { externalLink } : null;
|
||||
borderWidth: {
|
||||
default: "0",
|
||||
},
|
||||
},
|
||||
alt: {
|
||||
default: "image",
|
||||
},
|
||||
};
|
||||
},
|
||||
addNodeView() {
|
||||
return ReactNodeViewRenderer(ResizableImageTemplate);
|
||||
},
|
||||
});
|
||||
borderColor: {
|
||||
default: "rgb(0, 0, 0)",
|
||||
},
|
||||
alignment: {
|
||||
default: "center",
|
||||
renderHTML: ({ alignment }) => ({ "data-alignment": alignment }),
|
||||
parseHTML: (element) =>
|
||||
element.getAttribute("data-alignment") || "center",
|
||||
},
|
||||
externalLink: {
|
||||
default: null,
|
||||
renderHTML: ({ externalLink }) => {
|
||||
if (!externalLink) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
"data-external-link": externalLink,
|
||||
};
|
||||
},
|
||||
parseHTML: (element) => {
|
||||
const externalLink = element.getAttribute("data-external-link");
|
||||
return externalLink ? { externalLink } : null;
|
||||
},
|
||||
},
|
||||
alt: {
|
||||
default: "image",
|
||||
},
|
||||
isUploading: {
|
||||
default: false,
|
||||
},
|
||||
};
|
||||
},
|
||||
addNodeView() {
|
||||
return ReactNodeViewRenderer(ResizableImageTemplate);
|
||||
},
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
key: uploadKey,
|
||||
props: {
|
||||
handleDOMEvents: {
|
||||
drop: (view, event) => {
|
||||
event.preventDefault();
|
||||
|
||||
const hasFiles = event.dataTransfer?.files?.length;
|
||||
if (!hasFiles) return false;
|
||||
|
||||
const image = Array.from(event.dataTransfer.files).find(
|
||||
(file) => file.type.startsWith("image/")
|
||||
);
|
||||
|
||||
if (!this.options.uploadImage) {
|
||||
toast.error("Upload image is not supported");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!image) {
|
||||
toast.error("Only image is supported");
|
||||
return true;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const { schema } = view.state;
|
||||
|
||||
if (!schema.nodes.image) return false;
|
||||
|
||||
const coordinates = view.posAtCoords({
|
||||
left: event.clientX,
|
||||
top: event.clientY,
|
||||
});
|
||||
|
||||
const placeholder = URL.createObjectURL(image);
|
||||
const node = schema.nodes.image.create({
|
||||
src: placeholder,
|
||||
isUploading: true,
|
||||
});
|
||||
const transaction = view.state.tr.insert(
|
||||
coordinates?.pos || 0,
|
||||
node
|
||||
);
|
||||
view.dispatch(transaction);
|
||||
|
||||
this.options
|
||||
.uploadImage?.(image)
|
||||
.then((url) => {
|
||||
const updateTransaction = view.state.tr.setNodeMarkup(
|
||||
coordinates?.pos || 0,
|
||||
null,
|
||||
{
|
||||
src: url,
|
||||
isUploading: false,
|
||||
}
|
||||
);
|
||||
view.dispatch(updateTransaction);
|
||||
})
|
||||
.catch((error) => {
|
||||
// Remove the placeholder image node if there's an error
|
||||
const removeTransaction = view.state.tr.delete(
|
||||
coordinates?.pos || 0,
|
||||
(coordinates?.pos || 0) + 1
|
||||
);
|
||||
view.dispatch(removeTransaction);
|
||||
toast.error("Error uploading image:", error.message);
|
||||
console.error("Error uploading image:", error);
|
||||
});
|
||||
|
||||
return true;
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
},
|
||||
});
|
||||
|
@@ -27,6 +27,7 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import tippy, { GetReferenceClientRect } from "tippy.js";
|
||||
import { UploadFn } from "./ImageExtension";
|
||||
|
||||
export interface CommandProps {
|
||||
editor: Editor;
|
||||
@@ -65,6 +66,7 @@ export const SlashCommand = Extension.create({
|
||||
props.command({ editor, range });
|
||||
},
|
||||
},
|
||||
uploadImage: undefined as UploadFn | undefined,
|
||||
};
|
||||
},
|
||||
addProseMirrorPlugins() {
|
||||
@@ -77,7 +79,7 @@ export const SlashCommand = Extension.create({
|
||||
},
|
||||
});
|
||||
|
||||
const DEFAULT_SLASH_COMMANDS: SlashCommandItem[] = [
|
||||
const DEFAULT_SLASH_COMMANDS = (uploadImage?: UploadFn): SlashCommandItem[] => [
|
||||
{
|
||||
title: "Text",
|
||||
description: "Just start typing with plain text.",
|
||||
@@ -158,14 +160,46 @@ const DEFAULT_SLASH_COMMANDS: SlashCommandItem[] = [
|
||||
searchTerms: ["image"],
|
||||
icon: <ImageIcon className="h-4 w-4" />,
|
||||
command: ({ editor, range }: CommandProps) => {
|
||||
const imageUrl = prompt("Image URL: ") || "";
|
||||
if (uploadImage) {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "image/*";
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (file && uploadImage) {
|
||||
editor.chain().focus().deleteRange(range).run();
|
||||
const placeholder = URL.createObjectURL(file);
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.setImage({ src: placeholder })
|
||||
.updateAttributes("image", { isUploading: true })
|
||||
.run();
|
||||
try {
|
||||
console.log("before upload");
|
||||
const url = await uploadImage(file);
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.updateAttributes("image", { src: url, isUploading: false })
|
||||
.run();
|
||||
} catch (e) {
|
||||
editor.chain().focus().deleteNode("image").run();
|
||||
console.error("Failed to upload image:", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
} else {
|
||||
const imageUrl = prompt("Image URL: ") || "";
|
||||
|
||||
if (!imageUrl) {
|
||||
return;
|
||||
if (!imageUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
editor.chain().focus().deleteRange(range).run();
|
||||
editor.chain().focus().setImage({ src: imageUrl }).run();
|
||||
}
|
||||
|
||||
editor.chain().focus().deleteRange(range).run();
|
||||
editor.chain().focus().setImage({ src: imageUrl }).run();
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -186,16 +220,6 @@ const DEFAULT_SLASH_COMMANDS: SlashCommandItem[] = [
|
||||
editor.chain().focus().deleteRange(range).toggleBlockquote().run();
|
||||
},
|
||||
},
|
||||
// {
|
||||
// title: "Footer",
|
||||
// description: "Add a footer text to email.",
|
||||
// searchTerms: ["footer", "text"],
|
||||
// icon: <FootprintsIcon className="h-4 w-4" />,
|
||||
// command: ({ editor, range }: CommandProps) => {
|
||||
// editor.chain().focus().deleteRange(range).setFooter().run();
|
||||
// },
|
||||
// },
|
||||
|
||||
{
|
||||
title: "Button",
|
||||
description: "Add code.",
|
||||
@@ -372,22 +396,25 @@ const CommandList = ({
|
||||
};
|
||||
|
||||
export function getSlashCommandSuggestions(
|
||||
commands: SlashCommandItem[] = []
|
||||
commands: SlashCommandItem[] = [],
|
||||
uploadImage?: UploadFn
|
||||
): Omit<SuggestionOptions, "editor"> {
|
||||
return {
|
||||
items: ({ query }) => {
|
||||
return [...DEFAULT_SLASH_COMMANDS, ...commands].filter((item) => {
|
||||
if (typeof query === "string" && query.length > 0) {
|
||||
const search = query.toLowerCase();
|
||||
return (
|
||||
item.title.toLowerCase().includes(search) ||
|
||||
item.description.toLowerCase().includes(search) ||
|
||||
(item.searchTerms &&
|
||||
item.searchTerms.some((term: string) => term.includes(search)))
|
||||
);
|
||||
return [...DEFAULT_SLASH_COMMANDS(uploadImage), ...commands].filter(
|
||||
(item) => {
|
||||
if (typeof query === "string" && query.length > 0) {
|
||||
const search = query.toLowerCase();
|
||||
return (
|
||||
item.title.toLowerCase().includes(search) ||
|
||||
item.description.toLowerCase().includes(search) ||
|
||||
(item.searchTerms &&
|
||||
item.searchTerms.some((term: string) => term.includes(search)))
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
);
|
||||
},
|
||||
render: () => {
|
||||
let component: ReactRenderer<any>;
|
||||
|
@@ -16,9 +16,15 @@ import { SlashCommand, getSlashCommandSuggestions } from "./SlashCommand";
|
||||
import { VariableExtension } from "./VariableExtension";
|
||||
import { getVariableSuggestions } from "../nodes/variable";
|
||||
import { UnsubscribeFooterExtension } from "./UnsubsubscribeExtension";
|
||||
import { ResizableImageExtension } from "./ImageExtension";
|
||||
import { ResizableImageExtension, UploadFn } from "./ImageExtension";
|
||||
|
||||
export function extensions({ variables }: { variables?: Array<string> }) {
|
||||
export function extensions({
|
||||
variables,
|
||||
uploadImage,
|
||||
}: {
|
||||
variables?: Array<string>;
|
||||
uploadImage?: UploadFn;
|
||||
}) {
|
||||
const extensions = [
|
||||
StarterKit.configure({
|
||||
heading: {
|
||||
@@ -64,7 +70,8 @@ export function extensions({ variables }: { variables?: Array<string> }) {
|
||||
TaskItem,
|
||||
TaskList,
|
||||
SlashCommand.configure({
|
||||
suggestion: getSlashCommandSuggestions([]),
|
||||
suggestion: getSlashCommandSuggestions([], uploadImage),
|
||||
uploadImage,
|
||||
}),
|
||||
Placeholder.configure({
|
||||
placeholder: "write something on '/' for commands",
|
||||
@@ -75,7 +82,7 @@ export function extensions({ variables }: { variables?: Array<string> }) {
|
||||
suggestion: getVariableSuggestions(variables),
|
||||
}),
|
||||
UnsubscribeFooterExtension,
|
||||
ResizableImageExtension,
|
||||
ResizableImageExtension.configure({ uploadImage }),
|
||||
];
|
||||
|
||||
return extensions;
|
||||
|
Reference in New Issue
Block a user