calumk / editorjs-codecup

editorjs-codecup
9 stars 3 forks source link

Javascript <script> tag is not formatted #2

Closed flomirtech closed 9 months ago

flomirtech commented 9 months ago

Hello again, thank you for your work @calumk.

Unfortunately, as far as I'm concerned, everything would be fine if the script tags were displayed correctly.

Indeed, when I create a course, I enter code in your module and I don't put any tags, I have no problems. The content is saved in JSON format in the database. I retrieve it with :

<script>const fd = <?= $fd ?></script>

When I save without tags in the "codecup" module causes the display to become completely broken. Otherwise, everything works really well, which is a real shame.

flomirtech commented 9 months ago

On your example above, I have the same operation. When you want to store it for later display, the display breaks.

If, in your example, I hadn't set :

<script>TEST</script>

Everything would have been displayed correctly ^^

calumk commented 9 months ago

But where is your js code that loads the content?

What is $fd?

calumk commented 9 months ago

Oh ok I see now what $fd is

Are you using the cup.updatecode() method?

flomirtech commented 9 months ago

I don't use the cup.updatecode(), and I don't know what it is:

const ImageTool = window.ImageTool;

var editor = new EditorJS({
    holder: 'formation',
    autofocus: true,
    readOnly: true,
    tools: {
        header: {
            class: Header,
            config: {
                placeholder: 'Enter a header',
                levels: [1, 2, 3, 4],
                defaultLevel: 1,
            },
            inlineToolbar: true,
        },
        list: {
            class: List,
            tunes: ["anyTuneName"],
            inlineToolbar: true
        },
        marker: {
            class: Marker,
        },

        image: {
            class: SimpleImage,
            inlineToolbar: true,
            config: {
                placeholder: 'Paste image URL'
            }
        },
        code: {
            // class: editorjsCodeflask,
            class: editorJsCodeCup,
            options: {
                sandbox: true,
            }
        },
        // Ajout de la configuration de la force de retour à la ligne
        paragraph: {
            class: Paragraph,
            inlineToolbar: true,
            forceEnter: true, // ajouter un retour à la ligne après chaque balise <pre> et <code>
        },

        delimiter: {
            class: Delimiter,
            inlineToolbar: true,
            toolbox: {
                title: 'Insérer une séparation horizontale',
            },
        },

        underline: Underline,

        warning: {
            class: Warning,
            inlineToolbar: true,
            shortcut: 'CMD+SHIFT+W',
            config: {
                titlePlaceholder: 'Title',
                messagePlaceholder: 'Message',
            },
        },

        quote: Quote,

        alert: {
            class: Alert,
            inlineToolbar: true,
            tunes: ["anyTuneName"],
            shortcut: 'CMD+SHIFT+A',
            config: {
                defaultType: 'primary',
                messagePlaceholder: 'Enter something',
            },
        },

        nestedchecklist: editorjsNestedChecklist,

        anyTuneName: {
            class: AlignmentBlockTune,
            config: {
                default: "left",
                blocks: {
                    header: "center"
                }
            }
        },

        linkTool: {
            class: LinkTool,
            config: {
                endpoint: 'https://www.flomirtech.fr/inc/endpoint', // Your backend endpoint for url data fetching,
                pattern: /^#/,
                target: '_self'
            }
        },

        embed: {
            class: Embed,
            inlineToolbar: false,
            config: {
                services: {
                    youtube: true,
                    coub: true
                }
            }
        },

        raw: {
            class: RawTool,
            options: {
                sandbox: true,
            },
            toolbox: {
                title: 'Insérer du code HTML brut',
            },
        },
    },
    data: fd,
    onReady: () => {
        // disableEdit();
    },
    onChange: () => {
        saved();
    },
});

/**
 * It saves the data from the editor, then it takes the data and puts it in a hidden input
 * field
 */
function saved() {
    editor.save().then((savedData) => {
        // console.log('Enregistré', savedData);
        var about = document.querySelector('input[name=cours2]');
        about.value = JSON.stringify(savedData);
        // console.log(about.value);
    })
    // .catch((error) => {
        // console.log("Echec enregistrement", error)
    // })
}

function activeEdit() {
    editor.readOnly.toggle();
    $('.codeflask__textarea').css({
        "display": "block"
    });
}

// /* It's checking if the editor is ready to work. */
// editor.isReady.then(() => {
//     console.log('Editor.js is ready to work!')
// })
// /* It's catching the error. */
// .catch((reason) => {
//     console.log(`Editor.js initialization failed because of ${reason}`)
// });

With this function, I retrieve my course content :

function saved() {
    editor.save().then((savedData) => {
        // console.log('Enregistré', savedData);
        var about = document.querySelector('input[name=cours2]');
        about.value = JSON.stringify(savedData);
        // console.log(about.value);
    })
    // .catch((error) => {
        // console.log("Echec enregistrement", error)
    // })
}

=> input[name=cours2] is a hidden input.

And if I click on my "Save" buttun, it executes this :

/* It's updating the content of the editor. */
    if (isset($_POST['update'])) {
        if (!empty($_POST['cours2'])) {
            /* It's decoding the content of the editor. */
            $jsonC = json_decode($_POST['cours2']);

            /* It's checking if the content of the editor is empty. */
            if (!isset($jsonC->blocks[0])) {
                $_POST['cours2'] = '{"time":1665873759387,"blocks":[{"id":"IQzcrAghZ1","type":"paragraph","data":{"text":"Le cours est vide.","alignment":"left"}}],"version":"2.25.0"}';
            } else {
                /* It's updating the content of the editor. */
                $date = date('Y-m-d H:i:s');
                $req = $DB->prepare("UPDATE formation SET contenu = ?, editor = ?, date_edition = ? WHERE id_article = ?");
                $req->execute([$_POST['cours2'], $_SESSION['id'], $date, $cours['id_article']]);
                /* It's refreshing the page. */
                header('Location: ' . $_SERVER['REQUEST_URI']);
                exit;
            }
        }
    }

In my "< head >" section, I've loaded the "https://cdn.jsdelivr.net/npm/@calumk/editorjs-codecup@latest" CDN.

calumk commented 9 months ago

Ok, the issue is probably because you are going from PHP -> HTML -> JS?

You are writing the document from PHP to HTML

<script>
        var fd = <?= $fd ?>;
        document.getElementById('formation').innerHTML = fd;
</script>
<div id="formation"></div>

It might be that this is where the issue comes from?

It could be that the script tag is being executed because of your use of InnerHTML?

https://www.freecodecamp.org/news/innerhtml-vs-innertext-vs-textcontent/

or it could be not being escaped properly (if it is json format?

<?php
  $fd_encoded = json_encode( $fd);
  echo "<script>var data = $fd_encoded;</script>";
?>

I might be wrong, but I am pretty confident this issue is not related to the plugin. I am afraid this is related to how you are handling the data before it gets to the plugin.

flomirtech commented 9 months ago

Hello @calumk,

I reanalyzed in depth a question I had been asking myself all along. When I made Githubissues.

  • Githubissues is a development platform for aggregating issues.