Something went wrong. Try again.
a tool for shared writing and social publishing
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547import { MutableRefObject, useCallback } from "react";import { ReplicacheMutators, useReplicache } from "src/replicache";import { EditorView } from "prosemirror-view";import { restoreEditorState, setEditorState, useEditorStates,} from "src/state/useEditorState";import { Node as ProsemirrorNode } from "prosemirror-model";import { EditorState } from "prosemirror-state";import { schema } from "./schema";import { generateKeyBetween, generateNKeysBetween } from "fractional-indexing";import { addImage, prepareImage } from "src/utils/addImage";import { BlockProps } from "../Block";import { focusBlock } from "src/utils/focusBlock";import { useEntitySetContext } from "components/EntitySetProvider";import { v7 } from "uuid";import { Replicache } from "replicache";import { markdownToHtml } from "src/htmlMarkdownParsers";import { betterIsUrl } from "src/utils/isURL";import { TextSelection } from "prosemirror-state";import { UndoManager } from "src/undoManager";import type { FactInput } from "src/replicache/mutations";import { buildBlocksFromElements, parsePasteHTMLToElements, type BlockType, type BuiltBlock,} from "src/utils/paste/htmlToBlocks";import { resolveCopiedFootnoteRefs } from "src/utils/paste/resolveCopiedFootnoteRefs";import { renderFootnoteDefHTML } from "src/utils/renderFootnoteDefHTML";import { scanIndex } from "src/replicache/utils";import { groupCanvasBlock } from "src/utils/groupCanvasBlock";import { addGalleryImages } from "../ImageGalleryBlock/addGalleryImages";
export const useHandlePaste = ( entityID: string, propsRef: MutableRefObject<BlockProps>,) => { let { rep, undoManager } = useReplicache(); let entity_set = useEntitySetContext(); return useCallback( (view: EditorView, e: ClipboardEvent) => { if (!rep) return; if (!e.clipboardData) return; let textHTML = e.clipboardData.getData("text/html"); let text = e.clipboardData.getData("text"); let editorState = useEditorStates.getState().editorStates[entityID]; if (!editorState) return; if (text && betterIsUrl(text)) { let selection = view.state.selection as TextSelection; let tr = view.state.tr; let { from, to } = selection; if (selection.empty) { tr.insertText(text, selection.from); tr.addMark( from, from + text.length, schema.marks.link.create({ href: text }), ); } else { tr.addMark(from, to, schema.marks.link.create({ href: text })); } let oldState = view.state; let newState = view.state.apply(tr); undoManager.add({ undo: () => { if (!view?.hasFocus()) view?.focus(); setEditorState(entityID, { editor: oldState, }); }, redo: () => { if (!view?.hasFocus()) view?.focus(); setEditorState(entityID, { editor: newState, }); }, }); setEditorState(entityID, { editor: newState, }); return true; } const { listData, parent, position, nextPosition } = propsRef.current; // A lone canvas block has no "after it"; if the paste brings blocks, it // becomes the first block of a group that takes them. const groupEntity = propsRef.current.pageType === "canvas" ? v7() : null; let grouped: Promise<void> | undefined; const prepareParent = groupEntity ? () => (grouped ??= groupCanvasBlock(rep, undoManager, { page: parent, blockEntity: propsRef.current.entityID, groupEntity, permission_set: entity_set.set, })) : undefined; const pastePosition = groupEntity ? generateKeyBetween(null, null) : position; const pasteNextPosition = groupEntity ? null : nextPosition;
let imageFiles = Array.from(e.clipboardData.items) .filter((item) => item.kind === "file" && item.type.includes("image")) .map((item) => item.getAsFile()) .filter((file): file is File => !!file); let htmlIsOnlyImages = !textHTML || parsePasteHTMLToElements(textHTML).every((el) => el.tagName === "IMG"); if (imageFiles.length > 1 && htmlIsOnlyImages) { const intoEmptyBlock = editorState.editor.doc.textContent.length === 0; const entity = intoEmptyBlock ? propsRef.current.entityID : v7(); (async () => { if (!intoEmptyBlock) await rep.mutate.createEntity([ { entityID: entity, permission_set: entity_set.set }, ]); await undoManager.withUndoGroup(async () => { if (intoEmptyBlock) { await rep.mutate.assertFact({ entity, attribute: "block/type", data: { type: "block-type-union", value: "image-gallery" }, }); await rep.mutate.retractAttribute({ entity, attribute: "block/text", }); } else { await prepareParent?.(); await rep.mutate.assertFact([ { entity: groupEntity ?? parent, id: v7(), attribute: "card/block", data: { type: "ordered-reference", value: entity, position: generateKeyBetween( pastePosition, pasteNextPosition, ), }, }, { entity, attribute: "block/type", data: { type: "block-type-union", value: "image-gallery" }, }, ]); } }); if (groupEntity && !intoEmptyBlock) focusBlock( { entityID: propsRef.current.entityID, type: propsRef.current.type, parent: groupEntity, }, { type: "end" }, ); await addGalleryImages(rep, { galleryEntity: entity, permission_set: entity_set.set, files: imageFiles, }); })().catch(() => {}); e.preventDefault(); return true; } // if there is no html, but there is text, convert the text to markdown let xml = new DOMParser().parseFromString(textHTML, "text/html"); if ((!textHTML || !xml.children.length) && text) { textHTML = markdownToHtml(text); } if (textHTML) { let children = parsePasteHTMLToElements(textHTML); let hasImage = false; for (let item of e.clipboardData.items) { if (item.type.includes("image")) hasImage = true; } if ( !(children.length === 1 && children[0].tagName === "IMG" && hasImage) ) { resolveCopiedFootnoteRefs(children, (footnoteEntityID) => rep.query(async (tx) => { let [text] = await scanIndex(tx).eav( footnoteEntityID, "block/text", ); return text ? renderFootnoteDefHTML(text.data.value) : null; }), ).then(() => bulkPaste({ children, rep, undoManager, entity_set, propsRef, pasteParent: groupEntity ?? (listData ? listData.parent : parent), position: pastePosition, nextPosition: pasteNextPosition, prepareParent, }), ); } }
for (let item of e.clipboardData.items) { if (item?.type.includes("image")) { let file = item.getAsFile(); if (file) { // Decode the image FIRST, then commit the block's structural facts // (type / card/block) together with the optimistic block/image fact // in a single transaction. Committing them atomically means the block // never paints as an image-type block with no image — i.e. no empty // "Upload An Image" placeholder flashes before the picture appears. // The whole structural commit is one undo group (one Cmd-Z removes // the pasted image); finishUpload writes the post-upload fact with // ignoreUndo so it doesn't add a stray step on top of the group. const intoEmptyBlock = editorState.editor.doc.textContent.length === 0; const entity = intoEmptyBlock ? propsRef.current.entityID : v7(); prepareImage(file, rep, { attribute: "block/image", entityID: entity, ignoreUndo: true, }) .then(async ({ imageFact, finishUpload }) => { // finally → finishUpload guarantees the concurrency slot is // released even if a commit throws. try { if (intoEmptyBlock) { await undoManager.withUndoGroup(async () => { await rep.mutate.assertFact([ { entity, attribute: "block/type", data: { type: "block-type-union", value: "image" }, }, imageFact, ]); await rep.mutate.retractAttribute({ entity, attribute: "block/text", }); }); } else { // createEntity first (it renders nothing until referenced), // then commit the card/block reference, type, and image fact // in one transaction so the new block appears with its image. await rep.mutate.createEntity([ { entityID: entity, permission_set: entity_set.set }, ]); await undoManager.withUndoGroup(async () => { await prepareParent?.(); await rep.mutate.assertFact([ { entity: groupEntity ?? parent, id: v7(), attribute: "card/block", data: { type: "ordered-reference", value: entity, position: generateKeyBetween( pastePosition, pasteNextPosition, ), }, }, { entity, attribute: "block/type", data: { type: "block-type-union", value: "image" }, }, imageFact, ]); }); // Grouping remounts the text block's editor, dropping focus. if (groupEntity) focusBlock( { entityID: propsRef.current.entityID, type: propsRef.current.type, parent: groupEntity, }, { type: "end" }, ); } } finally { await finishUpload(); } }) .catch(() => {}); return true; } return; } } e.preventDefault(); e.stopPropagation(); return true; }, [rep, entity_set, entityID, propsRef, undoManager], );};
async function bulkPaste({ children, rep, undoManager, entity_set, propsRef, pasteParent, position, nextPosition, prepareParent,}: { children: HTMLElement[]; rep: Replicache<ReplicacheMutators>; undoManager: UndoManager; entity_set: { set: string }; propsRef: MutableRefObject<BlockProps>; pasteParent: string; position: string | null; nextPosition: string | null; // Runs before the first block is committed under pasteParent; a paste the // active block absorbs whole never needs it. prepareParent?: () => Promise<void>;}) { let result = buildBlocksFromElements(children, { parent: pasteParent, permission_set: entity_set.set, }); if (result.blocks.length === 0) return;
// Determine if the first built block should reuse the active block. const firstBuilt = result.blocks[0]; const activeType = propsRef.current.type; let activeReuse: { content: ProsemirrorNode; type: BlockType } | null = null; if ( firstBuilt && firstBuilt.parent === pasteParent && firstBuilt.parsedContent && (firstBuilt.type === "text" || firstBuilt.type === "heading" || firstBuilt.type === "blockquote") && (activeType === "heading" || activeType === "blockquote" || activeType === firstBuilt.type) ) { activeReuse = { content: firstBuilt.parsedContent, type: firstBuilt.type, }; }
// When active reuse drops the first built block, fan its non-content facts // out to the active block: alignment, text-size, list metadata, and any // card/block references that connect to nested children. Nested blocks that // pointed at firstBuilt as their parent get re-pointed at the active block. let bulkBlocks: BuiltBlock[]; const reuseFacts: FactInput[] = []; if (activeReuse) { const droppedID = firstBuilt.entityID; const activeID = propsRef.current.entityID; bulkBlocks = result.blocks .slice(1) .map((b) => (b.parent === droppedID ? { ...b, parent: activeID } : b)); for (const f of firstBuilt.facts) { // Only facts on the dropped block itself move to the active block; facts // the builder emitted for other entities (footnote content) stay put. if (f.entity !== droppedID) { reuseFacts.push(f); continue; } if (f.attribute === "block/type" || f.attribute === "block/text") continue; const remapped: FactInput = { ...f, entity: activeID }; reuseFacts.push(remapped); } } else { bulkBlocks = result.blocks; } const topLevel = bulkBlocks.filter((b) => b.parent === pasteParent); const positions = topLevel.length > 0 ? generateNKeysBetween( position || null, nextPosition || null, topLevel.length, ) : []; const positionByEntity = new Map<string, string>(); topLevel.forEach((b, i) => positionByEntity.set(b.entityID, positions[i]));
const entities: Array<{ entityID: string; permission_set: string }> & { ignoreUndo?: true; } = [ ...bulkBlocks.map((b) => ({ entityID: b.entityID, permission_set: entity_set.set, })), ...result.extraEntities, ];
const allFacts: FactInput[] & { ignoreUndo?: true } = []; for (const b of bulkBlocks) { allFacts.push(...b.facts); const position = positionByEntity.get(b.entityID); if (position !== undefined) { allFacts.push({ id: v7(), entity: b.parent, attribute: "card/block", data: { type: "ordered-reference", value: b.entityID, position, }, }); } } allFacts.push(...reuseFacts);
// Apply active-block reuse via the live editor BEFORE committing the bulk // payload so the user sees the absorbed content immediately. The Replicache // commit follows. let activeReuseUndo: { oldEditorState: EditorState; newEditorState: EditorState; } | null = null; if (activeReuse) { const activeID = propsRef.current.entityID; const liveState = useEditorStates.getState().editorStates[activeID]; if (liveState) { const oldEditorState = liveState.editor; const tr = liveState.editor.tr; const sel = liveState.editor.selection; if (!sel.empty) { tr.delete(sel.from, sel.to); } tr.replaceSelectionWith(activeReuse.content); const newEditorState = liveState.editor.apply(tr); setEditorState(activeID, { editor: newEditorState }); activeReuseUndo = { oldEditorState, newEditorState }; } }
const activeID = propsRef.current.entityID; const newEntityIDs = entities.map((e) => e.entityID);
// One undo group spans preparing the parent, the live-editor undo and the // bulk undo so a single Cmd-Z reverses the whole paste. await undoManager.withUndoGroup(async () => { if (topLevel.length > 0 && prepareParent) await prepareParent(); // Single transaction for entity creation; second for all facts. We split // these to fit the existing generic mutators — both honor ignoreUndo. entities.ignoreUndo = true; allFacts.ignoreUndo = true; if (entities.length > 0) await rep.mutate.createEntity(entities); if (allFacts.length > 0) await rep.mutate.assertFact(allFacts);
if (activeReuseUndo) { const { oldEditorState, newEditorState } = activeReuseUndo; undoManager.add({ undo: () => { const view = useEditorStates.getState().editorStates[activeID]?.view; if (view && !view.hasFocus()) view.focus(); restoreEditorState(activeID, oldEditorState); }, redo: () => { const view = useEditorStates.getState().editorStates[activeID]?.view; if (view && !view.hasFocus()) view.focus(); restoreEditorState(activeID, newEditorState); }, }); } if (newEntityIDs.length > 0) { const facts = allFacts.slice(); undoManager.add({ undo: async () => { for (const id of newEntityIDs) { await rep.mutate.deleteEntity({ entity: id, ignoreUndo: true }); } }, redo: async () => { const e = entities.slice() as Array<{ entityID: string; permission_set: string; }> & { ignoreUndo?: true }; const f = facts.slice() as FactInput[] & { ignoreUndo?: true }; e.ignoreUndo = true; f.ignoreUndo = true; await rep.mutate.createEntity(e); await rep.mutate.assertFact(f); }, }); } });
// Refetch images after the bulk commit so the new blocks are already present // locally when the uploads land. for (const task of result.imageTasks) { fetch(task.url) .then((res) => res.blob()) .then((blob) => { const file = new File([blob], "image.png", { type: blob.type }); return addImage(file, rep, { attribute: task.attribute, entityID: task.entityID, // The bulk undo group already reverts these entities; skip recording // the image facts so they don't add a stray undo step on top. ignoreUndo: true, }); }) .catch(() => { // Image refetch failed; leave the placeholder block. The renderer // already handles missing image data. }); }
// Cursor placement: focus the end of the last bulk-added block, or the // active block if reuse absorbed everything. const lastBulk = bulkBlocks[bulkBlocks.length - 1]; if (lastBulk) { focusBlock( { entityID: lastBulk.entityID, type: lastBulk.type, parent: lastBulk.parent, }, { type: "end" }, ); } else if (activeReuse) { focusBlock( { entityID: propsRef.current.entityID, type: activeReuse.type, parent: propsRef.current.parent, }, { type: "end" }, ); }}