Open Drarok opened 3 years ago
The same sample code is runnable on RunKit.
Removing the use of a cached instance fixes this issue, but might be a nuclear option – I don't know how inefficient this is.
I've found a better way! Keep the cached instance, but clear its text before each use! Also, I replaced the infinite loop previously caused by replacing execCommand with a function that calls itself.
This works:
const fs = require('fs');
const path = require('path');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
let quillFilePath = require.resolve('quill');
let quillMinFilePath = quillFilePath.replace('quill.js', 'quill.min.js');
let quillLibrary = fs.readFileSync(quillMinFilePath);
let mutationObserverPolyfill = fs.readFileSync(path.join(__dirname, 'polyfill.js'));
const JSDOM_TEMPLATE = `
<div id="editor">hello</div>
<script>${mutationObserverPolyfill}</script>
<script>${quillLibrary}</script>
<script>
document.getSelection = function() {
return {
getRangeAt: function() { }
};
};
document.execCommand = () => false;
</script>
`;
const cache = {};
const JSDOM_OPTIONS = { runScripts: 'dangerously', resources: 'usable' };
const getQuill = () => {
if (!cache.quill) {
const DOM = new JSDOM(JSDOM_TEMPLATE, JSDOM_OPTIONS);
cache.quill = new DOM.window.Quill('#editor');
} else {
cache.quill.setText(''); // This is the special sauce
}
return cache.quill;
}
exports.convertTextToDelta = (text) => {
const quill = getQuill();
quill.setText(text);
return quill.getContents();
};
exports.convertHtmlToDelta = (html) => {
const quill = getQuill();
return quill.clipboard.convert(html);
};
exports.convertDeltaToHtml = (delta) => {
const quill = getQuill();
quill.setContents(delta);
return quill.root.innerHTML;
};
Oops, I didn't mean for this issue to close. I've made a fork to solve my issue ASAP.
Output: