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

Handle mutations with text entry time stamps #794

Merged
merged 1 commit into from
Nov 3, 2021
Merged
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
7 changes: 1 addition & 6 deletions packages/outline-react/src/useOutlinePlainText.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {log} from 'outline';
import useLayoutEffect from './shared/useLayoutEffect';
import useOutlineEditorEvents from './useOutlineEditorEvents';
import {createParagraphNode, ParagraphNode} from 'outline/ParagraphNode';
import {CAN_USE_BEFORE_INPUT, IS_SAFARI, IS_CHROME} from 'shared/environment';
import {CAN_USE_BEFORE_INPUT} from 'shared/environment';
import {
onSelectionChange,
onKeyDownForPlainText,
Expand All @@ -29,7 +29,6 @@ import {
onDragStartPolyfill,
onTextMutation,
onInput,
applyMutationInputWebkitWorkaround,
onClick,
} from 'outline/events';
import useOutlineDragonSupport from './shared/useOutlineDragonSupport';
Expand Down Expand Up @@ -97,10 +96,6 @@ if (CAN_USE_BEFORE_INPUT) {
events.push(['drop', onDropPolyfill]);
}

if (IS_SAFARI || IS_CHROME) {
applyMutationInputWebkitWorkaround();
}

export default function useOutlinePlainText(editor: OutlineEditor): () => void {
useLayoutEffect(() => {
editor.registerNodeType('paragraph', ParagraphNode);
Expand Down
7 changes: 1 addition & 6 deletions packages/outline-react/src/useOutlineRichText.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {CodeNode} from 'outline/CodeNode';
import {ParagraphNode} from 'outline/ParagraphNode';
import {ListItemNode} from 'outline/ListItemNode';
import {createParagraphNode} from 'outline/ParagraphNode';
import {CAN_USE_BEFORE_INPUT, IS_SAFARI, IS_CHROME} from 'shared/environment';
import {CAN_USE_BEFORE_INPUT} from 'shared/environment';
import {
onSelectionChange,
onKeyDownForRichText,
Expand All @@ -35,7 +35,6 @@ import {
onDragStartPolyfill,
onTextMutation,
onInput,
applyMutationInputWebkitWorkaround,
onClick,
} from 'outline/events';
import useOutlineDragonSupport from './shared/useOutlineDragonSupport';
Expand Down Expand Up @@ -103,10 +102,6 @@ if (CAN_USE_BEFORE_INPUT) {
events.push(['drop', onDropPolyfill]);
}

if (IS_SAFARI || IS_CHROME) {
applyMutationInputWebkitWorkaround();
}

export default function useOutlineRichText(editor: OutlineEditor): () => void {
useLayoutEffect(() => {
editor.registerNodeType('heading', HeadingNode);
Expand Down
16 changes: 1 addition & 15 deletions packages/outline/src/core/OutlineEditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,9 +241,6 @@ class BaseOutlineEditor {
// Logging for updates
this._log = [];
}
getObserver(): null | MutationObserver {
return this._observer;
}
isComposing(): boolean {
return this._compositionKey != null;
}
Expand Down Expand Up @@ -374,11 +371,7 @@ class BaseOutlineEditor {
"setEditorState: the editor state is empty. Ensure the editor state's root node never becomes empty.",
);
}
const observer = this._observer;
if (observer !== null) {
const mutations = observer.takeRecords();
flushRootMutations(getSelf(this), mutations, observer);
}
flushRootMutations(getSelf(this));
if (this._pendingEditorState !== null) {
commitPendingUpdates(getSelf(this));
}
Expand Down Expand Up @@ -477,7 +470,6 @@ declare export class OutlineEditor {
_observer: null | MutationObserver;
_log: Array<string>;

getObserver(): null | MutationObserver;
isComposing(): boolean;
isEmpty(trim?: boolean): boolean;
registerNodeType(nodeType: string, klass: Class<OutlineNode>): void;
Expand All @@ -500,9 +492,3 @@ declare export class OutlineEditor {
focus(callbackFn?: () => void): void;
canShowPlaceholder(): boolean;
}

export function getEditorFromElement(element: Element): null | OutlineEditor {
// $FlowFixMe: internal field
const possibleEditor: void | OutlineEditor = element.__outlineEditor;
return possibleEditor != null ? possibleEditor : null;
}
246 changes: 136 additions & 110 deletions packages/outline/src/core/OutlineMutations.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,26 @@ import {
pushLogEntry,
} from './OutlineUtils';

// The time between a text entry event and the mutation observer firing.
const TEXT_MUTATION_VARIANCE = 100;

let isProcessingMutations: boolean = false;
let lastTextEntryTimeStamp = 0;

export function getIsProcesssingMutations(): boolean {
return isProcessingMutations;
}

function updateTimeStamp(event) {
lastTextEntryTimeStamp = event.timeStamp;
}

function initTextEntryListener(): void {
if (lastTextEntryTimeStamp === 0) {
window.addEventListener('textInput', updateTimeStamp, true);
}
}

function isManagedLineBreak(dom: Node, target: Node): boolean {
return (
// $FlowFixMe: internal field
Expand All @@ -40,11 +54,11 @@ function getLastSelection(editor: OutlineEditor): null | Selection {
});
}

function flushTextMutation(
function handleTextMutation(
target: Text,
node: TextNode,
editor: OutlineEditor,
) {
): void {
const domSelection = window.getSelection();
let anchorOffset = null;
let focusOffset = null;
Expand All @@ -63,133 +77,145 @@ export function flushMutations(
mutations: Array<MutationRecord>,
observer: MutationObserver,
): void {
let shouldRevertSelection = false;
for (let i = 0; i < mutations.length; i++) {
const mutation = mutations[i];
const type = mutation.type;
const target = mutation.target;
const targetNode = getNearestNodeFromDOMNode(target);

if (isDecoratorNode(targetNode)) {
continue;
}
if (type === 'characterData') {
// Text mutations are deferred and passed to mutation listeners to be
// processed outside of the Outline engine.
if (
target.nodeType === 3 &&
isTextNode(targetNode) &&
targetNode.isAttached()
) {
// $FlowFixMe: nodeType === 3 is a Text DOM node
flushTextMutation(((target: any): Text), targetNode, editor);
}
} else if (type === 'childList') {
shouldRevertSelection = true;
// We attempt to "undo" any changes that have occured outside
// of Outline. We want Outline's editor state to be source of truth.
// To the user, these will look like no-ops.
const addedDOMs = mutation.addedNodes;
const removedDOMs = mutation.removedNodes;
const siblingDOM = mutation.nextSibling;

for (let s = 0; s < removedDOMs.length; s++) {
const removedDOM = removedDOMs[s];
const node = getNodeFromDOMNode(removedDOM);
let placementDOM = siblingDOM;

if (node !== null && node.isAttached()) {
const nextSibling = node.getNextSibling();
if (nextSibling !== null) {
const key = nextSibling.getKey();
const nextSiblingDOM = editor.getElementByKey(key);
if (nextSiblingDOM !== null && nextSiblingDOM.parentNode !== null) {
placementDOM = nextSiblingDOM;
isProcessingMutations = true;
const shouldFlushTextMutations =
performance.now() - lastTextEntryTimeStamp > TEXT_MUTATION_VARIANCE;
try {
editor.update(() => {
pushLogEntry('onMutation');
let shouldRevertSelection = false;

for (let i = 0; i < mutations.length; i++) {
const mutation = mutations[i];
const type = mutation.type;
const target = mutation.target;
const targetNode = getNearestNodeFromDOMNode(target);

if (isDecoratorNode(targetNode)) {
continue;
}
if (type === 'characterData') {
// Text mutations are deferred and passed to mutation listeners to be
// processed outside of the Outline engine.
if (
shouldFlushTextMutations &&
target.nodeType === 3 &&
isTextNode(targetNode) &&
targetNode.isAttached()
) {
handleTextMutation(
// $FlowFixMe: nodeType === 3 is a Text DOM node
((target: any): Text),
targetNode,
editor,
);
}
} else if (type === 'childList') {
shouldRevertSelection = true;
// We attempt to "undo" any changes that have occured outside
// of Outline. We want Outline's editor state to be source of truth.
// To the user, these will look like no-ops.
const addedDOMs = mutation.addedNodes;
const removedDOMs = mutation.removedNodes;
const siblingDOM = mutation.nextSibling;

for (let s = 0; s < removedDOMs.length; s++) {
const removedDOM = removedDOMs[s];
const node = getNodeFromDOMNode(removedDOM);
let placementDOM = siblingDOM;

if (node !== null && node.isAttached()) {
const nextSibling = node.getNextSibling();
if (nextSibling !== null) {
const key = nextSibling.getKey();
const nextSiblingDOM = editor.getElementByKey(key);
if (
nextSiblingDOM !== null &&
nextSiblingDOM.parentNode !== null
) {
placementDOM = nextSiblingDOM;
}
}
}
if (placementDOM != null) {
while (placementDOM != null) {
const parentDOM = placementDOM.parentNode;
if (parentDOM === target) {
target.insertBefore(removedDOM, placementDOM);
break;
}
placementDOM = parentDOM;
}
} else {
target.appendChild(removedDOM);
}
}
}
if (placementDOM != null) {
while (placementDOM != null) {
const parentDOM = placementDOM.parentNode;
if (parentDOM === target) {
target.insertBefore(removedDOM, placementDOM);
break;
for (let s = 0; s < addedDOMs.length; s++) {
const addedDOM = addedDOMs[s];
const node = getNodeFromDOMNode(addedDOM);
const parentDOM = addedDOM.parentNode;
if (parentDOM != null && node === null) {
parentDOM.removeChild(addedDOM);
}
placementDOM = parentDOM;
}
} else {
target.appendChild(removedDOM);
}
}
for (let s = 0; s < addedDOMs.length; s++) {
const addedDOM = addedDOMs[s];
const node = getNodeFromDOMNode(addedDOM);
const parentDOM = addedDOM.parentNode;
if (parentDOM != null && node === null) {
parentDOM.removeChild(addedDOM);

// Capture all the mutations made during this function. This
// also prevents us having to process them on the next cycle
// of onMutation, as these mutations were made by us.
const records = observer.takeRecords();

// Check for any random auto-added <br> elements, and remove them.
// These get added by the browser when we undo the above mutations
// and this can lead to a broken UI.
if (records.length > 0) {
for (let i = 0; i < records.length; i++) {
const record = records[i];
const addedNodes = record.addedNodes;
const target = record.target;

for (let s = 0; s < addedNodes.length; s++) {
const addedDOM = addedNodes[s];
const parentDOM = addedDOM.parentNode;
if (
parentDOM != null &&
addedDOM.nodeName === 'BR' &&
!isManagedLineBreak(addedDOM, target)
) {
parentDOM.removeChild(addedDOM);
}
}
}
// Clear any of those removal mutations
observer.takeRecords();
}
}
}

// Capture all the mutations made during this function. This
// also prevents us having to process them on the next cycle
// of onMutation, as these mutations were made by us.
const records = observer.takeRecords();

// Check for any random auto-added <br> elements, and remove them.
// These get added by the browser when we undo the above mutations
// and this can lead to a broken UI.
if (records.length > 0) {
for (let i = 0; i < records.length; i++) {
const record = records[i];
const addedNodes = record.addedNodes;
const target = record.target;

for (let s = 0; s < addedNodes.length; s++) {
const addedDOM = addedNodes[s];
const parentDOM = addedDOM.parentNode;
if (
parentDOM != null &&
addedDOM.nodeName === 'BR' &&
!isManagedLineBreak(addedDOM, target)
) {
parentDOM.removeChild(addedDOM);
if (shouldRevertSelection) {
const selection = state.getSelection() || getLastSelection(editor);
if (selection !== null) {
selection.dirty = true;
state.setSelection(selection);
}
}
}
// Clear any of those removal mutations
observer.takeRecords();
}
if (shouldRevertSelection) {
const selection = state.getSelection() || getLastSelection(editor);
if (selection !== null) {
selection.dirty = true;
state.setSelection(selection);
}
}
}

export function flushRootMutations(
editor: OutlineEditor,
mutations: Array<MutationRecord>,
observer: MutationObserver,
): void {
isProcessingMutations = true;
try {
editor.update(() => {
pushLogEntry('onMutation');
flushMutations(editor, mutations, observer);
});
} finally {
isProcessingMutations = false;
}
}

export function flushRootMutations(editor: OutlineEditor): void {
const observer = editor._observer;
if (observer !== null) {
const mutations = observer.takeRecords();
flushMutations(editor, mutations, observer);
}
}

export function initMutationObserver(editor: OutlineEditor): void {
initTextEntryListener();
editor._observer = new MutationObserver(
(mutations: Array<MutationRecord>, observer: MutationObserver) => {
flushRootMutations(editor, mutations, observer);
flushMutations(editor, mutations, observer);
},
);
}
Loading