sphericalpm / lektor-simplemde

Plugin integrating SimpleMDE into Lektor admin
MIT License
14 stars 1 forks source link

SimpleMDE area does not refresh when switching between editing different pages #3

Open manulari opened 4 years ago

manulari commented 4 years ago

Steps to reproduce for me: 1) install lektor-simplemde 2) lektor server 3) open in browser, edit any page 4) click a subpage or parent page in the left sidebar

Result:
The SimpleMDE editing area still shows the old text.

Navigating to preview and then back fixes it.

I assume the admin interface is reusing parts of the dom when navigating between different pages, but haven't investigated in detail.

manulari commented 4 years ago

This is what I did now:

TEMPLATE = '''
{% extends "dash.html" %}
{% block scripts %}
  {{ super() }}
  <link rel="stylesheet" href="//cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
  <script src="//cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
  <script>
    (new MutationObserver(function() {
        [...document.getElementsByTagName('textarea')].forEach(e => {
            if (e.className === 'form-control') {
                e.classList.add('simplemde-attached');
                let editor = new SimpleMDE({ element: e, spellChecker: false,
                                             tabSize: 2, indentWithTabs: false,
                                             autosave: false });
                editor.codemirror.on('change', () => {
                    // update textarea value
                    /* only update if different, to avoid dirtying the state of the
                       textarea immediately on load, which would cause the admin
                       interface to ask for confirmation when leaving the page */
                    var v = editor.value();
                    if (e.value != v) {
                        e.value = v;

                        // dispatch a synthetic event for react to update its state
                        let ev = new Event('input', { bubbles: true });
                        ev.simulated = true;
                        e.dispatchEvent(ev);
                    }
                });
                new MutationObserver(function() {
                    if (e.value != editor.value()) {
                        console.log('c');
                        editor.codemirror.setValue(e.value);
                    }
                }).observe(e, { characterData: true, subtree: true });
            };
        });
    })).observe(
        document.getElementsByTagName('body')[0],
        {
            subtree: true,
            childList: true
        },
    );
  </script>
{% endblock %}
'''

Is this the right way to do it?

mvartanyan commented 4 years ago

Hey @manulari , why not send a pull request? It would be easier to see what changed and if it's right or not.

manulari commented 4 years ago

Hey @mvartanyan, Did you see my pull request?