Skip to content

Instantly share code, notes, and snippets.

@sushilbansal
Created April 18, 2020 08:53
Show Gist options
  • Save sushilbansal/10243ac4592a93a9289ae9430ad23544 to your computer and use it in GitHub Desktop.
Save sushilbansal/10243ac4592a93a9289ae9430ad23544 to your computer and use it in GitHub Desktop.
import imageExtensions from 'image-extensions';
import isUrl from 'is-url';
import { Transforms } from 'slate';
import { useEditor } from 'slate-react';
import { IconButton } from '@material-ui/core';
import { ImageCropper } from '../ImageCropper';
export const withSlateImages = (editor: any) => {
const { insertData, isVoid } = editor;
editor.isVoid = (element: any) => {
return element.type === "image" ? true : isVoid(element);
};
editor.insertData = (data: any) => {
const text = data.getData("text/plain");
const { files } = data;
if (files && files.length > 0) {
for (const file of files) {
const reader = new FileReader();
const [mime] = file.type.split("/");
if (mime === "image") {
reader.addEventListener("load", () => {
const url = reader.result;
insertImage(editor, url);
});
reader.readAsDataURL(file);
}
}
} else if (isImageUrl(text)) {
insertImage(editor, text);
} else {
insertData(data);
}
};
return editor;
};
export const ImageElement = ({ attributes, children, element }: any) => {
return (
<div {...attributes}>
<div contentEditable={false}>
<img
src={element.url}
style={{
maxHeight: 400,
maxWidth: "100%",
display: "block",
marginLeft: "auto",
marginRight: "auto",
}}
/>
</div>
{children}
</div>
);
};
const insertImage = (editor: any, url: any) => {
const image = { type: "image", url, children: [{ text: "" }] };
Transforms.insertNodes(editor, image);
};
export const InsertImageButton = ({ icon }: any) => {
const editor = useEditor();
const uploadedImageURL = (url: string) => {
insertImage(editor, url);
};
const uploadButtom = () => <IconButton component="span">{icon}</IconButton>;
return (
<ImageCropper
uploadTextIcon={uploadButtom}
uploadedImageURL={uploadedImageURL}
/>
);
};
const isImageUrl = (url: any) => {
if (!url) return false;
if (!isUrl(url)) return false;
const ext = new URL(url).pathname.split(".").pop();
return imageExtensions.includes(ext as string);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment