Ju99ernaut / grapesjs-script-editor

Edit or attach script to selected component
MIT License
26 stars 15 forks source link

How to enhance showCustomCode(target) via pluginsOpts #3

Closed abulka closed 3 years ago

abulka commented 3 years ago

Thanks for providing the commandAttachScript option so that developers can override functions within commands.js - I've used this technique successfully before e.g. getPreContent(), codeViewOptions, starter, onRun.

However I am finding it impossible to 'override' showCustomCode(target) because there are variables that are defined and relied on inside commands.js that I don't have access to when defining my own showCustomCode(target) externally. For example

pluginsOpts: {
    'grapesjs-script-editor': {
        commandAttachScript: {
            showCustomCode(target) { // <- I am trying to replace/inject this function
                const { editor, options } = this;
                const title = options.title || modalTitle;  // <- externally I don't have access to 'modalTitle'
                if (!content) content = this.getContent();  // <- 'content' is not defined - it is in the plugin, but not here
                    let code = target.getScriptString() || starter;
                    md.open({  // <- I don't have access to 'md' - it is in the plugin, but not here
etc.

Would you have any advice on how to customise this part of the plugin's behaviour? I basically want to remove any built in component script before showing the editor, then put the component script back (blended with user scripts) when the editor modal is closed. In this way I hope to protect any component scripts from being altered by users when they add their own user scripts.

Ju99ernaut commented 3 years ago

Most if not all of the variables that you don't have access to are also available from the editor or have no effect if you override them, most of these values correspond to options in pluginOpts so you can set them directly:

const title = 'Script';

Initially content is set to null so you can use this.content, as that's pretty much the only place it's used.

md is just editor.Modal.

abulka commented 3 years ago

Thanks! Those tips helped me build an injectable showCustomCode function successfully.