Skip to content

Commit

Permalink
fix: use image loader when using drag-and-drop images (#792)
Browse files Browse the repository at this point in the history
  • Loading branch information
splincode authored Feb 19, 2024
1 parent 4a61fb0 commit 406c393
Showing 1 changed file with 37 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import {Image} from '@tiptap/extension-image';
import {Plugin} from '@tiptap/pm/state';
import {DOMOutputSpec, NodeSpec} from 'prosemirror-model';
import {EditorView} from 'prosemirror-view';
import {take, takeWhile} from 'rxjs';

import {TUI_IMAGE_LOADER} from '../../tokens/image-loader';
import {TuiNodeView} from '../tiptap-node-view';
import {TuiImageEditorComponent} from './image-editor.component';
import type {TuiEditableImage} from './image-editor.options';
Expand Down Expand Up @@ -46,35 +48,39 @@ const DEFAULT_IMAGE_ATTRS = {
},
};

function pasteImage(view: EditorView, event: ClipboardEvent | DragEvent): void {
const dataTransfer =
event instanceof DragEvent ? event.dataTransfer : event.clipboardData;
const images = Array.from(dataTransfer?.files ?? []).filter(file =>
/image/i.test(file.type),
);

if (images.length) {
event.preventDefault();
}

images.forEach(image => {
const reader = new FileReader();

reader.onload = readerEvent => {
const node = view.state.schema.nodes.imageEditor.create({
src: readerEvent.target?.result,
});
const transaction = view.state.tr.replaceSelectionWith(node);

/**
* @note:
* workaround for `Applying a mismatched transaction`
*/
setTimeout(() => view.dispatch(transaction));
};

reader.readAsDataURL(image);
});
function pasteImage(injector: Injector) {
return (view: EditorView, event: ClipboardEvent | DragEvent): void => {
const dataTransfer =
event instanceof DragEvent ? event.dataTransfer : event.clipboardData;
const imagesFiles = Array.from(dataTransfer?.files ?? []).filter(file =>
/image/i.test(file.type),
);

if (imagesFiles.length) {
event.preventDefault();
}

const loader = injector.get(TUI_IMAGE_LOADER);

imagesFiles.forEach(file => {
loader(file)
.pipe(
take(1),
// eslint-disable-next-line rxjs/no-ignored-takewhile-value
takeWhile(() => !view.isDestroyed),
)
.subscribe(src => {
const node = view.state.schema.nodes.imageEditor.create({src});
const transaction = view.state.tr.replaceSelectionWith(node);

setTimeout?.(() => {
if (!view.isDestroyed) {
view.dispatch(transaction);
}
});
});
});
};
}

export function tuiCreateImageEditorExtension<T, K>({
Expand Down Expand Up @@ -138,8 +144,8 @@ export function tuiCreateImageEditorExtension<T, K>({
new Plugin({
props: {
handleDOMEvents: {
paste: pasteImage,
drop: pasteImage,
paste: pasteImage(injector),
drop: pasteImage(injector),
},
},
}),
Expand Down

0 comments on commit 406c393

Please sign in to comment.