Merge branch 'feat/asset-placeholders' into tiptap3-migration

This commit is contained in:
Philipinho
2026-01-20 15:21:24 +00:00
24 changed files with 698 additions and 431 deletions
@@ -328,6 +328,8 @@
"Upload any image from your device.": "Upload any image from your device.", "Upload any image from your device.": "Upload any image from your device.",
"Upload any video from your device.": "Upload any video from your device.", "Upload any video from your device.": "Upload any video from your device.",
"Upload any file from your device.": "Upload any file from your device.", "Upload any file from your device.": "Upload any file from your device.",
"Uploading {{name}}": "Uploading {{name}}",
"Uploading file": "Uploading file",
"Table": "Table", "Table": "Table",
"Insert a table.": "Insert a table.", "Insert a table.": "Insert a table.",
"Insert collapsible block.": "Insert collapsible block.", "Insert collapsible block.": "Insert collapsible block.",
@@ -1,11 +1,13 @@
import { NodeViewProps, NodeViewWrapper } from "@tiptap/react"; import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
import { Group, Text, Paper, ActionIcon } from "@mantine/core"; import { Group, Text, Paper, ActionIcon, Loader } from "@mantine/core";
import { getFileUrl } from "@/lib/config.ts"; import { getFileUrl } from "@/lib/config.ts";
import { IconDownload, IconPaperclip } from "@tabler/icons-react"; import { IconDownload, IconPaperclip } from "@tabler/icons-react";
import { useHover } from "@mantine/hooks"; import { useHover } from "@mantine/hooks";
import { formatBytes } from "@/lib"; import { formatBytes } from "@/lib";
import { useTranslation } from "react-i18next";
export default function AttachmentView(props: NodeViewProps) { export default function AttachmentView(props: NodeViewProps) {
const { t } = useTranslation();
const { node, selected } = props; const { node, selected } = props;
const { url, name, size } = node.attrs; const { url, name, size } = node.attrs;
const { hovered, ref } = useHover(); const { hovered, ref } = useHover();
@@ -20,26 +22,28 @@ export default function AttachmentView(props: NodeViewProps) {
wrap="nowrap" wrap="nowrap"
h={25} h={25}
> >
<Group justify="space-between" wrap="nowrap"> <Group wrap="nowrap" gap="sm" style={{ minWidth: 0, flex: 1 }}>
<IconPaperclip size={20} /> {url ? (
<IconPaperclip size={20} style={{ flexShrink: 0 }} />
) : (
<Loader size={20} style={{ flexShrink: 0 }} />
)}
<Text component="span" size="md" truncate="end"> <Text component="span" size="md" truncate="end" style={{ minWidth: 0 }}>
{name} {url ? name : t("Uploading {{name}}", { name })}
</Text> </Text>
<Text component="span" size="sm" c="dimmed" inline> <Text component="span" size="sm" c="dimmed" style={{ flexShrink: 0 }}>
{formatBytes(size)} {formatBytes(size)}
</Text> </Text>
</Group> </Group>
{selected || hovered ? ( {url && (selected || hovered) && (
<a href={getFileUrl(url)} target="_blank"> <a href={getFileUrl(url)} target="_blank">
<ActionIcon variant="default" aria-label="download file"> <ActionIcon variant="default" aria-label="download file">
<IconDownload size={18} /> <IconDownload size={18} />
</ActionIcon> </ActionIcon>
</a> </a>
) : (
""
)} )}
</Group> </Group>
</Paper> </Paper>
@@ -1,13 +1,12 @@
import type { EditorView } from "@tiptap/pm/view";
import { uploadImageAction } from "@/features/editor/components/image/upload-image-action.tsx"; import { uploadImageAction } from "@/features/editor/components/image/upload-image-action.tsx";
import { uploadVideoAction } from "@/features/editor/components/video/upload-video-action.tsx"; import { uploadVideoAction } from "@/features/editor/components/video/upload-video-action.tsx";
import { uploadAttachmentAction } from "../attachment/upload-attachment-action"; import { uploadAttachmentAction } from "../attachment/upload-attachment-action";
import { createMentionAction } from "@/features/editor/components/link/internal-link-paste.ts"; import { createMentionAction } from "@/features/editor/components/link/internal-link-paste.ts";
import { Slice } from "@tiptap/pm/model";
import { INTERNAL_LINK_REGEX } from "@/lib/constants.ts"; import { INTERNAL_LINK_REGEX } from "@/lib/constants.ts";
import { Editor } from "@tiptap/core";
export const handlePaste = ( export const handlePaste = (
view: EditorView, editor: Editor,
event: ClipboardEvent, event: ClipboardEvent,
pageId: string, pageId: string,
creatorId?: string, creatorId?: string,
@@ -18,7 +17,7 @@ export const handlePaste = (
// we have to do this validation here to allow the default link extension to takeover if needs be // we have to do this validation here to allow the default link extension to takeover if needs be
event.preventDefault(); event.preventDefault();
const url = clipboardData.trim(); const url = clipboardData.trim();
const { from: pos, empty } = view.state.selection; const { from: pos, empty } = editor.state.selection;
const match = INTERNAL_LINK_REGEX.exec(url); const match = INTERNAL_LINK_REGEX.exec(url);
const currentPageMatch = INTERNAL_LINK_REGEX.exec(window.location.href); const currentPageMatch = INTERNAL_LINK_REGEX.exec(window.location.href);
@@ -34,19 +33,27 @@ export const handlePaste = (
return false; return false;
} }
const anchorId = match[6] ? match[6].split('#')[0] : undefined; const anchorId = match[6] ? match[6].split("#")[0] : undefined;
const urlWithoutAnchor = anchorId ? url.substring(0, url.indexOf("#")) : url; const urlWithoutAnchor = anchorId
createMentionAction(urlWithoutAnchor, view, pos, creatorId, anchorId); ? url.substring(0, url.indexOf("#"))
: url;
createMentionAction(
urlWithoutAnchor,
editor.view,
pos,
creatorId,
anchorId,
);
return true; return true;
} }
if (event.clipboardData?.files.length) { if (event.clipboardData?.files.length) {
event.preventDefault(); event.preventDefault();
for (const file of event.clipboardData.files) { for (const file of event.clipboardData.files) {
const pos = view.state.selection.from; const pos = editor.state.selection.from;
uploadImageAction(file, view, pos, pageId); uploadImageAction(file, editor, pos, pageId);
uploadVideoAction(file, view, pos, pageId); uploadVideoAction(file, editor, pos, pageId);
uploadAttachmentAction(file, view, pos, pageId); uploadAttachmentAction(file, editor, pos, pageId);
} }
return true; return true;
} }
@@ -54,7 +61,7 @@ export const handlePaste = (
}; };
export const handleFileDrop = ( export const handleFileDrop = (
view: EditorView, editor: Editor,
event: DragEvent, event: DragEvent,
moved: boolean, moved: boolean,
pageId: string, pageId: string,
@@ -63,14 +70,14 @@ export const handleFileDrop = (
event.preventDefault(); event.preventDefault();
for (const file of event.dataTransfer.files) { for (const file of event.dataTransfer.files) {
const coordinates = view.posAtCoords({ const coordinates = editor.view.posAtCoords({
left: event.clientX, left: event.clientX,
top: event.clientY, top: event.clientY,
}); });
uploadImageAction(file, view, coordinates?.pos ?? 0 - 1, pageId); uploadImageAction(file, editor, coordinates?.pos ?? 0 - 1, pageId);
uploadVideoAction(file, view, coordinates?.pos ?? 0 - 1, pageId); uploadVideoAction(file, editor, coordinates?.pos ?? 0 - 1, pageId);
uploadAttachmentAction(file, view, coordinates?.pos ?? 0 - 1, pageId); uploadAttachmentAction(file, editor, coordinates?.pos ?? 0 - 1, pageId);
} }
return true; return true;
} }
@@ -43,7 +43,7 @@ export function ImageMenu({ editor }: EditorMenuProps) {
return false; return false;
} }
return editor.isActive("image"); return editor.isActive("image") && editor.getAttributes("image").src;
}, },
[editor], [editor],
); );
@@ -0,0 +1,27 @@
.imageWrapper {
display: flex;
justify-content: center;
align-items: center;
border-radius: 8px;
overflow: hidden;
animation: pulse 1.2s ease-in-out infinite;
@mixin light {
background: linear-gradient(-90deg, var(--mantine-color-gray-3) 0%, var(--mantine-color-gray-1) 50%, var(--mantine-color-gray-3) 100%);
background-size: 400% 400%;
}
@mixin dark {
background: linear-gradient(-90deg, var(--mantine-color-dark-6) 0%, var(--mantine-color-dark-5) 50%, var(--mantine-color-dark-6) 100%);
background-size: 400% 400%;
}
@keyframes pulse {
0% {
background-position: 0% 0%;
}
100% {
background-position: -135% 0%;
}
}
}
@@ -1,30 +1,70 @@
import { NodeViewProps, NodeViewWrapper } from "@tiptap/react"; import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
import { Group, Image, Loader, Text } from "@mantine/core";
import { useMemo } from "react"; import { useMemo } from "react";
import { Image } from "@mantine/core";
import { getFileUrl } from "@/lib/config.ts"; import { getFileUrl } from "@/lib/config.ts";
import clsx from "clsx"; import clsx from "clsx";
import classes from "./image-view.module.css";
import { useTranslation } from "react-i18next";
export default function ImageView(props: NodeViewProps) { export default function ImageView(props: NodeViewProps) {
const { node, selected } = props; const { t } = useTranslation();
const { src, width, align, title } = node.attrs; const { editor, node, selected } = props;
const { src, width, align, title, aspectRatio, placeholder } = node.attrs;
const alignClass = useMemo(() => { const alignClass = useMemo(() => {
if (align === "left") return "alignLeft"; if (align === "left") return "alignLeft";
if (align === "right") return "alignRight"; if (align === "right") return "alignRight";
if (align === "center") return "alignCenter"; if (align === "center") return "alignCenter";
return "alignCenter"; return "alignCenter";
}, [align]); }, [align]);
const previewSrc = useMemo(() => {
editor.storage.shared.imagePreviews =
editor.storage.shared.imagePreviews || {};
if (placeholder?.id) {
return editor.storage.shared.imagePreviews[placeholder.id];
}
return null;
}, [placeholder, editor]);
return ( return (
<NodeViewWrapper data-drag-handle> <NodeViewWrapper data-drag-handle>
<Image <div
radius="md" className={clsx(
fit="contain" selected && "ProseMirror-selectednode",
w={width} classes.imageWrapper,
src={getFileUrl(src)} alignClass,
alt={title} )}
className={clsx(selected ? "ProseMirror-selectednode" : "", alignClass)} style={{
/> aspectRatio: aspectRatio ? aspectRatio : src ? undefined : "16 / 9",
width,
}}
>
{src && (
<Image radius="md" fit="contain" src={getFileUrl(src)} alt={title} />
)}
{!src && previewSrc && (
<Group pos="relative" h="100%" w="100%">
<Image
radius="md"
fit="contain"
src={previewSrc}
alt={placeholder?.name}
/>
<Loader size={20} pos="absolute" bottom={6} right={6} />
</Group>
)}
{!src && !previewSrc && (
<Group justify="center" wrap="nowrap" gap="xs" maw="100%" px="md">
<Loader size={20} style={{ flexShrink: 0 }} />
<Text component="span" size="sm" truncate="end">
{placeholder?.name
? t("Uploading {{name}}", { name: placeholder.name })
: t("Uploading file")}
</Text>
</Group>
)}
</div>
</NodeViewWrapper> </NodeViewWrapper>
); );
} }
@@ -174,9 +174,13 @@ const CommandGroups: SlashMenuGroupedItemsType = {
if (input.files?.length) { if (input.files?.length) {
for (const file of input.files) { for (const file of input.files) {
const pos = editor.view.state.selection.from; const pos = editor.view.state.selection.from;
uploadImageAction(file, editor.view, pos, pageId);
uploadImageAction(file, editor, pos, pageId);
} }
} }
// Reset the input value to allow uploading the same file again if needed
input.value = "";
}; };
input.click(); input.click();
}, },
@@ -197,12 +201,18 @@ const CommandGroups: SlashMenuGroupedItemsType = {
const input = document.createElement("input"); const input = document.createElement("input");
input.type = "file"; input.type = "file";
input.accept = "video/*"; input.accept = "video/*";
input.multiple = true;
input.onchange = async () => { input.onchange = async () => {
if (input.files?.length) { if (input.files?.length) {
const file = input.files[0]; for (const file of input.files) {
const pos = editor.view.state.selection.from; const pos = editor.view.state.selection.from;
uploadVideoAction(file, editor.view, pos, pageId);
uploadVideoAction(file, editor, pos, pageId);
}
} }
// Reset the input value to allow uploading the same file again if needed
input.value = "";
}; };
input.click(); input.click();
}, },
@@ -223,12 +233,18 @@ const CommandGroups: SlashMenuGroupedItemsType = {
const input = document.createElement("input"); const input = document.createElement("input");
input.type = "file"; input.type = "file";
input.accept = ""; input.accept = "";
input.multiple = true;
input.onchange = async () => { input.onchange = async () => {
if (input.files?.length) { if (input.files?.length) {
const file = input.files[0]; for (const file of input.files) {
const pos = editor.view.state.selection.from; const pos = editor.view.state.selection.from;
uploadAttachmentAction(file, editor.view, pos, pageId, true);
uploadAttachmentAction(file, editor, pos, pageId, true);
}
} }
// Reset the input value to allow uploading the same file again if needed
input.value = "";
}; };
input.click(); input.click();
}, },
@@ -20,7 +20,7 @@ export function VideoMenu({ editor }: EditorMenuProps) {
const editorState = useEditorState({ const editorState = useEditorState({
editor, editor,
selector: ctx => { selector: (ctx) => {
if (!ctx.editor) { if (!ctx.editor) {
return null; return null;
} }
@@ -43,7 +43,7 @@ export function VideoMenu({ editor }: EditorMenuProps) {
return false; return false;
} }
return editor.isActive("video"); return editor.isActive("video") && editor.getAttributes("video").src;
}, },
[editor], [editor],
); );
@@ -0,0 +1,33 @@
.videoWrapper {
display: flex;
justify-content: center;
align-items: center;
border-radius: 8px;
overflow: hidden;
animation: pulse 1.2s ease-in-out infinite;
@mixin light {
background: linear-gradient(-90deg, var(--mantine-color-gray-3) 0%, var(--mantine-color-gray-1) 50%, var(--mantine-color-gray-3) 100%);
background-size: 400% 400%;
}
@mixin dark {
background: linear-gradient(-90deg, var(--mantine-color-dark-6) 0%, var(--mantine-color-dark-5) 50%, var(--mantine-color-dark-6) 100%);
background-size: 400% 400%;
}
@keyframes pulse {
0% {
background-position: 0% 0%;
}
100% {
background-position: -135% 0%;
}
}
}
.video {
display: block;
width: 100%;
height: 100%;
border-radius: 8px;
}
@@ -1,29 +1,75 @@
import { NodeViewProps, NodeViewWrapper } from "@tiptap/react"; import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
import { Group, Loader, Text } from "@mantine/core";
import { useMemo } from "react"; import { useMemo } from "react";
import { getFileUrl } from "@/lib/config.ts"; import { getFileUrl } from "@/lib/config.ts";
import clsx from "clsx"; import clsx from "clsx";
import classes from "./video-view.module.css";
import { useTranslation } from "react-i18next";
export default function VideoView(props: NodeViewProps) { export default function VideoView(props: NodeViewProps) {
const { node, selected } = props; const { t } = useTranslation();
const { src, width, align } = node.attrs; const { editor, node, selected } = props;
const { src, width, align, aspectRatio, placeholder } = node.attrs;
const alignClass = useMemo(() => { const alignClass = useMemo(() => {
if (align === "left") return "alignLeft"; if (align === "left") return "alignLeft";
if (align === "right") return "alignRight"; if (align === "right") return "alignRight";
if (align === "center") return "alignCenter"; if (align === "center") return "alignCenter";
return "alignCenter"; return "alignCenter";
}, [align]); }, [align]);
const previewSrc = useMemo(() => {
editor.storage.shared.videoPreviews =
editor.storage.shared.videoPreviews || {};
if (placeholder?.id) {
return editor.storage.shared.videoPreviews[placeholder.id];
}
return null;
}, [placeholder, editor]);
return ( return (
<NodeViewWrapper data-drag-handle> <NodeViewWrapper data-drag-handle>
<video <div
preload="metadata" className={clsx(
width={width} selected && "ProseMirror-selectednode",
controls classes.videoWrapper,
src={getFileUrl(src)} alignClass,
className={clsx(selected ? "ProseMirror-selectednode" : "", alignClass)} )}
style={{ display: "block" }} style={{
/> aspectRatio: aspectRatio ? aspectRatio : src ? undefined : "16 / 9",
width,
}}
>
{src && (
<video
className={classes.video}
preload="metadata"
controls
src={getFileUrl(src)}
/>
)}
{!src && previewSrc && (
<Group pos="relative" h="100%" w="100%">
<video
className={classes.video}
preload="metadata"
controls
src={previewSrc}
/>
<Loader size={20} pos="absolute" top={6} right={6} />
</Group>
)}
{!src && !previewSrc && (
<Group justify="center" wrap="nowrap" gap="xs" maw="100%" px="md">
<Loader size={20} style={{ flexShrink: 0 }} />
<Text component="span" size="sm" truncate="end">
{placeholder?.name
? t("Uploading {{name}}", { name: placeholder.name })
: t("Uploading file")}
</Text>
</Group>
)}
</div>
</NodeViewWrapper> </NodeViewWrapper>
); );
} }
@@ -42,6 +42,7 @@ import {
Heading, Heading,
Highlight, Highlight,
UniqueID, UniqueID,
SharedStorage,
} from "@docmost/editor-ext"; } from "@docmost/editor-ext";
import { import {
randomElement, randomElement,
@@ -107,6 +108,7 @@ export const mainExtensions = [
}, },
}, },
}), }),
SharedStorage,
Heading, Heading,
UniqueID.configure({ UniqueID.configure({
types: ["heading", "paragraph"], types: ["heading", "paragraph"],
+23 -11
View File
@@ -16,6 +16,7 @@ import {
onSyncedParameters, onSyncedParameters,
} from "@hocuspocus/provider"; } from "@hocuspocus/provider";
import { import {
Editor,
EditorContent, EditorContent,
EditorProvider, EditorProvider,
useEditor, useEditor,
@@ -79,7 +80,7 @@ export default function PageEditor({
}: PageEditorProps) { }: PageEditorProps) {
const collaborationURL = useCollaborationUrl(); const collaborationURL = useCollaborationUrl();
const isComponentMounted = useRef(false); const isComponentMounted = useRef(false);
const editorCreated = useRef(false); const editorRef = useRef<Editor | null>(null);
useEffect(() => { useEffect(() => {
isComponentMounted.current = true; isComponentMounted.current = true;
@@ -93,7 +94,7 @@ export default function PageEditor({
const [isLocalSynced, setIsLocalSynced] = useState(false); const [isLocalSynced, setIsLocalSynced] = useState(false);
const [isRemoteSynced, setIsRemoteSynced] = useState(false); const [isRemoteSynced, setIsRemoteSynced] = useState(false);
const [yjsConnectionStatus, setYjsConnectionStatus] = useAtom( const [yjsConnectionStatus, setYjsConnectionStatus] = useAtom(
yjsConnectionStatusAtom yjsConnectionStatusAtom,
); );
const menuContainerRef = useRef(null); const menuContainerRef = useRef(null);
const { data: collabQuery, refetch: refetchCollabToken } = useCollabToken(); const { data: collabQuery, refetch: refetchCollabToken } = useCollabToken();
@@ -104,8 +105,8 @@ export default function PageEditor({
const userPageEditMode = const userPageEditMode =
currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit; currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
const canScroll = useCallback( const canScroll = useCallback(
() => isComponentMounted.current && editorCreated.current, () => Boolean(isComponentMounted.current && editorRef.current),
[isComponentMounted, editorCreated] [isComponentMounted],
); );
const { handleScrollTo } = useEditorScroll({ canScroll }); const { handleScrollTo } = useEditorScroll({ canScroll });
// Providers only created once per pageId // Providers only created once per pageId
@@ -253,10 +254,21 @@ export default function PageEditor({
} }
}, },
}, },
handlePaste: (view, event, slice) => handlePaste: (_view, event) => {
handlePaste(view, event, pageId, currentUser?.user.id), if (!editorRef.current) return false;
handleDrop: (view, event, _slice, moved) =>
handleFileDrop(view, event, moved, pageId), return handlePaste(
editorRef.current,
event,
pageId,
currentUser?.user.id,
);
},
handleDrop: (_view, event, _slice, moved) => {
if (!editorRef.current) return false;
return handleFileDrop(editorRef.current, event, moved, pageId);
},
}, },
onCreate({ editor }) { onCreate({ editor }) {
if (editor) { if (editor) {
@@ -265,7 +277,7 @@ export default function PageEditor({
// @ts-ignore // @ts-ignore
editor.storage.pageId = pageId; editor.storage.pageId = pageId;
handleScrollTo(editor); handleScrollTo(editor);
editorCreated.current = true; editorRef.current = editor;
} }
}, },
onUpdate({ editor }) { onUpdate({ editor }) {
@@ -275,7 +287,7 @@ export default function PageEditor({
debouncedUpdateContent(editorJson); debouncedUpdateContent(editorJson);
}, },
}, },
[pageId, editable, extensions] [pageId, editable, extensions],
); );
const editorIsEditable = useEditorState({ const editorIsEditable = useEditorState({
@@ -320,7 +332,7 @@ export default function PageEditor({
return () => { return () => {
document.removeEventListener( document.removeEventListener(
"ACTIVE_COMMENT_EVENT", "ACTIVE_COMMENT_EVENT",
handleActiveCommentEvent handleActiveCommentEvent,
); );
}; };
}, []); }, []);
+1
View File
@@ -64,6 +64,7 @@
"dompurify": "^3.2.6", "dompurify": "^3.2.6",
"fractional-indexing-jittered": "^1.0.0", "fractional-indexing-jittered": "^1.0.0",
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"image-dimensions": "^2.5.0",
"ioredis": "^5.4.1", "ioredis": "^5.4.1",
"jszip": "^3.10.1", "jszip": "^3.10.1",
"linkifyjs": "^4.3.2", "linkifyjs": "^4.3.2",
+1
View File
@@ -23,3 +23,4 @@ export * from "./lib/subpages";
export * from "./lib/highlight"; export * from "./lib/highlight";
export * from "./lib/heading/heading"; export * from "./lib/heading/heading";
export * from "./lib/unique-id"; export * from "./lib/unique-id";
export * from "./lib/shared-storage";
@@ -1,126 +1,125 @@
import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state"; import { Node } from "@tiptap/pm/model";
import { Decoration, DecorationSet } from "@tiptap/pm/view"; import { MediaUploadOptions, UploadFn } from "../media-utils";
import {
insertTrailingNode,
MediaUploadOptions,
UploadFn,
} from "../media-utils";
import { IAttachment } from "../types"; import { IAttachment } from "../types";
import { generateNodeId } from "../utils";
import { Command } from "@tiptap/core";
const uploadKey = new PluginKey("attachment-upload"); const findAttachmentNodeByPlaceholderId = (
doc: Node,
placeholderId: string,
): { node: Node; pos: number } | null => {
let result: { node: Node; pos: number } | null = null;
export const AttachmentUploadPlugin = ({ doc.descendants((node, pos) => {
placeholderClass, if (result) return false;
}: { if (
placeholderClass: string; node.type.name === "attachment" &&
}) => node.attrs.placeholder?.id === placeholderId
new Plugin({ ) {
key: uploadKey, result = { node, pos };
state: { return false;
init() { }
return DecorationSet.empty; return true;
},
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 realPos = pos + 1;
const deco = Decoration.widget(realPos, 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: {}) { return result;
const decos = uploadKey.getState(state) as DecorationSet; };
const found = decos.find(undefined, undefined, (spec) => spec.id == id); const handleAttachmentUpload =
return found.length ? found[0]?.from : null;
}
export const handleAttachmentUpload =
({ validateFn, onUpload }: MediaUploadOptions): UploadFn => ({ validateFn, onUpload }: MediaUploadOptions): UploadFn =>
async (file, view, pos, pageId, allowMedia) => { async (file, editor, pos, pageId, allowMedia) => {
const validated = validateFn?.(file, allowMedia); const validated = validateFn?.(file, allowMedia);
// @ts-ignore // @ts-ignore
if (!validated) return; if (!validated) return;
// A fresh object to act as the ID for this upload
const id = {};
// Replace the selection with a placeholder const placeholderId = generateNodeId();
const tr = view.state.tr;
if (!tr.selection.empty) tr.deleteSelection();
tr.setMeta(uploadKey, { let placeholderInserted = false;
add: {
id,
pos,
fileName: file.name,
},
});
insertTrailingNode(tr, pos, view); const insertPlaceholder = (): Command => {
view.dispatch(tr); return ({ tr, state }) => {
const initialPlaceholderNode = state.schema.nodes.attachment?.create({
placeholder: {
id: placeholderId,
},
name: file.name,
size: file.size,
});
await onUpload(file, pageId).then( if (!initialPlaceholderNode) return false;
(attachment: IAttachment) => {
const { schema } = view.state;
const pos = findPlaceholder(view.state, id); const { parent } = tr.doc.resolve(pos);
const isEmptyTextBlock = parent.isTextblock && !parent.childCount;
if (pos == null) return; if (isEmptyTextBlock) {
tr.replaceRangeWith(pos - 1, pos + 1, initialPlaceholderNode);
} else {
tr.insert(pos, initialPlaceholderNode);
}
if (!attachment) return; return true;
};
};
const replacePlaceholderWithAttachment = (
attachment: IAttachment,
): Command => {
return ({ tr }) => {
const { pos: currentPos = null } =
findAttachmentNodeByPlaceholderId(tr.doc, placeholderId) || {};
const node = schema.nodes.attachment?.create({ // If the placeholder is not found or attachment is missing, abort the process
if (currentPos === null || !attachment) return false;
// Update the placeholder node with the actual attachment data
tr.setNodeMarkup(currentPos, undefined, {
url: `/api/files/${attachment.id}/${attachment.fileName}`, url: `/api/files/${attachment.id}/${attachment.fileName}`,
name: attachment.fileName, name: attachment.fileName,
mime: attachment.mimeType, mime: attachment.mimeType,
size: attachment.fileSize, size: attachment.fileSize,
attachmentId: attachment.id, attachmentId: attachment.id,
}); });
if (!node) return;
const transaction = view.state.tr return true;
.replaceWith(pos, pos, node) };
.setMeta(uploadKey, { remove: { id } }); };
view.dispatch(transaction); const removePlaceholder = (): Command => {
}, return ({ tr }) => {
() => { const { pos: currentPos = null } =
// Deletes the placeholder on error findAttachmentNodeByPlaceholderId(tr.doc, placeholderId) || {};
const transaction = view.state.tr
.delete(pos, pos) if (currentPos === null) return false;
.setMeta(uploadKey, { remove: { id } });
view.dispatch(transaction); tr.delete(currentPos, currentPos + 2);
},
); return true;
};
};
// Only show the placeholder if the upload takes more than 250ms
const insertPlaceholderTimeout = setTimeout(() => {
editor.commands.command(insertPlaceholder());
placeholderInserted = true;
}, 250);
try {
const attachment: IAttachment = await onUpload(file, pageId);
clearTimeout(insertPlaceholderTimeout);
if (placeholderInserted) {
setTimeout(() => {
editor.commands.command(replacePlaceholderWithAttachment(attachment));
}, 100);
} else {
editor
.chain()
.command(insertPlaceholder())
.command(replacePlaceholderWithAttachment(attachment))
.run();
}
} catch (error) {
clearTimeout(insertPlaceholderTimeout);
editor.commands.command(removePlaceholder());
}
}; };
export { handleAttachmentUpload };
@@ -1,6 +1,5 @@
import { Node, mergeAttributes } from "@tiptap/core"; import { Node, mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react"; import { ReactNodeViewRenderer } from "@tiptap/react";
import { AttachmentUploadPlugin } from "./attachment-upload";
export interface AttachmentOptions { export interface AttachmentOptions {
HTMLAttributes: Record<string, any>; HTMLAttributes: Record<string, any>;
@@ -13,6 +12,7 @@ export interface AttachmentAttributes {
mime?: string; // e.g. application/zip mime?: string; // e.g. application/zip
size?: number; size?: number;
attachmentId?: string; attachmentId?: string;
placeholder?: string;
} }
declare module "@tiptap/core" { declare module "@tiptap/core" {
@@ -75,6 +75,10 @@ export const Attachment = Node.create<AttachmentOptions>({
"data-attachment-id": attributes.attachmentId, "data-attachment-id": attributes.attachmentId,
}), }),
}, },
placeholder: {
default: null,
rendered: false,
},
}; };
}, },
@@ -92,7 +96,7 @@ export const Attachment = Node.create<AttachmentOptions>({
mergeAttributes( mergeAttributes(
{ "data-type": this.name }, { "data-type": this.name },
this.options.HTMLAttributes, this.options.HTMLAttributes,
HTMLAttributes HTMLAttributes,
), ),
[ [
"a", "a",
@@ -125,12 +129,4 @@ export const Attachment = Node.create<AttachmentOptions>({
return ReactNodeViewRenderer(this.options.view); return ReactNodeViewRenderer(this.options.view);
}, },
addProseMirrorPlugins() {
return [
AttachmentUploadPlugin({
placeholderClass: "attachment-placeholder",
}),
];
},
}); });
+123 -105
View File
@@ -1,127 +1,145 @@
import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state"; import { imageDimensionsFromStream } from "image-dimensions";
import { Decoration, DecorationSet } from "@tiptap/pm/view"; import { MediaUploadOptions, UploadFn } from "../media-utils";
import { insertTrailingNode, MediaUploadOptions, UploadFn } from "../media-utils";
import { IAttachment } from "../types"; import { IAttachment } from "../types";
import { generateNodeId } from "../utils";
import { Node } from "@tiptap/pm/model";
import { Command } from "@tiptap/core";
const uploadKey = new PluginKey("image-upload"); const findImageNodeByPlaceholderId = (
doc: Node,
placeholderId: string,
): { node: Node; pos: number } | null => {
let result: { node: Node; pos: number } | null = null;
export const ImageUploadPlugin = ({ doc.descendants((node, pos) => {
placeholderClass, if (result) return false;
}: { if (
placeholderClass: string; node.type.name === "image" &&
}) => node.attrs.placeholder?.id === placeholderId
new Plugin({ ) {
key: uploadKey, result = { node, pos };
state: { return false;
init() { }
return DecorationSet.empty; return true;
},
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, src } = action.add;
const placeholder = document.createElement("div");
placeholder.setAttribute("class", "img-placeholder");
const image = document.createElement("img");
image.setAttribute("class", placeholderClass);
image.src = src;
placeholder.appendChild(image);
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: {}) { return result;
const decos = uploadKey.getState(state) as DecorationSet; };
const found = decos.find(undefined, undefined, (spec) => spec.id == id); const handleImageUpload =
return found.length ? found[0]?.from : null;
}
export const handleImageUpload =
({ validateFn, onUpload }: MediaUploadOptions): UploadFn => ({ validateFn, onUpload }: MediaUploadOptions): UploadFn =>
async (file, view, pos, pageId) => { async (file, editor, pos, pageId) => {
// check if the file is an image // check if the file is an image
const validated = validateFn?.(file); const validated = validateFn?.(file);
// @ts-ignore // @ts-ignore
if (!validated) return; if (!validated) return;
// A fresh object to act as the ID for this upload
const id = {};
const reader = new FileReader(); const objectUrl = URL.createObjectURL(file);
reader.readAsDataURL(file); const imageDimensions = await imageDimensionsFromStream(file.stream());
reader.onload = () => { const placeholderId = generateNodeId();
const tr = view.state.tr; const aspectRatio = imageDimensions
// Replace the selection with a placeholder ? imageDimensions.width / imageDimensions.height
if (!tr.selection.empty) tr.deleteSelection(); : undefined;
tr.setMeta(uploadKey, { let placeholderInserted = false;
add: {
id,
pos,
src: reader.result,
},
});
insertTrailingNode(tr, pos, view); editor.storage.shared.imagePreviews =
view.dispatch(tr); editor.storage.shared.imagePreviews || {};
editor.storage.shared.imagePreviews[placeholderId] = objectUrl;
const insertPlaceholder = (): Command => {
return ({ tr, state }) => {
const initialPlaceholderNode = state.schema.nodes.image?.create({
placeholder: {
id: placeholderId,
name: file.name,
},
aspectRatio,
});
if (!initialPlaceholderNode) return false;
const { parent } = tr.doc.resolve(pos);
const isEmptyTextBlock = parent.isTextblock && !parent.childCount;
if (isEmptyTextBlock) {
// Replace e.g. empty paragraph with the image
tr.replaceRangeWith(pos - 1, pos + 1, initialPlaceholderNode);
} else {
tr.insert(pos, initialPlaceholderNode);
}
return true;
};
}; };
const replacePlaceholderWithImage = (attachment: IAttachment): Command => {
return ({ tr }) => {
const { pos: currentPos = null } =
findImageNodeByPlaceholderId(tr.doc, placeholderId) || {};
await onUpload(file, pageId).then( // If the placeholder is not found or attachment is missing, abort the process
(attachment: IAttachment) => { if (currentPos === null || !attachment) return false;
const { schema } = view.state;
const pos = findPlaceholder(view.state, id); // Update the placeholder node with the actual image data
tr.setNodeMarkup(currentPos, undefined, {
// If the content around the placeholder has been deleted, drop
// the image
if (pos == null) return;
// Otherwise, insert it at the placeholder's position, and remove
// the placeholder
if (!attachment) return;
const node = schema.nodes.image?.create({
src: `/api/files/${attachment.id}/${attachment.fileName}`, src: `/api/files/${attachment.id}/${attachment.fileName}`,
attachmentId: attachment.id, attachmentId: attachment.id,
title: attachment.fileName,
size: attachment.fileSize, size: attachment.fileSize,
aspectRatio,
}); });
if (!node) return;
const transaction = view.state.tr return true;
.replaceWith(pos, pos, node) };
.setMeta(uploadKey, { remove: { id } }); };
view.dispatch(transaction); const removePlaceholder = (): Command => {
}, return ({ tr }) => {
() => { const { pos: currentPos = null } =
// Deletes the image placeholder on error findImageNodeByPlaceholderId(tr.doc, placeholderId) || {};
const transaction = view.state.tr
.delete(pos, pos) if (currentPos === null) return false;
.setMeta(uploadKey, { remove: { id } });
view.dispatch(transaction); // Remove the placeholder node
}, tr.delete(currentPos, currentPos + 2);
);
return true;
};
};
// Only show the placeholder if the upload takes more than 250ms
const insertPlaceholderTimeout = setTimeout(() => {
editor.commands.command(insertPlaceholder());
placeholderInserted = true;
}, 250);
const disposePreviewFile = () => {
URL.revokeObjectURL(objectUrl);
if (editor.storage.shared.imagePreviews) {
delete editor.storage.shared.imagePreviews[placeholderId];
}
};
try {
const attachment: IAttachment = await onUpload(file, pageId);
clearTimeout(insertPlaceholderTimeout);
if (placeholderInserted) {
setTimeout(() => {
editor.commands.command(replacePlaceholderWithImage(attachment));
disposePreviewFile();
}, 100);
} else {
editor
.chain()
.command(insertPlaceholder())
.command(replacePlaceholderWithImage(attachment))
.run();
disposePreviewFile();
}
} catch (error) {
clearTimeout(insertPlaceholderTimeout);
editor.commands.command(removePlaceholder());
disposePreviewFile();
}
}; };
export { handleImageUpload };
+17 -11
View File
@@ -1,7 +1,6 @@
import Image from "@tiptap/extension-image"; import Image from "@tiptap/extension-image";
import { ImageOptions as DefaultImageOptions } from "@tiptap/extension-image"; import { ImageOptions as DefaultImageOptions } from "@tiptap/extension-image";
import { ReactNodeViewRenderer } from "@tiptap/react"; import { ReactNodeViewRenderer } from "@tiptap/react";
import { ImageUploadPlugin } from "./image-upload";
import { mergeAttributes, Range } from "@tiptap/core"; import { mergeAttributes, Range } from "@tiptap/core";
export interface ImageOptions extends DefaultImageOptions { export interface ImageOptions extends DefaultImageOptions {
@@ -10,11 +9,15 @@ export interface ImageOptions extends DefaultImageOptions {
export interface ImageAttributes { export interface ImageAttributes {
src?: string; src?: string;
alt?: string; alt?: string;
title?: string;
align?: string; align?: string;
attachmentId?: string; attachmentId?: string;
size?: number; size?: number;
width?: number; width?: number;
aspectRatio?: number;
placeholder?: {
id: string;
name: string;
};
} }
declare module "@tiptap/core" { declare module "@tiptap/core" {
@@ -22,7 +25,7 @@ declare module "@tiptap/core" {
imageBlock: { imageBlock: {
setImage: (attributes: ImageAttributes) => ReturnType; setImage: (attributes: ImageAttributes) => ReturnType;
setImageAt: ( setImageAt: (
attributes: ImageAttributes & { pos: number | Range } attributes: ImageAttributes & { pos: number | Range },
) => ReturnType; ) => ReturnType;
setImageAlign: (align: "left" | "center" | "right") => ReturnType; setImageAlign: (align: "left" | "center" | "right") => ReturnType;
setImageWidth: (width: number) => ReturnType; setImageWidth: (width: number) => ReturnType;
@@ -90,6 +93,17 @@ export const TiptapImage = Image.extend<ImageOptions>({
"data-size": attributes.size, "data-size": attributes.size,
}), }),
}, },
aspectRatio: {
default: null,
parseHTML: (element) => element.getAttribute("data-aspect-ratio"),
renderHTML: (attributes: ImageAttributes) => ({
"data-aspect-ratio": attributes.aspectRatio,
}),
},
placeholder: {
default: null,
rendered: false,
},
}; };
}, },
@@ -140,12 +154,4 @@ export const TiptapImage = Image.extend<ImageOptions>({
return ReactNodeViewRenderer(this.options.view); return ReactNodeViewRenderer(this.options.view);
}, },
addProseMirrorPlugins() {
return [
ImageUploadPlugin({
placeholderClass: "image-upload",
}),
];
},
}); });
+2 -16
View File
@@ -1,9 +1,8 @@
import type { EditorView } from "@tiptap/pm/view"; import { Editor } from "@tiptap/core";
import { Transaction } from "@tiptap/pm/state";
export type UploadFn = ( export type UploadFn = (
file: File, file: File,
view: EditorView, editor: Editor,
pos: number, pos: number,
pageId: string, pageId: string,
// only applicable to file attachments // only applicable to file attachments
@@ -14,16 +13,3 @@ export interface MediaUploadOptions {
validateFn?: (file: File, allowMedia?: boolean) => void; validateFn?: (file: File, allowMedia?: boolean) => void;
onUpload: (file: File, pageId: string) => Promise<any>; onUpload: (file: File, pageId: string) => Promise<any>;
} }
export function insertTrailingNode(
tr: Transaction,
pos: number,
view: EditorView,
) {
// create trailing node after decoration
// if decoration is at the last node
const currentDocSize = view.state.doc.content.size;
if (pos + 1 === currentDocSize) {
tr.insert(currentDocSize, view.state.schema.nodes.paragraph.create());
}
}
@@ -0,0 +1 @@
export { SharedStorage } from "./shared-storage";
@@ -0,0 +1,17 @@
import { Extension } from "@tiptap/core";
declare module "@tiptap/core" {
interface Storage {
shared: Record<string, any>;
}
}
const SharedStorage = Extension.create({
name: "shared",
addStorage() {
return {};
},
});
export { SharedStorage };
+144 -107
View File
@@ -1,132 +1,169 @@
import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state"; import { MediaUploadOptions, UploadFn } from "../media-utils";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import {
insertTrailingNode,
MediaUploadOptions,
UploadFn,
} from "../media-utils";
import { IAttachment } from "../types"; import { IAttachment } from "../types";
import { generateNodeId } from "../utils";
import { Node } from "@tiptap/pm/model";
import { Command } from "@tiptap/core";
const uploadKey = new PluginKey("video-upload"); const findVideoNodeByPlaceholderId = (
doc: Node,
placeholderId: string,
): { node: Node; pos: number } | null => {
let result: { node: Node; pos: number } | null = null;
export const VideoUploadPlugin = ({ doc.descendants((node, pos) => {
placeholderClass, if (result) return false;
}: {
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, src } = action.add;
const placeholder = document.createElement("div"); if (
placeholder.setAttribute("class", "video-placeholder"); node.type.name === "video" &&
const video = document.createElement("video"); node.attrs.placeholder?.id === placeholderId
video.setAttribute("class", placeholderClass); ) {
video.src = src; result = { node, pos };
placeholder.appendChild(video); return false;
const deco = Decoration.widget(pos + 1, placeholder, { }
id,
}); return true;
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: {}) { return result;
const decos = uploadKey.getState(state) as DecorationSet; };
const found = decos.find(undefined, undefined, (spec) => spec.id == id); const getVideoDimensions = (
return found.length ? found[0]?.from : null; url: string,
} ): Promise<
{ width: number; height: number; aspectRatio: number } | undefined
> => {
return new Promise<
{ width: number; height: number; aspectRatio: number } | undefined
>((resolve) => {
const video = document.createElement("video");
export const handleVideoUpload = video.preload = "metadata";
video.onloadedmetadata = () => {
const width = video.videoWidth;
const height = video.videoHeight;
const aspectRatio = height > 0 ? width / height : 1;
resolve({ width, height, aspectRatio });
};
video.onerror = () => {
resolve(undefined);
};
video.src = url;
});
};
const handleVideoUpload =
({ validateFn, onUpload }: MediaUploadOptions): UploadFn => ({ validateFn, onUpload }: MediaUploadOptions): UploadFn =>
async (file, view, pos, pageId) => { async (file, editor, pos, pageId) => {
// check if the file is an image // check if the file is valid
const validated = validateFn?.(file); const validated = validateFn?.(file);
// @ts-ignore // @ts-ignore
if (!validated) return; if (!validated) return;
// A fresh object to act as the ID for this upload
const id = {};
// Replace the selection with a placeholder const objectUrl = URL.createObjectURL(file);
const videoDimensions = await getVideoDimensions(objectUrl);
const placeholderId = generateNodeId();
const aspectRatio = videoDimensions.aspectRatio;
const reader = new FileReader(); let placeholderInserted = false;
reader.readAsDataURL(file);
reader.onload = () => {
const tr = view.state.tr;
if (!tr.selection.empty) tr.deleteSelection();
tr.setMeta(uploadKey, { editor.storage.shared.videoPreviews =
add: { editor.storage.shared.videoPreviews || {};
id, editor.storage.shared.videoPreviews[placeholderId] = objectUrl;
pos,
src: reader.result,
},
});
insertTrailingNode(tr, pos, view); const insertPlaceholder = (): Command => {
view.dispatch(tr); return ({ tr, state }) => {
const initialPlaceholderNode = state.schema.nodes.video?.create({
placeholder: {
id: placeholderId,
name: file.name,
},
aspectRatio,
});
if (!initialPlaceholderNode) return false;
const { parent } = tr.doc.resolve(pos);
const isEmptyTextBlock = parent.isTextblock && !parent.childCount;
if (isEmptyTextBlock) {
// Replace e.g. empty paragraph with the video
tr.replaceRangeWith(pos - 1, pos + 1, initialPlaceholderNode);
} else {
tr.insert(pos, initialPlaceholderNode);
}
return true;
};
}; };
const replacePlaceholderWithVideo = (attachment: IAttachment): Command => {
return ({ tr }) => {
const { pos: currentPos = null } =
findVideoNodeByPlaceholderId(tr.doc, placeholderId) || {};
await onUpload(file, pageId).then( // If the placeholder is not found or attachment is missing, abort the process
(attachment: IAttachment) => { if (currentPos === null || !attachment) return;
const { schema } = view.state;
const pos = findPlaceholder(view.state, id); // Update the placeholder node with the actual video data
tr.setNodeMarkup(currentPos, undefined, {
// If the content around the placeholder has been deleted, drop
// the image
if (pos == null) return;
// Otherwise, insert it at the placeholder's position, and remove
// the placeholder
if (!attachment) return;
const node = schema.nodes.video?.create({
src: `/api/files/${attachment.id}/${attachment.fileName}`, src: `/api/files/${attachment.id}/${attachment.fileName}`,
attachmentId: attachment.id, attachmentId: attachment.id,
title: attachment.fileName, title: attachment.fileName,
size: attachment.fileSize, size: attachment.fileSize,
aspectRatio,
}); });
if (!node) return;
const transaction = view.state.tr return true;
.replaceWith(pos, pos, node) };
.setMeta(uploadKey, { remove: { id } }); };
view.dispatch(transaction); const removePlaceholder = (): Command => {
}, return ({ tr }) => {
() => { const { pos: currentPos = null } =
// Deletes the image placeholder on error findVideoNodeByPlaceholderId(tr.doc, placeholderId) || {};
const transaction = view.state.tr
.delete(pos, pos) if (currentPos === null) return false;
.setMeta(uploadKey, { remove: { id } });
view.dispatch(transaction); tr.delete(currentPos, currentPos + 2);
},
); return true;
};
};
// Only show the placeholder if the upload takes more than 250ms
const insertPlaceholderTimeout = setTimeout(() => {
editor.commands.command(insertPlaceholder());
placeholderInserted = true;
}, 250);
const disposePreviewFile = () => {
URL.revokeObjectURL(objectUrl);
if (editor.storage.shared.videoPreviews) {
delete editor.storage.shared.videoPreviews[placeholderId];
}
};
try {
const attachment: IAttachment = await onUpload(file, pageId);
clearTimeout(insertPlaceholderTimeout);
if (placeholderInserted) {
setTimeout(() => {
editor.commands.command(replacePlaceholderWithVideo(attachment));
disposePreviewFile();
}, 100);
} else {
editor
.chain()
.command(insertPlaceholder())
.command(replacePlaceholderWithVideo(attachment))
.run();
disposePreviewFile();
}
} catch (error) {
clearTimeout(insertPlaceholderTimeout);
editor.commands.command(removePlaceholder());
disposePreviewFile();
}
}; };
export { handleVideoUpload };
+18 -12
View File
@@ -1,6 +1,5 @@
import { ReactNodeViewRenderer } from "@tiptap/react"; import { ReactNodeViewRenderer } from "@tiptap/react";
import { VideoUploadPlugin } from "./video-upload"; import { Range, Node } from "@tiptap/core";
import { mergeAttributes, Range, Node, nodeInputRule } from "@tiptap/core";
export interface VideoOptions { export interface VideoOptions {
view: any; view: any;
@@ -8,11 +7,15 @@ export interface VideoOptions {
} }
export interface VideoAttributes { export interface VideoAttributes {
src?: string; src?: string;
title?: string;
align?: string; align?: string;
attachmentId?: string; attachmentId?: string;
size?: number; size?: number;
width?: number; width?: number;
aspectRatio?: number;
placeholder?: {
id: string;
name: string;
};
} }
declare module "@tiptap/core" { declare module "@tiptap/core" {
@@ -20,7 +23,7 @@ declare module "@tiptap/core" {
videoBlock: { videoBlock: {
setVideo: (attributes: VideoAttributes) => ReturnType; setVideo: (attributes: VideoAttributes) => ReturnType;
setVideoAt: ( setVideoAt: (
attributes: VideoAttributes & { pos: number | Range } attributes: VideoAttributes & { pos: number | Range },
) => ReturnType; ) => ReturnType;
setVideoAlign: (align: "left" | "center" | "right") => ReturnType; setVideoAlign: (align: "left" | "center" | "right") => ReturnType;
setVideoWidth: (width: number) => ReturnType; setVideoWidth: (width: number) => ReturnType;
@@ -81,6 +84,17 @@ export const TiptapVideo = Node.create<VideoOptions>({
"data-align": attributes.align, "data-align": attributes.align,
}), }),
}, },
aspectRatio: {
default: null,
parseHTML: (element) => element.getAttribute("data-aspect-ratio"),
renderHTML: (attributes: VideoAttributes) => ({
"data-aspect-ratio": attributes.aspectRatio,
}),
},
placeholder: {
default: null,
rendered: false,
},
}; };
}, },
@@ -131,12 +145,4 @@ export const TiptapVideo = Node.create<VideoOptions>({
return ReactNodeViewRenderer(this.options.view); return ReactNodeViewRenderer(this.options.view);
}, },
addProseMirrorPlugins() {
return [
VideoUploadPlugin({
placeholderClass: "video-upload",
}),
];
},
}); });
+10
View File
@@ -153,6 +153,9 @@ importers:
highlight.js: highlight.js:
specifier: ^11.11.1 specifier: ^11.11.1
version: 11.11.1 version: 11.11.1
image-dimensions:
specifier: ^2.5.0
version: 2.5.0
ioredis: ioredis:
specifier: ^5.4.1 specifier: ^5.4.1
version: 5.4.1 version: 5.4.1
@@ -6878,6 +6881,11 @@ packages:
image-blob-reduce@3.0.1: image-blob-reduce@3.0.1:
resolution: {integrity: sha512-/VmmWgIryG/wcn4TVrV7cC4mlfUC/oyiKIfSg5eVM3Ten/c1c34RJhMYKCWTnoSMHSqXLt3tsrBR4Q2HInvN+Q==} resolution: {integrity: sha512-/VmmWgIryG/wcn4TVrV7cC4mlfUC/oyiKIfSg5eVM3Ten/c1c34RJhMYKCWTnoSMHSqXLt3tsrBR4Q2HInvN+Q==}
image-dimensions@2.5.0:
resolution: {integrity: sha512-CKZPHjAEtSg9lBV9eER0bhNn/yrY7cFEQEhkwjLhqLY+Na8lcP1pEyWsaGMGc8t2qbKWA/tuqbhFQpOKGN72Yw==}
engines: {node: '>=18'}
hasBin: true
image-size@0.5.5: image-size@0.5.5:
resolution: {integrity: sha512-6TDAlDPZxUFCv+fuOkIoXT/V/f3Qbq8e37p+YOiYrUv3v9cc3/6x78VdfPgFVaB9dZYeLUfKgHRebpkm/oP2VQ==} resolution: {integrity: sha512-6TDAlDPZxUFCv+fuOkIoXT/V/f3Qbq8e37p+YOiYrUv3v9cc3/6x78VdfPgFVaB9dZYeLUfKgHRebpkm/oP2VQ==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
@@ -17744,6 +17752,8 @@ snapshots:
dependencies: dependencies:
pica: 7.1.1 pica: 7.1.1
image-dimensions@2.5.0: {}
image-size@0.5.5: image-size@0.5.5:
optional: true optional: true