Skip to content
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

Correctly handle different javascript realms/documents #4330

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion packages/quill/src/core/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import CursorBlot from '../blots/cursor.js';
import type Scroll from '../blots/scroll.js';
import TextBlot, { escapeText } from '../blots/text.js';
import { Range } from './selection.js';
import { isElement } from './utils/crossRealmIsElement.js';

const ASCII = /^[ -~]*$/;

Expand Down Expand Up @@ -406,7 +407,7 @@ function convertHTML(
}
return `${start}>${parts.join('')}<${end}`;
}
return blot.domNode instanceof Element ? blot.domNode.outerHTML : '';
return isElement(blot.domNode) ? blot.domNode.outerHTML : '';
}

function combineFormats(
Expand Down
30 changes: 19 additions & 11 deletions packages/quill/src/core/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,6 @@ import logger from './logger.js';
const debug = logger('quill:events');
const EVENTS = ['selectionchange', 'mousedown', 'mouseup', 'click'];

EVENTS.forEach((eventName) => {
document.addEventListener(eventName, (...args) => {
Array.from(document.querySelectorAll('.ql-container')).forEach((node) => {
const quill = instances.get(node);
if (quill && quill.emitter) {
quill.emitter.handleDOM(...args);
}
});
});
});

class Emitter extends EventEmitter<string> {
static events = {
EDITOR_CHANGE: 'editor-change',
Expand All @@ -39,6 +28,24 @@ class Emitter extends EventEmitter<string> {
USER: 'user',
} as const;

private static registeredDocuments = new WeakMap<Document, boolean>();

static registerEventsOnDocument(doc: Document) {
if (Emitter.registeredDocuments.get(doc)) return;
Emitter.registeredDocuments.set(doc, true);

EVENTS.forEach((eventName) => {
doc.addEventListener(eventName, (...args) => {
Array.from(doc.querySelectorAll('.ql-container')).forEach((node) => {
const quill = instances.get(node);
if (quill && quill.emitter) {
quill.emitter.handleDOM(...args);
}
});
});
});
}

protected domListeners: Record<string, { node: Node; handler: Function }[]>;

constructor() {
Expand All @@ -62,6 +69,7 @@ class Emitter extends EventEmitter<string> {
}

listenDOM(eventName: string, node: Node, handler: EventListener) {
Emitter.registerEventsOnDocument(node.ownerDocument ?? document);
if (!this.domListeners[eventName]) {
this.domListeners[eventName] = [];
}
Expand Down
2 changes: 2 additions & 0 deletions packages/quill/src/core/quill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ class Quill {

container: HTMLElement;
root: HTMLDivElement;
rootDocument: Document;
scroll: Scroll;
emitter: Emitter;
protected allowReadOnlyEdits: boolean;
Expand All @@ -195,6 +196,7 @@ class Quill {
constructor(container: HTMLElement | string, options: QuillOptions = {}) {
this.options = expandConfig(container, options);
this.container = this.options.container;
this.rootDocument = this.container.ownerDocument;
if (this.container == null) {
debug.error('Invalid Quill container', container);
return;
Expand Down
23 changes: 13 additions & 10 deletions packages/quill/src/core/selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { EmitterSource } from './emitter.js';
import logger from './logger.js';
import type Cursor from '../blots/cursor.js';
import type Scroll from '../blots/scroll.js';
import { isElement } from './utils/crossRealmIsElement.js';

const debug = logger('quill:selection');

Expand Down Expand Up @@ -42,6 +43,7 @@ class Selection {
mouseDown: boolean;

root: HTMLElement;
rootDocument: Document;
cursor: Cursor;
savedRange: Range;
lastRange: Range | null;
Expand All @@ -53,6 +55,7 @@ class Selection {
this.composing = false;
this.mouseDown = false;
this.root = this.scroll.domNode;
this.rootDocument = this.root.ownerDocument;
// @ts-expect-error
this.cursor = this.scroll.create('cursor', this);
// savedRange is last non-null range
Expand Down Expand Up @@ -132,10 +135,10 @@ class Selection {
}

handleDragging() {
this.emitter.listenDOM('mousedown', document.body, () => {
this.emitter.listenDOM('mousedown', this.rootDocument.body, () => {
this.mouseDown = true;
});
this.emitter.listenDOM('mouseup', document.body, () => {
this.emitter.listenDOM('mouseup', this.rootDocument.body, () => {
this.mouseDown = false;
this.update(Emitter.sources.USER);
});
Expand Down Expand Up @@ -224,7 +227,7 @@ class Selection {
}
rect = range.getBoundingClientRect();
} else {
if (!(leaf.domNode instanceof Element)) return null;
if (!isElement(leaf.domNode)) return null;
rect = leaf.domNode.getBoundingClientRect();
if (offset > 0) side = 'right';
}
Expand All @@ -239,7 +242,7 @@ class Selection {
}

getNativeRange(): NormalizedRange | null {
const selection = document.getSelection();
const selection = this.rootDocument.getSelection();
if (selection == null || selection.rangeCount <= 0) return null;
const nativeRange = selection.getRangeAt(0);
if (nativeRange == null) return null;
Expand All @@ -262,10 +265,10 @@ class Selection {
}

hasFocus(): boolean {
const doc = this.rootDocument;
return (
document.activeElement === this.root ||
(document.activeElement != null &&
contains(this.root, document.activeElement))
doc.activeElement === this.root ||
(doc.activeElement != null && contains(this.root, doc.activeElement))
);
}

Expand Down Expand Up @@ -372,7 +375,7 @@ class Selection {
) {
return;
}
const selection = document.getSelection();
const selection = this.rootDocument.getSelection();
if (selection == null) return;
if (startNode != null) {
if (!this.hasFocus()) this.root.focus({ preventScroll: true });
Expand All @@ -385,14 +388,14 @@ class Selection {
endNode !== native.endContainer ||
endOffset !== native.endOffset
) {
if (startNode instanceof Element && startNode.tagName === 'BR') {
if (isElement(startNode) && startNode.tagName === 'BR') {
// @ts-expect-error Fix me later
startOffset = Array.from(startNode.parentNode.childNodes).indexOf(
startNode,
);
startNode = startNode.parentNode;
}
if (endNode instanceof Element && endNode.tagName === 'BR') {
if (isElement(endNode) && endNode.tagName === 'BR') {
// @ts-expect-error Fix me later
endOffset = Array.from(endNode.parentNode.childNodes).indexOf(
endNode,
Expand Down
16 changes: 16 additions & 0 deletions packages/quill/src/core/utils/crossRealmIsElement.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function isElement(value: any): value is Element {
return (
value instanceof Element ||
value instanceof (value?.ownerDocument?.defaultView?.Element ?? Element)
);
}

function isHTMLElement(value: any): value is HTMLElement {
return (
value instanceof HTMLElement ||
value instanceof
(value?.ownerDocument?.defaultView?.HTMLElement ?? HTMLElement)
);
}

export { isElement, isHTMLElement };
7 changes: 3 additions & 4 deletions packages/quill/src/core/utils/scrollRectIntoView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ const getScrollDistance = (

const scrollRectIntoView = (root: HTMLElement, targetRect: Rect) => {
const document = root.ownerDocument;
const win = document.defaultView ?? window;

let rect = targetRect;

Expand All @@ -69,11 +70,9 @@ const scrollRectIntoView = (root: HTMLElement, targetRect: Rect) => {
? {
top: 0,
right:
window.visualViewport?.width ??
document.documentElement.clientWidth,
win.visualViewport?.width ?? document.documentElement.clientWidth,
bottom:
window.visualViewport?.height ??
document.documentElement.clientHeight,
win.visualViewport?.height ?? document.documentElement.clientHeight,
left: 0,
}
: getElementRect(current);
Expand Down
11 changes: 6 additions & 5 deletions packages/quill/src/modules/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { FontStyle } from '../formats/font.js';
import { SizeStyle } from '../formats/size.js';
import { deleteRange } from './keyboard.js';
import normalizeExternalHTML from './normalizeExternalHTML/index.js';
import { isElement, isHTMLElement } from '../core/utils/crossRealmIsElement.js';

const debug = logger('quill:clipboard');

Expand Down Expand Up @@ -312,7 +313,7 @@ function deltaEndsWith(delta: Delta, text: string) {
}

function isLine(node: Node, scroll: ScrollBlot) {
if (!(node instanceof Element)) return false;
if (!isElement(node)) return false;
const match = scroll.query(node);
// @ts-expect-error
if (match && match.prototype instanceof EmbedBlot) return false;
Expand Down Expand Up @@ -554,7 +555,8 @@ function matchNewline(node: Node, delta: Delta, scroll: ScrollBlot) {
if (!deltaEndsWith(delta, '\n')) {
if (
isLine(node, scroll) &&
(node.childNodes.length > 0 || node instanceof HTMLParagraphElement)
(node.childNodes.length > 0 ||
(isHTMLElement(node) && node.tagName === 'P'))
) {
return delta.insert('\n');
}
Expand Down Expand Up @@ -649,16 +651,15 @@ function matchText(node: HTMLElement, delta: Delta, scroll: ScrollBlot) {
(node.previousSibling == null &&
node.parentElement != null &&
isLine(node.parentElement, scroll)) ||
(node.previousSibling instanceof Element &&
isLine(node.previousSibling, scroll))
(isElement(node.previousSibling) && isLine(node.previousSibling, scroll))
) {
text = text.replace(/^\s+/, replacer.bind(replacer, false));
}
if (
(node.nextSibling == null &&
node.parentElement != null &&
isLine(node.parentElement, scroll)) ||
(node.nextSibling instanceof Element && isLine(node.nextSibling, scroll))
(isElement(node.nextSibling) && isLine(node.nextSibling, scroll))
) {
text = text.replace(/\s+$/, replacer.bind(replacer, false));
}
Expand Down
7 changes: 4 additions & 3 deletions packages/quill/src/modules/syntax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,10 +235,11 @@ class Syntax extends Module<SyntaxOptions> {
initListener() {
this.quill.on(Quill.events.SCROLL_BLOT_MOUNT, (blot: Blot) => {
if (!(blot instanceof SyntaxCodeBlockContainer)) return;
const select = this.quill.root.ownerDocument.createElement('select');
const doc = this.quill.rootDocument;
const select = doc.createElement('select');
// @ts-expect-error Fix me later
this.options.languages.forEach(({ key, label }) => {
const option = select.ownerDocument.createElement('option');
const option = doc.createElement('option');
option.textContent = label;
option.setAttribute('value', key);
select.appendChild(option);
Expand Down Expand Up @@ -299,7 +300,7 @@ class Syntax extends Module<SyntaxOptions> {
return delta.insert(line);
}, new Delta());
}
const container = this.quill.root.ownerDocument.createElement('div');
const container = this.quill.rootDocument.createElement('div');
container.classList.add(CodeBlock.className);
container.innerHTML = highlight(this.options.hljs, language, text);
return traverse(
Expand Down
5 changes: 3 additions & 2 deletions packages/quill/src/modules/toolbar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Quill from '../core/quill.js';
import logger from '../core/logger.js';
import Module from '../core/module.js';
import type { Range } from '../core/selection.js';
import { isHTMLElement } from '../core/utils/crossRealmIsElement.js';

const debug = logger('quill:toolbar');

Expand Down Expand Up @@ -36,11 +37,11 @@ class Toolbar extends Module<ToolbarProps> {
quill.container?.parentNode?.insertBefore(container, quill.container);
this.container = container;
} else if (typeof this.options.container === 'string') {
this.container = document.querySelector(this.options.container);
this.container = quill.rootDocument.querySelector(this.options.container);
} else {
this.container = this.options.container;
}
if (!(this.container instanceof HTMLElement)) {
if (!isHTMLElement(this.container)) {
debug.error('Container required for toolbar', this.options);
return;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/quill/src/modules/uiNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,13 @@ class UINode extends Module {
}
};

document.addEventListener('selectionchange', listener, {
this.quill.rootDocument.addEventListener('selectionchange', listener, {
once: true,
});
}

private handleSelectionChange() {
const selection = document.getSelection();
const selection = this.quill.rootDocument.getSelection();
if (!selection) return;
const range = selection.getRangeAt(0);
if (range.collapsed !== true || range.startOffset !== 0) return;
Expand Down
9 changes: 5 additions & 4 deletions packages/quill/src/modules/uploader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ class Uploader extends Module<UploaderOptions> {
quill.root.addEventListener('drop', (e) => {
e.preventDefault();
let native: ReturnType<typeof document.createRange> | null = null;
if (document.caretRangeFromPoint) {
native = document.caretRangeFromPoint(e.clientX, e.clientY);
const doc = quill.rootDocument;
if (doc.caretRangeFromPoint) {
native = doc.caretRangeFromPoint(e.clientX, e.clientY);
// @ts-expect-error
} else if (document.caretPositionFromPoint) {
} else if (doc.caretPositionFromPoint) {
// @ts-expect-error
const position = document.caretPositionFromPoint(e.clientX, e.clientY);
const position = doc.caretPositionFromPoint(e.clientX, e.clientY);
native = document.createRange();
native.setStart(position.offsetNode, position.offset);
native.setEnd(position.offsetNode, position.offset);
Expand Down
9 changes: 5 additions & 4 deletions packages/quill/src/themes/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,18 @@ class BaseTheme extends Theme {

constructor(quill: Quill, options: ThemeOptions) {
super(quill, options);
const doc = quill.rootDocument ?? document;
const listener = (e: MouseEvent) => {
if (!document.body.contains(quill.root)) {
document.body.removeEventListener('click', listener);
if (!doc.body.contains(quill.root)) {
doc.body.removeEventListener('click', listener);
return;
}
if (
this.tooltip != null &&
// @ts-expect-error
!this.tooltip.root.contains(e.target) &&
// @ts-expect-error
document.activeElement !== this.tooltip.textbox &&
doc.activeElement !== this.tooltip.textbox &&
!this.quill.hasFocus()
) {
this.tooltip.hide();
Expand All @@ -90,7 +91,7 @@ class BaseTheme extends Theme {
});
}
};
quill.emitter.listenDOM('click', document.body, listener);
quill.emitter.listenDOM('click', doc.body, listener);
}

addModule(name: 'clipboard'): Clipboard;
Expand Down
3 changes: 2 additions & 1 deletion packages/quill/src/themes/bubble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class BubbleTooltip extends BaseTooltip {
this.quill.on(
Emitter.events.EDITOR_CHANGE,
(type, range, oldRange, source) => {
const doc = quill.rootDocument;
if (type !== Emitter.events.SELECTION_CHANGE) return;
if (
range != null &&
Expand Down Expand Up @@ -58,7 +59,7 @@ class BubbleTooltip extends BaseTooltip {
}
}
} else if (
document.activeElement !== this.textbox &&
doc.activeElement !== this.textbox &&
this.quill.hasFocus()
) {
this.hide();
Expand Down
2 changes: 1 addition & 1 deletion packages/quill/src/ui/tooltip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class Tooltip {

constructor(quill: Quill, boundsContainer?: HTMLElement) {
this.quill = quill;
this.boundsContainer = boundsContainer || document.body;
this.boundsContainer = boundsContainer || quill.rootDocument.body;
this.root = quill.addContainer('ql-tooltip');
// @ts-expect-error
this.root.innerHTML = this.constructor.TEMPLATE;
Expand Down
Loading