GrapesJS / preset-newsletter

GrapesJS preset configuration for the newsletter editor.
https://grapesjs.com/demo-newsletter-editor.html
BSD 3-Clause "New" or "Revised" License
193 stars 143 forks source link

How to run import command on another event? #34

Closed lorrandavid closed 6 years ago

lorrandavid commented 6 years ago

I'm using the new GrapeJS which let me append the panels to other elements, so I have my menu where all the actions are happening but I can't find out how to run the import command on another element using editor.runCommand('name') or something else.

How can I achieve this?

lorrandavid commented 6 years ago

Maybe it's cleaner to create a plugin but I got it done like this:

var commands = editor.Commands;
commands.add('edit-template', {
    run(editor, sender) {
        var codeViewer = editor && editor.CodeManager.getViewer('CodeMirror').clone();
        var btnImp = document.createElement("button");
        var container = document.createElement("div");
        var currentTemplate = editor.runCommand('gjs-get-inlined-html');

        // Setup save button
        btnImp.innerHTML = 'Save';
        btnImp.className = 'gjs-btn-prim gjs-btn-import';
        btnImp.addEventListener('click', function() {
            var code = codeViewer.editor.getValue();
            editor.DomComponents.getWrapper().set('content', '');
            editor.setComponents(code);
            editor.Modal.close();
        });

        codeViewer.set({
            codeName: 'htmlmixed',
            theme: 'hopscotch',
            readOnly: 0
        });

        var md = editor.Modal;
        var modalContent = md.getContentEl();
        var viewer = codeViewer.editor;
        md.setTitle('HTML Editor ');

        if(!viewer) {
            var txtarea = document.createElement('textarea');
            var labelEl = document.createElement('div');
            labelEl.className = 'import-label';
            labelEl.innerHTML = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem vero praesentium odit eum, dicta molestiae cupiditate vitae eaque asperiores nisi fugiat earum amet, officia ut, quisquam eligendi dignissimos ipsam. Aliquid.';
            container.appendChild(labelEl);
            container.appendChild(txtarea);
            container.appendChild(btnImp);
            codeViewer.init(txtarea);
            viewer = codeViewer.editor;
        }

        md.setContent('');
        md.setContent(container);
        codeViewer.setContent(currentTemplate);
        md.open();
        viewer.refresh();
    }
});