GrapesJS Native HTML5 D&D

by artur_arseniev

HTML

<script src="https://unpkg.com/grapesjs"></script>
<link rel="stylesheet" href="https://unpkg.com/grapesjs/dist/css/grapes.min.css">
<script src="https://unpkg.com/grapesjs-blocks-basic"></script>
<div draggable="true">
I'm a div with draggable="true"! Drag me in!!!!
</div>
<div>
I'm a div! Select my text and drag me in!!!!
</div>
<img...

CSS

body, html {
  margin: 0;
  height: 100%;
}

Babel + JSX

const editor = grapesjs.init({
	container: '#gjs',
  fromElement: true,
  height: '100%',
  storageManager: false,
  plugins: ['gjs-blocks-basic']
});

document.querySelectorAll('[draggable=true]').forEach(el => {
	el.addEventListener('dragstart', ev => {
  	const { target } = ev;
    // You can use only 'text' data type if you want 
    // to support also IE11
    ev.dataTransfer.setData('text', 
    	`<span>${target.innerHTML}</span>`);
  })
})

// You can use `canvas:dragdata` to customize 
// the data based on dataTransfer
editor.on('canvas:dragdata', (dataTransfer, result) => {
	// use dataTransfer.files if you need to read from droppped files
	const text = dataTransfer.getData('text');
	if (text) {
  	// result.content can also be any Component Definition, 
    // not only a string
  	result.content = `<div>
    	${text}
    	<div>Extra content</div>
    </div>`;
  }
})