Skip to content

refactor!: update to Quill v2, drop outdated Firefox patch #9007

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,37 @@ export const contentStyles = css`
.ql-align-right {
text-align: right;
}

.ql-code-block-container {
font-family: monospace;
}

.ql-editor li {
list-style-type: none;
position: relative;
}

.ql-editor li > .ql-ui::before {
display: inline-block;
margin-left: -1.5em;
margin-right: 0.3em;
text-align: right;
white-space: nowrap;
width: 1.2em;
}

.ql-editor li[data-list='bullet'] {
list-style-type: disc;
}

.ql-editor li[data-list='ordered'] {
counter-increment: list-0;
}

.ql-editor li[data-list='ordered'] > .ql-ui::before {
content: counter(list-0, decimal) '. ';
}

/* quill core end */

blockquote {
Expand All @@ -85,22 +116,14 @@ export const contentStyles = css`
padding-left: 1em;
}

code,
pre {
background-color: #f0f0f0;
border-radius: 0.1875em;
}

pre {
/* Quill converts <pre> to this */
.ql-code-block-container {
white-space: pre-wrap;
margin-bottom: 0.3125em;
margin-top: 0.3125em;
padding: 0.3125em 0.625em;
}

code {
font-size: 85%;
padding: 0.125em 0.25em;
background-color: #f0f0f0;
border-radius: 0.1875em;
}

img {
Expand Down
131 changes: 35 additions & 96 deletions packages/rich-text-editor/src/vaadin-rich-text-editor-mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,40 +10,30 @@
*/
import '../vendor/vaadin-quill.js';
import { timeOut } from '@vaadin/component-base/src/async.js';
import { isFirefox } from '@vaadin/component-base/src/browser-utils.js';
import { Debouncer } from '@vaadin/component-base/src/debounce.js';
import { I18nMixin } from '@vaadin/component-base/src/i18n-mixin.js';

const Quill = window.Quill;

// Workaround for text disappearing when accepting spellcheck suggestion
// See https://github.com/quilljs/quill/issues/2096#issuecomment-399576957
const Inline = Quill.import('blots/inline');

class CustomColor extends Inline {
constructor(domNode, value) {
super(domNode, value);

// Map <font> properties
domNode.style.color = domNode.color;

const span = this.replaceWith(new Inline(Inline.create()));

span.children.forEach((child) => {
if (child.attributes) child.attributes.copy(span);
if (child.unwrap) child.unwrap();
});

this.remove();

return span; // eslint-disable-line no-constructor-return
// Fix to add `spellcheck="false"` on the `<pre>` tag removed by Quill
// TODO: Quill also removes `<code>` tag from the output, should add it?
const QuillCodeBlockContainer = Quill.import('formats/code-block-container');

class CodeBlockContainer extends QuillCodeBlockContainer {
html(index, length) {
const markup = super.html(index, length);
const tempDiv = document.createElement('div');
tempDiv.innerHTML = markup;
const preTag = tempDiv.querySelector('pre');
if (preTag) {
preTag.setAttribute('spellcheck', 'false');
return preTag.outerHTML;
}
return markup; // fallback
}
}

CustomColor.blotName = 'customColor';
CustomColor.tagName = 'FONT';

Quill.register(CustomColor, true);
Quill.register('formats/code-block-container', CodeBlockContainer, true);

const HANDLERS = [
'bold',
Expand All @@ -70,8 +60,6 @@ const STATE = {
CLICKED: 2,
};

const TAB_KEY = 9;

const DEFAULT_I18N = {
undo: 'undo',
redo: 'redo',
Expand Down Expand Up @@ -352,11 +340,6 @@ export const RichTextEditorMixin = (superClass) =>
this.__patchToolbar();
this.__patchKeyboard();

/* c8 ignore next 3 */
if (isFirefox) {
this.__patchFirefoxFocus();
}

this.__setDirection(this.__dir);

const editorContent = editor.querySelector('.ql-editor');
Expand All @@ -380,23 +363,21 @@ export const RichTextEditorMixin = (superClass) =>
}
});

const TAB_KEY = 9;

editorContent.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (!this.__tabBindings) {
this.__tabBindings = this._editor.keyboard.bindings[TAB_KEY];
this._editor.keyboard.bindings[TAB_KEY] = null;
this.__tabBindings = this._editor.keyboard.bindings.Tab;
this._editor.keyboard.bindings.Tab = null;
}
} else if (this.__tabBindings) {
this._editor.keyboard.bindings[TAB_KEY] = this.__tabBindings;
this._editor.keyboard.bindings.Tab = this.__tabBindings;
this.__tabBindings = null;
}
});

editorContent.addEventListener('blur', () => {
if (this.__tabBindings) {
this._editor.keyboard.bindings[TAB_KEY] = this.__tabBindings;
this._editor.keyboard.bindings.Tab = this.__tabBindings;
this.__tabBindings = null;
}
});
Expand Down Expand Up @@ -483,7 +464,7 @@ export const RichTextEditorMixin = (superClass) =>
buttons[index].focus();
}
// Esc and Tab focuses the content
if (e.keyCode === 27 || (e.keyCode === TAB_KEY && !e.shiftKey)) {
if (e.keyCode === 27 || (e.key === 'Tab' && !e.shiftKey)) {
e.preventDefault();
this._editor.focus();
}
Expand Down Expand Up @@ -529,52 +510,6 @@ export const RichTextEditorMixin = (superClass) =>
return elem;
}

/** @private */
__patchFirefoxFocus() {
// In Firefox 63+ with native Shadow DOM, when moving focus out of
// contenteditable and back again within same shadow root, cursor
// disappears. See https://bugzilla.mozilla.org/show_bug.cgi?id=1496769
const editorContent = this.shadowRoot.querySelector('.ql-editor');
let isFake = false;

const focusFake = () => {
isFake = true;
this.__fakeTarget = this.__createFakeFocusTarget();
document.body.appendChild(this.__fakeTarget);
// Let the focus step out of shadow root!
this.__fakeTarget.focus();
return new Promise((resolve) => {
setTimeout(resolve);
});
};

const focusBack = (offsetNode, offset) => {
this._editor.focus();
if (offsetNode) {
this._editor.selection.setNativeRange(offsetNode, offset);
}
document.body.removeChild(this.__fakeTarget);
delete this.__fakeTarget;
isFake = false;
};

editorContent.addEventListener('mousedown', (e) => {
if (!this._editor.hasFocus()) {
const { x, y } = e;
const { offset, offsetNode } = document.caretPositionFromPoint(x, y);
focusFake().then(() => {
focusBack(offsetNode, offset);
});
}
});

editorContent.addEventListener('focusin', () => {
if (isFake === false) {
focusFake().then(() => focusBack());
}
});
}

/** @private */
__patchToolbar() {
const toolbar = this._editor.getModule('toolbar');
Expand Down Expand Up @@ -602,19 +537,19 @@ export const RichTextEditorMixin = (superClass) =>
this._toolbar.querySelector('button:not([tabindex])').focus();
};

const keyboard = this._editor.getModule('keyboard');
const bindings = keyboard.bindings[TAB_KEY];
const keyboard = this._editor.keyboard;
const bindings = keyboard.bindings.Tab;

// Exclude Quill shift-tab bindings, except for code block,
// as some of those are breaking when on a newline in the list
// https://github.com/vaadin/vaadin-rich-text-editor/issues/67
const originalBindings = bindings.filter((b) => !b.shiftKey || (b.format && b.format['code-block']));
const moveFocusBinding = { key: TAB_KEY, shiftKey: true, handler: focusToolbar };
const moveFocusBinding = { key: 'Tab', shiftKey: true, handler: focusToolbar };

keyboard.bindings[TAB_KEY] = [...originalBindings, moveFocusBinding];
keyboard.bindings.Tab = [...originalBindings, moveFocusBinding];

// Alt-f10 focuses a toolbar button
keyboard.addBinding({ key: 121, altKey: true, handler: focusToolbar });
keyboard.addBinding({ key: 'F10', altKey: true, handler: focusToolbar });
}

/** @private */
Expand Down Expand Up @@ -653,6 +588,7 @@ export const RichTextEditorMixin = (superClass) =>
_applyLink(link) {
if (link) {
this._markToolbarClicked();
this._editor.focus();
this._editor.format('link', link, SOURCE.USER);
this._editor.getModule('toolbar').update(this._editor.selection.savedRange);
}
Expand Down Expand Up @@ -735,6 +671,7 @@ export const RichTextEditorMixin = (superClass) =>
const color = event.detail.color;
this._colorValue = color === '#000000' ? null : color;
this._markToolbarClicked();
this._editor.focus();
this._editor.format('color', this._colorValue, SOURCE.USER);
this._toolbar.style.setProperty('--_color-value', this._colorValue);
this._colorEditing = false;
Expand All @@ -750,15 +687,19 @@ export const RichTextEditorMixin = (superClass) =>
const color = event.detail.color;
this._backgroundValue = color === '#ffffff' ? null : color;
this._markToolbarClicked();
this._editor.focus();
this._editor.format('background', this._backgroundValue, SOURCE.USER);
this._toolbar.style.setProperty('--_background-value', this._backgroundValue);
this._backgroundEditing = false;
}

/** @private */
__updateHtmlValue() {
const editor = this.shadowRoot.querySelector('.ql-editor');
let content = editor.innerHTML;
// We have to use this instead of `innerHTML` to get correct tags like `<pre>` etc.
let content = this._editor.getSemanticHTML();

// TODO there are some issues e.g. `spellcheck="false"` not preserved
// See https://github.com/slab/quill/issues/4289

// Remove Quill classes, e.g. ql-syntax, except for align
content = content.replace(/class="([^"]*)"/gu, (_match, group1) => {
Expand All @@ -767,8 +708,6 @@ export const RichTextEditorMixin = (superClass) =>
});
return `class="${classes.join(' ')}"`;
});
// Remove meta spans, e.g. cursor which are empty after Quill classes removed
content = content.replace(/<span[^>]*><\/span>/gu, '');

// Replace Quill align classes with inline styles
[this.__dir === 'rtl' ? 'left' : 'right', 'center', 'justify'].forEach((align) => {
Expand Down Expand Up @@ -827,7 +766,7 @@ export const RichTextEditorMixin = (superClass) =>
htmlValue = htmlValue.replaceAll(/>[^<]*</gu, (match) => match.replaceAll(character, replacement)); // NOSONAR
});

const deltaFromHtml = this._editor.clipboard.convert(htmlValue);
const deltaFromHtml = this._editor.clipboard.convert({ html: htmlValue });

// Restore whitespace characters after the conversion
Object.entries(whitespaceCharacters).forEach(([character, replacement]) => {
Expand Down
Loading