import { t } from "i18next"; import { TextSelection } from "prosemirror-state"; import { v4 as uuidv4 } from "uuid"; import type { EditorView } from "prosemirror-view"; import type { EditorNotice } from "../types"; import FileHelper from "../lib/FileHelper"; import { findBlockInsertPos } from "../queries/findBlockInsertPos"; import uploadPlaceholderPlugin, { findPlaceholder, getUrlAttr, setUploadProgress, } from "../lib/uploadPlaceholder"; export type Options = { /** Set to true to force images and videos to become file attachments */ isAttachment?: boolean; /** Set to true to replace any existing image at the users selection */ replaceExisting?: boolean; /** Callback fired to upload a file */ uploadFile?: ( file: File | string, options?: { id?: string; onProgress?: (fractionComplete: number) => void; } ) => Promise; /** Callback fired when the user starts a file upload */ onFileUploadStart?: () => void; /** Callback fired when the user completes a file upload */ onFileUploadStop?: () => void; /** Callback fired to surface a notice to the user */ onNotice?: EditorNotice; /** Attributes to overwrite */ attrs?: { /** Width to use when inserting image */ width?: number; /** Height to use when inserting image */ height?: number; /** Alt text / caption to use when inserting image */ alt?: string | null; /** Caption to use when inserting video */ title?: string | null; /** Layout class for alignment when inserting image */ layoutClass?: string | null; /** Whether to show a PDF preview embed for attachment nodes */ preview?: boolean; }; }; const insertFiles = async function ( view: EditorView, event: | Event | React.ChangeEvent | React.DragEvent, pos: number, files: File[], options: Options ) { const { uploadFile, onFileUploadStart, onFileUploadStop } = options; // okay, we have some dropped files and a handler – lets stop this // event going any further up the stack event.preventDefault(); // let the user know we're starting to process the files onFileUploadStart?.(); const { schema } = view.state; // we'll use this to track of how many files have succeeded or failed let complete = 0; const filesToUpload = ( await Promise.all( files.map(async (original) => { const file = FileHelper.withContentType(original); const isImage = FileHelper.isImage(file.type) && !options.isAttachment && !!schema.nodes.image; const isVideo = FileHelper.isVideo(file.type) && !options.isAttachment && !!schema.nodes.video; // a file that cannot be inserted as an image or video falls back to an // attachment node – if the schema in use has none then it cannot be // represented at all and should be skipped. if (!isImage && !isVideo && !schema.nodes.attachment) { return undefined; } const getDimensions = isImage ? (f: File) => FileHelper.getImageDimensions(f) : isVideo ? (f: File) => FileHelper.getVideoDimensions(f) : undefined; const dimensions = await getDimensions?.(file); // the node type and attributes the upload becomes, without the URL const type = isImage ? schema.nodes.image : isVideo ? schema.nodes.video : schema.nodes.attachment; const attrs = isImage ? { source: await FileHelper.getImageSourceAttr(file), ...dimensions, ...options.attrs, } : isVideo ? { title: file.name ?? t("Untitled"), ...dimensions, ...options.attrs, } : { title: file.name ?? t("Untitled"), size: file.size, contentType: file.type, preview: false, ...options.attrs, }; return { id: uuidv4(), type, attrs, file, }; }) ) ).filter((upload) => upload !== undefined); // none of the dropped files can be represented in this schema, nothing to do if (filesToUpload.length === 0) { onFileUploadStop?.(); return; } // the user might have dropped multiple files at once, we need to loop for (const upload of filesToUpload) { const { tr } = view.state; const { type } = upload; tr.setMeta(uploadPlaceholderPlugin, { add: { id: upload.id, // a block placeholder must not be shown inside a paragraph pos: options.replaceExisting ? pos : findBlockInsertPos(tr.doc, pos, type), file: upload.file, type: type.name, attrs: upload.attrs, replaceExisting: options.replaceExisting, }, }); // the replaced node is hidden, so it must not stay selected const replaced = options.replaceExisting ? tr.doc.nodeAt(pos) : null; if (replaced) { tr.setSelection( TextSelection.near(tr.doc.resolve(pos + replaced.nodeSize)) ); } view.dispatch(tr); // start uploading the file to the server. Using "then" syntax // to allow all placeholders to be entered at once with the uploads // happening in the background in parallel. uploadFile?.(upload.file, { id: upload.id, onProgress: (progress) => setUploadProgress(upload.id, progress), }) // then this should be able to get the full URL as well .then((src) => { if (view.isDestroyed) { return; } const result = findPlaceholder(view.state, upload.id); if (result === null) { return; } // the editor continues to display the local file, see getDisplayUrl const [from, to] = result; const node = type.create({ ...upload.attrs, [getUrlAttr(type)]: src, }); view.dispatch( view.state.tr .replaceWith(from, to || from, node) .setMeta(uploadPlaceholderPlugin, { remove: { id: upload.id, node }, }) ); }) .catch((error) => { // Imported dynamically so the Sentry SDK stays out of the module graph // until an upload actually fails, keeping it off server-side startup. void import("@sentry/react") .then((Sentry) => Sentry.captureException(error)) .catch(() => { // Reporting is best-effort; the error is logged below regardless. }); // oxlint-disable-next-line no-console console.error(error); if (view.isDestroyed) { return; } // cleanup the placeholder if there is a failure view.dispatch( view.state.tr.setMeta(uploadPlaceholderPlugin, { remove: { id: upload.id }, }) ); options.onNotice?.( error.message || t("Sorry, an error occurred uploading the file"), "error" ); }) .finally(() => { complete++; // once everything is done, let the user know if (complete === filesToUpload.length && onFileUploadStop) { onFileUploadStop(); } }); } }; export default insertFiles;