/**
 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */
import { logWarning, EmitterMixin, CKEditorError, compareArrays, toArray, toMap, isIterable, ObservableMixin, count, EventInfo, Collection, keyCodes, isText, env, remove as remove$1, insertAt, diff, isNode, isComment, indexOf, fastDiff, global, isValidAttributeName, first, getAncestors, DomEmitterMixin, getCode, isArrowKeyCode, scrollViewportToShowTarget, spliceArray, uid, priorities, isInsideSurrogatePair, isInsideCombinedSymbol, isInsideEmojiSequence } from '@ckeditor/ckeditor5-utils/dist/index.js';
import { clone, isPlainObject, isObject, unset, get, merge, set, extend, debounce, isEqualWith, cloneDeep, isEqual } from 'lodash-es';

// Each document stores information about its placeholder elements and check functions.
const documentPlaceholders = new WeakMap();
let hasDisplayedPlaceholderDeprecationWarning = false;
/**
 * A helper that enables a placeholder on the provided view element (also updates its visibility).
 * The placeholder is a CSS pseudo–element (with a text content) attached to the element.
 *
 * To change the placeholder text, change value of the `placeholder` property in the provided `element`.
 *
 * To disable the placeholder, use {@link module:engine/view/placeholder~disablePlaceholder `disablePlaceholder()`} helper.
 *
 * @param options Configuration options of the placeholder.
 * @param options.view Editing view instance.
 * @param options.element Element that will gain a placeholder. See `options.isDirectHost` to learn more.
 * @param options.isDirectHost If set `false`, the placeholder will not be enabled directly
 * in the passed `element` but in one of its children (selected automatically, i.e. a first empty child element).
 * Useful when attaching placeholders to elements that can host other elements (not just text), for instance,
 * editable root elements.
 * @param options.text Placeholder text. It's **deprecated** and will be removed soon. Use
 * {@link module:engine/view/placeholder~PlaceholderableElement#placeholder `options.element.placeholder`} instead.
 * @param options.keepOnFocus If set `true`, the placeholder stay visible when the host element is focused.
 */ function enablePlaceholder({ view, element, text, isDirectHost = true, keepOnFocus = false }) {
    const doc = view.document;
    // Use a single a single post fixer per—document to update all placeholders.
    if (!documentPlaceholders.has(doc)) {
        documentPlaceholders.set(doc, new Map());
        // If a post-fixer callback makes a change, it should return `true` so other post–fixers
        // can re–evaluate the document again.
        doc.registerPostFixer((writer)=>updateDocumentPlaceholders(doc, writer));
        // Update placeholders on isComposing state change since rendering is disabled while in composition mode.
        doc.on('change:isComposing', ()=>{
            view.change((writer)=>updateDocumentPlaceholders(doc, writer));
        }, {
            priority: 'high'
        });
    }
    if (element.is('editableElement')) {
        element.on('change:placeholder', (evtInfo, evt, text)=>{
            setPlaceholder(text);
        });
    }
    if (element.placeholder) {
        setPlaceholder(element.placeholder);
    } else if (text) {
        setPlaceholder(text);
    }
    if (text) {
        showPlaceholderTextDeprecationWarning();
    }
    function setPlaceholder(text) {
        // Store information about the element placeholder under its document.
        documentPlaceholders.get(doc).set(element, {
            text,
            isDirectHost,
            keepOnFocus,
            hostElement: isDirectHost ? element : null
        });
        // Update the placeholders right away.
        view.change((writer)=>updateDocumentPlaceholders(doc, writer));
    }
}
/**
 * Disables the placeholder functionality from a given element.
 *
 * See {@link module:engine/view/placeholder~enablePlaceholder `enablePlaceholder()`} to learn more.
 */ function disablePlaceholder(view, element) {
    const doc = element.document;
    if (!documentPlaceholders.has(doc)) {
        return;
    }
    view.change((writer)=>{
        const placeholders = documentPlaceholders.get(doc);
        const config = placeholders.get(element);
        writer.removeAttribute('data-placeholder', config.hostElement);
        hidePlaceholder(writer, config.hostElement);
        placeholders.delete(element);
    });
}
/**
 * Shows a placeholder in the provided element by changing related attributes and CSS classes.
 *
 * **Note**: This helper will not update the placeholder visibility nor manage the
 * it in any way in the future. What it does is a one–time state change of an element. Use
 * {@link module:engine/view/placeholder~enablePlaceholder `enablePlaceholder()`} and
 * {@link module:engine/view/placeholder~disablePlaceholder `disablePlaceholder()`} for full
 * placeholder functionality.
 *
 * **Note**: This helper will blindly show the placeholder directly in the root editable element if
 * one is passed, which could result in a visual clash if the editable element has some children
 * (for instance, an empty paragraph). Use {@link module:engine/view/placeholder~enablePlaceholder `enablePlaceholder()`}
 * in that case or make sure the correct element is passed to the helper.
 *
 * @returns `true`, if any changes were made to the `element`.
 */ function showPlaceholder(writer, element) {
    if (!element.hasClass('ck-placeholder')) {
        writer.addClass('ck-placeholder', element);
        return true;
    }
    return false;
}
/**
 * Hides a placeholder in the element by changing related attributes and CSS classes.
 *
 * **Note**: This helper will not update the placeholder visibility nor manage the
 * it in any way in the future. What it does is a one–time state change of an element. Use
 * {@link module:engine/view/placeholder~enablePlaceholder `enablePlaceholder()`} and
 * {@link module:engine/view/placeholder~disablePlaceholder `disablePlaceholder()`} for full
 * placeholder functionality.
 *
 * @returns `true`, if any changes were made to the `element`.
 */ function hidePlaceholder(writer, element) {
    if (element.hasClass('ck-placeholder')) {
        writer.removeClass('ck-placeholder', element);
        return true;
    }
    return false;
}
/**
 * Checks if a placeholder should be displayed in the element.
 *
 * **Note**: This helper will blindly check the possibility of showing a placeholder directly in the
 * root editable element if one is passed, which may not be the expected result. If an element can
 * host other elements (not just text), most likely one of its children should be checked instead
 * because it will be the final host for the placeholder. Use
 * {@link module:engine/view/placeholder~enablePlaceholder `enablePlaceholder()`} in that case or make
 * sure the correct element is passed to the helper.
 *
 * @param element Element that holds the placeholder.
 * @param keepOnFocus Focusing the element will keep the placeholder visible.
 */ function needsPlaceholder(element, keepOnFocus) {
    if (!element.isAttached()) {
        return false;
    }
    // Anything but uiElement(s) counts as content.
    const hasContent = Array.from(element.getChildren()).some((element)=>!element.is('uiElement'));
    if (hasContent) {
        return false;
    }
    const doc = element.document;
    const viewSelection = doc.selection;
    const selectionAnchor = viewSelection.anchor;
    if (doc.isComposing && selectionAnchor && selectionAnchor.parent === element) {
        return false;
    }
    // Skip the focus check and make the placeholder visible already regardless of document focus state.
    if (keepOnFocus) {
        return true;
    }
    // If the document is blurred.
    if (!doc.isFocused) {
        return true;
    }
    // If document is focused and the element is empty but the selection is not anchored inside it.
    return !!selectionAnchor && selectionAnchor.parent !== element;
}
/**
 * Updates all placeholders associated with a document in a post–fixer callback.
 *
 * @returns True if any changes were made to the view document.
 */ function updateDocumentPlaceholders(doc, writer) {
    const placeholders = documentPlaceholders.get(doc);
    const directHostElements = [];
    let wasViewModified = false;
    // First set placeholders on the direct hosts.
    for (const [element, config] of placeholders){
        if (config.isDirectHost) {
            directHostElements.push(element);
            if (updatePlaceholder(writer, element, config)) {
                wasViewModified = true;
            }
        }
    }
    // Then set placeholders on the indirect hosts but only on those that does not already have an direct host placeholder.
    for (const [element, config] of placeholders){
        if (config.isDirectHost) {
            continue;
        }
        const hostElement = getChildPlaceholderHostSubstitute(element);
        // When not a direct host, it could happen that there is no child element
        // capable of displaying a placeholder.
        if (!hostElement) {
            continue;
        }
        // Don't override placeholder if the host element already has some direct placeholder.
        if (directHostElements.includes(hostElement)) {
            continue;
        }
        // Update the host element (used for setting and removing the placeholder).
        config.hostElement = hostElement;
        if (updatePlaceholder(writer, element, config)) {
            wasViewModified = true;
        }
    }
    return wasViewModified;
}
/**
 * Updates a single placeholder in a post–fixer callback.
 *
 * @returns True if any changes were made to the view document.
 */ function updatePlaceholder(writer, element, config) {
    const { text, isDirectHost, hostElement } = config;
    let wasViewModified = false;
    // This may be necessary when updating the placeholder text to something else.
    if (hostElement.getAttribute('data-placeholder') !== text) {
        writer.setAttribute('data-placeholder', text, hostElement);
        wasViewModified = true;
    }
    // If the host element is not a direct host then placeholder is needed only when there is only one element.
    const isOnlyChild = isDirectHost || element.childCount == 1;
    if (isOnlyChild && needsPlaceholder(hostElement, config.keepOnFocus)) {
        if (showPlaceholder(writer, hostElement)) {
            wasViewModified = true;
        }
    } else if (hidePlaceholder(writer, hostElement)) {
        wasViewModified = true;
    }
    return wasViewModified;
}
/**
 * Gets a child element capable of displaying a placeholder if a parent element can host more
 * than just text (for instance, when it is a root editable element). The child element
 * can then be used in other placeholder helpers as a substitute of its parent.
 */ function getChildPlaceholderHostSubstitute(parent) {
    if (parent.childCount) {
        const firstChild = parent.getChild(0);
        if (firstChild.is('element') && !firstChild.is('uiElement') && !firstChild.is('attributeElement')) {
            return firstChild;
        }
    }
    return null;
}
/**
 * Displays a deprecation warning message in the console, but only once per page load.
 */ function showPlaceholderTextDeprecationWarning() {
    if (!hasDisplayedPlaceholderDeprecationWarning) {
        /**
		 * The "text" option in the {@link module:engine/view/placeholder~enablePlaceholder `enablePlaceholder()`}
		 * function is deprecated and will be removed soon.
		 *
		 * See the {@glink updating/guides/update-to-39#view-element-placeholder Migration to v39} guide for
		 * more information on how to apply this change.
		 *
		 * @error enableplaceholder-deprecated-text-option
		 */ logWarning('enableplaceholder-deprecated-text-option');
    }
    hasDisplayedPlaceholderDeprecationWarning = true;
}

/**
 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */ /**
 * @module engine/view/typecheckable
 */ let TypeCheckable$1 = class TypeCheckable {
    /* istanbul ignore next -- @preserve */ is() {
        // There are a lot of overloads above.
        // Overriding method in derived classes remove them and only `is( type: string ): boolean` is visible which we don't want.
        // One option would be to copy them all to all classes, but that's ugly.
        // It's best when TypeScript compiler doesn't see those overloads, except the one in the top base class.
        // To overload a method, but not let the compiler see it, do after class definition:
        // `MyClass.prototype.is = function( type: string ) {...}`
        throw new Error('is() method is abstract');
    }
};

/**
 * Abstract view node class.
 *
 * This is an abstract class. Its constructor should not be used directly.
 * Use the {@link module:engine/view/downcastwriter~DowncastWriter} or {@link module:engine/view/upcastwriter~UpcastWriter}
 * to create new instances of view nodes.
 */ let Node$2 = class Node extends /* #__PURE__ */ EmitterMixin(TypeCheckable$1) {
    /**
	 * The document instance to which this node belongs.
	 */ document;
    /**
	 * Parent element. Null by default. Set by {@link module:engine/view/element~Element#_insertChild}.
	 */ parent;
    /**
	 * Creates a tree view node.
	 *
	 * @param document The document instance to which this node belongs.
	 */ constructor(document){
        super();
        this.document = document;
        this.parent = null;
    }
    /**
	 * Index of the node in the parent element or null if the node has no parent.
	 *
	 * Accessing this property throws an error if this node's parent element does not contain it.
	 * This means that view tree got broken.
	 */ get index() {
        let pos;
        if (!this.parent) {
            return null;
        }
        // No parent or child doesn't exist in parent's children.
        if ((pos = this.parent.getChildIndex(this)) == -1) {
            /**
			 * The node's parent does not contain this node. It means that the document tree is corrupted.
			 *
			 * @error view-node-not-found-in-parent
			 */ throw new CKEditorError('view-node-not-found-in-parent', this);
        }
        return pos;
    }
    /**
	 * Node's next sibling, or `null` if it is the last child.
	 */ get nextSibling() {
        const index = this.index;
        return index !== null && this.parent.getChild(index + 1) || null;
    }
    /**
	 * Node's previous sibling, or `null` if it is the first child.
	 */ get previousSibling() {
        const index = this.index;
        return index !== null && this.parent.getChild(index - 1) || null;
    }
    /**
	 * Top-most ancestor of the node. If the node has no parent it is the root itself.
	 */ get root() {
        // eslint-disable-next-line @typescript-eslint/no-this-alias, consistent-this
        let root = this;
        while(root.parent){
            root = root.parent;
        }
        return root;
    }
    /**
	 * Returns true if the node is in a tree rooted in the document (is a descendant of one of its roots).
	 */ isAttached() {
        return this.root.is('rootElement');
    }
    /**
	 * Gets a path to the node. The path is an array containing indices of consecutive ancestors of this node,
	 * beginning from {@link module:engine/view/node~Node#root root}, down to this node's index.
	 *
	 * ```ts
	 * const abc = downcastWriter.createText( 'abc' );
	 * const foo = downcastWriter.createText( 'foo' );
	 * const h1 = downcastWriter.createElement( 'h1', null, downcastWriter.createText( 'header' ) );
	 * const p = downcastWriter.createElement( 'p', null, [ abc, foo ] );
	 * const div = downcastWriter.createElement( 'div', null, [ h1, p ] );
	 * foo.getPath(); // Returns [ 1, 3 ]. `foo` is in `p` which is in `div`. `p` starts at offset 1, while `foo` at 3.
	 * h1.getPath(); // Returns [ 0 ].
	 * div.getPath(); // Returns [].
	 * ```
	 *
	 * @returns The path.
	 */ getPath() {
        const path = [];
        // eslint-disable-next-line @typescript-eslint/no-this-alias, consistent-this
        let node = this;
        while(node.parent){
            path.unshift(node.index);
            node = node.parent;
        }
        return path;
    }
    /**
	 * Returns ancestors array of this node.
	 *
	 * @param options Options object.
	 * @param options.includeSelf When set to `true` this node will be also included in parent's array.
	 * @param options.parentFirst When set to `true`, array will be sorted from node's parent to root element,
	 * otherwise root element will be the first item in the array.
	 * @returns Array with ancestors.
	 */ getAncestors(options = {}) {
        const ancestors = [];
        let parent = options.includeSelf ? this : this.parent;
        while(parent){
            ancestors[options.parentFirst ? 'push' : 'unshift'](parent);
            parent = parent.parent;
        }
        return ancestors;
    }
    /**
	 * Returns a {@link module:engine/view/element~Element} or {@link module:engine/view/documentfragment~DocumentFragment}
	 * which is a common ancestor of both nodes.
	 *
	 * @param node The second node.
	 * @param options Options object.
	 * @param options.includeSelf When set to `true` both nodes will be considered "ancestors" too.
	 * Which means that if e.g. node A is inside B, then their common ancestor will be B.
	 */ getCommonAncestor(node, options = {}) {
        const ancestorsA = this.getAncestors(options);
        const ancestorsB = node.getAncestors(options);
        let i = 0;
        while(ancestorsA[i] == ancestorsB[i] && ancestorsA[i]){
            i++;
        }
        return i === 0 ? null : ancestorsA[i - 1];
    }
    /**
	 * Returns whether this node is before given node. `false` is returned if nodes are in different trees (for example,
	 * in different {@link module:engine/view/documentfragment~DocumentFragment}s).
	 *
	 * @param node Node to compare with.
	 */ isBefore(node) {
        // Given node is not before this node if they are same.
        if (this == node) {
            return false;
        }
        // Return `false` if it is impossible to compare nodes.
        if (this.root !== node.root) {
            return false;
        }
        const thisPath = this.getPath();
        const nodePath = node.getPath();
        const result = compareArrays(thisPath, nodePath);
        switch(result){
            case 'prefix':
                return true;
            case 'extension':
                return false;
            default:
                return thisPath[result] < nodePath[result];
        }
    }
    /**
	 * Returns whether this node is after given node. `false` is returned if nodes are in different trees (for example,
	 * in different {@link module:engine/view/documentfragment~DocumentFragment}s).
	 *
	 * @param node Node to compare with.
	 */ isAfter(node) {
        // Given node is not before this node if they are same.
        if (this == node) {
            return false;
        }
        // Return `false` if it is impossible to compare nodes.
        if (this.root !== node.root) {
            return false;
        }
        // In other cases, just check if the `node` is before, and return the opposite.
        return !this.isBefore(node);
    }
    /**
	 * Removes node from parent.
	 *
	 * @internal
	 */ _remove() {
        this.parent._removeChildren(this.index);
    }
    /**
	 * @internal
	 * @param type Type of the change.
	 * @param node Changed node.
	 * @fires change
	 */ _fireChange(type, node) {
        this.fire(`change:${type}`, node);
        if (this.parent) {
            this.parent._fireChange(type, node);
        }
    }
    /**
	 * Custom toJSON method to solve child-parent circular dependencies.
	 *
	 * @returns Clone of this object with the parent property removed.
	 */ toJSON() {
        const json = clone(this);
        // Due to circular references we need to remove parent reference.
        delete json.parent;
        return json;
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Node$2.prototype.is = function(type) {
    return type === 'node' || type === 'view:node';
};

/**
 * Tree view text node.
 *
 * The constructor of this class should not be used directly. To create a new text node instance
 * use the {@link module:engine/view/downcastwriter~DowncastWriter#createText `DowncastWriter#createText()`}
 * method when working on data downcasted from the model or the
 * {@link module:engine/view/upcastwriter~UpcastWriter#createText `UpcastWriter#createText()`}
 * method when working on non-semantic views.
 */ let Text$1 = class Text extends Node$2 {
    /**
	 * The text content.
	 *
	 * Setting the data fires the {@link module:engine/view/node~Node#event:change:text change event}.
	 */ _textData;
    /**
	 * Creates a tree view text node.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#createText
	 * @internal
	 * @param document The document instance to which this text node belongs.
	 * @param data The text's data.
	 */ constructor(document, data){
        super(document);
        this._textData = data;
    }
    /**
	 * The text content.
	 */ get data() {
        return this._textData;
    }
    /**
	 * The `_data` property is controlled by a getter and a setter.
	 *
	 * The getter is required when using the addition assignment operator on protected property:
	 *
	 * ```ts
	 * const foo = downcastWriter.createText( 'foo' );
	 * const bar = downcastWriter.createText( 'bar' );
	 *
	 * foo._data += bar.data;   // executes: `foo._data = foo._data + bar.data`
	 * console.log( foo.data ); // prints: 'foobar'
	 * ```
	 *
	 * If the protected getter didn't exist, `foo._data` will return `undefined` and result of the merge will be invalid.
	 *
	 * The setter sets data and fires the {@link module:engine/view/node~Node#event:change:text change event}.
	 *
	 * @internal
	 */ get _data() {
        return this.data;
    }
    set _data(data) {
        this._fireChange('text', this);
        this._textData = data;
    }
    /**
	 * Checks if this text node is similar to other text node.
	 * Both nodes should have the same data to be considered as similar.
	 *
	 * @param otherNode Node to check if it is same as this node.
	 */ isSimilar(otherNode) {
        if (!(otherNode instanceof Text)) {
            return false;
        }
        return this === otherNode || this.data === otherNode.data;
    }
    /**
	 * Clones this node.
	 *
	 * @internal
	 * @returns Text node that is a clone of this node.
	 */ _clone() {
        return new Text(this.document, this.data);
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Text$1.prototype.is = function(type) {
    return type === '$text' || type === 'view:$text' || // This are legacy values kept for backward compatibility.
    type === 'text' || type === 'view:text' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
    type === 'node' || type === 'view:node';
};

/**
 * TextProxy is a wrapper for substring of {@link module:engine/view/text~Text}. Instance of this class is created by
 * {@link module:engine/view/treewalker~TreeWalker} when only a part of {@link module:engine/view/text~Text} needs to be returned.
 *
 * `TextProxy` has an API similar to {@link module:engine/view/text~Text Text} and allows to do most of the common tasks performed
 * on view nodes.
 *
 * **Note:** Some `TextProxy` instances may represent whole text node, not just a part of it.
 * See {@link module:engine/view/textproxy~TextProxy#isPartial}.
 *
 * **Note:** `TextProxy` is a readonly interface.
 *
 * **Note:** `TextProxy` instances are created on the fly basing on the current state of parent {@link module:engine/view/text~Text}.
 * Because of this it is highly unrecommended to store references to `TextProxy instances because they might get
 * invalidated due to operations on Document. Also TextProxy is not a {@link module:engine/view/node~Node} so it can not be
 * inserted as a child of {@link module:engine/view/element~Element}.
 *
 * `TextProxy` instances are created by {@link module:engine/view/treewalker~TreeWalker view tree walker}. You should not need to create
 * an instance of this class by your own.
 */ let TextProxy$1 = class TextProxy extends TypeCheckable$1 {
    /**
	 * Reference to the {@link module:engine/view/text~Text} element which TextProxy is a substring.
	 */ textNode;
    /**
	 * Text data represented by this text proxy.
	 */ data;
    /**
	 * Offset in the `textNode` where this `TextProxy` instance starts.
	 */ offsetInText;
    /**
	 * Creates a text proxy.
	 *
	 * @internal
	 * @param textNode Text node which part is represented by this text proxy.
	 * @param offsetInText Offset in {@link module:engine/view/textproxy~TextProxy#textNode text node}
	 * from which the text proxy starts.
	 * @param length Text proxy length, that is how many text node's characters, starting from `offsetInText` it represents.
	 * @constructor
	 */ constructor(textNode, offsetInText, length){
        super();
        this.textNode = textNode;
        if (offsetInText < 0 || offsetInText > textNode.data.length) {
            /**
			 * Given offsetInText value is incorrect.
			 *
			 * @error view-textproxy-wrong-offsetintext
			 */ throw new CKEditorError('view-textproxy-wrong-offsetintext', this);
        }
        if (length < 0 || offsetInText + length > textNode.data.length) {
            /**
			 * Given length value is incorrect.
			 *
			 * @error view-textproxy-wrong-length
			 */ throw new CKEditorError('view-textproxy-wrong-length', this);
        }
        this.data = textNode.data.substring(offsetInText, offsetInText + length);
        this.offsetInText = offsetInText;
    }
    /**
	 * Offset size of this node.
	 */ get offsetSize() {
        return this.data.length;
    }
    /**
	 * Flag indicating whether `TextProxy` instance covers only part of the original {@link module:engine/view/text~Text text node}
	 * (`true`) or the whole text node (`false`).
	 *
	 * This is `false` when text proxy starts at the very beginning of {@link module:engine/view/textproxy~TextProxy#textNode textNode}
	 * ({@link module:engine/view/textproxy~TextProxy#offsetInText offsetInText} equals `0`) and text proxy sizes is equal to
	 * text node size.
	 */ get isPartial() {
        return this.data.length !== this.textNode.data.length;
    }
    /**
	 * Parent of this text proxy, which is same as parent of text node represented by this text proxy.
	 */ get parent() {
        return this.textNode.parent;
    }
    /**
	 * Root of this text proxy, which is same as root of text node represented by this text proxy.
	 */ get root() {
        return this.textNode.root;
    }
    /**
	 * {@link module:engine/view/document~Document View document} that owns this text proxy, or `null` if the text proxy is inside
	 * {@link module:engine/view/documentfragment~DocumentFragment document fragment}.
	 */ get document() {
        return this.textNode.document;
    }
    /**
	 * Returns ancestors array of this text proxy.
	 *
	 * @param options Options object.
	 * @param options.includeSelf When set to `true`, textNode will be also included in parent's array.
	 * @param options.parentFirst When set to `true`, array will be sorted from text proxy parent to
	 * root element, otherwise root element will be the first item in the array.
	 * @returns Array with ancestors.
	 */ getAncestors(options = {}) {
        const ancestors = [];
        let parent = options.includeSelf ? this.textNode : this.parent;
        while(parent !== null){
            ancestors[options.parentFirst ? 'push' : 'unshift'](parent);
            parent = parent.parent;
        }
        return ancestors;
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
TextProxy$1.prototype.is = function(type) {
    return type === '$textProxy' || type === 'view:$textProxy' || // This are legacy values kept for backward compatibility.
    type === 'textProxy' || type === 'view:textProxy';
};

/**
 * View matcher class.
 * Instance of this class can be used to find {@link module:engine/view/element~Element elements} that match given pattern.
 */ class Matcher {
    _patterns = [];
    /**
	 * Creates new instance of Matcher.
	 *
	 * @param pattern Match patterns. See {@link module:engine/view/matcher~Matcher#add add method} for more information.
	 */ constructor(...pattern){
        this.add(...pattern);
    }
    /**
	 * Adds pattern or patterns to matcher instance.
	 *
	 * ```ts
	 * // String.
	 * matcher.add( 'div' );
	 *
	 * // Regular expression.
	 * matcher.add( /^\w/ );
	 *
	 * // Single class.
	 * matcher.add( {
	 * 	classes: 'foobar'
	 * } );
	 * ```
	 *
	 * See {@link module:engine/view/matcher~MatcherPattern} for more examples.
	 *
	 * Multiple patterns can be added in one call:
	 *
	 * ```ts
	 * matcher.add( 'div', { classes: 'foobar' } );
	 * ```
	 *
	 * @param pattern Object describing pattern details. If string or regular expression
	 * is provided it will be used to match element's name. Pattern can be also provided in a form
	 * of a function - then this function will be called with each {@link module:engine/view/element~Element element} as a parameter.
	 * Function's return value will be stored under `match` key of the object returned from
	 * {@link module:engine/view/matcher~Matcher#match match} or {@link module:engine/view/matcher~Matcher#matchAll matchAll} methods.
	 */ add(...pattern) {
        for (let item of pattern){
            // String or RegExp pattern is used as element's name.
            if (typeof item == 'string' || item instanceof RegExp) {
                item = {
                    name: item
                };
            }
            this._patterns.push(item);
        }
    }
    /**
	 * Matches elements for currently stored patterns. Returns match information about first found
	 * {@link module:engine/view/element~Element element}, otherwise returns `null`.
	 *
	 * Example of returned object:
	 *
	 * ```ts
	 * {
	 * 	element: <instance of found element>,
	 * 	pattern: <pattern used to match found element>,
	 * 	match: {
	 * 		name: true,
	 * 		attributes: [ 'title', 'href' ],
	 * 		classes: [ 'foo' ],
	 * 		styles: [ 'color', 'position' ]
	 * 	}
	 * }
	 * ```
	 *
	 * @see module:engine/view/matcher~Matcher#add
	 * @see module:engine/view/matcher~Matcher#matchAll
	 * @param element View element to match against stored patterns.
	 */ match(...element) {
        for (const singleElement of element){
            for (const pattern of this._patterns){
                const match = isElementMatching(singleElement, pattern);
                if (match) {
                    return {
                        element: singleElement,
                        pattern,
                        match
                    };
                }
            }
        }
        return null;
    }
    /**
	 * Matches elements for currently stored patterns. Returns array of match information with all found
	 * {@link module:engine/view/element~Element elements}. If no element is found - returns `null`.
	 *
	 * @see module:engine/view/matcher~Matcher#add
	 * @see module:engine/view/matcher~Matcher#match
	 * @param element View element to match against stored patterns.
	 * @returns Array with match information about found elements or `null`. For more information
	 * see {@link module:engine/view/matcher~Matcher#match match method} description.
	 */ matchAll(...element) {
        const results = [];
        for (const singleElement of element){
            for (const pattern of this._patterns){
                const match = isElementMatching(singleElement, pattern);
                if (match) {
                    results.push({
                        element: singleElement,
                        pattern,
                        match
                    });
                }
            }
        }
        return results.length > 0 ? results : null;
    }
    /**
	 * Returns the name of the element to match if there is exactly one pattern added to the matcher instance
	 * and it matches element name defined by `string` (not `RegExp`). Otherwise, returns `null`.
	 *
	 * @returns Element name trying to match.
	 */ getElementName() {
        if (this._patterns.length !== 1) {
            return null;
        }
        const pattern = this._patterns[0];
        const name = pattern.name;
        return typeof pattern != 'function' && name && !(name instanceof RegExp) ? name : null;
    }
}
/**
 * Returns match information if {@link module:engine/view/element~Element element} is matching provided pattern.
 * If element cannot be matched to provided pattern - returns `null`.
 *
 * @returns Returns object with match information or null if element is not matching.
 */ function isElementMatching(element, pattern) {
    // If pattern is provided as function - return result of that function;
    if (typeof pattern == 'function') {
        return pattern(element);
    }
    const match = {};
    // Check element's name.
    if (pattern.name) {
        match.name = matchName(pattern.name, element.name);
        if (!match.name) {
            return null;
        }
    }
    // Check element's attributes.
    if (pattern.attributes) {
        match.attributes = matchAttributes(pattern.attributes, element);
        if (!match.attributes) {
            return null;
        }
    }
    // Check element's classes.
    if (pattern.classes) {
        match.classes = matchClasses(pattern.classes, element);
        if (!match.classes) {
            return null;
        }
    }
    // Check element's styles.
    if (pattern.styles) {
        match.styles = matchStyles(pattern.styles, element);
        if (!match.styles) {
            return null;
        }
    }
    return match;
}
/**
 * Checks if name can be matched by provided pattern.
 *
 * @returns Returns `true` if name can be matched, `false` otherwise.
 */ function matchName(pattern, name) {
    // If pattern is provided as RegExp - test against this regexp.
    if (pattern instanceof RegExp) {
        return !!name.match(pattern);
    }
    return pattern === name;
}
/**
 * Checks if an array of key/value pairs can be matched against provided patterns.
 *
 * Patterns can be provided in a following ways:
 * - a boolean value matches any attribute with any value (or no value):
 *
 * ```ts
 * pattern: true
 * ```
 *
 * - a RegExp expression or object matches any attribute name:
 *
 * ```ts
 * pattern: /h[1-6]/
 * ```
 *
 * - an object matches any attribute that has the same name as the object item's key, where object item's value is:
 * 	- equal to `true`, which matches any attribute value:
 *
 * ```ts
 * pattern: {
 * 	required: true
 * }
 * ```
 *
 * 	- a string that is equal to attribute value:
 *
 * ```ts
 * pattern: {
 * 	rel: 'nofollow'
 * }
 * ```
 *
 * 	- a regular expression that matches attribute value,
 *
 * ```ts
 * pattern: {
 * 	src: /^https/
 * }
 * ```
 *
 * - an array with items, where the item is:
 * 	- a string that is equal to attribute value:
 *
 * ```ts
 * pattern: [ 'data-property-1', 'data-property-2' ],
 * ```
 *
 * 	- an object with `key` and `value` property, where `key` is a regular expression matching attribute name and
 * 		`value` is either regular expression matching attribute value or a string equal to attribute value:
 *
 * ```ts
 * pattern: [
 * 	{ key: /^data-property-/, value: true },
 * 	// or:
 * 	{ key: /^data-property-/, value: 'foobar' },
 * 	// or:
 * 	{ key: /^data-property-/, value: /^foo/ }
 * ]
 * ```
 *
 * @param patterns Object with information about attributes to match.
 * @param keys Attribute, style or class keys.
 * @param valueGetter A function providing value for a given item key.
 * @returns Returns array with matched attribute names or `null` if no attributes were matched.
 */ function matchPatterns(patterns, keys, valueGetter) {
    const normalizedPatterns = normalizePatterns(patterns);
    const normalizedItems = Array.from(keys);
    const match = [];
    normalizedPatterns.forEach(([patternKey, patternValue])=>{
        normalizedItems.forEach((itemKey)=>{
            if (isKeyMatched(patternKey, itemKey) && isValueMatched(patternValue, itemKey, valueGetter)) {
                match.push(itemKey);
            }
        });
    });
    // Return matches only if there are at least as many of them as there are patterns.
    // The RegExp pattern can match more than one item.
    if (!normalizedPatterns.length || match.length < normalizedPatterns.length) {
        return undefined;
    }
    return match;
}
/**
 * Bring all the possible pattern forms to an array of arrays where first item is a key and second is a value.
 *
 * Examples:
 *
 * Boolean pattern value:
 *
 * ```ts
 * true
 * ```
 *
 * to
 *
 * ```ts
 * [ [ true, true ] ]
 * ```
 *
 * Textual pattern value:
 *
 * ```ts
 * 'attribute-name-or-class-or-style'
 * ```
 *
 * to
 *
 * ```ts
 * [ [ 'attribute-name-or-class-or-style', true ] ]
 * ```
 *
 * Regular expression:
 *
 * ```ts
 * /^data-.*$/
 * ```
 *
 * to
 *
 * ```ts
 * [ [ /^data-.*$/, true ] ]
 * ```
 *
 * Objects (plain or with `key` and `value` specified explicitly):
 *
 * ```ts
 * {
 * 	src: /^https:.*$/
 * }
 * ```
 *
 * or
 *
 * ```ts
 * [ {
 * 	key: 'src',
 * 	value: /^https:.*$/
 * } ]
 * ```
 *
 * to:
 *
 * ```ts
 * [ [ 'src', /^https:.*$/ ] ]
 * ```
 *
 * @returns Returns an array of objects or null if provided patterns were not in an expected form.
 */ function normalizePatterns(patterns) {
    if (Array.isArray(patterns)) {
        return patterns.map((pattern)=>{
            if (isPlainObject(pattern)) {
                if (pattern.key === undefined || pattern.value === undefined) {
                    // Documented at the end of matcher.js.
                    logWarning('matcher-pattern-missing-key-or-value', pattern);
                }
                return [
                    pattern.key,
                    pattern.value
                ];
            }
            // Assume the pattern is either String or RegExp.
            return [
                pattern,
                true
            ];
        });
    }
    if (isPlainObject(patterns)) {
        return Object.entries(patterns);
    }
    // Other cases (true, string or regexp).
    return [
        [
            patterns,
            true
        ]
    ];
}
/**
 * @param patternKey A pattern representing a key we want to match.
 * @param itemKey An actual item key (e.g. `'src'`, `'background-color'`, `'ck-widget'`) we're testing against pattern.
 */ function isKeyMatched(patternKey, itemKey) {
    return patternKey === true || patternKey === itemKey || patternKey instanceof RegExp && itemKey.match(patternKey);
}
/**
 * @param patternValue A pattern representing a value we want to match.
 * @param itemKey An item key, e.g. `background`, `href`, 'rel', etc.
 * @param valueGetter A function used to provide a value for a given `itemKey`.
 */ function isValueMatched(patternValue, itemKey, valueGetter) {
    if (patternValue === true) {
        return true;
    }
    const itemValue = valueGetter(itemKey);
    // For now, the reducers are not returning the full tree of properties.
    // Casting to string preserves the old behavior until the root cause is fixed.
    // More can be found in https://github.com/ckeditor/ckeditor5/issues/10399.
    return patternValue === itemValue || patternValue instanceof RegExp && !!String(itemValue).match(patternValue);
}
/**
 * Checks if attributes of provided element can be matched against provided patterns.
 *
 * @param patterns Object with information about attributes to match. Each key of the object will be
 * used as attribute name. Value of each key can be a string or regular expression to match against attribute value.
 * @param  element Element which attributes will be tested.
 * @returns Returns array with matched attribute names or `null` if no attributes were matched.
 */ function matchAttributes(patterns, element) {
    const attributeKeys = new Set(element.getAttributeKeys());
    // `style` and `class` attribute keys are deprecated. Only allow them in object pattern
    // for backward compatibility.
    if (isPlainObject(patterns)) {
        if (patterns.style !== undefined) {
            // Documented at the end of matcher.js.
            logWarning('matcher-pattern-deprecated-attributes-style-key', patterns);
        }
        if (patterns.class !== undefined) {
            // Documented at the end of matcher.js.
            logWarning('matcher-pattern-deprecated-attributes-class-key', patterns);
        }
    } else {
        attributeKeys.delete('style');
        attributeKeys.delete('class');
    }
    return matchPatterns(patterns, attributeKeys, (key)=>element.getAttribute(key));
}
/**
 * Checks if classes of provided element can be matched against provided patterns.
 *
 * @param patterns Array of strings or regular expressions to match against element's classes.
 * @param element Element which classes will be tested.
 * @returns Returns array with matched class names or `null` if no classes were matched.
 */ function matchClasses(patterns, element) {
    // We don't need `getter` here because patterns for classes are always normalized to `[ className, true ]`.
    return matchPatterns(patterns, element.getClassNames(), /* istanbul ignore next -- @preserve */ ()=>{});
}
/**
 * Checks if styles of provided element can be matched against provided patterns.
 *
 * @param patterns Object with information about styles to match. Each key of the object will be
 * used as style name. Value of each key can be a string or regular expression to match against style value.
 * @param element Element which styles will be tested.
 * @returns Returns array with matched style names or `null` if no styles were matched.
 */ function matchStyles(patterns, element) {
    return matchPatterns(patterns, element.getStyleNames(true), (key)=>element.getStyle(key));
}
 /**
 * The key-value matcher pattern is missing key or value. Both must be present.
 * Refer the documentation: {@link module:engine/view/matcher~MatcherPattern}.
 *
 * @param pattern Pattern with missing properties.
 * @error matcher-pattern-missing-key-or-value
 */  /**
 * The key-value matcher pattern for `attributes` option is using deprecated `style` key.
 *
 * Use `styles` matcher pattern option instead:
 *
 * ```ts
 * // Instead of:
 * const pattern = {
 * 	attributes: {
 * 		key1: 'value1',
 * 		key2: 'value2',
 * 		style: /^border.*$/
 * 	}
 * }
 *
 * // Use:
 * const pattern = {
 * 	attributes: {
 * 		key1: 'value1',
 * 		key2: 'value2'
 * 	},
 * 	styles: /^border.*$/
 * }
 * ```
 *
 * Refer to the {@glink updating/guides/update-to-29##update-to-ckeditor-5-v2910 Migration to v29.1.0} guide
 * and {@link module:engine/view/matcher~MatcherPattern} documentation.
 *
 * @param pattern Pattern with missing properties.
 * @error matcher-pattern-deprecated-attributes-style-key
 */  /**
 * The key-value matcher pattern for `attributes` option is using deprecated `class` key.
 *
 * Use `classes` matcher pattern option instead:
 *
 * ```ts
 * // Instead of:
 * const pattern = {
 * 	attributes: {
 * 		key1: 'value1',
 * 		key2: 'value2',
 * 		class: 'foobar'
 * 	}
 * }
 *
 * // Use:
 * const pattern = {
 * 	attributes: {
 * 		key1: 'value1',
 * 		key2: 'value2'
 * 	},
 * 	classes: 'foobar'
 * }
 * ```
 *
 * Refer to the {@glink updating/guides/update-to-29##update-to-ckeditor-5-v2910 Migration to v29.1.0} guide
 * and the {@link module:engine/view/matcher~MatcherPattern} documentation.
 *
 * @param pattern Pattern with missing properties.
 * @error matcher-pattern-deprecated-attributes-class-key
 */

/**
 * Styles map. Allows handling (adding, removing, retrieving) a set of style rules (usually, of an element).
 */ class StylesMap {
    /**
	 * Keeps an internal representation of styles map. Normalized styles are kept as object tree to allow unified modification and
	 * value access model using lodash's get, set, unset, etc methods.
	 *
	 * When no style processor rules are defined it acts as simple key-value storage.
	 */ _styles;
    /**
	 * An instance of the {@link module:engine/view/stylesmap~StylesProcessor}.
	 */ _styleProcessor;
    /**
	 * Creates Styles instance.
	 */ constructor(styleProcessor){
        this._styles = {};
        this._styleProcessor = styleProcessor;
    }
    /**
	 * Returns true if style map has no styles set.
	 */ get isEmpty() {
        const entries = Object.entries(this._styles);
        return !entries.length;
    }
    /**
	 * Number of styles defined.
	 */ get size() {
        if (this.isEmpty) {
            return 0;
        }
        return this.getStyleNames().length;
    }
    /**
	 * Set styles map to a new value.
	 *
	 * ```ts
	 * styles.setTo( 'border:1px solid blue;margin-top:1px;' );
	 * ```
	 */ setTo(inlineStyle) {
        this.clear();
        const parsedStyles = parseInlineStyles(inlineStyle);
        for (const [key, value] of parsedStyles){
            this._styleProcessor.toNormalizedForm(key, value, this._styles);
        }
    }
    /**
	 * Checks if a given style is set.
	 *
	 * ```ts
	 * styles.setTo( 'margin-left:1px;' );
	 *
	 * styles.has( 'margin-left' );    // -> true
	 * styles.has( 'padding' );        // -> false
	 * ```
	 *
	 * **Note**: This check supports normalized style names.
	 *
	 * ```ts
	 * // Enable 'margin' shorthand processing:
	 * editor.data.addStyleProcessorRules( addMarginRules );
	 *
	 * styles.setTo( 'margin:2px;' );
	 *
	 * styles.has( 'margin' );         // -> true
	 * styles.has( 'margin-top' );     // -> true
	 * styles.has( 'margin-left' );    // -> true
	 *
	 * styles.remove( 'margin-top' );
	 *
	 * styles.has( 'margin' );         // -> false
	 * styles.has( 'margin-top' );     // -> false
	 * styles.has( 'margin-left' );    // -> true
	 * ```
	 *
	 * @param name Style name.
	 */ has(name) {
        if (this.isEmpty) {
            return false;
        }
        const styles = this._styleProcessor.getReducedForm(name, this._styles);
        const propertyDescriptor = styles.find(([property])=>property === name);
        // Only return a value if it is set;
        return Array.isArray(propertyDescriptor);
    }
    set(nameOrObject, valueOrObject) {
        if (isObject(nameOrObject)) {
            for (const [key, value] of Object.entries(nameOrObject)){
                this._styleProcessor.toNormalizedForm(key, value, this._styles);
            }
        } else {
            this._styleProcessor.toNormalizedForm(nameOrObject, valueOrObject, this._styles);
        }
    }
    /**
	 * Removes given style.
	 *
	 * ```ts
	 * styles.setTo( 'background:#f00;margin-right:2px;' );
	 *
	 * styles.remove( 'background' );
	 *
	 * styles.toString();   // -> 'margin-right:2px;'
	 * ```
	 *
	 * ***Note**:* This method uses {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules
	 * enabled style processor rules} to normalize passed values.
	 *
	 * ```ts
	 * // Enable 'margin' shorthand processing:
	 * editor.data.addStyleProcessorRules( addMarginRules );
	 *
	 * styles.setTo( 'margin:1px' );
	 *
	 * styles.remove( 'margin-top' );
	 * styles.remove( 'margin-right' );
	 *
	 * styles.toString(); // -> 'margin-bottom:1px;margin-left:1px;'
	 * ```
	 *
	 * @param name Style name.
	 */ remove(name) {
        const path = toPath(name);
        unset(this._styles, path);
        delete this._styles[name];
        this._cleanEmptyObjectsOnPath(path);
    }
    /**
	 * Returns a normalized style object or a single value.
	 *
	 * ```ts
	 * // Enable 'margin' shorthand processing:
	 * editor.data.addStyleProcessorRules( addMarginRules );
	 *
	 * const styles = new Styles();
	 * styles.setTo( 'margin:1px 2px 3em;' );
	 *
	 * styles.getNormalized( 'margin' );
	 * // will log:
	 * // {
	 * //     top: '1px',
	 * //     right: '2px',
	 * //     bottom: '3em',
	 * //     left: '2px'     // normalized value from margin shorthand
	 * // }
	 *
	 * styles.getNormalized( 'margin-left' ); // -> '2px'
	 * ```
	 *
	 * **Note**: This method will only return normalized styles if a style processor was defined.
	 *
	 * @param name Style name.
	 */ getNormalized(name) {
        return this._styleProcessor.getNormalized(name, this._styles);
    }
    /**
	 * Returns a normalized style string. Styles are sorted by name.
	 *
	 * ```ts
	 * styles.set( 'margin' , '1px' );
	 * styles.set( 'background', '#f00' );
	 *
	 * styles.toString(); // -> 'background:#f00;margin:1px;'
	 * ```
	 *
	 * **Note**: This method supports normalized styles if defined.
	 *
	 * ```ts
	 * // Enable 'margin' shorthand processing:
	 * editor.data.addStyleProcessorRules( addMarginRules );
	 *
	 * styles.set( 'margin' , '1px' );
	 * styles.set( 'background', '#f00' );
	 * styles.remove( 'margin-top' );
	 * styles.remove( 'margin-right' );
	 *
	 * styles.toString(); // -> 'background:#f00;margin-bottom:1px;margin-left:1px;'
	 * ```
	 */ toString() {
        if (this.isEmpty) {
            return '';
        }
        return this.getStylesEntries().map((arr)=>arr.join(':')).sort().join(';') + ';';
    }
    /**
	 * Returns property as a value string or undefined if property is not set.
	 *
	 * ```ts
	 * // Enable 'margin' shorthand processing:
	 * editor.data.addStyleProcessorRules( addMarginRules );
	 *
	 * const styles = new Styles();
	 * styles.setTo( 'margin:1px;' );
	 * styles.set( 'margin-bottom', '3em' );
	 *
	 * styles.getAsString( 'margin' ); // -> 'margin: 1px 1px 3em;'
	 * ```
	 *
	 * Note, however, that all sub-values must be set for the longhand property name to return a value:
	 *
	 * ```ts
	 * const styles = new Styles();
	 * styles.setTo( 'margin:1px;' );
	 * styles.remove( 'margin-bottom' );
	 *
	 * styles.getAsString( 'margin' ); // -> undefined
	 * ```
	 *
	 * In the above scenario, it is not possible to return a `margin` value, so `undefined` is returned.
	 * Instead, you should use:
	 *
	 * ```ts
	 * const styles = new Styles();
	 * styles.setTo( 'margin:1px;' );
	 * styles.remove( 'margin-bottom' );
	 *
	 * for ( const styleName of styles.getStyleNames() ) {
	 * 	console.log( styleName, styles.getAsString( styleName ) );
	 * }
	 * // 'margin-top', '1px'
	 * // 'margin-right', '1px'
	 * // 'margin-left', '1px'
	 * ```
	 *
	 * In general, it is recommend to iterate over style names like in the example above. This way, you will always get all
	 * the currently set style values. So, if all the 4 margin values would be set
	 * the for-of loop above would yield only `'margin'`, `'1px'`:
	 *
	 * ```ts
	 * const styles = new Styles();
	 * styles.setTo( 'margin:1px;' );
	 *
	 * for ( const styleName of styles.getStyleNames() ) {
	 * 	console.log( styleName, styles.getAsString( styleName ) );
	 * }
	 * // 'margin', '1px'
	 * ```
	 *
	 * **Note**: To get a normalized version of a longhand property use the {@link #getNormalized `#getNormalized()`} method.
	 */ getAsString(propertyName) {
        if (this.isEmpty) {
            return;
        }
        if (this._styles[propertyName] && !isObject(this._styles[propertyName])) {
            // Try return styles set directly - values that are not parsed.
            return this._styles[propertyName];
        }
        const styles = this._styleProcessor.getReducedForm(propertyName, this._styles);
        const propertyDescriptor = styles.find(([property])=>property === propertyName);
        // Only return a value if it is set;
        if (Array.isArray(propertyDescriptor)) {
            return propertyDescriptor[1];
        }
    }
    /**
	 * Returns all style properties names as they would appear when using {@link #toString `#toString()`}.
	 *
	 * When `expand` is set to true and there's a shorthand style property set, it will also return all equivalent styles:
	 *
	 * ```ts
	 * stylesMap.setTo( 'margin: 1em' )
	 * ```
	 *
	 * will be expanded to:
	 *
	 * ```ts
	 * [ 'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ]
	 * ```
	 *
	 * @param expand Expand shorthand style properties and all return equivalent style representations.
	 */ getStyleNames(expand = false) {
        if (this.isEmpty) {
            return [];
        }
        if (expand) {
            return this._styleProcessor.getStyleNames(this._styles);
        }
        const entries = this.getStylesEntries();
        return entries.map(([key])=>key);
    }
    /**
	 * Removes all styles.
	 */ clear() {
        this._styles = {};
    }
    /**
	 * Returns normalized styles entries for further processing.
	 */ getStylesEntries() {
        const parsed = [];
        const keys = Object.keys(this._styles);
        for (const key of keys){
            parsed.push(...this._styleProcessor.getReducedForm(key, this._styles));
        }
        return parsed;
    }
    /**
	 * Removes empty objects upon removing an entry from internal object.
	 */ _cleanEmptyObjectsOnPath(path) {
        const pathParts = path.split('.');
        const isChildPath = pathParts.length > 1;
        if (!isChildPath) {
            return;
        }
        const parentPath = pathParts.splice(0, pathParts.length - 1).join('.');
        const parentObject = get(this._styles, parentPath);
        if (!parentObject) {
            return;
        }
        const isParentEmpty = !Object.keys(parentObject).length;
        if (isParentEmpty) {
            this.remove(parentPath);
        }
    }
}
/**
 * Style processor is responsible for writing and reading a normalized styles object.
 */ class StylesProcessor {
    _normalizers;
    _extractors;
    _reducers;
    _consumables;
    /**
	 * Creates StylesProcessor instance.
	 *
	 * @internal
	 */ constructor(){
        this._normalizers = new Map();
        this._extractors = new Map();
        this._reducers = new Map();
        this._consumables = new Map();
    }
    /**
	 * Parse style string value to a normalized object and appends it to styles object.
	 *
	 * ```ts
	 * const styles = {};
	 *
	 * stylesProcessor.toNormalizedForm( 'margin', '1px', styles );
	 *
	 * // styles will consist: { margin: { top: '1px', right: '1px', bottom: '1px', left: '1px; } }
	 * ```
	 *
	 * **Note**: To define normalizer callbacks use {@link #setNormalizer}.
	 *
	 * @param name Name of style property.
	 * @param propertyValue Value of style property.
	 * @param styles Object holding normalized styles.
	 */ toNormalizedForm(name, propertyValue, styles) {
        if (isObject(propertyValue)) {
            appendStyleValue(styles, toPath(name), propertyValue);
            return;
        }
        if (this._normalizers.has(name)) {
            const normalizer = this._normalizers.get(name);
            const { path, value } = normalizer(propertyValue);
            appendStyleValue(styles, path, value);
        } else {
            appendStyleValue(styles, name, propertyValue);
        }
    }
    /**
	 * Returns a normalized version of a style property.
	 *
	 * ```ts
	 * const styles = {
	 * 	margin: { top: '1px', right: '1px', bottom: '1px', left: '1px; },
	 * 	background: { color: '#f00' }
	 * };
	 *
	 * stylesProcessor.getNormalized( 'background' );
	 * // will return: { color: '#f00' }
	 *
	 * stylesProcessor.getNormalized( 'margin-top' );
	 * // will return: '1px'
	 * ```
	 *
	 * **Note**: In some cases extracting single value requires defining an extractor callback {@link #setExtractor}.
	 *
	 * @param name Name of style property.
	 * @param styles Object holding normalized styles.
	 */ getNormalized(name, styles) {
        if (!name) {
            return merge({}, styles);
        }
        // Might be empty string.
        if (styles[name] !== undefined) {
            return styles[name];
        }
        if (this._extractors.has(name)) {
            const extractor = this._extractors.get(name);
            if (typeof extractor === 'string') {
                return get(styles, extractor);
            }
            const value = extractor(name, styles);
            if (value) {
                return value;
            }
        }
        return get(styles, toPath(name));
    }
    /**
	 * Returns a reduced form of style property form normalized object.
	 *
	 * For default margin reducer, the below code:
	 *
	 * ```ts
	 * stylesProcessor.getReducedForm( 'margin', {
	 * 	margin: { top: '1px', right: '1px', bottom: '2px', left: '1px; }
	 * } );
	 * ```
	 *
	 * will return:
	 *
	 * ```ts
	 * [
	 * 	[ 'margin', '1px 1px 2px' ]
	 * ]
	 * ```
	 *
	 * because it might be represented as a shorthand 'margin' value. However if one of margin long hand values is missing it should return:
	 *
	 * ```ts
	 * [
	 * 	[ 'margin-top', '1px' ],
	 * 	[ 'margin-right', '1px' ],
	 * 	[ 'margin-bottom', '2px' ]
	 * 	// the 'left' value is missing - cannot use 'margin' shorthand.
	 * ]
	 * ```
	 *
	 * **Note**: To define reducer callbacks use {@link #setReducer}.
	 *
	 * @param name Name of style property.
	 */ getReducedForm(name, styles) {
        const normalizedValue = this.getNormalized(name, styles);
        // Might be empty string.
        if (normalizedValue === undefined) {
            return [];
        }
        if (this._reducers.has(name)) {
            const reducer = this._reducers.get(name);
            return reducer(normalizedValue);
        }
        return [
            [
                name,
                normalizedValue
            ]
        ];
    }
    /**
	 * Return all style properties. Also expand shorthand properties (e.g. `margin`, `background`) if respective extractor is available.
	 *
	 * @param styles Object holding normalized styles.
	 */ getStyleNames(styles) {
        // Find all extractable styles that have a value.
        const expandedStyleNames = Array.from(this._consumables.keys()).filter((name)=>{
            const style = this.getNormalized(name, styles);
            if (style && typeof style == 'object') {
                return Object.keys(style).length;
            }
            return style;
        });
        // For simple styles (for example `color`) we don't have a map of those styles
        // but they are 1 to 1 with normalized object keys.
        const styleNamesKeysSet = new Set([
            ...expandedStyleNames,
            ...Object.keys(styles)
        ]);
        return Array.from(styleNamesKeysSet);
    }
    /**
	 * Returns related style names.
	 *
	 * ```ts
	 * stylesProcessor.getRelatedStyles( 'margin' );
	 * // will return: [ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ];
	 *
	 * stylesProcessor.getRelatedStyles( 'margin-top' );
	 * // will return: [ 'margin' ];
	 * ```
	 *
	 * **Note**: To define new style relations load an existing style processor or use
	 * {@link module:engine/view/stylesmap~StylesProcessor#setStyleRelation `StylesProcessor.setStyleRelation()`}.
	 */ getRelatedStyles(name) {
        return this._consumables.get(name) || [];
    }
    /**
	 * Adds a normalizer method for a style property.
	 *
	 * A normalizer returns describing how the value should be normalized.
	 *
	 * For instance 'margin' style is a shorthand for four margin values:
	 *
	 * - 'margin-top'
	 * - 'margin-right'
	 * - 'margin-bottom'
	 * - 'margin-left'
	 *
	 * and can be written in various ways if some values are equal to others. For instance `'margin: 1px 2em;'` is a shorthand for
	 * `'margin-top: 1px;margin-right: 2em;margin-bottom: 1px;margin-left: 2em'`.
	 *
	 * A normalizer should parse various margin notations as a single object:
	 *
	 * ```ts
	 * const styles = {
	 * 	margin: {
	 * 		top: '1px',
	 * 		right: '2em',
	 * 		bottom: '1px',
	 * 		left: '2em'
	 * 	}
	 * };
	 * ```
	 *
	 * Thus a normalizer for 'margin' style should return an object defining style path and value to store:
	 *
	 * ```ts
	 * const returnValue = {
	 * 	path: 'margin',
	 * 	value: {
	 * 		top: '1px',
	 * 		right: '2em',
	 * 		bottom: '1px',
	 * 		left: '2em'
	 * 	}
	 * };
	 * ```
	 *
	 * Additionally to fully support all margin notations there should be also defined 4 normalizers for longhand margin notations. Below
	 * is an example for 'margin-top' style property normalizer:
	 *
	 * ```ts
	 * stylesProcessor.setNormalizer( 'margin-top', valueString => {
	 * 	return {
	 * 		path: 'margin.top',
	 * 		value: valueString
	 * 	}
	 * } );
	 * ```
	 */ setNormalizer(name, callback) {
        this._normalizers.set(name, callback);
    }
    /**
	 * Adds a extractor callback for a style property.
	 *
	 * Most normalized style values are stored as one level objects. It is assumed that `'margin-top'` style will be stored as:
	 *
	 * ```ts
	 * const styles = {
	 * 	margin: {
	 * 		top: 'value'
	 * 	}
	 * }
	 * ```
	 *
	 * However, some styles can have conflicting notations and thus it might be harder to extract a style value from shorthand. For instance
	 * the 'border-top-style' can be defined using `'border-top:solid'`, `'border-style:solid none none none'` or by `'border:solid'`
	 * shorthands. The default border styles processors stores styles as:
	 *
	 * ```ts
	 * const styles = {
	 * 	border: {
	 * 		style: {
	 * 			top: 'solid'
	 * 		}
	 * 	}
	 * }
	 * ```
	 *
	 * as it is better to modify border style independently from other values. On the other part the output of the border might be
	 * desired as `border-top`, `border-left`, etc notation.
	 *
	 * In the above example an extractor should return a side border value that combines style, color and width:
	 *
	 * ```ts
	 * styleProcessor.setExtractor( 'border-top', styles => {
	 * 	return {
	 * 		color: styles.border.color.top,
	 * 		style: styles.border.style.top,
	 * 		width: styles.border.width.top
	 * 	}
	 * } );
	 * ```
	 *
	 * @param callbackOrPath Callback that return a requested value or path string for single values.
	 */ setExtractor(name, callbackOrPath) {
        this._extractors.set(name, callbackOrPath);
    }
    /**
	 * Adds a reducer callback for a style property.
	 *
	 * Reducer returns a minimal notation for given style name. For longhand properties it is not required to write a reducer as
	 * by default the direct value from style path is taken.
	 *
	 * For shorthand styles a reducer should return minimal style notation either by returning single name-value tuple or multiple tuples
	 * if a shorthand cannot be used. For instance for a margin shorthand a reducer might return:
	 *
	 * ```ts
	 * const marginShortHandTuple = [
	 * 	[ 'margin', '1px 1px 2px' ]
	 * ];
	 * ```
	 *
	 * or a longhand tuples for defined values:
	 *
	 * ```ts
	 * // Considering margin.bottom and margin.left are undefined.
	 * const marginLonghandsTuples = [
	 * 	[ 'margin-top', '1px' ],
	 * 	[ 'margin-right', '1px' ]
	 * ];
	 * ```
	 *
	 * A reducer obtains a normalized style value:
	 *
	 * ```ts
	 * // Simplified reducer that always outputs 4 values which are always present:
	 * stylesProcessor.setReducer( 'margin', margin => {
	 * 	return [
	 * 		[ 'margin', `${ margin.top } ${ margin.right } ${ margin.bottom } ${ margin.left }` ]
	 * 	]
	 * } );
	 * ```
	 */ setReducer(name, callback) {
        this._reducers.set(name, callback);
    }
    /**
	 * Defines a style shorthand relation to other style notations.
	 *
	 * ```ts
	 * stylesProcessor.setStyleRelation( 'margin', [
	 * 	'margin-top',
	 * 	'margin-right',
	 * 	'margin-bottom',
	 * 	'margin-left'
	 * ] );
	 * ```
	 *
	 * This enables expanding of style names for shorthands. For instance, if defined,
	 * {@link module:engine/conversion/viewconsumable~ViewConsumable view consumable} items are automatically created
	 * for long-hand margin style notation alongside the `'margin'` item.
	 *
	 * This means that when an element being converted has a style `margin`, a converter for `margin-left` will work just
	 * fine since the view consumable will contain a consumable `margin-left` item (thanks to the relation) and
	 * `element.getStyle( 'margin-left' )` will work as well assuming that the style processor was correctly configured.
	 * However, once `margin-left` is consumed, `margin` will not be consumable anymore.
	 */ setStyleRelation(shorthandName, styleNames) {
        this._mapStyleNames(shorthandName, styleNames);
        for (const alsoName of styleNames){
            this._mapStyleNames(alsoName, [
                shorthandName
            ]);
        }
    }
    /**
	 * Set two-way binding of style names.
	 */ _mapStyleNames(name, styleNames) {
        if (!this._consumables.has(name)) {
            this._consumables.set(name, []);
        }
        this._consumables.get(name).push(...styleNames);
    }
}
/**
 * Parses inline styles and puts property - value pairs into styles map.
 *
 * @param stylesString Styles to parse.
 * @returns Map of parsed properties and values.
 */ function parseInlineStyles(stylesString) {
    // `null` if no quote was found in input string or last found quote was a closing quote. See below.
    let quoteType = null;
    let propertyNameStart = 0;
    let propertyValueStart = 0;
    let propertyName = null;
    const stylesMap = new Map();
    // Do not set anything if input string is empty.
    if (stylesString === '') {
        return stylesMap;
    }
    // Fix inline styles that do not end with `;` so they are compatible with algorithm below.
    if (stylesString.charAt(stylesString.length - 1) != ';') {
        stylesString = stylesString + ';';
    }
    // Seek the whole string for "special characters".
    for(let i = 0; i < stylesString.length; i++){
        const char = stylesString.charAt(i);
        if (quoteType === null) {
            // No quote found yet or last found quote was a closing quote.
            switch(char){
                case ':':
                    // Most of time colon means that property name just ended.
                    // Sometimes however `:` is found inside property value (for example in background image url).
                    if (!propertyName) {
                        // Treat this as end of property only if property name is not already saved.
                        // Save property name.
                        propertyName = stylesString.substr(propertyNameStart, i - propertyNameStart);
                        // Save this point as the start of property value.
                        propertyValueStart = i + 1;
                    }
                    break;
                case '"':
                case '\'':
                    // Opening quote found (this is an opening quote, because `quoteType` is `null`).
                    quoteType = char;
                    break;
                case ';':
                    {
                        // Property value just ended.
                        // Use previously stored property value start to obtain property value.
                        const propertyValue = stylesString.substr(propertyValueStart, i - propertyValueStart);
                        if (propertyName) {
                            // Save parsed part.
                            stylesMap.set(propertyName.trim(), propertyValue.trim());
                        }
                        propertyName = null;
                        // Save this point as property name start. Property name starts immediately after previous property value ends.
                        propertyNameStart = i + 1;
                        break;
                    }
            }
        } else if (char === quoteType) {
            // If a quote char is found and it is a closing quote, mark this fact by `null`-ing `quoteType`.
            quoteType = null;
        }
    }
    return stylesMap;
}
/**
 * Return lodash compatible path from style name.
 */ function toPath(name) {
    return name.replace('-', '.');
}
/**
 * Appends style definition to the styles object.
 */ function appendStyleValue(stylesObject, nameOrPath, valueOrObject) {
    let valueToSet = valueOrObject;
    if (isObject(valueOrObject)) {
        valueToSet = merge({}, get(stylesObject, nameOrPath), valueOrObject);
    }
    set(stylesObject, nameOrPath, valueToSet);
}

// @if CK_DEBUG_ENGINE // const { convertMapToTags } = require( '../dev-utils/utils' );
/**
 * View element.
 *
 * The editing engine does not define a fixed semantics of its elements (it is "DTD-free").
 * This is why the type of the {@link module:engine/view/element~Element} need to
 * be defined by the feature developer. When creating an element you should use one of the following methods:
 *
 * * {@link module:engine/view/downcastwriter~DowncastWriter#createContainerElement `downcastWriter#createContainerElement()`}
 * in order to create a {@link module:engine/view/containerelement~ContainerElement},
 * * {@link module:engine/view/downcastwriter~DowncastWriter#createAttributeElement `downcastWriter#createAttributeElement()`}
 * in order to create a {@link module:engine/view/attributeelement~AttributeElement},
 * * {@link module:engine/view/downcastwriter~DowncastWriter#createEmptyElement `downcastWriter#createEmptyElement()`}
 * in order to create a {@link module:engine/view/emptyelement~EmptyElement}.
 * * {@link module:engine/view/downcastwriter~DowncastWriter#createUIElement `downcastWriter#createUIElement()`}
 * in order to create a {@link module:engine/view/uielement~UIElement}.
 * * {@link module:engine/view/downcastwriter~DowncastWriter#createEditableElement `downcastWriter#createEditableElement()`}
 * in order to create a {@link module:engine/view/editableelement~EditableElement}.
 *
 * Note that for view elements which are not created from the model, like elements from mutations, paste or
 * {@link module:engine/controller/datacontroller~DataController#set data.set} it is not possible to define the type of the element.
 * In such cases the {@link module:engine/view/upcastwriter~UpcastWriter#createElement `UpcastWriter#createElement()`} method
 * should be used to create generic view elements.
 */ let Element$1 = class Element extends Node$2 {
    /**
	 * Name of the element.
	 */ name;
    /**
	 * A list of attribute names that should be rendered in the editing pipeline even though filtering mechanisms
	 * implemented in the {@link module:engine/view/domconverter~DomConverter} (for instance,
	 * {@link module:engine/view/domconverter~DomConverter#shouldRenderAttribute}) would filter them out.
	 *
	 * These attributes can be specified as an option when the element is created by
	 * the {@link module:engine/view/downcastwriter~DowncastWriter}. To check whether an unsafe an attribute should
	 * be permitted, use the {@link #shouldRenderUnsafeAttribute} method.
	 *
	 * @internal
	 */ _unsafeAttributesToRender = [];
    /**
	 * Map of attributes, where attributes names are keys and attributes values are values.
	 */ _attrs;
    /**
	 * Array of child nodes.
	 */ _children;
    /**
	 * Set of classes associated with element instance.
	 */ _classes;
    /**
	 * Normalized styles.
	 */ _styles;
    /**
	 * Map of custom properties.
	 * Custom properties can be added to element instance, will be cloned but not rendered into DOM.
	 */ _customProperties = new Map();
    /**
	 * Creates a view element.
	 *
	 * Attributes can be passed in various formats:
	 *
	 * ```ts
	 * new Element( viewDocument, 'div', { class: 'editor', contentEditable: 'true' } ); // object
	 * new Element( viewDocument, 'div', [ [ 'class', 'editor' ], [ 'contentEditable', 'true' ] ] ); // map-like iterator
	 * new Element( viewDocument, 'div', mapOfAttributes ); // map
	 * ```
	 *
	 * @internal
	 * @param document The document instance to which this element belongs.
	 * @param name Node name.
	 * @param attrs Collection of attributes.
	 * @param children A list of nodes to be inserted into created element.
	 */ constructor(document, name, attrs, children){
        super(document);
        this.name = name;
        this._attrs = parseAttributes(attrs);
        this._children = [];
        if (children) {
            this._insertChild(0, children);
        }
        this._classes = new Set();
        if (this._attrs.has('class')) {
            // Remove class attribute and handle it by class set.
            const classString = this._attrs.get('class');
            parseClasses(this._classes, classString);
            this._attrs.delete('class');
        }
        this._styles = new StylesMap(this.document.stylesProcessor);
        if (this._attrs.has('style')) {
            // Remove style attribute and handle it by styles map.
            this._styles.setTo(this._attrs.get('style'));
            this._attrs.delete('style');
        }
    }
    /**
	 * Number of element's children.
	 */ get childCount() {
        return this._children.length;
    }
    /**
	 * Is `true` if there are no nodes inside this element, `false` otherwise.
	 */ get isEmpty() {
        return this._children.length === 0;
    }
    /**
	 * Gets child at the given index.
	 *
	 * @param index Index of child.
	 * @returns Child node.
	 */ getChild(index) {
        return this._children[index];
    }
    /**
	 * Gets index of the given child node. Returns `-1` if child node is not found.
	 *
	 * @param node Child node.
	 * @returns Index of the child node.
	 */ getChildIndex(node) {
        return this._children.indexOf(node);
    }
    /**
	 * Gets child nodes iterator.
	 *
	 * @returns Child nodes iterator.
	 */ getChildren() {
        return this._children[Symbol.iterator]();
    }
    /**
	 * Returns an iterator that contains the keys for attributes. Order of inserting attributes is not preserved.
	 *
	 * @returns Keys for attributes.
	 */ *getAttributeKeys() {
        if (this._classes.size > 0) {
            yield 'class';
        }
        if (!this._styles.isEmpty) {
            yield 'style';
        }
        yield* this._attrs.keys();
    }
    /**
	 * Returns iterator that iterates over this element's attributes.
	 *
	 * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
	 * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
	 */ *getAttributes() {
        yield* this._attrs.entries();
        if (this._classes.size > 0) {
            yield [
                'class',
                this.getAttribute('class')
            ];
        }
        if (!this._styles.isEmpty) {
            yield [
                'style',
                this.getAttribute('style')
            ];
        }
    }
    /**
	 * Gets attribute by key. If attribute is not present - returns undefined.
	 *
	 * @param key Attribute key.
	 * @returns Attribute value.
	 */ getAttribute(key) {
        if (key == 'class') {
            if (this._classes.size > 0) {
                return [
                    ...this._classes
                ].join(' ');
            }
            return undefined;
        }
        if (key == 'style') {
            const inlineStyle = this._styles.toString();
            return inlineStyle == '' ? undefined : inlineStyle;
        }
        return this._attrs.get(key);
    }
    /**
	 * Returns a boolean indicating whether an attribute with the specified key exists in the element.
	 *
	 * @param key Attribute key.
	 * @returns `true` if attribute with the specified key exists in the element, `false` otherwise.
	 */ hasAttribute(key) {
        if (key == 'class') {
            return this._classes.size > 0;
        }
        if (key == 'style') {
            return !this._styles.isEmpty;
        }
        return this._attrs.has(key);
    }
    /**
	 * Checks if this element is similar to other element.
	 * Both elements should have the same name and attributes to be considered as similar. Two similar elements
	 * can contain different set of children nodes.
	 */ isSimilar(otherElement) {
        if (!(otherElement instanceof Element)) {
            return false;
        }
        // If exactly the same Element is provided - return true immediately.
        if (this === otherElement) {
            return true;
        }
        // Check element name.
        if (this.name != otherElement.name) {
            return false;
        }
        // Check number of attributes, classes and styles.
        if (this._attrs.size !== otherElement._attrs.size || this._classes.size !== otherElement._classes.size || this._styles.size !== otherElement._styles.size) {
            return false;
        }
        // Check if attributes are the same.
        for (const [key, value] of this._attrs){
            if (!otherElement._attrs.has(key) || otherElement._attrs.get(key) !== value) {
                return false;
            }
        }
        // Check if classes are the same.
        for (const className of this._classes){
            if (!otherElement._classes.has(className)) {
                return false;
            }
        }
        // Check if styles are the same.
        for (const property of this._styles.getStyleNames()){
            if (!otherElement._styles.has(property) || otherElement._styles.getAsString(property) !== this._styles.getAsString(property)) {
                return false;
            }
        }
        return true;
    }
    /**
	 * Returns true if class is present.
	 * If more then one class is provided - returns true only when all classes are present.
	 *
	 * ```ts
	 * element.hasClass( 'foo' ); // Returns true if 'foo' class is present.
	 * element.hasClass( 'foo', 'bar' ); // Returns true if 'foo' and 'bar' classes are both present.
	 * ```
	 */ hasClass(...className) {
        for (const name of className){
            if (!this._classes.has(name)) {
                return false;
            }
        }
        return true;
    }
    /**
	 * Returns iterator that contains all class names.
	 */ getClassNames() {
        return this._classes.keys();
    }
    /**
	 * Returns style value for the given property mae.
	 * If the style does not exist `undefined` is returned.
	 *
	 * **Note**: This method can work with normalized style names if
	 * {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules a particular style processor rule is enabled}.
	 * See {@link module:engine/view/stylesmap~StylesMap#getAsString `StylesMap#getAsString()`} for details.
	 *
	 * For an element with style set to `'margin:1px'`:
	 *
	 * ```ts
	 * // Enable 'margin' shorthand processing:
	 * editor.data.addStyleProcessorRules( addMarginRules );
	 *
	 * const element = view.change( writer => {
	 * 	const element = writer.createElement();
	 * 	writer.setStyle( 'margin', '1px' );
	 * 	writer.setStyle( 'margin-bottom', '3em' );
	 *
	 * 	return element;
	 * } );
	 *
	 * element.getStyle( 'margin' ); // -> 'margin: 1px 1px 3em;'
	 * ```
	 */ getStyle(property) {
        return this._styles.getAsString(property);
    }
    /**
	 * Returns a normalized style object or single style value.
	 *
	 * For an element with style set to: margin:1px 2px 3em;
	 *
	 * ```ts
	 * element.getNormalizedStyle( 'margin' ) );
	 * ```
	 *
	 * will return:
	 *
	 * ```ts
	 * {
	 * 	top: '1px',
	 * 	right: '2px',
	 * 	bottom: '3em',
	 * 	left: '2px'    // a normalized value from margin shorthand
	 * }
	 * ```
	 *
	 * and reading for single style value:
	 *
	 * ```ts
	 * styles.getNormalizedStyle( 'margin-left' );
	 * ```
	 *
	 * Will return a `2px` string.
	 *
	 * **Note**: This method will return normalized values only if
	 * {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules a particular style processor rule is enabled}.
	 * See {@link module:engine/view/stylesmap~StylesMap#getNormalized `StylesMap#getNormalized()`} for details.
	 *
	 * @param property Name of CSS property
	 */ getNormalizedStyle(property) {
        return this._styles.getNormalized(property);
    }
    /**
	 * Returns iterator that contains all style names.
	 *
	 * @param expand Expand shorthand style properties and return all equivalent style representations.
	 */ getStyleNames(expand) {
        return this._styles.getStyleNames(expand);
    }
    /**
	 * Returns true if style keys are present.
	 * If more then one style property is provided - returns true only when all properties are present.
	 *
	 * ```ts
	 * element.hasStyle( 'color' ); // Returns true if 'border-top' style is present.
	 * element.hasStyle( 'color', 'border-top' ); // Returns true if 'color' and 'border-top' styles are both present.
	 * ```
	 */ hasStyle(...property) {
        for (const name of property){
            if (!this._styles.has(name)) {
                return false;
            }
        }
        return true;
    }
    /**
	 * Returns ancestor element that match specified pattern.
	 * Provided patterns should be compatible with {@link module:engine/view/matcher~Matcher Matcher} as it is used internally.
	 *
	 * @see module:engine/view/matcher~Matcher
	 * @param patterns Patterns used to match correct ancestor. See {@link module:engine/view/matcher~Matcher}.
	 * @returns Found element or `null` if no matching ancestor was found.
	 */ findAncestor(...patterns) {
        const matcher = new Matcher(...patterns);
        let parent = this.parent;
        while(parent && !parent.is('documentFragment')){
            if (matcher.match(parent)) {
                return parent;
            }
            parent = parent.parent;
        }
        return null;
    }
    /**
	 * Returns the custom property value for the given key.
	 */ getCustomProperty(key) {
        return this._customProperties.get(key);
    }
    /**
	 * Returns an iterator which iterates over this element's custom properties.
	 * Iterator provides `[ key, value ]` pairs for each stored property.
	 */ *getCustomProperties() {
        yield* this._customProperties.entries();
    }
    /**
	 * Returns identity string based on element's name, styles, classes and other attributes.
	 * Two elements that {@link #isSimilar are similar} will have same identity string.
	 * It has the following format:
	 *
	 * ```ts
	 * 'name class="class1,class2" style="style1:value1;style2:value2" attr1="val1" attr2="val2"'
	 * ```
 	 *
	 * For example:
	 *
	 * ```ts
	 * const element = writer.createContainerElement( 'foo', {
	 * 	banana: '10',
	 * 	apple: '20',
	 * 	style: 'color: red; border-color: white;',
	 * 	class: 'baz'
	 * } );
	 *
	 * // returns 'foo class="baz" style="border-color:white;color:red" apple="20" banana="10"'
	 * element.getIdentity();
	 * ```
	 *
	 * **Note**: Classes, styles and other attributes are sorted alphabetically.
	 */ getIdentity() {
        const classes = Array.from(this._classes).sort().join(',');
        const styles = this._styles.toString();
        const attributes = Array.from(this._attrs).map((i)=>`${i[0]}="${i[1]}"`).sort().join(' ');
        return this.name + (classes == '' ? '' : ` class="${classes}"`) + (!styles ? '' : ` style="${styles}"`) + (attributes == '' ? '' : ` ${attributes}`);
    }
    /**
	 * Decides whether an unsafe attribute is whitelisted and should be rendered in the editing pipeline even though filtering mechanisms
	 * like {@link module:engine/view/domconverter~DomConverter#shouldRenderAttribute} say it should not.
	 *
	 * Unsafe attribute names can be specified when creating an element via {@link module:engine/view/downcastwriter~DowncastWriter}.
	 *
	 * @param attributeName The name of the attribute to be checked.
	 */ shouldRenderUnsafeAttribute(attributeName) {
        return this._unsafeAttributesToRender.includes(attributeName);
    }
    /**
	 * Clones provided element.
	 *
	 * @internal
	 * @param deep If set to `true` clones element and all its children recursively. When set to `false`,
	 * element will be cloned without any children.
	 * @returns Clone of this element.
	 */ _clone(deep = false) {
        const childrenClone = [];
        if (deep) {
            for (const child of this.getChildren()){
                childrenClone.push(child._clone(deep));
            }
        }
        // ContainerElement and AttributeElement should be also cloned properly.
        const cloned = new this.constructor(this.document, this.name, this._attrs, childrenClone);
        // Classes and styles are cloned separately - this solution is faster than adding them back to attributes and
        // parse once again in constructor.
        cloned._classes = new Set(this._classes);
        cloned._styles.set(this._styles.getNormalized());
        // Clone custom properties.
        cloned._customProperties = new Map(this._customProperties);
        // Clone filler offset method.
        // We can't define this method in a prototype because it's behavior which
        // is changed by e.g. toWidget() function from ckeditor5-widget. Perhaps this should be one of custom props.
        cloned.getFillerOffset = this.getFillerOffset;
        // Clone unsafe attributes list.
        cloned._unsafeAttributesToRender = this._unsafeAttributesToRender;
        return cloned;
    }
    /**
	 * {@link module:engine/view/element~Element#_insertChild Insert} a child node or a list of child nodes at the end of this node
	 * and sets the parent of these nodes to this element.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#insert
	 * @internal
	 * @param items Items to be inserted.
	 * @fires change
	 * @returns Number of appended nodes.
	 */ _appendChild(items) {
        return this._insertChild(this.childCount, items);
    }
    /**
	 * Inserts a child node or a list of child nodes on the given index and sets the parent of these nodes to
	 * this element.
	 *
	 * @internal
	 * @see module:engine/view/downcastwriter~DowncastWriter#insert
	 * @param index Position where nodes should be inserted.
	 * @param items Items to be inserted.
	 * @fires change
	 * @returns Number of inserted nodes.
	 */ _insertChild(index, items) {
        this._fireChange('children', this);
        let count = 0;
        const nodes = normalize$3(this.document, items);
        for (const node of nodes){
            // If node that is being added to this element is already inside another element, first remove it from the old parent.
            if (node.parent !== null) {
                node._remove();
            }
            node.parent = this;
            node.document = this.document;
            this._children.splice(index, 0, node);
            index++;
            count++;
        }
        return count;
    }
    /**
	 * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#remove
	 * @internal
	 * @param index Number of the first node to remove.
	 * @param howMany Number of nodes to remove.
	 * @fires change
	 * @returns The array of removed nodes.
	 */ _removeChildren(index, howMany = 1) {
        this._fireChange('children', this);
        for(let i = index; i < index + howMany; i++){
            this._children[i].parent = null;
        }
        return this._children.splice(index, howMany);
    }
    /**
	 * Adds or overwrite attribute with a specified key and value.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#setAttribute
	 * @internal
	 * @param key Attribute key.
	 * @param value Attribute value.
	 * @fires change
	 */ _setAttribute(key, value) {
        const stringValue = String(value);
        this._fireChange('attributes', this);
        if (key == 'class') {
            parseClasses(this._classes, stringValue);
        } else if (key == 'style') {
            this._styles.setTo(stringValue);
        } else {
            this._attrs.set(key, stringValue);
        }
    }
    /**
	 * Removes attribute from the element.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#removeAttribute
	 * @internal
	 * @param key Attribute key.
	 * @returns Returns true if an attribute existed and has been removed.
	 * @fires change
	 */ _removeAttribute(key) {
        this._fireChange('attributes', this);
        // Remove class attribute.
        if (key == 'class') {
            if (this._classes.size > 0) {
                this._classes.clear();
                return true;
            }
            return false;
        }
        // Remove style attribute.
        if (key == 'style') {
            if (!this._styles.isEmpty) {
                this._styles.clear();
                return true;
            }
            return false;
        }
        // Remove other attributes.
        return this._attrs.delete(key);
    }
    /**
	 * Adds specified class.
	 *
	 * ```ts
	 * element._addClass( 'foo' ); // Adds 'foo' class.
	 * element._addClass( [ 'foo', 'bar' ] ); // Adds 'foo' and 'bar' classes.
	 * ```
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#addClass
	 * @internal
	 * @fires change
	 */ _addClass(className) {
        this._fireChange('attributes', this);
        for (const name of toArray(className)){
            this._classes.add(name);
        }
    }
    /**
	 * Removes specified class.
	 *
	 * ```ts
	 * element._removeClass( 'foo' );  // Removes 'foo' class.
	 * element._removeClass( [ 'foo', 'bar' ] ); // Removes both 'foo' and 'bar' classes.
	 * ```
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#removeClass
	 * @internal
	 * @fires change
	 */ _removeClass(className) {
        this._fireChange('attributes', this);
        for (const name of toArray(className)){
            this._classes.delete(name);
        }
    }
    _setStyle(property, value) {
        this._fireChange('attributes', this);
        if (typeof property != 'string') {
            this._styles.set(property);
        } else {
            this._styles.set(property, value);
        }
    }
    /**
	 * Removes specified style.
	 *
	 * ```ts
	 * element._removeStyle( 'color' );  // Removes 'color' style.
	 * element._removeStyle( [ 'color', 'border-top' ] ); // Removes both 'color' and 'border-top' styles.
	 * ```
	 *
	 * **Note**: This method can work with normalized style names if
	 * {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules a particular style processor rule is enabled}.
	 * See {@link module:engine/view/stylesmap~StylesMap#remove `StylesMap#remove()`} for details.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#removeStyle
	 * @internal
	 * @fires change
	 */ _removeStyle(property) {
        this._fireChange('attributes', this);
        for (const name of toArray(property)){
            this._styles.remove(name);
        }
    }
    /**
	 * Sets a custom property. Unlike attributes, custom properties are not rendered to the DOM,
	 * so they can be used to add special data to elements.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#setCustomProperty
	 * @internal
	 */ _setCustomProperty(key, value) {
        this._customProperties.set(key, value);
    }
    /**
	 * Removes the custom property stored under the given key.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#removeCustomProperty
	 * @internal
	 * @returns Returns true if property was removed.
	 */ _removeCustomProperty(key) {
        return this._customProperties.delete(key);
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Element$1.prototype.is = function(type, name) {
    if (!name) {
        return type === 'element' || type === 'view:element' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'node' || type === 'view:node';
    } else {
        return name === this.name && (type === 'element' || type === 'view:element');
    }
};
/**
 * Parses attributes provided to the element constructor before they are applied to an element. If attributes are passed
 * as an object (instead of `Iterable`), the object is transformed to the map. Attributes with `null` value are removed.
 * Attributes with non-`String` value are converted to `String`.
 *
 * @param attrs Attributes to parse.
 * @returns Parsed attributes.
 */ function parseAttributes(attrs) {
    const attrsMap = toMap(attrs);
    for (const [key, value] of attrsMap){
        if (value === null) {
            attrsMap.delete(key);
        } else if (typeof value != 'string') {
            attrsMap.set(key, String(value));
        }
    }
    return attrsMap;
}
/**
 * Parses class attribute and puts all classes into classes set.
 * Classes set s cleared before insertion.
 *
 * @param classesSet Set to insert parsed classes.
 * @param classesString String with classes to parse.
 */ function parseClasses(classesSet, classesString) {
    const classArray = classesString.split(/\s+/);
    classesSet.clear();
    classArray.forEach((name)=>classesSet.add(name));
}
/**
 * Converts strings to Text and non-iterables to arrays.
 */ function normalize$3(document, nodes) {
    // Separate condition because string is iterable.
    if (typeof nodes == 'string') {
        return [
            new Text$1(document, nodes)
        ];
    }
    if (!isIterable(nodes)) {
        nodes = [
            nodes
        ];
    }
    // Array.from to enable .map() on non-arrays.
    return Array.from(nodes).map((node)=>{
        if (typeof node == 'string') {
            return new Text$1(document, node);
        }
        if (node instanceof TextProxy$1) {
            return new Text$1(document, node.data);
        }
        return node;
    });
}

/**
 * Containers are elements which define document structure. They define boundaries for
 * {@link module:engine/view/attributeelement~AttributeElement attributes}. They are mostly used for block elements like `<p>` or `<div>`.
 *
 * Editing engine does not define a fixed HTML DTD. This is why a feature developer needs to choose between various
 * types (container element, {@link module:engine/view/attributeelement~AttributeElement attribute element},
 * {@link module:engine/view/emptyelement~EmptyElement empty element}, etc) when developing a feature.
 *
 * The container element should be your default choice when writing a converter, unless:
 *
 * * this element represents a model text attribute (then use {@link module:engine/view/attributeelement~AttributeElement}),
 * * this is an empty element like `<img>` (then use {@link module:engine/view/emptyelement~EmptyElement}),
 * * this is a root element,
 * * this is a nested editable element (then use  {@link module:engine/view/editableelement~EditableElement}).
 *
 * To create a new container element instance use the
 * {@link module:engine/view/downcastwriter~DowncastWriter#createContainerElement `DowncastWriter#createContainerElement()`}
 * method.
 */ class ContainerElement extends Element$1 {
    /**
	 * Creates a container element.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#createContainerElement
	 * @see module:engine/view/element~Element
	 * @internal
	 * @param document The document instance to which this element belongs.
	 * @param name Node name.
	 * @param attrs Collection of attributes.
	 * @param children A list of nodes to be inserted into created element.
	 */ constructor(document, name, attrs, children){
        super(document, name, attrs, children);
        this.getFillerOffset = getFillerOffset$4;
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
ContainerElement.prototype.is = function(type, name) {
    if (!name) {
        return type === 'containerElement' || type === 'view:containerElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'element' || type === 'view:element' || type === 'node' || type === 'view:node';
    } else {
        return name === this.name && (type === 'containerElement' || type === 'view:containerElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'element' || type === 'view:element');
    }
};
/**
 * Returns block {@link module:engine/view/filler filler} offset or `null` if block filler is not needed.
 *
 * @returns Block filler offset or `null` if block filler is not needed.
 */ function getFillerOffset$4() {
    const children = [
        ...this.getChildren()
    ];
    const lastChild = children[this.childCount - 1];
    // Block filler is required after a `<br>` if it's the last element in its container. See #1422.
    if (lastChild && lastChild.is('element', 'br')) {
        return this.childCount;
    }
    for (const child of children){
        // If there's any non-UI element – don't render the bogus.
        if (!child.is('uiElement')) {
            return null;
        }
    }
    // If there are only UI elements – render the bogus at the end of the element.
    return this.childCount;
}

/**
 * Editable element which can be a {@link module:engine/view/rooteditableelement~RootEditableElement root}
 * or nested editable area in the editor.
 *
 * Editable is automatically read-only when its {@link module:engine/view/document~Document Document} is read-only.
 *
 * The constructor of this class shouldn't be used directly. To create new `EditableElement` use the
 * {@link module:engine/view/downcastwriter~DowncastWriter#createEditableElement `downcastWriter#createEditableElement()`} method.
 */ class EditableElement extends /* #__PURE__ */ ObservableMixin(ContainerElement) {
    /**
	 * Creates an editable element.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#createEditableElement
	 * @internal
	 * @param document The document instance to which this element belongs.
	 * @param name Node name.
	 * @param attrs Collection of attributes.
	 * @param children A list of nodes to be inserted into created element.
	 */ constructor(document, name, attributes, children){
        super(document, name, attributes, children);
        this.set('isReadOnly', false);
        this.set('isFocused', false);
        this.set('placeholder', undefined);
        this.bind('isReadOnly').to(document);
        this.bind('isFocused').to(document, 'isFocused', (isFocused)=>isFocused && document.selection.editableElement == this);
        // Update focus state based on selection changes.
        this.listenTo(document.selection, 'change', ()=>{
            this.isFocused = document.isFocused && document.selection.editableElement == this;
        });
    }
    destroy() {
        this.stopListening();
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
EditableElement.prototype.is = function(type, name) {
    if (!name) {
        return type === 'editableElement' || type === 'view:editableElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'containerElement' || type === 'view:containerElement' || type === 'element' || type === 'view:element' || type === 'node' || type === 'view:node';
    } else {
        return name === this.name && (type === 'editableElement' || type === 'view:editableElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'containerElement' || type === 'view:containerElement' || type === 'element' || type === 'view:element');
    }
};

const rootNameSymbol = Symbol('rootName');
/**
 * Class representing a single root in the data view. A root can be either {@link ~RootEditableElement#isReadOnly editable or read-only},
 * but in both cases it is called "an editable". Roots can contain other {@link module:engine/view/editableelement~EditableElement
 * editable elements} making them "nested editables".
 */ class RootEditableElement extends EditableElement {
    /**
	 * Creates root editable element.
	 *
	 * @param document The document instance to which this element belongs.
	 * @param name Node name.
	 */ constructor(document, name){
        super(document, name);
        this.rootName = 'main';
    }
    /**
	 * Name of this root inside {@link module:engine/view/document~Document} that is an owner of this root. If no
	 * other name is set, `main` name is used.
	 *
	 * @readonly
	 */ get rootName() {
        return this.getCustomProperty(rootNameSymbol);
    }
    set rootName(rootName) {
        this._setCustomProperty(rootNameSymbol, rootName);
    }
    /**
	 * Overrides old element name and sets new one.
	 * This is needed because view roots are created before they are attached to the DOM.
	 * The name of the root element is temporary at this stage. It has to be changed when the
	 * view root element is attached to the DOM element.
	 *
	 * @internal
	 * @param name The new name of element.
	 */ set _name(name) {
        this.name = name;
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
RootEditableElement.prototype.is = function(type, name) {
    if (!name) {
        return type === 'rootElement' || type === 'view:rootElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'editableElement' || type === 'view:editableElement' || type === 'containerElement' || type === 'view:containerElement' || type === 'element' || type === 'view:element' || type === 'node' || type === 'view:node';
    } else {
        return name === this.name && (type === 'rootElement' || type === 'view:rootElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'editableElement' || type === 'view:editableElement' || type === 'containerElement' || type === 'view:containerElement' || type === 'element' || type === 'view:element');
    }
};

/**
 * Position iterator class. It allows to iterate forward and backward over the document.
 */ let TreeWalker$1 = class TreeWalker {
    /**
	 * Walking direction. Defaults `'forward'`.
	 */ direction;
    /**
	 * Iterator boundaries.
	 *
	 * When the iterator is walking `'forward'` on the end of boundary or is walking `'backward'`
	 * on the start of boundary, then `{ done: true }` is returned.
	 *
	 * If boundaries are not defined they are set before first and after last child of the root node.
	 */ boundaries;
    /**
	 * Flag indicating whether all characters from {@link module:engine/view/text~Text} should be returned as one
	 * {@link module:engine/view/text~Text} or one by one as {@link module:engine/view/textproxy~TextProxy}.
	 */ singleCharacters;
    /**
	 * Flag indicating whether iterator should enter elements or not. If the iterator is shallow child nodes of any
	 * iterated node will not be returned along with `elementEnd` tag.
	 */ shallow;
    /**
	 * Flag indicating whether iterator should ignore `elementEnd` tags. If set to `true`, walker will not
	 * return a parent node of the start position. Each {@link module:engine/view/element~Element} will be returned once.
	 * When set to `false` each element might be returned twice: for `'elementStart'` and `'elementEnd'`.
	 */ ignoreElementEnd;
    /**
	 * Iterator position. If start position is not defined then position depends on {@link #direction}. If direction is
	 * `'forward'` position starts form the beginning, when direction is `'backward'` position starts from the end.
	 */ _position;
    /**
	 * Start boundary parent.
	 */ _boundaryStartParent;
    /**
	 * End boundary parent.
	 */ _boundaryEndParent;
    /**
	 * Creates a range iterator. All parameters are optional, but you have to specify either `boundaries` or `startPosition`.
	 *
	 * @param options Object with configuration.
	 */ constructor(options = {}){
        if (!options.boundaries && !options.startPosition) {
            /**
			 * Neither boundaries nor starting position have been defined.
			 *
			 * @error view-tree-walker-no-start-position
			 */ throw new CKEditorError('view-tree-walker-no-start-position', null);
        }
        if (options.direction && options.direction != 'forward' && options.direction != 'backward') {
            /**
			 * Only `backward` and `forward` direction allowed.
			 *
			 * @error view-tree-walker-unknown-direction
			 */ throw new CKEditorError('view-tree-walker-unknown-direction', options.startPosition, {
                direction: options.direction
            });
        }
        this.boundaries = options.boundaries || null;
        if (options.startPosition) {
            this._position = Position$1._createAt(options.startPosition);
        } else {
            this._position = Position$1._createAt(options.boundaries[options.direction == 'backward' ? 'end' : 'start']);
        }
        this.direction = options.direction || 'forward';
        this.singleCharacters = !!options.singleCharacters;
        this.shallow = !!options.shallow;
        this.ignoreElementEnd = !!options.ignoreElementEnd;
        this._boundaryStartParent = this.boundaries ? this.boundaries.start.parent : null;
        this._boundaryEndParent = this.boundaries ? this.boundaries.end.parent : null;
    }
    /**
	 * Iterable interface.
	 */ [Symbol.iterator]() {
        return this;
    }
    /**
	 * Iterator position. If start position is not defined then position depends on {@link #direction}. If direction is
	 * `'forward'` position starts form the beginning, when direction is `'backward'` position starts from the end.
	 */ get position() {
        return this._position;
    }
    /**
	 * Moves {@link #position} in the {@link #direction} skipping values as long as the callback function returns `true`.
	 *
	 * For example:
	 *
	 * ```ts
	 * walker.skip( value => value.type == 'text' ); // <p>{}foo</p> -> <p>foo[]</p>
	 * walker.skip( value => true ); // Move the position to the end: <p>{}foo</p> -> <p>foo</p>[]
	 * walker.skip( value => false ); // Do not move the position.
	 * ```
	 *
	 * @param skip Callback function. Gets {@link module:engine/view/treewalker~TreeWalkerValue} and should
	 * return `true` if the value should be skipped or `false` if not.
	 */ skip(skip) {
        let nextResult;
        let prevPosition;
        do {
            prevPosition = this.position;
            nextResult = this.next();
        }while (!nextResult.done && skip(nextResult.value))
        if (!nextResult.done) {
            this._position = prevPosition;
        }
    }
    /**
	 * Gets the next tree walker's value.
	 *
	 * @returns Object implementing iterator interface, returning
	 * information about taken step.
	 */ next() {
        if (this.direction == 'forward') {
            return this._next();
        } else {
            return this._previous();
        }
    }
    /**
	 * Makes a step forward in view. Moves the {@link #position} to the next position and returns the encountered value.
	 */ _next() {
        let position = this.position.clone();
        const previousPosition = this.position;
        const parent = position.parent;
        // We are at the end of the root.
        if (parent.parent === null && position.offset === parent.childCount) {
            return {
                done: true,
                value: undefined
            };
        }
        // We reached the walker boundary.
        if (parent === this._boundaryEndParent && position.offset == this.boundaries.end.offset) {
            return {
                done: true,
                value: undefined
            };
        }
        // Get node just after current position.
        let node;
        // Text is a specific parent because it contains string instead of child nodes.
        if (parent instanceof Text$1) {
            if (position.isAtEnd) {
                // Prevent returning "elementEnd" for Text node. Skip that value and return the next walker step.
                this._position = Position$1._createAfter(parent);
                return this._next();
            }
            node = parent.data[position.offset];
        } else {
            node = parent.getChild(position.offset);
        }
        if (node instanceof Element$1) {
            if (!this.shallow) {
                position = new Position$1(node, 0);
            } else {
                // We are past the walker boundaries.
                if (this.boundaries && this.boundaries.end.isBefore(position)) {
                    return {
                        done: true,
                        value: undefined
                    };
                }
                position.offset++;
            }
            this._position = position;
            return this._formatReturnValue('elementStart', node, previousPosition, position, 1);
        }
        if (node instanceof Text$1) {
            if (this.singleCharacters) {
                position = new Position$1(node, 0);
                this._position = position;
                return this._next();
            }
            let charactersCount = node.data.length;
            let item;
            // If text stick out of walker range, we need to cut it and wrap in TextProxy.
            if (node == this._boundaryEndParent) {
                charactersCount = this.boundaries.end.offset;
                item = new TextProxy$1(node, 0, charactersCount);
                position = Position$1._createAfter(item);
            } else {
                item = new TextProxy$1(node, 0, node.data.length);
                // If not just keep moving forward.
                position.offset++;
            }
            this._position = position;
            return this._formatReturnValue('text', item, previousPosition, position, charactersCount);
        }
        if (typeof node == 'string') {
            let textLength;
            if (this.singleCharacters) {
                textLength = 1;
            } else {
                // Check if text stick out of walker range.
                const endOffset = parent === this._boundaryEndParent ? this.boundaries.end.offset : parent.data.length;
                textLength = endOffset - position.offset;
            }
            const textProxy = new TextProxy$1(parent, position.offset, textLength);
            position.offset += textLength;
            this._position = position;
            return this._formatReturnValue('text', textProxy, previousPosition, position, textLength);
        }
        // `node` is not set, we reached the end of current `parent`.
        position = Position$1._createAfter(parent);
        this._position = position;
        if (this.ignoreElementEnd) {
            return this._next();
        }
        return this._formatReturnValue('elementEnd', parent, previousPosition, position);
    }
    /**
	 * Makes a step backward in view. Moves the {@link #position} to the previous position and returns the encountered value.
	 */ _previous() {
        let position = this.position.clone();
        const previousPosition = this.position;
        const parent = position.parent;
        // We are at the beginning of the root.
        if (parent.parent === null && position.offset === 0) {
            return {
                done: true,
                value: undefined
            };
        }
        // We reached the walker boundary.
        if (parent == this._boundaryStartParent && position.offset == this.boundaries.start.offset) {
            return {
                done: true,
                value: undefined
            };
        }
        // Get node just before current position.
        let node;
        // Text {@link module:engine/view/text~Text} element is a specific parent because contains string instead of child nodes.
        if (parent instanceof Text$1) {
            if (position.isAtStart) {
                // Prevent returning "elementStart" for Text node. Skip that value and return the next walker step.
                this._position = Position$1._createBefore(parent);
                return this._previous();
            }
            node = parent.data[position.offset - 1];
        } else {
            node = parent.getChild(position.offset - 1);
        }
        if (node instanceof Element$1) {
            if (this.shallow) {
                position.offset--;
                this._position = position;
                return this._formatReturnValue('elementStart', node, previousPosition, position, 1);
            }
            position = new Position$1(node, node.childCount);
            this._position = position;
            if (this.ignoreElementEnd) {
                return this._previous();
            }
            return this._formatReturnValue('elementEnd', node, previousPosition, position);
        }
        if (node instanceof Text$1) {
            if (this.singleCharacters) {
                position = new Position$1(node, node.data.length);
                this._position = position;
                return this._previous();
            }
            let charactersCount = node.data.length;
            let item;
            // If text stick out of walker range, we need to cut it and wrap in TextProxy.
            if (node == this._boundaryStartParent) {
                const offset = this.boundaries.start.offset;
                item = new TextProxy$1(node, offset, node.data.length - offset);
                charactersCount = item.data.length;
                position = Position$1._createBefore(item);
            } else {
                item = new TextProxy$1(node, 0, node.data.length);
                // If not just keep moving backward.
                position.offset--;
            }
            this._position = position;
            return this._formatReturnValue('text', item, previousPosition, position, charactersCount);
        }
        if (typeof node == 'string') {
            let textLength;
            if (!this.singleCharacters) {
                // Check if text stick out of walker range.
                const startOffset = parent === this._boundaryStartParent ? this.boundaries.start.offset : 0;
                textLength = position.offset - startOffset;
            } else {
                textLength = 1;
            }
            position.offset -= textLength;
            const textProxy = new TextProxy$1(parent, position.offset, textLength);
            this._position = position;
            return this._formatReturnValue('text', textProxy, previousPosition, position, textLength);
        }
        // `node` is not set, we reached the beginning of current `parent`.
        position = Position$1._createBefore(parent);
        this._position = position;
        return this._formatReturnValue('elementStart', parent, previousPosition, position, 1);
    }
    /**
	 * Format returned data and adjust `previousPosition` and `nextPosition` if reach the bound of the {@link module:engine/view/text~Text}.
	 *
	 * @param type Type of step.
	 * @param item Item between old and new position.
	 * @param previousPosition Previous position of iterator.
	 * @param nextPosition Next position of iterator.
	 * @param length Length of the item.
	 */ _formatReturnValue(type, item, previousPosition, nextPosition, length) {
        // Text is a specific parent, because contains string instead of children.
        // Walker doesn't enter to the Text except situations when walker is iterating over every single character,
        // or the bound starts/ends inside the Text. So when the position is at the beginning or at the end of the Text
        // we move it just before or just after Text.
        if (item instanceof TextProxy$1) {
            // Position is at the end of Text.
            if (item.offsetInText + item.data.length == item.textNode.data.length) {
                if (this.direction == 'forward' && !(this.boundaries && this.boundaries.end.isEqual(this.position))) {
                    nextPosition = Position$1._createAfter(item.textNode);
                    // When we change nextPosition of returned value we need also update walker current position.
                    this._position = nextPosition;
                } else {
                    previousPosition = Position$1._createAfter(item.textNode);
                }
            }
            // Position is at the begining ot the text.
            if (item.offsetInText === 0) {
                if (this.direction == 'backward' && !(this.boundaries && this.boundaries.start.isEqual(this.position))) {
                    nextPosition = Position$1._createBefore(item.textNode);
                    // When we change nextPosition of returned value we need also update walker current position.
                    this._position = nextPosition;
                } else {
                    previousPosition = Position$1._createBefore(item.textNode);
                }
            }
        }
        return {
            done: false,
            value: {
                type,
                item,
                previousPosition,
                nextPosition,
                length
            }
        };
    }
};

/**
 * Position in the view tree. Position is represented by its parent node and an offset in this parent.
 *
 * In order to create a new position instance use the `createPosition*()` factory methods available in:
 *
 * * {@link module:engine/view/view~View}
 * * {@link module:engine/view/downcastwriter~DowncastWriter}
 * * {@link module:engine/view/upcastwriter~UpcastWriter}
 */ let Position$1 = class Position extends TypeCheckable$1 {
    /**
	 * Position parent.
	 */ parent;
    /**
	 * Position offset.
	 */ offset;
    /**
	 * Creates a position.
	 *
	 * @param parent Position parent.
	 * @param offset Position offset.
	 */ constructor(parent, offset){
        super();
        this.parent = parent;
        this.offset = offset;
    }
    /**
	 * Node directly after the position. Equals `null` when there is no node after position or position is located
	 * inside text node.
	 */ get nodeAfter() {
        if (this.parent.is('$text')) {
            return null;
        }
        return this.parent.getChild(this.offset) || null;
    }
    /**
	 * Node directly before the position. Equals `null` when there is no node before position or position is located
	 * inside text node.
	 */ get nodeBefore() {
        if (this.parent.is('$text')) {
            return null;
        }
        return this.parent.getChild(this.offset - 1) || null;
    }
    /**
	 * Is `true` if position is at the beginning of its {@link module:engine/view/position~Position#parent parent}, `false` otherwise.
	 */ get isAtStart() {
        return this.offset === 0;
    }
    /**
	 * Is `true` if position is at the end of its {@link module:engine/view/position~Position#parent parent}, `false` otherwise.
	 */ get isAtEnd() {
        const endOffset = this.parent.is('$text') ? this.parent.data.length : this.parent.childCount;
        return this.offset === endOffset;
    }
    /**
	 * Position's root, that is the root of the position's parent element.
	 */ get root() {
        return this.parent.root;
    }
    /**
	 * {@link module:engine/view/editableelement~EditableElement EditableElement} instance that contains this position, or `null` if
	 * position is not inside an editable element.
	 */ get editableElement() {
        let editable = this.parent;
        while(!(editable instanceof EditableElement)){
            if (editable.parent) {
                editable = editable.parent;
            } else {
                return null;
            }
        }
        return editable;
    }
    /**
	 * Returns a new instance of Position with offset incremented by `shift` value.
	 *
	 * @param shift How position offset should get changed. Accepts negative values.
	 * @returns Shifted position.
	 */ getShiftedBy(shift) {
        const shifted = Position._createAt(this);
        const offset = shifted.offset + shift;
        shifted.offset = offset < 0 ? 0 : offset;
        return shifted;
    }
    /**
	 * Gets the farthest position which matches the callback using
	 * {@link module:engine/view/treewalker~TreeWalker TreeWalker}.
	 *
	 * For example:
	 *
	 * ```ts
	 * getLastMatchingPosition( value => value.type == 'text' ); // <p>{}foo</p> -> <p>foo[]</p>
	 * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } ); // <p>foo[]</p> -> <p>{}foo</p>
	 * getLastMatchingPosition( value => false ); // Do not move the position.
	 * ```
	 *
	 * @param skip Callback function. Gets {@link module:engine/view/treewalker~TreeWalkerValue} and should
	 * return `true` if the value should be skipped or `false` if not.
	 * @param options Object with configuration options. See {@link module:engine/view/treewalker~TreeWalker}.
	 * @returns The position after the last item which matches the `skip` callback test.
	 */ getLastMatchingPosition(skip, options = {}) {
        options.startPosition = this;
        const treeWalker = new TreeWalker$1(options);
        treeWalker.skip(skip);
        return treeWalker.position;
    }
    /**
	 * Returns ancestors array of this position, that is this position's parent and it's ancestors.
	 *
	 * @returns Array with ancestors.
	 */ getAncestors() {
        if (this.parent.is('documentFragment')) {
            return [
                this.parent
            ];
        } else {
            return this.parent.getAncestors({
                includeSelf: true
            });
        }
    }
    /**
	 * Returns a {@link module:engine/view/node~Node} or {@link module:engine/view/documentfragment~DocumentFragment}
	 * which is a common ancestor of both positions.
	 */ getCommonAncestor(position) {
        const ancestorsA = this.getAncestors();
        const ancestorsB = position.getAncestors();
        let i = 0;
        while(ancestorsA[i] == ancestorsB[i] && ancestorsA[i]){
            i++;
        }
        return i === 0 ? null : ancestorsA[i - 1];
    }
    /**
	 * Checks whether this position equals given position.
	 *
	 * @param otherPosition Position to compare with.
	 * @returns True if positions are same.
	 */ isEqual(otherPosition) {
        return this.parent == otherPosition.parent && this.offset == otherPosition.offset;
    }
    /**
	 * Checks whether this position is located before given position. When method returns `false` it does not mean that
	 * this position is after give one. Two positions may be located inside separate roots and in that situation this
	 * method will still return `false`.
	 *
	 * @see module:engine/view/position~Position#isAfter
	 * @see module:engine/view/position~Position#compareWith
	 * @param otherPosition Position to compare with.
	 * @returns Returns `true` if this position is before given position.
	 */ isBefore(otherPosition) {
        return this.compareWith(otherPosition) == 'before';
    }
    /**
	 * Checks whether this position is located after given position. When method returns `false` it does not mean that
	 * this position is before give one. Two positions may be located inside separate roots and in that situation this
	 * method will still return `false`.
	 *
	 * @see module:engine/view/position~Position#isBefore
	 * @see module:engine/view/position~Position#compareWith
	 * @param otherPosition Position to compare with.
	 * @returns Returns `true` if this position is after given position.
	 */ isAfter(otherPosition) {
        return this.compareWith(otherPosition) == 'after';
    }
    /**
	 * Checks whether this position is before, after or in same position that other position. Two positions may be also
	 * different when they are located in separate roots.
	 *
	 * @param otherPosition Position to compare with.
	 */ compareWith(otherPosition) {
        if (this.root !== otherPosition.root) {
            return 'different';
        }
        if (this.isEqual(otherPosition)) {
            return 'same';
        }
        // Get path from root to position's parent element.
        const thisPath = this.parent.is('node') ? this.parent.getPath() : [];
        const otherPath = otherPosition.parent.is('node') ? otherPosition.parent.getPath() : [];
        // Add the positions' offsets to the parents offsets.
        thisPath.push(this.offset);
        otherPath.push(otherPosition.offset);
        // Compare both path arrays to find common ancestor.
        const result = compareArrays(thisPath, otherPath);
        switch(result){
            case 'prefix':
                return 'before';
            case 'extension':
                return 'after';
            default:
                // Cast to number to avoid having 'same' as a type of `result`.
                return thisPath[result] < otherPath[result] ? 'before' : 'after';
        }
    }
    /**
	 * Creates a {@link module:engine/view/treewalker~TreeWalker TreeWalker} instance with this positions as a start position.
	 *
	 * @param options Object with configuration options. See {@link module:engine/view/treewalker~TreeWalker}
	 */ getWalker(options = {}) {
        options.startPosition = this;
        return new TreeWalker$1(options);
    }
    /**
	 * Clones this position.
	 */ clone() {
        return new Position(this.parent, this.offset);
    }
    /**
	 * Creates position at the given location. The location can be specified as:
	 *
	 * * a {@link module:engine/view/position~Position position},
	 * * parent element and offset (offset defaults to `0`),
	 * * parent element and `'end'` (sets position at the end of that element),
	 * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
	 *
	 * This method is a shortcut to other constructors such as:
	 *
	 * * {@link module:engine/view/position~Position._createBefore},
	 * * {@link module:engine/view/position~Position._createAfter}.
	 *
	 * @internal
	 * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/view/item~Item view item}.
	 */ static _createAt(itemOrPosition, offset) {
        if (itemOrPosition instanceof Position) {
            return new this(itemOrPosition.parent, itemOrPosition.offset);
        } else {
            const node = itemOrPosition;
            if (offset == 'end') {
                offset = node.is('$text') ? node.data.length : node.childCount;
            } else if (offset == 'before') {
                return this._createBefore(node);
            } else if (offset == 'after') {
                return this._createAfter(node);
            } else if (offset !== 0 && !offset) {
                /**
				 * {@link module:engine/view/view~View#createPositionAt `View#createPositionAt()`}
				 * requires the offset to be specified when the first parameter is a view item.
				 *
				 * @error view-createpositionat-offset-required
				 */ throw new CKEditorError('view-createpositionat-offset-required', node);
            }
            return new Position(node, offset);
        }
    }
    /**
	 * Creates a new position after given view item.
	 *
	 * @internal
	 * @param item View item after which the position should be located.
	 */ static _createAfter(item) {
        // TextProxy is not a instance of Node so we need do handle it in specific way.
        if (item.is('$textProxy')) {
            return new Position(item.textNode, item.offsetInText + item.data.length);
        }
        if (!item.parent) {
            /**
			 * You can not make a position after a root.
			 *
			 * @error view-position-after-root
			 * @param {module:engine/view/node~Node} root
			 */ throw new CKEditorError('view-position-after-root', item, {
                root: item
            });
        }
        return new Position(item.parent, item.index + 1);
    }
    /**
	 * Creates a new position before given view item.
	 *
	 * @internal
	 * @param item View item before which the position should be located.
	 */ static _createBefore(item) {
        // TextProxy is not a instance of Node so we need do handle it in specific way.
        if (item.is('$textProxy')) {
            return new Position(item.textNode, item.offsetInText);
        }
        if (!item.parent) {
            /**
			 * You cannot make a position before a root.
			 *
			 * @error view-position-before-root
			 * @param {module:engine/view/node~Node} root
			 */ throw new CKEditorError('view-position-before-root', item, {
                root: item
            });
        }
        return new Position(item.parent, item.index);
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Position$1.prototype.is = function(type) {
    return type === 'position' || type === 'view:position';
};

/**
 * Range in the view tree. A range is represented by its start and end {@link module:engine/view/position~Position positions}.
 *
 * In order to create a new position instance use the `createPosition*()` factory methods available in:
 *
 * * {@link module:engine/view/view~View}
 * * {@link module:engine/view/downcastwriter~DowncastWriter}
 * * {@link module:engine/view/upcastwriter~UpcastWriter}
 */ let Range$1 = class Range extends TypeCheckable$1 {
    /**
	 * Start position.
	 */ start;
    /**
	 * End position.
	 */ end;
    /**
	 * Creates a range spanning from `start` position to `end` position.
	 *
	 * **Note:** Constructor creates it's own {@link module:engine/view/position~Position} instances basing on passed values.
	 *
	 * @param start Start position.
	 * @param end End position. If not set, range will be collapsed at the `start` position.
	 */ constructor(start, end = null){
        super();
        this.start = start.clone();
        this.end = end ? end.clone() : start.clone();
    }
    /**
	 * Iterable interface.
	 *
	 * Iterates over all {@link module:engine/view/item~Item view items} that are in this range and returns
	 * them together with additional information like length or {@link module:engine/view/position~Position positions},
	 * grouped as {@link module:engine/view/treewalker~TreeWalkerValue}.
	 *
	 * This iterator uses {@link module:engine/view/treewalker~TreeWalker TreeWalker} with `boundaries` set to this range and
	 * `ignoreElementEnd` option
	 * set to `true`.
	 */ *[Symbol.iterator]() {
        yield* new TreeWalker$1({
            boundaries: this,
            ignoreElementEnd: true
        });
    }
    /**
	 * Returns whether the range is collapsed, that is it start and end positions are equal.
	 */ get isCollapsed() {
        return this.start.isEqual(this.end);
    }
    /**
	 * Returns whether this range is flat, that is if {@link module:engine/view/range~Range#start start} position and
	 * {@link module:engine/view/range~Range#end end} position are in the same {@link module:engine/view/position~Position#parent parent}.
	 */ get isFlat() {
        return this.start.parent === this.end.parent;
    }
    /**
	 * Range root element.
	 */ get root() {
        return this.start.root;
    }
    /**
	 * Creates a maximal range that has the same content as this range but is expanded in both ways (at the beginning
	 * and at the end).
	 *
	 * For example:
	 *
	 * ```html
	 * <p>Foo</p><p><b>{Bar}</b></p> -> <p>Foo</p>[<p><b>Bar</b>]</p>
	 * <p><b>foo</b>{bar}<span></span></p> -> <p><b>foo[</b>bar<span></span>]</p>
	 * ```
	 *
	 * Note that in the sample above:
	 *
	 * - `<p>` have type of {@link module:engine/view/containerelement~ContainerElement},
	 * - `<b>` have type of {@link module:engine/view/attributeelement~AttributeElement},
	 * - `<span>` have type of {@link module:engine/view/uielement~UIElement}.
	 *
	 * @returns Enlarged range.
	 */ getEnlarged() {
        let start = this.start.getLastMatchingPosition(enlargeTrimSkip, {
            direction: 'backward'
        });
        let end = this.end.getLastMatchingPosition(enlargeTrimSkip);
        // Fix positions, in case if they are in Text node.
        if (start.parent.is('$text') && start.isAtStart) {
            start = Position$1._createBefore(start.parent);
        }
        if (end.parent.is('$text') && end.isAtEnd) {
            end = Position$1._createAfter(end.parent);
        }
        return new Range(start, end);
    }
    /**
	 * Creates a minimum range that has the same content as this range but is trimmed in both ways (at the beginning
	 * and at the end).
	 *
	 * For example:
	 *
	 * ```html
	 * <p>Foo</p>[<p><b>Bar</b>]</p> -> <p>Foo</p><p><b>{Bar}</b></p>
	 * <p><b>foo[</b>bar<span></span>]</p> -> <p><b>foo</b>{bar}<span></span></p>
	 * ```
	 *
	 * Note that in the sample above:
	 *
	 * - `<p>` have type of {@link module:engine/view/containerelement~ContainerElement},
	 * - `<b>` have type of {@link module:engine/view/attributeelement~AttributeElement},
	 * - `<span>` have type of {@link module:engine/view/uielement~UIElement}.
	 *
	 * @returns Shrunk range.
	 */ getTrimmed() {
        let start = this.start.getLastMatchingPosition(enlargeTrimSkip);
        if (start.isAfter(this.end) || start.isEqual(this.end)) {
            return new Range(start, start);
        }
        let end = this.end.getLastMatchingPosition(enlargeTrimSkip, {
            direction: 'backward'
        });
        const nodeAfterStart = start.nodeAfter;
        const nodeBeforeEnd = end.nodeBefore;
        // Because TreeWalker prefers positions next to text node, we need to move them manually into these text nodes.
        if (nodeAfterStart && nodeAfterStart.is('$text')) {
            start = new Position$1(nodeAfterStart, 0);
        }
        if (nodeBeforeEnd && nodeBeforeEnd.is('$text')) {
            end = new Position$1(nodeBeforeEnd, nodeBeforeEnd.data.length);
        }
        return new Range(start, end);
    }
    /**
	 * Two ranges are equal if their start and end positions are equal.
	 *
	 * @param otherRange Range to compare with.
	 * @returns `true` if ranges are equal, `false` otherwise
	 */ isEqual(otherRange) {
        return this == otherRange || this.start.isEqual(otherRange.start) && this.end.isEqual(otherRange.end);
    }
    /**
	 * Checks whether this range contains given {@link module:engine/view/position~Position position}.
	 *
	 * @param position Position to check.
	 * @returns `true` if given {@link module:engine/view/position~Position position} is contained in this range, `false` otherwise.
	 */ containsPosition(position) {
        return position.isAfter(this.start) && position.isBefore(this.end);
    }
    /**
	 * Checks whether this range contains given {@link module:engine/view/range~Range range}.
	 *
	 * @param otherRange Range to check.
	 * @param loose Whether the check is loose or strict. If the check is strict (`false`), compared range cannot
	 * start or end at the same position as this range boundaries. If the check is loose (`true`), compared range can start, end or
	 * even be equal to this range. Note that collapsed ranges are always compared in strict mode.
	 * @returns `true` if given {@link module:engine/view/range~Range range} boundaries are contained by this range, `false`
	 * otherwise.
	 */ containsRange(otherRange, loose = false) {
        if (otherRange.isCollapsed) {
            loose = false;
        }
        const containsStart = this.containsPosition(otherRange.start) || loose && this.start.isEqual(otherRange.start);
        const containsEnd = this.containsPosition(otherRange.end) || loose && this.end.isEqual(otherRange.end);
        return containsStart && containsEnd;
    }
    /**
	 * Computes which part(s) of this {@link module:engine/view/range~Range range} is not a part of given
	 * {@link module:engine/view/range~Range range}.
	 * Returned array contains zero, one or two {@link module:engine/view/range~Range ranges}.
	 *
	 * Examples:
	 *
	 * ```ts
	 * let foo = downcastWriter.createText( 'foo' );
	 * let img = downcastWriter.createContainerElement( 'img' );
	 * let bar = downcastWriter.createText( 'bar' );
	 * let p = downcastWriter.createContainerElement( 'p', null, [ foo, img, bar ] );
	 *
	 * let range = view.createRange( view.createPositionAt( foo, 2 ), view.createPositionAt( bar, 1 ); // "o", img, "b" are in range.
	 * let otherRange = view.createRange( // "oo", img, "ba" are in range.
	 * 	view.createPositionAt( foo, 1 ),
	 * 	view.createPositionAt( bar, 2 )
	 * );
	 * let transformed = range.getDifference( otherRange );
	 * // transformed array has no ranges because `otherRange` contains `range`
	 *
	 * otherRange = view.createRange( view.createPositionAt( foo, 1 ), view.createPositionAt( p, 2 ); // "oo", img are in range.
	 * transformed = range.getDifference( otherRange );
	 * // transformed array has one range: from ( p, 2 ) to ( bar, 1 )
	 *
	 * otherRange = view.createRange( view.createPositionAt( p, 1 ), view.createPositionAt( p, 2 ) ); // img is in range.
	 * transformed = range.getDifference( otherRange );
	 * // transformed array has two ranges: from ( foo, 1 ) to ( p, 1 ) and from ( p, 2 ) to ( bar, 1 )
	 * ```
	 *
	 * @param otherRange Range to differentiate against.
	 * @returns The difference between ranges.
	 */ getDifference(otherRange) {
        const ranges = [];
        if (this.isIntersecting(otherRange)) {
            // Ranges intersect.
            if (this.containsPosition(otherRange.start)) {
                // Given range start is inside this range. This means that we have to
                // add shrunken range - from the start to the middle of this range.
                ranges.push(new Range(this.start, otherRange.start));
            }
            if (this.containsPosition(otherRange.end)) {
                // Given range end is inside this range. This means that we have to
                // add shrunken range - from the middle of this range to the end.
                ranges.push(new Range(otherRange.end, this.end));
            }
        } else {
            // Ranges do not intersect, return the original range.
            ranges.push(this.clone());
        }
        return ranges;
    }
    /**
	 * Returns an intersection of this {@link module:engine/view/range~Range range} and given {@link module:engine/view/range~Range range}.
	 * Intersection is a common part of both of those ranges. If ranges has no common part, returns `null`.
	 *
	 * Examples:
	 *
	 * ```ts
	 * let foo = downcastWriter.createText( 'foo' );
	 * let img = downcastWriter.createContainerElement( 'img' );
	 * let bar = downcastWriter.createText( 'bar' );
	 * let p = downcastWriter.createContainerElement( 'p', null, [ foo, img, bar ] );
	 *
	 * let range = view.createRange( view.createPositionAt( foo, 2 ), view.createPositionAt( bar, 1 ); // "o", img, "b" are in range.
	 * let otherRange = view.createRange( view.createPositionAt( foo, 1 ), view.createPositionAt( p, 2 ); // "oo", img are in range.
	 * let transformed = range.getIntersection( otherRange ); // range from ( foo, 1 ) to ( p, 2 ).
	 *
	 * otherRange = view.createRange( view.createPositionAt( bar, 1 ), view.createPositionAt( bar, 3 ); "ar" is in range.
	 * transformed = range.getIntersection( otherRange ); // null - no common part.
	 * ```
	 *
	 * @param otherRange Range to check for intersection.
	 * @returns A common part of given ranges or `null` if ranges have no common part.
	 */ getIntersection(otherRange) {
        if (this.isIntersecting(otherRange)) {
            // Ranges intersect, so a common range will be returned.
            // At most, it will be same as this range.
            let commonRangeStart = this.start;
            let commonRangeEnd = this.end;
            if (this.containsPosition(otherRange.start)) {
                // Given range start is inside this range. This means thaNt we have to
                // shrink common range to the given range start.
                commonRangeStart = otherRange.start;
            }
            if (this.containsPosition(otherRange.end)) {
                // Given range end is inside this range. This means that we have to
                // shrink common range to the given range end.
                commonRangeEnd = otherRange.end;
            }
            return new Range(commonRangeStart, commonRangeEnd);
        }
        // Ranges do not intersect, so they do not have common part.
        return null;
    }
    /**
	 * Creates a {@link module:engine/view/treewalker~TreeWalker TreeWalker} instance with this range as a boundary.
	 *
	 * @param options Object with configuration options. See {@link module:engine/view/treewalker~TreeWalker}.
	 */ getWalker(options = {}) {
        options.boundaries = this;
        return new TreeWalker$1(options);
    }
    /**
	 * Returns a {@link module:engine/view/node~Node} or {@link module:engine/view/documentfragment~DocumentFragment}
	 * which is a common ancestor of range's both ends (in which the entire range is contained).
	 */ getCommonAncestor() {
        return this.start.getCommonAncestor(this.end);
    }
    /**
	 * Returns an {@link module:engine/view/element~Element Element} contained by the range.
	 * The element will be returned when it is the **only** node within the range and **fully–contained**
	 * at the same time.
	 */ getContainedElement() {
        if (this.isCollapsed) {
            return null;
        }
        let nodeAfterStart = this.start.nodeAfter;
        let nodeBeforeEnd = this.end.nodeBefore;
        // Handle the situation when the range position is at the beginning / at the end of a text node.
        // In such situation `.nodeAfter` and `.nodeBefore` are `null` but the range still might be spanning
        // over one element.
        //
        // <p>Foo{<span class="widget"></span>}bar</p> vs <p>Foo[<span class="widget"></span>]bar</p>
        //
        // These are basically the same range, only the difference is if the range position is at
        // at the end/at the beginning of a text node or just before/just after the text node.
        //
        if (this.start.parent.is('$text') && this.start.isAtEnd && this.start.parent.nextSibling) {
            nodeAfterStart = this.start.parent.nextSibling;
        }
        if (this.end.parent.is('$text') && this.end.isAtStart && this.end.parent.previousSibling) {
            nodeBeforeEnd = this.end.parent.previousSibling;
        }
        if (nodeAfterStart && nodeAfterStart.is('element') && nodeAfterStart === nodeBeforeEnd) {
            return nodeAfterStart;
        }
        return null;
    }
    /**
	 * Clones this range.
	 */ clone() {
        return new Range(this.start, this.end);
    }
    /**
	 * Returns an iterator that iterates over all {@link module:engine/view/item~Item view items} that are in this range and returns
	 * them.
	 *
	 * This method uses {@link module:engine/view/treewalker~TreeWalker} with `boundaries` set to this range and `ignoreElementEnd` option
	 * set to `true`. However it returns only {@link module:engine/view/item~Item items},
	 * not {@link module:engine/view/treewalker~TreeWalkerValue}.
	 *
	 * You may specify additional options for the tree walker. See {@link module:engine/view/treewalker~TreeWalker} for
	 * a full list of available options.
	 *
	 * @param options Object with configuration options. See {@link module:engine/view/treewalker~TreeWalker}.
	 */ *getItems(options = {}) {
        options.boundaries = this;
        options.ignoreElementEnd = true;
        const treeWalker = new TreeWalker$1(options);
        for (const value of treeWalker){
            yield value.item;
        }
    }
    /**
	 * Returns an iterator that iterates over all {@link module:engine/view/position~Position positions} that are boundaries or
	 * contained in this range.
	 *
	 * This method uses {@link module:engine/view/treewalker~TreeWalker} with `boundaries` set to this range. However it returns only
	 * {@link module:engine/view/position~Position positions}, not {@link module:engine/view/treewalker~TreeWalkerValue}.
	 *
	 * You may specify additional options for the tree walker. See {@link module:engine/view/treewalker~TreeWalker} for
	 * a full list of available options.
	 *
	 * @param options Object with configuration options. See {@link module:engine/view/treewalker~TreeWalker}.
	 */ *getPositions(options = {}) {
        options.boundaries = this;
        const treeWalker = new TreeWalker$1(options);
        yield treeWalker.position;
        for (const value of treeWalker){
            yield value.nextPosition;
        }
    }
    /**
	 * Checks and returns whether this range intersects with the given range.
	 *
	 * @param otherRange Range to compare with.
	 * @returns True if ranges intersect.
	 */ isIntersecting(otherRange) {
        return this.start.isBefore(otherRange.end) && this.end.isAfter(otherRange.start);
    }
    /**
	 * Creates a range from the given parents and offsets.
	 *
	 * @internal
	 * @param startElement Start position parent element.
	 * @param startOffset Start position offset.
	 * @param endElement End position parent element.
	 * @param endOffset End position offset.
	 * @returns Created range.
	 */ static _createFromParentsAndOffsets(startElement, startOffset, endElement, endOffset) {
        return new this(new Position$1(startElement, startOffset), new Position$1(endElement, endOffset));
    }
    /**
	 * Creates a new range, spreading from specified {@link module:engine/view/position~Position position} to a position moved by
	 * given `shift`. If `shift` is a negative value, shifted position is treated as the beginning of the range.
	 *
	 * @internal
	 * @param position Beginning of the range.
	 * @param shift How long the range should be.
	 */ static _createFromPositionAndShift(position, shift) {
        const start = position;
        const end = position.getShiftedBy(shift);
        return shift > 0 ? new this(start, end) : new this(end, start);
    }
    /**
	 * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
	 * that element and ends after the last child of that element.
	 *
	 * @internal
	 * @param element Element which is a parent for the range.
	 */ static _createIn(element) {
        return this._createFromParentsAndOffsets(element, 0, element, element.childCount);
    }
    /**
	 * Creates a range that starts before given {@link module:engine/view/item~Item view item} and ends after it.
	 *
	 * @internal
	 */ static _createOn(item) {
        const size = item.is('$textProxy') ? item.offsetSize : 1;
        return this._createFromPositionAndShift(Position$1._createBefore(item), size);
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Range$1.prototype.is = function(type) {
    return type === 'range' || type === 'view:range';
};
/**
 * Function used by getEnlarged and getTrimmed methods.
 */ function enlargeTrimSkip(value) {
    if (value.item.is('attributeElement') || value.item.is('uiElement')) {
        return true;
    }
    return false;
}

/**
 * Class representing an arbirtary selection in the view.
 * See also {@link module:engine/view/documentselection~DocumentSelection}.
 *
 * New selection instances can be created via the constructor or one these methods:
 *
 * * {@link module:engine/view/view~View#createSelection `View#createSelection()`},
 * * {@link module:engine/view/upcastwriter~UpcastWriter#createSelection `UpcastWriter#createSelection()`}.
 *
 * A selection can consist of {@link module:engine/view/range~Range ranges} that can be set by using
 * the {@link module:engine/view/selection~Selection#setTo `Selection#setTo()`} method.
 */ let Selection$1 = class Selection extends /* #__PURE__ */ EmitterMixin(TypeCheckable$1) {
    /**
	 * Stores all ranges that are selected.
	 */ _ranges;
    /**
	 * Specifies whether the last added range was added as a backward or forward range.
	 */ _lastRangeBackward;
    /**
	 * Specifies whether selection instance is fake.
	 */ _isFake;
    /**
	 * Fake selection's label.
	 */ _fakeSelectionLabel;
    /**
	 * Creates new selection instance.
	 *
	 * **Note**: The selection constructor is available as a factory method:
	 *
	 * * {@link module:engine/view/view~View#createSelection `View#createSelection()`},
	 * * {@link module:engine/view/upcastwriter~UpcastWriter#createSelection `UpcastWriter#createSelection()`}.
	 *
	 * ```ts
	 * // Creates empty selection without ranges.
	 * const selection = writer.createSelection();
	 *
	 * // Creates selection at the given range.
	 * const range = writer.createRange( start, end );
	 * const selection = writer.createSelection( range );
	 *
	 * // Creates selection at the given ranges
	 * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
	 * const selection = writer.createSelection( ranges );
	 *
	 * // Creates selection from the other selection.
	 * const otherSelection = writer.createSelection();
	 * const selection = writer.createSelection( otherSelection );
	 *
	 * // Creates selection from the document selection.
	 * const selection = writer.createSelection( editor.editing.view.document.selection );
	 *
	 * // Creates selection at the given position.
	 * const position = writer.createPositionFromPath( root, path );
	 * const selection = writer.createSelection( position );
	 *
	 * // Creates collapsed selection at the position of given item and offset.
	 * const paragraph = writer.createContainerElement( 'paragraph' );
	 * const selection = writer.createSelection( paragraph, offset );
	 *
	 * // Creates a range inside an {@link module:engine/view/element~Element element} which starts before the
	 * // first child of that element and ends after the last child of that element.
	 * const selection = writer.createSelection( paragraph, 'in' );
	 *
	 * // Creates a range on an {@link module:engine/view/item~Item item} which starts before the item and ends
	 * // just after the item.
	 * const selection = writer.createSelection( paragraph, 'on' );
	 * ```
	 *
	 * `Selection`'s constructor allow passing additional options (`backward`, `fake` and `label`) as the last argument.
	 *
	 * ```ts
	 * // Creates backward selection.
	 * const selection = writer.createSelection( range, { backward: true } );
	 * ```
	 *
	 * Fake selection does not render as browser native selection over selected elements and is hidden to the user.
	 * This way, no native selection UI artifacts are displayed to the user and selection over elements can be
	 * represented in other way, for example by applying proper CSS class.
	 *
	 * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM
	 * (and be  properly handled by screen readers).
	 *
	 * ```ts
	 * // Creates fake selection with label.
	 * const selection = writer.createSelection( range, { fake: true, label: 'foo' } );
	 * ```
	 *
	 * @internal
	 */ constructor(...args){
        super();
        this._ranges = [];
        this._lastRangeBackward = false;
        this._isFake = false;
        this._fakeSelectionLabel = '';
        if (args.length) {
            this.setTo(...args);
        }
    }
    /**
	 * Returns true if selection instance is marked as `fake`.
	 *
	 * @see #setTo
	 */ get isFake() {
        return this._isFake;
    }
    /**
	 * Returns fake selection label.
	 *
	 * @see #setTo
	 */ get fakeSelectionLabel() {
        return this._fakeSelectionLabel;
    }
    /**
	 * Selection anchor. Anchor may be described as a position where the selection starts. Together with
	 * {@link #focus focus} they define the direction of selection, which is important
	 * when expanding/shrinking selection. Anchor is always the start or end of the most recent added range.
	 * It may be a bit unintuitive when there are multiple ranges in selection.
	 *
	 * @see #focus
	 */ get anchor() {
        if (!this._ranges.length) {
            return null;
        }
        const range = this._ranges[this._ranges.length - 1];
        const anchor = this._lastRangeBackward ? range.end : range.start;
        return anchor.clone();
    }
    /**
	 * Selection focus. Focus is a position where the selection ends.
	 *
	 * @see #anchor
	 */ get focus() {
        if (!this._ranges.length) {
            return null;
        }
        const range = this._ranges[this._ranges.length - 1];
        const focus = this._lastRangeBackward ? range.start : range.end;
        return focus.clone();
    }
    /**
	 * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
	 * collapsed.
	 */ get isCollapsed() {
        return this.rangeCount === 1 && this._ranges[0].isCollapsed;
    }
    /**
	 * Returns number of ranges in selection.
	 */ get rangeCount() {
        return this._ranges.length;
    }
    /**
	 * Specifies whether the {@link #focus} precedes {@link #anchor}.
	 */ get isBackward() {
        return !this.isCollapsed && this._lastRangeBackward;
    }
    /**
	 * {@link module:engine/view/editableelement~EditableElement EditableElement} instance that contains this selection, or `null`
	 * if the selection is not inside an editable element.
	 */ get editableElement() {
        if (this.anchor) {
            return this.anchor.editableElement;
        }
        return null;
    }
    /**
	 * Returns an iterable that contains copies of all ranges added to the selection.
	 */ *getRanges() {
        for (const range of this._ranges){
            yield range.clone();
        }
    }
    /**
	 * Returns copy of the first range in the selection. First range is the one which
	 * {@link module:engine/view/range~Range#start start} position {@link module:engine/view/position~Position#isBefore is before} start
	 * position of all other ranges (not to confuse with the first range added to the selection).
	 * Returns `null` if no ranges are added to selection.
	 */ getFirstRange() {
        let first = null;
        for (const range of this._ranges){
            if (!first || range.start.isBefore(first.start)) {
                first = range;
            }
        }
        return first ? first.clone() : null;
    }
    /**
	 * Returns copy of the last range in the selection. Last range is the one which {@link module:engine/view/range~Range#end end}
	 * position {@link module:engine/view/position~Position#isAfter is after} end position of all other ranges (not to confuse
	 * with the last range added to the selection). Returns `null` if no ranges are added to selection.
	 */ getLastRange() {
        let last = null;
        for (const range of this._ranges){
            if (!last || range.end.isAfter(last.end)) {
                last = range;
            }
        }
        return last ? last.clone() : null;
    }
    /**
	 * Returns copy of the first position in the selection. First position is the position that
	 * {@link module:engine/view/position~Position#isBefore is before} any other position in the selection ranges.
	 * Returns `null` if no ranges are added to selection.
	 */ getFirstPosition() {
        const firstRange = this.getFirstRange();
        return firstRange ? firstRange.start.clone() : null;
    }
    /**
	 * Returns copy of the last position in the selection. Last position is the position that
	 * {@link module:engine/view/position~Position#isAfter is after} any other position in the selection ranges.
	 * Returns `null` if no ranges are added to selection.
	 */ getLastPosition() {
        const lastRange = this.getLastRange();
        return lastRange ? lastRange.end.clone() : null;
    }
    /**
	 * Checks whether, this selection is equal to given selection. Selections are equal if they have same directions,
	 * same number of ranges and all ranges from one selection equal to a range from other selection.
	 *
	 * @param otherSelection Selection to compare with.
	 * @returns `true` if selections are equal, `false` otherwise.
	 */ isEqual(otherSelection) {
        if (this.isFake != otherSelection.isFake) {
            return false;
        }
        if (this.isFake && this.fakeSelectionLabel != otherSelection.fakeSelectionLabel) {
            return false;
        }
        if (this.rangeCount != otherSelection.rangeCount) {
            return false;
        } else if (this.rangeCount === 0) {
            return true;
        }
        if (!this.anchor.isEqual(otherSelection.anchor) || !this.focus.isEqual(otherSelection.focus)) {
            return false;
        }
        for (const thisRange of this._ranges){
            let found = false;
            for (const otherRange of otherSelection._ranges){
                if (thisRange.isEqual(otherRange)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return false;
            }
        }
        return true;
    }
    /**
	 * Checks whether this selection is similar to given selection. Selections are similar if they have same directions, same
	 * number of ranges, and all {@link module:engine/view/range~Range#getTrimmed trimmed} ranges from one selection are
	 * equal to any trimmed range from other selection.
	 *
	 * @param otherSelection Selection to compare with.
	 * @returns `true` if selections are similar, `false` otherwise.
	 */ isSimilar(otherSelection) {
        if (this.isBackward != otherSelection.isBackward) {
            return false;
        }
        const numOfRangesA = count(this.getRanges());
        const numOfRangesB = count(otherSelection.getRanges());
        // If selections have different number of ranges, they cannot be similar.
        if (numOfRangesA != numOfRangesB) {
            return false;
        }
        // If both selections have no ranges, they are similar.
        if (numOfRangesA == 0) {
            return true;
        }
        // Check if each range in one selection has a similar range in other selection.
        for (let rangeA of this.getRanges()){
            rangeA = rangeA.getTrimmed();
            let found = false;
            for (let rangeB of otherSelection.getRanges()){
                rangeB = rangeB.getTrimmed();
                if (rangeA.start.isEqual(rangeB.start) && rangeA.end.isEqual(rangeB.end)) {
                    found = true;
                    break;
                }
            }
            // For `rangeA`, neither range in `otherSelection` was similar. So selections are not similar.
            if (!found) {
                return false;
            }
        }
        // There were no ranges that weren't matched. Selections are similar.
        return true;
    }
    /**
	 * Returns the selected element. {@link module:engine/view/element~Element Element} is considered as selected if there is only
	 * one range in the selection, and that range contains exactly one element.
	 * Returns `null` if there is no selected element.
	 */ getSelectedElement() {
        if (this.rangeCount !== 1) {
            return null;
        }
        return this.getFirstRange().getContainedElement();
    }
    /**
	 * Sets this selection's ranges and direction to the specified location based on the given
	 * {@link module:engine/view/selection~Selectable selectable}.
	 *
	 * ```ts
	 * // Sets selection to the given range.
	 * const range = writer.createRange( start, end );
	 * selection.setTo( range );
	 *
	 * // Sets selection to given ranges.
	 * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
	 * selection.setTo( range );
	 *
	 * // Sets selection to the other selection.
	 * const otherSelection = writer.createSelection();
	 * selection.setTo( otherSelection );
	 *
	 * // Sets selection to contents of DocumentSelection.
	 * selection.setTo( editor.editing.view.document.selection );
	 *
	 * // Sets collapsed selection at the given position.
	 * const position = writer.createPositionAt( root, path );
	 * selection.setTo( position );
	 *
	 * // Sets collapsed selection at the position of given item and offset.
	 * selection.setTo( paragraph, offset );
	 * ```
	 *
	 * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
	 * that element and ends after the last child of that element.
	 *
	 * ```ts
	 * selection.setTo( paragraph, 'in' );
	 * ```
	 *
	 * Creates a range on an {@link module:engine/view/item~Item item} which starts before the item and ends just after the item.
	 *
	 * ```ts
	 * selection.setTo( paragraph, 'on' );
	 *
	 * // Clears selection. Removes all ranges.
	 * selection.setTo( null );
	 * ```
	 *
	 * `Selection#setTo()` method allow passing additional options (`backward`, `fake` and `label`) as the last argument.
	 *
	 * ```ts
	 * // Sets selection as backward.
	 * selection.setTo( range, { backward: true } );
	 * ```
	 *
	 * Fake selection does not render as browser native selection over selected elements and is hidden to the user.
	 * This way, no native selection UI artifacts are displayed to the user and selection over elements can be
	 * represented in other way, for example by applying proper CSS class.
	 *
	 * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM
	 * (and be  properly handled by screen readers).
	 *
	 * ```ts
	 * // Creates fake selection with label.
	 * selection.setTo( range, { fake: true, label: 'foo' } );
	 * ```
	 *
	 * @fires change
	 */ setTo(...args) {
        let [selectable, placeOrOffset, options] = args;
        if (typeof placeOrOffset == 'object') {
            options = placeOrOffset;
            placeOrOffset = undefined;
        }
        if (selectable === null) {
            this._setRanges([]);
            this._setFakeOptions(options);
        } else if (selectable instanceof Selection || selectable instanceof DocumentSelection$1) {
            this._setRanges(selectable.getRanges(), selectable.isBackward);
            this._setFakeOptions({
                fake: selectable.isFake,
                label: selectable.fakeSelectionLabel
            });
        } else if (selectable instanceof Range$1) {
            this._setRanges([
                selectable
            ], options && options.backward);
            this._setFakeOptions(options);
        } else if (selectable instanceof Position$1) {
            this._setRanges([
                new Range$1(selectable)
            ]);
            this._setFakeOptions(options);
        } else if (selectable instanceof Node$2) {
            const backward = !!options && !!options.backward;
            let range;
            if (placeOrOffset === undefined) {
                /**
				 * selection.setTo requires the second parameter when the first parameter is a node.
				 *
				 * @error view-selection-setto-required-second-parameter
				 */ throw new CKEditorError('view-selection-setto-required-second-parameter', this);
            } else if (placeOrOffset == 'in') {
                range = Range$1._createIn(selectable);
            } else if (placeOrOffset == 'on') {
                range = Range$1._createOn(selectable);
            } else {
                range = new Range$1(Position$1._createAt(selectable, placeOrOffset));
            }
            this._setRanges([
                range
            ], backward);
            this._setFakeOptions(options);
        } else if (isIterable(selectable)) {
            // We assume that the selectable is an iterable of ranges.
            // Array.from() is used to prevent setting ranges to the old iterable
            this._setRanges(selectable, options && options.backward);
            this._setFakeOptions(options);
        } else {
            /**
			 * Cannot set selection to given place.
			 *
			 * @error view-selection-setto-not-selectable
			 */ throw new CKEditorError('view-selection-setto-not-selectable', this);
        }
        this.fire('change');
    }
    /**
	 * Moves {@link #focus} to the specified location.
	 *
	 * The location can be specified in the same form as {@link module:engine/view/view~View#createPositionAt view.createPositionAt()}
	 * parameters.
	 *
	 * @fires change
	 * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/view/item~Item view item}.
	 */ setFocus(itemOrPosition, offset) {
        if (this.anchor === null) {
            /**
			 * Cannot set selection focus if there are no ranges in selection.
			 *
			 * @error view-selection-setfocus-no-ranges
			 */ throw new CKEditorError('view-selection-setfocus-no-ranges', this);
        }
        const newFocus = Position$1._createAt(itemOrPosition, offset);
        if (newFocus.compareWith(this.focus) == 'same') {
            return;
        }
        const anchor = this.anchor;
        this._ranges.pop();
        if (newFocus.compareWith(anchor) == 'before') {
            this._addRange(new Range$1(newFocus, anchor), true);
        } else {
            this._addRange(new Range$1(anchor, newFocus));
        }
        this.fire('change');
    }
    /**
	 * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
	 * is treated like the last added range and is used to set {@link #anchor anchor} and {@link #focus focus}.
	 * Accepts a flag describing in which way the selection is made.
	 *
	 * @param newRanges Iterable object of ranges to set.
	 * @param isLastBackward Flag describing if last added range was selected forward - from start to end
	 * (`false`) or backward - from end to start (`true`). Defaults to `false`.
	 */ _setRanges(newRanges, isLastBackward = false) {
        // New ranges should be copied to prevent removing them by setting them to `[]` first.
        // Only applies to situations when selection is set to the same selection or same selection's ranges.
        newRanges = Array.from(newRanges);
        this._ranges = [];
        for (const range of newRanges){
            this._addRange(range);
        }
        this._lastRangeBackward = !!isLastBackward;
    }
    /**
	 * Sets this selection instance to be marked as `fake`. A fake selection does not render as browser native selection
	 * over selected elements and is hidden to the user. This way, no native selection UI artifacts are displayed to
	 * the user and selection over elements can be represented in other way, for example by applying proper CSS class.
	 *
	 * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM (and be
	 * properly handled by screen readers).
	 */ _setFakeOptions(options = {}) {
        this._isFake = !!options.fake;
        this._fakeSelectionLabel = options.fake ? options.label || '' : '';
    }
    /**
	 * Adds a range to the selection. Added range is copied. This means that passed range is not saved in the
	 * selection instance and you can safely operate on it.
	 *
	 * Accepts a flag describing in which way the selection is made - passed range might be selected from
	 * {@link module:engine/view/range~Range#start start} to {@link module:engine/view/range~Range#end end}
	 * or from {@link module:engine/view/range~Range#end end} to {@link module:engine/view/range~Range#start start}.
	 * The flag is used to set {@link #anchor anchor} and {@link #focus focus} properties.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
	 * with ranges already stored in Selection instance.
	 */ _addRange(range, isBackward = false) {
        if (!(range instanceof Range$1)) {
            /**
			 * Selection range set to an object that is not an instance of {@link module:engine/view/range~Range}.
			 *
			 * @error view-selection-add-range-not-range
			 */ throw new CKEditorError('view-selection-add-range-not-range', this);
        }
        this._pushRange(range);
        this._lastRangeBackward = !!isBackward;
    }
    /**
	 * Adds range to selection - creates copy of given range so it can be safely used and modified.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
	 * with ranges already stored in selection instance.
	 */ _pushRange(range) {
        for (const storedRange of this._ranges){
            if (range.isIntersecting(storedRange)) {
                /**
				 * Trying to add a range that intersects with another range from selection.
				 *
				 * @error view-selection-range-intersects
				 * @param {module:engine/view/range~Range} addedRange Range that was added to the selection.
				 * @param {module:engine/view/range~Range} intersectingRange Range from selection that intersects with `addedRange`.
				 */ throw new CKEditorError('view-selection-range-intersects', this, {
                    addedRange: range,
                    intersectingRange: storedRange
                });
            }
        }
        this._ranges.push(new Range$1(range.start, range.end));
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Selection$1.prototype.is = function(type) {
    return type === 'selection' || type === 'view:selection';
};

/**
 * Class representing the document selection in the view.
 *
 * Its instance is available in {@link module:engine/view/document~Document#selection `Document#selection`}.
 *
 * It is similar to {@link module:engine/view/selection~Selection} but
 * it has a read-only API and can be modified only by the writer available in
 * the {@link module:engine/view/view~View#change `View#change()`} block
 * (so via {@link module:engine/view/downcastwriter~DowncastWriter#setSelection `DowncastWriter#setSelection()`}).
 */ let DocumentSelection$1 = class DocumentSelection extends /* #__PURE__ */ EmitterMixin(TypeCheckable$1) {
    /**
	 * Selection is used internally (`DocumentSelection` is a proxy to that selection).
	 */ _selection;
    constructor(...args){
        super();
        this._selection = new Selection$1();
        // Delegate change event to be fired on DocumentSelection instance.
        this._selection.delegate('change').to(this);
        // Set selection data.
        if (args.length) {
            this._selection.setTo(...args);
        }
    }
    /**
	 * Returns true if selection instance is marked as `fake`.
	 *
	 * @see #_setTo
	 */ get isFake() {
        return this._selection.isFake;
    }
    /**
	 * Returns fake selection label.
	 *
	 * @see #_setTo
	 */ get fakeSelectionLabel() {
        return this._selection.fakeSelectionLabel;
    }
    /**
	 * Selection anchor. Anchor may be described as a position where the selection starts. Together with
	 * {@link #focus focus} they define the direction of selection, which is important
	 * when expanding/shrinking selection. Anchor is always the start or end of the most recent added range.
	 * It may be a bit unintuitive when there are multiple ranges in selection.
	 *
	 * @see #focus
	 */ get anchor() {
        return this._selection.anchor;
    }
    /**
	 * Selection focus. Focus is a position where the selection ends.
	 *
	 * @see #anchor
	 */ get focus() {
        return this._selection.focus;
    }
    /**
	 * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
	 * collapsed.
	 */ get isCollapsed() {
        return this._selection.isCollapsed;
    }
    /**
	 * Returns number of ranges in selection.
	 */ get rangeCount() {
        return this._selection.rangeCount;
    }
    /**
	 * Specifies whether the {@link #focus} precedes {@link #anchor}.
	 */ get isBackward() {
        return this._selection.isBackward;
    }
    /**
	 * {@link module:engine/view/editableelement~EditableElement EditableElement} instance that contains this selection, or `null`
	 * if the selection is not inside an editable element.
	 */ get editableElement() {
        return this._selection.editableElement;
    }
    /**
	 * Used for the compatibility with the {@link module:engine/view/selection~Selection#isEqual} method.
	 *
	 * @internal
	 */ get _ranges() {
        return this._selection._ranges;
    }
    /**
	 * Returns an iterable that contains copies of all ranges added to the selection.
	 */ *getRanges() {
        yield* this._selection.getRanges();
    }
    /**
	 * Returns copy of the first range in the selection. First range is the one which
	 * {@link module:engine/view/range~Range#start start} position {@link module:engine/view/position~Position#isBefore is before} start
	 * position of all other ranges (not to confuse with the first range added to the selection).
	 * Returns `null` if no ranges are added to selection.
	 */ getFirstRange() {
        return this._selection.getFirstRange();
    }
    /**
	 * Returns copy of the last range in the selection. Last range is the one which {@link module:engine/view/range~Range#end end}
	 * position {@link module:engine/view/position~Position#isAfter is after} end position of all other ranges (not to confuse
	 * with the last range added to the selection). Returns `null` if no ranges are added to selection.
	 */ getLastRange() {
        return this._selection.getLastRange();
    }
    /**
	 * Returns copy of the first position in the selection. First position is the position that
	 * {@link module:engine/view/position~Position#isBefore is before} any other position in the selection ranges.
	 * Returns `null` if no ranges are added to selection.
	 */ getFirstPosition() {
        return this._selection.getFirstPosition();
    }
    /**
	 * Returns copy of the last position in the selection. Last position is the position that
	 * {@link module:engine/view/position~Position#isAfter is after} any other position in the selection ranges.
	 * Returns `null` if no ranges are added to selection.
	 */ getLastPosition() {
        return this._selection.getLastPosition();
    }
    /**
	 * Returns the selected element. {@link module:engine/view/element~Element Element} is considered as selected if there is only
	 * one range in the selection, and that range contains exactly one element.
	 * Returns `null` if there is no selected element.
	 */ getSelectedElement() {
        return this._selection.getSelectedElement();
    }
    /**
	 * Checks whether, this selection is equal to given selection. Selections are equal if they have same directions,
	 * same number of ranges and all ranges from one selection equal to a range from other selection.
	 *
	 * @param otherSelection Selection to compare with.
	 * @returns `true` if selections are equal, `false` otherwise.
	 */ isEqual(otherSelection) {
        return this._selection.isEqual(otherSelection);
    }
    /**
	 * Checks whether this selection is similar to given selection. Selections are similar if they have same directions, same
	 * number of ranges, and all {@link module:engine/view/range~Range#getTrimmed trimmed} ranges from one selection are
	 * equal to any trimmed range from other selection.
	 *
	 * @param otherSelection Selection to compare with.
	 * @returns `true` if selections are similar, `false` otherwise.
	 */ isSimilar(otherSelection) {
        return this._selection.isSimilar(otherSelection);
    }
    /**
	 * Sets this selection's ranges and direction to the specified location based on the given
	 * {@link module:engine/view/selection~Selectable selectable}.
	 *
	 * ```ts
	 * // Sets selection to the given range.
	 * const range = writer.createRange( start, end );
	 * documentSelection._setTo( range );
	 *
	 * // Sets selection to given ranges.
	 * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( start2, end2 ) ];
	 * documentSelection._setTo( range );
	 *
	 * // Sets selection to the other selection.
	 * const otherSelection = writer.createSelection();
	 * documentSelection._setTo( otherSelection );
	 *
	 * // Sets collapsed selection at the given position.
	 * const position = writer.createPositionAt( root, offset );
	 * documentSelection._setTo( position );
	 *
	 * // Sets collapsed selection at the position of given item and offset.
	 * documentSelection._setTo( paragraph, offset );
	 * ```
	 *
	 * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
	 * that element and ends after the last child of that element.
	 *
	 * ```ts
	 * documentSelection._setTo( paragraph, 'in' );
	 * ```
	 *
	 * Creates a range on an {@link module:engine/view/item~Item item} which starts before the item and ends just after the item.
	 *
	 * ```ts
	 * documentSelection._setTo( paragraph, 'on' );
	 *
	 * // Clears selection. Removes all ranges.
	 * documentSelection._setTo( null );
	 * ```
	 *
	 * `Selection#_setTo()` method allow passing additional options (`backward`, `fake` and `label`) as the last argument.
	 *
	 * ```ts
	 * // Sets selection as backward.
	 * documentSelection._setTo( range, { backward: true } );
	 * ```
	 *
	 * Fake selection does not render as browser native selection over selected elements and is hidden to the user.
	 * This way, no native selection UI artifacts are displayed to the user and selection over elements can be
	 * represented in other way, for example by applying proper CSS class.
	 *
	 * Additionally fake's selection label can be provided. It will be used to des cribe fake selection in DOM
	 * (and be  properly handled by screen readers).
	 *
	 * ```ts
	 * // Creates fake selection with label.
	 * documentSelection._setTo( range, { fake: true, label: 'foo' } );
	 * ```
	 *
	 * @internal
	 * @fires change
	 */ _setTo(...args) {
        this._selection.setTo(...args);
    }
    /**
	 * Moves {@link #focus} to the specified location.
	 *
	 * The location can be specified in the same form as {@link module:engine/view/view~View#createPositionAt view.createPositionAt()}
	 * parameters.
	 *
	 * @internal
	 * @fires change
	 * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/view/item~Item view item}.
	 */ _setFocus(itemOrPosition, offset) {
        this._selection.setFocus(itemOrPosition, offset);
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
DocumentSelection$1.prototype.is = function(type) {
    return type === 'selection' || type == 'documentSelection' || type == 'view:selection' || type == 'view:documentSelection';
};

/**
 * The event object passed to bubbling event callbacks. It is used to provide information about the event as well as a tool to
 * manipulate it.
 */ class BubblingEventInfo extends EventInfo {
    /**
	 * The view range that the bubbling should start from.
	 */ startRange;
    /**
	 * The current event phase.
	 */ _eventPhase;
    /**
	 * The current bubbling target.
	 */ _currentTarget;
    /**
	 * @param source The emitter.
	 * @param name The event name.
	 * @param startRange The view range that the bubbling should start from.
	 */ constructor(source, name, startRange){
        super(source, name);
        this.startRange = startRange;
        this._eventPhase = 'none';
        this._currentTarget = null;
    }
    /**
	 * The current event phase.
	 */ get eventPhase() {
        return this._eventPhase;
    }
    /**
	 * The current bubbling target.
	 */ get currentTarget() {
        return this._currentTarget;
    }
}

const contextsSymbol = Symbol('bubbling contexts');
/**
 * Bubbling emitter mixin for the view document as described in the {@link ~BubblingEmitter} interface.
 *
 * This function creates a class that inherits from the provided `base` and implements `Emitter` interface.
 * The base class must implement {@link module:utils/emittermixin~Emitter} interface.
 *
 * ```ts
 * class BaseClass extends EmitterMixin() {
 * 	// ...
 * }
 *
 * class MyClass extends BubblingEmitterMixin( BaseClass ) {
 * 	// This class derives from `BaseClass` and implements the `BubblingEmitter` interface.
 * }
 * ```
 */ function BubblingEmitterMixin(base) {
    class Mixin extends base {
        fire(eventOrInfo, ...eventArgs) {
            try {
                const eventInfo = eventOrInfo instanceof EventInfo ? eventOrInfo : new EventInfo(this, eventOrInfo);
                const eventContexts = getBubblingContexts(this);
                if (!eventContexts.size) {
                    return;
                }
                updateEventInfo(eventInfo, 'capturing', this);
                // The capture phase of the event.
                if (fireListenerFor(eventContexts, '$capture', eventInfo, ...eventArgs)) {
                    return eventInfo.return;
                }
                const startRange = eventInfo.startRange || this.selection.getFirstRange();
                const selectedElement = startRange ? startRange.getContainedElement() : null;
                const isCustomContext = selectedElement ? Boolean(getCustomContext(eventContexts, selectedElement)) : false;
                let node = selectedElement || getDeeperRangeParent(startRange);
                updateEventInfo(eventInfo, 'atTarget', node);
                // For the not yet bubbling event trigger for $text node if selection can be there and it's not a custom context selected.
                if (!isCustomContext) {
                    if (fireListenerFor(eventContexts, '$text', eventInfo, ...eventArgs)) {
                        return eventInfo.return;
                    }
                    updateEventInfo(eventInfo, 'bubbling', node);
                }
                while(node){
                    // Root node handling.
                    if (node.is('rootElement')) {
                        if (fireListenerFor(eventContexts, '$root', eventInfo, ...eventArgs)) {
                            return eventInfo.return;
                        }
                    } else if (node.is('element')) {
                        if (fireListenerFor(eventContexts, node.name, eventInfo, ...eventArgs)) {
                            return eventInfo.return;
                        }
                    }
                    // Check custom contexts (i.e., a widget).
                    if (fireListenerFor(eventContexts, node, eventInfo, ...eventArgs)) {
                        return eventInfo.return;
                    }
                    node = node.parent;
                    updateEventInfo(eventInfo, 'bubbling', node);
                }
                updateEventInfo(eventInfo, 'bubbling', this);
                // Document context.
                fireListenerFor(eventContexts, '$document', eventInfo, ...eventArgs);
                return eventInfo.return;
            } catch (err) {
                // @if CK_DEBUG // throw err;
                /* istanbul ignore next -- @preserve */ CKEditorError.rethrowUnexpectedError(err, this);
            }
        }
        _addEventListener(event, callback, options) {
            const contexts = toArray(options.context || '$document');
            const eventContexts = getBubblingContexts(this);
            for (const context of contexts){
                let emitter = eventContexts.get(context);
                if (!emitter) {
                    emitter = new (EmitterMixin())();
                    eventContexts.set(context, emitter);
                }
                this.listenTo(emitter, event, callback, options);
            }
        }
        _removeEventListener(event, callback) {
            const eventContexts = getBubblingContexts(this);
            for (const emitter of eventContexts.values()){
                this.stopListening(emitter, event, callback);
            }
        }
    }
    return Mixin;
}
// Backward compatibility with `mix`.
{
    const mixin = BubblingEmitterMixin(Object);
    [
        'fire',
        '_addEventListener',
        '_removeEventListener'
    ].forEach((key)=>{
        BubblingEmitterMixin[key] = mixin.prototype[key];
    });
}/**
 * Update the event info bubbling fields.
 *
 * @param eventInfo The event info object to update.
 * @param eventPhase The current event phase.
 * @param currentTarget The current bubbling target.
 */ function updateEventInfo(eventInfo, eventPhase, currentTarget) {
    if (eventInfo instanceof BubblingEventInfo) {
        eventInfo._eventPhase = eventPhase;
        eventInfo._currentTarget = currentTarget;
    }
}
/**
 * Fires the listener for the specified context. Returns `true` if event was stopped.
 *
 * @param eventInfo The `EventInfo` object.
 * @param eventArgs Additional arguments to be passed to the callbacks.
 * @returns True if event stop was called.
 */ function fireListenerFor(eventContexts, context, eventInfo, ...eventArgs) {
    const emitter = typeof context == 'string' ? eventContexts.get(context) : getCustomContext(eventContexts, context);
    if (!emitter) {
        return false;
    }
    emitter.fire(eventInfo, ...eventArgs);
    return eventInfo.stop.called;
}
/**
 * Returns an emitter for a specified view node.
 */ function getCustomContext(eventContexts, node) {
    for (const [context, emitter] of eventContexts){
        if (typeof context == 'function' && context(node)) {
            return emitter;
        }
    }
    return null;
}
/**
 * Returns bubbling contexts map for the source (emitter).
 */ function getBubblingContexts(source) {
    if (!source[contextsSymbol]) {
        source[contextsSymbol] = new Map();
    }
    return source[contextsSymbol];
}
/**
 * Returns the deeper parent element for the range.
 */ function getDeeperRangeParent(range) {
    if (!range) {
        return null;
    }
    const startParent = range.start.parent;
    const endParent = range.end.parent;
    const startPath = startParent.getPath();
    const endPath = endParent.getPath();
    return startPath.length > endPath.length ? startParent : endParent;
}

// @if CK_DEBUG_ENGINE // const { logDocument } = require( '../dev-utils/utils' );
/**
 * Document class creates an abstract layer over the content editable area, contains a tree of view elements and
 * {@link module:engine/view/documentselection~DocumentSelection view selection} associated with this document.
 */ let Document$1 = class Document extends /* #__PURE__ */ BubblingEmitterMixin(/* #__PURE__ */ ObservableMixin()) {
    /**
	 * Selection done on this document.
	 */ selection;
    /**
	 * Roots of the view tree. Collection of the {@link module:engine/view/element~Element view elements}.
	 *
	 * View roots are created as a result of binding between {@link module:engine/view/document~Document#roots} and
	 * {@link module:engine/model/document~Document#roots} and this is handled by
	 * {@link module:engine/controller/editingcontroller~EditingController}, so to create view root we need to create
	 * model root using {@link module:engine/model/document~Document#createRoot}.
	 */ roots;
    /**
	 * The styles processor instance used by this document when normalizing styles.
	 */ stylesProcessor;
    /**
	 * Post-fixer callbacks registered to the view document.
	 */ _postFixers = new Set();
    /**
	 * Creates a Document instance.
	 *
	 * @param stylesProcessor The styles processor instance.
	 */ constructor(stylesProcessor){
        super();
        this.selection = new DocumentSelection$1();
        this.roots = new Collection({
            idProperty: 'rootName'
        });
        this.stylesProcessor = stylesProcessor;
        this.set('isReadOnly', false);
        this.set('isFocused', false);
        this.set('isSelecting', false);
        this.set('isComposing', false);
    }
    /**
	 * Gets a {@link module:engine/view/document~Document#roots view root element} with the specified name. If the name is not
	 * specific "main" root is returned.
	 *
	 * @param name Name of the root.
	 * @returns The view root element with the specified name or null when there is no root of given name.
	 */ getRoot(name = 'main') {
        return this.roots.get(name);
    }
    /**
	 * Allows registering post-fixer callbacks. A post-fixers mechanism allows to update the view tree just before it is rendered
	 * to the DOM.
	 *
	 * Post-fixers are executed right after all changes from the outermost change block were applied but
	 * before the {@link module:engine/view/view~View#event:render render event} is fired. If a post-fixer callback made
	 * a change, it should return `true`. When this happens, all post-fixers are fired again to check if something else should
	 * not be fixed in the new document tree state.
	 *
	 * View post-fixers are useful when you want to apply some fixes whenever the view structure changes. Keep in mind that
	 * changes executed in a view post-fixer should not break model-view mapping.
	 *
	 * The types of changes which should be safe:
	 *
	 * * adding or removing attribute from elements,
	 * * changes inside of {@link module:engine/view/uielement~UIElement UI elements},
	 * * {@link module:engine/controller/editingcontroller~EditingController#reconvertItem marking some of the model elements to be
	 * re-converted}.
	 *
	 * Try to avoid changes which touch view structure:
	 *
	 * * you should not add or remove nor wrap or unwrap any view elements,
	 * * you should not change the editor data model in a view post-fixer.
	 *
	 * As a parameter, a post-fixer callback receives a {@link module:engine/view/downcastwriter~DowncastWriter downcast writer}.
	 *
	 * Typically, a post-fixer will look like this:
	 *
	 * ```ts
	 * editor.editing.view.document.registerPostFixer( writer => {
	 * 	if ( checkSomeCondition() ) {
	 * 		writer.doSomething();
	 *
	 * 		// Let other post-fixers know that something changed.
	 * 		return true;
	 * 	}
	 *
	 * 	return false;
	 * } );
	 * ```
	 *
	 * Note that nothing happens right after you register a post-fixer (e.g. execute such a code in the console).
	 * That is because adding a post-fixer does not execute it.
	 * The post-fixer will be executed as soon as any change in the document needs to cause its rendering.
	 * If you want to re-render the editor's view after registering the post-fixer then you should do it manually by calling
	 * {@link module:engine/view/view~View#forceRender `view.forceRender()`}.
	 *
	 * If you need to register a callback which is executed when DOM elements are already updated,
	 * use {@link module:engine/view/view~View#event:render render event}.
	 */ registerPostFixer(postFixer) {
        this._postFixers.add(postFixer);
    }
    /**
	 * Destroys this instance. Makes sure that all observers are destroyed and listeners removed.
	 */ destroy() {
        this.roots.forEach((root)=>root.destroy());
        this.stopListening();
    }
    /**
	 * Performs post-fixer loops. Executes post-fixer callbacks as long as none of them has done any changes to the model.
	 *
	 * @internal
	 */ _callPostFixers(writer) {
        let wasFixed = false;
        do {
            for (const callback of this._postFixers){
                wasFixed = callback(writer);
                if (wasFixed) {
                    break;
                }
            }
        }while (wasFixed)
    }
};

// Default attribute priority.
const DEFAULT_PRIORITY = 10;
/**
 * Attribute elements are used to represent formatting elements in the view (think – `<b>`, `<span style="font-size: 2em">`, etc.).
 * Most often they are created when downcasting model text attributes.
 *
 * Editing engine does not define a fixed HTML DTD. This is why a feature developer needs to choose between various
 * types (container element, {@link module:engine/view/attributeelement~AttributeElement attribute element},
 * {@link module:engine/view/emptyelement~EmptyElement empty element}, etc) when developing a feature.
 *
 * To create a new attribute element instance use the
 * {@link module:engine/view/downcastwriter~DowncastWriter#createAttributeElement `DowncastWriter#createAttributeElement()`} method.
 */ class AttributeElement extends Element$1 {
    static DEFAULT_PRIORITY = DEFAULT_PRIORITY;
    /**
	 * Element priority. Decides in what order elements are wrapped by {@link module:engine/view/downcastwriter~DowncastWriter}.
	 *
	 * @internal
	 * @readonly
	 */ _priority = DEFAULT_PRIORITY;
    /**
	 * Element identifier. If set, it is used by {@link module:engine/view/element~Element#isSimilar},
	 * and then two elements are considered similar if, and only if they have the same `_id`.
	 *
	 * @internal
	 * @readonly
	 */ _id = null;
    /**
	 * Keeps all the attribute elements that have the same {@link module:engine/view/attributeelement~AttributeElement#id ids}
	 * and still exist in the view tree.
	 *
	 * This property is managed by {@link module:engine/view/downcastwriter~DowncastWriter}.
	 */ _clonesGroup = null;
    /**
	 * Creates an attribute element.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#createAttributeElement
	 * @see module:engine/view/element~Element
	 * @protected
	 * @param document The document instance to which this element belongs.
	 * @param name Node name.
	 * @param attrs Collection of attributes.
	 * @param children A list of nodes to be inserted into created element.
	 */ constructor(document, name, attrs, children){
        super(document, name, attrs, children);
        this.getFillerOffset = getFillerOffset$3;
    }
    /**
	 * Element priority. Decides in what order elements are wrapped by {@link module:engine/view/downcastwriter~DowncastWriter}.
	 */ get priority() {
        return this._priority;
    }
    /**
	 * Element identifier. If set, it is used by {@link module:engine/view/element~Element#isSimilar},
	 * and then two elements are considered similar if, and only if they have the same `id`.
	 */ get id() {
        return this._id;
    }
    /**
	 * Returns all {@link module:engine/view/attributeelement~AttributeElement attribute elements} that has the
	 * same {@link module:engine/view/attributeelement~AttributeElement#id id} and are in the view tree (were not removed).
	 *
	 * Note: If this element has been removed from the tree, returned set will not include it.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError attribute-element-get-elements-with-same-id-no-id}
	 * if this element has no `id`.
	 *
	 * @returns Set containing all the attribute elements
	 * with the same `id` that were added and not removed from the view tree.
	 */ getElementsWithSameId() {
        if (this.id === null) {
            /**
			 * Cannot get elements with the same id for an attribute element without id.
			 *
			 * @error attribute-element-get-elements-with-same-id-no-id
			 */ throw new CKEditorError('attribute-element-get-elements-with-same-id-no-id', this);
        }
        return new Set(this._clonesGroup);
    }
    /**
	 * Checks if this element is similar to other element.
	 *
	 * If none of elements has set {@link module:engine/view/attributeelement~AttributeElement#id}, then both elements
	 * should have the same name, attributes and priority to be considered as similar. Two similar elements can contain
	 * different set of children nodes.
	 *
	 * If at least one element has {@link module:engine/view/attributeelement~AttributeElement#id} set, then both
	 * elements have to have the same {@link module:engine/view/attributeelement~AttributeElement#id} value to be
	 * considered similar.
	 *
	 * Similarity is important for {@link module:engine/view/downcastwriter~DowncastWriter}. For example:
	 *
	 * * two following similar elements can be merged together into one, longer element,
	 * * {@link module:engine/view/downcastwriter~DowncastWriter#unwrap} checks similarity of passed element and processed element to
	 * decide whether processed element should be unwrapped,
	 * * etc.
	 */ isSimilar(otherElement) {
        // If any element has an `id` set, just compare the ids.
        if (this.id !== null || otherElement.id !== null) {
            return this.id === otherElement.id;
        }
        return super.isSimilar(otherElement) && this.priority == otherElement.priority;
    }
    /**
	 * Clones provided element with priority.
	 *
	 * @internal
	 * @param deep If set to `true` clones element and all its children recursively. When set to `false`,
	 * element will be cloned without any children.
	 * @returns Clone of this element.
	 */ _clone(deep = false) {
        const cloned = super._clone(deep);
        // Clone priority too.
        cloned._priority = this._priority;
        // And id too.
        cloned._id = this._id;
        return cloned;
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
AttributeElement.prototype.is = function(type, name) {
    if (!name) {
        return type === 'attributeElement' || type === 'view:attributeElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'element' || type === 'view:element' || type === 'node' || type === 'view:node';
    } else {
        return name === this.name && (type === 'attributeElement' || type === 'view:attributeElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'element' || type === 'view:element');
    }
};
/**
 * Returns block {@link module:engine/view/filler~Filler filler} offset or `null` if block filler is not needed.
 *
 * @returns Block filler offset or `null` if block filler is not needed.
 */ function getFillerOffset$3() {
    // <b>foo</b> does not need filler.
    if (nonUiChildrenCount(this)) {
        return null;
    }
    let element = this.parent;
    // <p><b></b></p> needs filler -> <p><b><br></b></p>
    while(element && element.is('attributeElement')){
        if (nonUiChildrenCount(element) > 1) {
            return null;
        }
        element = element.parent;
    }
    if (!element || nonUiChildrenCount(element) > 1) {
        return null;
    }
    // Render block filler at the end of element (after all ui elements).
    return this.childCount;
}
/**
 * Returns total count of children that are not {@link module:engine/view/uielement~UIElement UIElements}.
 */ function nonUiChildrenCount(element) {
    return Array.from(element.getChildren()).filter((element)=>!element.is('uiElement')).length;
}

/**
 * Empty element class. It is used to represent elements that cannot contain any child nodes (for example `<img>` elements).
 *
 * To create a new empty element use the
 * {@link module:engine/view/downcastwriter~DowncastWriter#createEmptyElement `downcastWriter#createEmptyElement()`} method.
 */ class EmptyElement extends Element$1 {
    /**
	 * Creates new instance of EmptyElement.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-emptyelement-cannot-add` when third parameter is passed,
	 * to inform that usage of EmptyElement is incorrect (adding child nodes to EmptyElement is forbidden).
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#createEmptyElement
	 * @internal
	 * @param document The document instance to which this element belongs.
	 * @param name Node name.
	 * @param attrs Collection of attributes.
	 * @param children A list of nodes to be inserted into created element.
	 */ constructor(document, name, attributes, children){
        super(document, name, attributes, children);
        this.getFillerOffset = getFillerOffset$2;
    }
    /**
	 * Overrides {@link module:engine/view/element~Element#_insertChild} method.
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-emptyelement-cannot-add` to prevent
	 * adding any child nodes to EmptyElement.
	 *
	 * @internal
	 */ _insertChild(index, items) {
        if (items && (items instanceof Node$2 || Array.from(items).length > 0)) {
            /**
			 * Cannot add children to {@link module:engine/view/emptyelement~EmptyElement}.
			 *
			 * @error view-emptyelement-cannot-add
			 */ throw new CKEditorError('view-emptyelement-cannot-add', [
                this,
                items
            ]);
        }
        return 0;
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
EmptyElement.prototype.is = function(type, name) {
    if (!name) {
        return type === 'emptyElement' || type === 'view:emptyElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'element' || type === 'view:element' || type === 'node' || type === 'view:node';
    } else {
        return name === this.name && (type === 'emptyElement' || type === 'view:emptyElement' || type === 'element' || type === 'view:element');
    }
};
/**
 * Returns `null` because block filler is not needed for EmptyElements.
 */ function getFillerOffset$2() {
    return null;
}

/**
 * UI element class. It should be used to represent editing UI which needs to be injected into the editing view
 * If possible, you should keep your UI outside the editing view. However, if that is not possible,
 * UI elements can be used.
 *
 * How a UI element is rendered is in your control (you pass a callback to
 * {@link module:engine/view/downcastwriter~DowncastWriter#createUIElement `downcastWriter#createUIElement()`}).
 * The editor will ignore your UI element – the selection cannot be placed in it, it is skipped (invisible) when
 * the user modifies the selection by using arrow keys and the editor does not listen to any mutations which
 * happen inside your UI elements.
 *
 * The limitation is that you cannot convert a model element to a UI element. UI elements need to be
 * created for {@link module:engine/model/markercollection~Marker markers} or as additinal elements
 * inside normal {@link module:engine/view/containerelement~ContainerElement container elements}.
 *
 * To create a new UI element use the
 * {@link module:engine/view/downcastwriter~DowncastWriter#createUIElement `downcastWriter#createUIElement()`} method.
 */ class UIElement extends Element$1 {
    /**
	 * Creates new instance of UIElement.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-uielement-cannot-add` when third parameter is passed,
	 * to inform that usage of UIElement is incorrect (adding child nodes to UIElement is forbidden).
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#createUIElement
	 * @internal
	 * @param document The document instance to which this element belongs.
	 * @param name Node name.
	 * @param attrs Collection of attributes.
	 * @param children A list of nodes to be inserted into created element.
	 */ constructor(document, name, attrs, children){
        super(document, name, attrs, children);
        this.getFillerOffset = getFillerOffset$1;
    }
    /**
	 * Overrides {@link module:engine/view/element~Element#_insertChild} method.
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-uielement-cannot-add` to prevent adding any child nodes
	 * to UIElement.
	 *
	 * @internal
	 */ _insertChild(index, items) {
        if (items && (items instanceof Node$2 || Array.from(items).length > 0)) {
            /**
			 * Cannot add children to {@link module:engine/view/uielement~UIElement}.
			 *
			 * @error view-uielement-cannot-add
			 */ throw new CKEditorError('view-uielement-cannot-add', [
                this,
                items
            ]);
        }
        return 0;
    }
    /**
	 * Renders this {@link module:engine/view/uielement~UIElement} to DOM. This method is called by
	 * {@link module:engine/view/domconverter~DomConverter}.
	 * Do not use inheritance to create custom rendering method, replace `render()` method instead:
	 *
	 * ```ts
	 * const myUIElement = downcastWriter.createUIElement( 'span' );
	 * myUIElement.render = function( domDocument, domConverter ) {
	 * 	const domElement = this.toDomElement( domDocument );
	 *
	 * 	domConverter.setContentOf( domElement, '<b>this is ui element</b>' );
	 *
	 * 	return domElement;
	 * };
	 * ```
	 *
	 * If changes in your UI element should trigger some editor UI update you should call
	 * the {@link module:ui/editorui/editorui~EditorUI#update `editor.ui.update()`} method
	 * after rendering your UI element.
	 *
	 * @param domConverter Instance of the DomConverter used to optimize the output.
	 */ render(domDocument, domConverter// eslint-disable-line @typescript-eslint/no-unused-vars
    ) {
        // Provide basic, default output.
        return this.toDomElement(domDocument);
    }
    /**
	 * Creates DOM element based on this view UIElement.
	 * Note that each time this method is called new DOM element is created.
	 */ toDomElement(domDocument) {
        const domElement = domDocument.createElement(this.name);
        for (const key of this.getAttributeKeys()){
            domElement.setAttribute(key, this.getAttribute(key));
        }
        return domElement;
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
UIElement.prototype.is = function(type, name) {
    if (!name) {
        return type === 'uiElement' || type === 'view:uiElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'element' || type === 'view:element' || type === 'node' || type === 'view:node';
    } else {
        return name === this.name && (type === 'uiElement' || type === 'view:uiElement' || type === 'element' || type === 'view:element');
    }
};
/**
 * This function injects UI element handling to the given {@link module:engine/view/document~Document document}.
 *
 * A callback is added to {@link module:engine/view/document~Document#event:keydown document keydown event}.
 * The callback handles the situation when right arrow key is pressed and selection is collapsed before a UI element.
 * Without this handler, it would be impossible to "jump over" UI element using right arrow key.
 *
 * @param view View controller to which the quirks handling will be injected.
 */ function injectUiElementHandling(view) {
    view.document.on('arrowKey', (evt, data)=>jumpOverUiElement(evt, data, view.domConverter), {
        priority: 'low'
    });
}
/**
 * Returns `null` because block filler is not needed for UIElements.
 */ function getFillerOffset$1() {
    return null;
}
/**
 * Selection cannot be placed in a `UIElement`. Whenever it is placed there, it is moved before it. This
 * causes a situation when it is impossible to jump over `UIElement` using right arrow key, because the selection
 * ends up in ui element (in DOM) and is moved back to the left. This handler fixes this situation.
 */ function jumpOverUiElement(evt, data, domConverter) {
    if (data.keyCode == keyCodes.arrowright) {
        const domSelection = data.domTarget.ownerDocument.defaultView.getSelection();
        const domSelectionCollapsed = domSelection.rangeCount == 1 && domSelection.getRangeAt(0).collapsed;
        // Jump over UI element if selection is collapsed or shift key is pressed. These are the cases when selection would extend.
        if (domSelectionCollapsed || data.shiftKey) {
            const domParent = domSelection.focusNode;
            const domOffset = domSelection.focusOffset;
            const viewPosition = domConverter.domPositionToView(domParent, domOffset);
            // In case if dom element is not converted to view or is not mapped or something. Happens for example in some tests.
            if (viewPosition === null) {
                return;
            }
            // Skip all following ui elements.
            let jumpedOverAnyUiElement = false;
            const nextViewPosition = viewPosition.getLastMatchingPosition((value)=>{
                if (value.item.is('uiElement')) {
                    // Remember that there was at least one ui element.
                    jumpedOverAnyUiElement = true;
                }
                // Jump over ui elements, jump over empty attribute elements, move up from inside of attribute element.
                if (value.item.is('uiElement') || value.item.is('attributeElement')) {
                    return true;
                }
                // Don't jump over text or don't get out of container element.
                return false;
            });
            // If anything has been skipped, fix position.
            // This `if` could be possibly omitted but maybe it is better not to mess with DOM selection if not needed.
            if (jumpedOverAnyUiElement) {
                const newDomPosition = domConverter.viewPositionToDom(nextViewPosition);
                if (domSelectionCollapsed) {
                    // Selection was collapsed, so collapse it at further position.
                    domSelection.collapse(newDomPosition.parent, newDomPosition.offset);
                } else {
                    // Selection was not collapse, so extend it instead of collapsing.
                    domSelection.extend(newDomPosition.parent, newDomPosition.offset);
                }
            }
        }
    }
}

/**
 * The raw element class.
 *
 * The raw elements work as data containers ("wrappers", "sandboxes") but their children are not managed or
 * even recognized by the editor. This encapsulation allows integrations to maintain custom DOM structures
 * in the editor content without, for instance, worrying about compatibility with other editor features.
 * Raw elements are a perfect tool for integration with external frameworks and data sources.
 *
 * Unlike {@link module:engine/view/uielement~UIElement UI elements}, raw elements act like real editor
 * content (similar to {@link module:engine/view/containerelement~ContainerElement} or
 * {@link module:engine/view/emptyelement~EmptyElement}), they are considered by the editor selection and
 * {@link module:widget/utils~toWidget they can work as widgets}.
 *
 * To create a new raw element, use the
 * {@link module:engine/view/downcastwriter~DowncastWriter#createRawElement `downcastWriter#createRawElement()`} method.
 */ class RawElement extends Element$1 {
    /**
	 * Creates a new instance of a raw element.
	 *
	 * Throws the `view-rawelement-cannot-add` {@link module:utils/ckeditorerror~CKEditorError CKEditorError} when the `children`
	 * parameter is passed to inform that the usage of `RawElement` is incorrect (adding child nodes to `RawElement` is forbidden).
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#createRawElement
	 * @internal
	 * @param document The document instance to which this element belongs.
	 * @param name Node name.
	 * @param attrs Collection of attributes.
	 * @param children A list of nodes to be inserted into created element.
	 */ constructor(document, name, attrs, children){
        super(document, name, attrs, children);
        // Returns `null` because filler is not needed for raw elements.
        this.getFillerOffset = getFillerOffset;
    }
    /**
	 * Overrides the {@link module:engine/view/element~Element#_insertChild} method.
	 * Throws the `view-rawelement-cannot-add` {@link module:utils/ckeditorerror~CKEditorError CKEditorError} to prevent
	 * adding any child nodes to a raw element.
	 *
	 * @internal
	 */ _insertChild(index, items) {
        if (items && (items instanceof Node$2 || Array.from(items).length > 0)) {
            /**
			 * Cannot add children to a {@link module:engine/view/rawelement~RawElement} instance.
			 *
			 * @error view-rawelement-cannot-add
			 */ throw new CKEditorError('view-rawelement-cannot-add', [
                this,
                items
            ]);
        }
        return 0;
    }
    /**
	 * This allows rendering the children of a {@link module:engine/view/rawelement~RawElement} on the DOM level.
	 * This method is called by the {@link module:engine/view/domconverter~DomConverter} with the raw DOM element
	 * passed as an argument, leaving the number and shape of the children up to the integrator.
	 *
	 * This method **must be defined** for the raw element to work:
	 *
	 * ```ts
	 * const myRawElement = downcastWriter.createRawElement( 'div' );
	 *
	 * myRawElement.render = function( domElement, domConverter ) {
	 * 	domConverter.setContentOf( domElement, '<b>This is the raw content of myRawElement.</b>' );
	 * };
	 * ```
	 *
	 * @param domElement The native DOM element representing the raw view element.
	 * @param domConverter Instance of the DomConverter used to optimize the output.
	 */ render(domElement, domConverter) {}
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
RawElement.prototype.is = function(type, name) {
    if (!name) {
        return type === 'rawElement' || type === 'view:rawElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === this.name || type === 'view:' + this.name || type === 'element' || type === 'view:element' || type === 'node' || type === 'view:node';
    } else {
        return name === this.name && (type === 'rawElement' || type === 'view:rawElement' || type === 'element' || type === 'view:element');
    }
};
/**
 * Returns `null` because block filler is not needed for raw elements.
 */ function getFillerOffset() {
    return null;
}

/**
 * Document fragment.
 *
 * To create a new document fragment instance use the
 * {@link module:engine/view/upcastwriter~UpcastWriter#createDocumentFragment `UpcastWriter#createDocumentFragment()`}
 * method.
 */ let DocumentFragment$1 = class DocumentFragment extends /* #__PURE__ */ EmitterMixin(TypeCheckable$1) {
    /**
	 * The document to which this document fragment belongs.
	 */ document;
    /**
	 * Array of child nodes.
	 */ _children = [];
    /**
	 * Map of custom properties.
	 * Custom properties can be added to document fragment instance.
	 */ _customProperties = new Map();
    /**
	 * Creates new DocumentFragment instance.
	 *
	 * @internal
	 * @param document The document to which this document fragment belongs.
	 * @param children A list of nodes to be inserted into the created document fragment.
	 */ constructor(document, children){
        super();
        this.document = document;
        if (children) {
            this._insertChild(0, children);
        }
    }
    /**
	 * Iterable interface.
	 *
	 * Iterates over nodes added to this document fragment.
	 */ [Symbol.iterator]() {
        return this._children[Symbol.iterator]();
    }
    /**
	 * Number of child nodes in this document fragment.
	 */ get childCount() {
        return this._children.length;
    }
    /**
	 * Is `true` if there are no nodes inside this document fragment, `false` otherwise.
	 */ get isEmpty() {
        return this.childCount === 0;
    }
    /**
	 * Artificial root of `DocumentFragment`. Returns itself. Added for compatibility reasons.
	 */ get root() {
        return this;
    }
    /**
	 * Artificial parent of `DocumentFragment`. Returns `null`. Added for compatibility reasons.
	 */ get parent() {
        return null;
    }
    /**
	 * Artificial element name. Returns `undefined`. Added for compatibility reasons.
	 */ get name() {
        return undefined;
    }
    /**
	 * Artificial element getFillerOffset. Returns `undefined`. Added for compatibility reasons.
	 */ get getFillerOffset() {
        return undefined;
    }
    /**
	 * Returns the custom property value for the given key.
	 */ getCustomProperty(key) {
        return this._customProperties.get(key);
    }
    /**
	 * Returns an iterator which iterates over this document fragment's custom properties.
	 * Iterator provides `[ key, value ]` pairs for each stored property.
	 */ *getCustomProperties() {
        yield* this._customProperties.entries();
    }
    /**
	 * {@link module:engine/view/documentfragment~DocumentFragment#_insertChild Insert} a child node or a list of child nodes at the end
	 * and sets the parent of these nodes to this fragment.
	 *
	 * @internal
	 * @param items Items to be inserted.
	 * @returns Number of appended nodes.
	 */ _appendChild(items) {
        return this._insertChild(this.childCount, items);
    }
    /**
	 * Gets child at the given index.
	 *
	 * @param index Index of child.
	 * @returns Child node.
	 */ getChild(index) {
        return this._children[index];
    }
    /**
	 * Gets index of the given child node. Returns `-1` if child node is not found.
	 *
	 * @param node Child node.
	 * @returns Index of the child node.
	 */ getChildIndex(node) {
        return this._children.indexOf(node);
    }
    /**
	 * Gets child nodes iterator.
	 *
	 * @returns Child nodes iterator.
	 */ getChildren() {
        return this._children[Symbol.iterator]();
    }
    /**
	 * Inserts a child node or a list of child nodes on the given index and sets the parent of these nodes to
	 * this fragment.
	 *
	 * @internal
	 * @param index Position where nodes should be inserted.
	 * @param items Items to be inserted.
	 * @returns Number of inserted nodes.
	 */ _insertChild(index, items) {
        this._fireChange('children', this);
        let count = 0;
        const nodes = normalize$2(this.document, items);
        for (const node of nodes){
            // If node that is being added to this element is already inside another element, first remove it from the old parent.
            if (node.parent !== null) {
                node._remove();
            }
            node.parent = this;
            this._children.splice(index, 0, node);
            index++;
            count++;
        }
        return count;
    }
    /**
	 * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
	 *
	 * @internal
	 * @param index Number of the first node to remove.
	 * @param howMany Number of nodes to remove.
	 * @returns The array of removed nodes.
	 */ _removeChildren(index, howMany = 1) {
        this._fireChange('children', this);
        for(let i = index; i < index + howMany; i++){
            this._children[i].parent = null;
        }
        return this._children.splice(index, howMany);
    }
    /**
	 * Fires `change` event with given type of the change.
	 *
	 * @internal
	 * @param type Type of the change.
	 * @param node Changed node.
	 */ _fireChange(type, node) {
        this.fire('change:' + type, node);
    }
    /**
	 * Sets a custom property. They can be used to add special data to elements.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#setCustomProperty
	 * @internal
	 */ _setCustomProperty(key, value) {
        this._customProperties.set(key, value);
    }
    /**
	 * Removes the custom property stored under the given key.
	 *
	 * @see module:engine/view/downcastwriter~DowncastWriter#removeCustomProperty
	 * @internal
	 * @returns Returns true if property was removed.
	 */ _removeCustomProperty(key) {
        return this._customProperties.delete(key);
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
DocumentFragment$1.prototype.is = function(type) {
    return type === 'documentFragment' || type === 'view:documentFragment';
};
/**
 * Converts strings to Text and non-iterables to arrays.
 */ function normalize$2(document, nodes) {
    // Separate condition because string is iterable.
    if (typeof nodes == 'string') {
        return [
            new Text$1(document, nodes)
        ];
    }
    if (!isIterable(nodes)) {
        nodes = [
            nodes
        ];
    }
    // Array.from to enable .map() on non-arrays.
    return Array.from(nodes).map((node)=>{
        if (typeof node == 'string') {
            return new Text$1(document, node);
        }
        if (node instanceof TextProxy$1) {
            return new Text$1(document, node.data);
        }
        return node;
    });
}

/**
 * View downcast writer.
 *
 * It provides a set of methods used to manipulate view nodes.
 *
 * Do not create an instance of this writer manually. To modify a view structure, use
 * the {@link module:engine/view/view~View#change `View#change()`} block.
 *
 * The `DowncastWriter` is designed to work with semantic views which are the views that were/are being downcasted from the model.
 * To work with ordinary views (e.g. parsed from a pasted content) use the
 * {@link module:engine/view/upcastwriter~UpcastWriter upcast writer}.
 *
 * Read more about changing the view in the {@glink framework/architecture/editing-engine#changing-the-view Changing the view}
 * section of the {@glink framework/architecture/editing-engine Editing engine architecture} guide.
 */ class DowncastWriter {
    /**
	 * The view document instance in which this writer operates.
	 */ document;
    /**
	 * Holds references to the attribute groups that share the same {@link module:engine/view/attributeelement~AttributeElement#id id}.
	 * The keys are `id`s, the values are `Set`s holding {@link module:engine/view/attributeelement~AttributeElement}s.
	 */ _cloneGroups = new Map();
    /**
	 * The slot factory used by the `elementToStructure` downcast helper.
	 */ _slotFactory = null;
    /**
	 * @param document The view document instance.
	 */ constructor(document){
        this.document = document;
    }
    setSelection(...args) {
        this.document.selection._setTo(...args);
    }
    /**
	 * Moves {@link module:engine/view/documentselection~DocumentSelection#focus selection's focus} to the specified location.
	 *
	 * The location can be specified in the same form as {@link module:engine/view/view~View#createPositionAt view.createPositionAt()}
	 * parameters.
	 *
	 * @param Offset or one of the flags. Used only when the first parameter is a {@link module:engine/view/item~Item view item}.
	 */ setSelectionFocus(itemOrPosition, offset) {
        this.document.selection._setFocus(itemOrPosition, offset);
    }
    /**
	 * Creates a new {@link module:engine/view/documentfragment~DocumentFragment} instance.
	 *
	 * @param children A list of nodes to be inserted into the created document fragment.
	 * @returns The created document fragment.
	 */ createDocumentFragment(children) {
        return new DocumentFragment$1(this.document, children);
    }
    /**
	 * Creates a new {@link module:engine/view/text~Text text node}.
	 *
	 * ```ts
	 * writer.createText( 'foo' );
	 * ```
	 *
	 * @param data The text's data.
	 * @returns The created text node.
	 */ createText(data) {
        return new Text$1(this.document, data);
    }
    /**
	 * Creates a new {@link module:engine/view/attributeelement~AttributeElement}.
	 *
	 * ```ts
	 * writer.createAttributeElement( 'strong' );
	 * writer.createAttributeElement( 'a', { href: 'foo.bar' } );
	 *
	 * // Make `<a>` element contain other attributes element so the `<a>` element is not broken.
	 * writer.createAttributeElement( 'a', { href: 'foo.bar' }, { priority: 5 } );
	 *
	 * // Set `id` of a marker element so it is not joined or merged with "normal" elements.
	 * writer.createAttributeElement( 'span', { class: 'my-marker' }, { id: 'marker:my' } );
	 * ```
	 *
	 * @param name Name of the element.
	 * @param attributes Element's attributes.
	 * @param options Element's options.
	 * @param options.priority Element's {@link module:engine/view/attributeelement~AttributeElement#priority priority}.
	 * @param options.id Element's {@link module:engine/view/attributeelement~AttributeElement#id id}.
	 * @param options.renderUnsafeAttributes A list of attribute names that should be rendered in the editing
	 * pipeline even though they would normally be filtered out by unsafe attribute detection mechanisms.
	 * @returns Created element.
	 */ createAttributeElement(name, attributes, options = {}) {
        const attributeElement = new AttributeElement(this.document, name, attributes);
        if (typeof options.priority === 'number') {
            attributeElement._priority = options.priority;
        }
        if (options.id) {
            attributeElement._id = options.id;
        }
        if (options.renderUnsafeAttributes) {
            attributeElement._unsafeAttributesToRender.push(...options.renderUnsafeAttributes);
        }
        return attributeElement;
    }
    createContainerElement(name, attributes, childrenOrOptions = {}, options = {}) {
        let children = null;
        if (isPlainObject(childrenOrOptions)) {
            options = childrenOrOptions;
        } else {
            children = childrenOrOptions;
        }
        const containerElement = new ContainerElement(this.document, name, attributes, children);
        if (options.renderUnsafeAttributes) {
            containerElement._unsafeAttributesToRender.push(...options.renderUnsafeAttributes);
        }
        return containerElement;
    }
    /**
	 * Creates a new {@link module:engine/view/editableelement~EditableElement}.
	 *
	 * ```ts
	 * writer.createEditableElement( 'div' );
	 * writer.createEditableElement( 'div', { id: 'foo-1234' } );
	 * ```
	 *
	 * Note: The editable element is to be used in the editing pipeline. Usually, together with
	 * {@link module:widget/utils~toWidgetEditable `toWidgetEditable()`}.
	 *
	 * @param name Name of the element.
	 * @param attributes Elements attributes.
	 * @param options Element's options.
	 * @param options.renderUnsafeAttributes A list of attribute names that should be rendered in the editing
	 * pipeline even though they would normally be filtered out by unsafe attribute detection mechanisms.
	 * @returns Created element.
	 */ createEditableElement(name, attributes, options = {}) {
        const editableElement = new EditableElement(this.document, name, attributes);
        if (options.renderUnsafeAttributes) {
            editableElement._unsafeAttributesToRender.push(...options.renderUnsafeAttributes);
        }
        return editableElement;
    }
    /**
	 * Creates a new {@link module:engine/view/emptyelement~EmptyElement}.
	 *
	 * ```ts
	 * writer.createEmptyElement( 'img' );
	 * writer.createEmptyElement( 'img', { id: 'foo-1234' } );
	 * ```
	 *
	 * @param name Name of the element.
	 * @param attributes Elements attributes.
	 * @param options Element's options.
	 * @param options.renderUnsafeAttributes A list of attribute names that should be rendered in the editing
	 * pipeline even though they would normally be filtered out by unsafe attribute detection mechanisms.
	 * @returns Created element.
	 */ createEmptyElement(name, attributes, options = {}) {
        const emptyElement = new EmptyElement(this.document, name, attributes);
        if (options.renderUnsafeAttributes) {
            emptyElement._unsafeAttributesToRender.push(...options.renderUnsafeAttributes);
        }
        return emptyElement;
    }
    /**
	 * Creates a new {@link module:engine/view/uielement~UIElement}.
	 *
	 * ```ts
	 * writer.createUIElement( 'span' );
	 * writer.createUIElement( 'span', { id: 'foo-1234' } );
	 * ```
	 *
	 * A custom render function can be provided as the third parameter:
	 *
	 * ```ts
	 * writer.createUIElement( 'span', null, function( domDocument ) {
	 * 	const domElement = this.toDomElement( domDocument );
	 * 	domElement.innerHTML = '<b>this is ui element</b>';
	 *
	 * 	return domElement;
	 * } );
	 * ```
	 *
	 * Unlike {@link #createRawElement raw elements}, UI elements are by no means editor content, for instance,
	 * they are ignored by the editor selection system.
	 *
	 * You should not use UI elements as data containers. Check out {@link #createRawElement} instead.
	 *
	 * @param name The name of the element.
	 * @param attributes Element attributes.
	 * @param renderFunction A custom render function.
	 * @returns The created element.
	 */ createUIElement(name, attributes, renderFunction) {
        const uiElement = new UIElement(this.document, name, attributes);
        if (renderFunction) {
            uiElement.render = renderFunction;
        }
        return uiElement;
    }
    /**
	 * Creates a new {@link module:engine/view/rawelement~RawElement}.
	 *
	 * ```ts
	 * writer.createRawElement( 'span', { id: 'foo-1234' }, function( domElement ) {
	 * 	domElement.innerHTML = '<b>This is the raw content of the raw element.</b>';
	 * } );
	 * ```
	 *
	 * Raw elements work as data containers ("wrappers", "sandboxes") but their children are not managed or
	 * even recognized by the editor. This encapsulation allows integrations to maintain custom DOM structures
	 * in the editor content without, for instance, worrying about compatibility with other editor features.
	 * Raw elements are a perfect tool for integration with external frameworks and data sources.
	 *
	 * Unlike {@link #createUIElement UI elements}, raw elements act like "real" editor content (similar to
	 * {@link module:engine/view/containerelement~ContainerElement} or {@link module:engine/view/emptyelement~EmptyElement}),
	 * and they are considered by the editor selection.
	 *
	 * You should not use raw elements to render the UI in the editor content. Check out {@link #createUIElement `#createUIElement()`}
	 * instead.
	 *
	 * @param name The name of the element.
	 * @param attributes Element attributes.
	 * @param renderFunction A custom render function.
	 * @param options Element's options.
	 * @param options.renderUnsafeAttributes A list of attribute names that should be rendered in the editing
	 * pipeline even though they would normally be filtered out by unsafe attribute detection mechanisms.
	 * @returns The created element.
	 */ createRawElement(name, attributes, renderFunction, options = {}) {
        const rawElement = new RawElement(this.document, name, attributes);
        if (renderFunction) {
            rawElement.render = renderFunction;
        }
        if (options.renderUnsafeAttributes) {
            rawElement._unsafeAttributesToRender.push(...options.renderUnsafeAttributes);
        }
        return rawElement;
    }
    /**
	 * Adds or overwrites the element's attribute with a specified key and value.
	 *
	 * ```ts
	 * writer.setAttribute( 'href', 'http://ckeditor.com', linkElement );
	 * ```
	 *
	 * @param key The attribute key.
	 * @param value The attribute value.
	 */ setAttribute(key, value, element) {
        element._setAttribute(key, value);
    }
    /**
	 * Removes attribute from the element.
	 *
	 * ```ts
	 * writer.removeAttribute( 'href', linkElement );
	 * ```
	 *
	 * @param key Attribute key.
	 */ removeAttribute(key, element) {
        element._removeAttribute(key);
    }
    /**
	 * Adds specified class to the element.
	 *
	 * ```ts
	 * writer.addClass( 'foo', linkElement );
	 * writer.addClass( [ 'foo', 'bar' ], linkElement );
	 * ```
	 */ addClass(className, element) {
        element._addClass(className);
    }
    /**
	 * Removes specified class from the element.
	 *
	 * ```ts
	 * writer.removeClass( 'foo', linkElement );
	 * writer.removeClass( [ 'foo', 'bar' ], linkElement );
	 * ```
	 */ removeClass(className, element) {
        element._removeClass(className);
    }
    setStyle(property, value, element) {
        if (isPlainObject(property) && element === undefined) {
            value._setStyle(property);
        } else {
            element._setStyle(property, value);
        }
    }
    /**
	 * Removes specified style from the element.
	 *
	 * ```ts
	 * writer.removeStyle( 'color', element ); // Removes 'color' style.
	 * writer.removeStyle( [ 'color', 'border-top' ], element ); // Removes both 'color' and 'border-top' styles.
	 * ```
	 *
	 * **Note**: This method can work with normalized style names if
	 * {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules a particular style processor rule is enabled}.
	 * See {@link module:engine/view/stylesmap~StylesMap#remove `StylesMap#remove()`} for details.
	 */ removeStyle(property, element) {
        element._removeStyle(property);
    }
    /**
	 * Sets a custom property on element. Unlike attributes, custom properties are not rendered to the DOM,
	 * so they can be used to add special data to elements.
	 */ setCustomProperty(key, value, element) {
        element._setCustomProperty(key, value);
    }
    /**
	 * Removes a custom property stored under the given key.
	 *
	 * @returns Returns true if property was removed.
	 */ removeCustomProperty(key, element) {
        return element._removeCustomProperty(key);
    }
    /**
	 * Breaks attribute elements at the provided position or at the boundaries of a provided range. It breaks attribute elements
	 * up to their first ancestor that is a container element.
	 *
	 * In following examples `<p>` is a container, `<b>` and `<u>` are attribute elements:
	 *
	 * ```html
	 * <p>foo<b><u>bar{}</u></b></p> -> <p>foo<b><u>bar</u></b>[]</p>
	 * <p>foo<b><u>{}bar</u></b></p> -> <p>foo{}<b><u>bar</u></b></p>
	 * <p>foo<b><u>b{}ar</u></b></p> -> <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
	 * <p><b>fo{o</b><u>ba}r</u></p> -> <p><b>fo</b><b>o</b><u>ba</u><u>r</u></b></p>
	 * ```
	 *
	 * **Note:** {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container.
	 *
	 * **Note:** The difference between {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes breakAttributes()} and
	 * {@link module:engine/view/downcastwriter~DowncastWriter#breakContainer breakContainer()} is that `breakAttributes()` breaks all
	 * {@link module:engine/view/attributeelement~AttributeElement attribute elements} that are ancestors of a given `position`,
	 * up to the first encountered {@link module:engine/view/containerelement~ContainerElement container element}.
	 * `breakContainer()` assumes that a given `position` is directly in the container element and breaks that container element.
	 *
	 * Throws the `view-writer-invalid-range-container` {@link module:utils/ckeditorerror~CKEditorError CKEditorError}
	 * when the {@link module:engine/view/range~Range#start start}
	 * and {@link module:engine/view/range~Range#end end} positions of a passed range are not placed inside same parent container.
	 *
	 * Throws the `view-writer-cannot-break-empty-element` {@link module:utils/ckeditorerror~CKEditorError CKEditorError}
	 * when trying to break attributes inside an {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
	 *
	 * Throws the `view-writer-cannot-break-ui-element` {@link module:utils/ckeditorerror~CKEditorError CKEditorError}
	 * when trying to break attributes inside a {@link module:engine/view/uielement~UIElement UIElement}.
	 *
	 * @see module:engine/view/attributeelement~AttributeElement
	 * @see module:engine/view/containerelement~ContainerElement
	 * @see module:engine/view/downcastwriter~DowncastWriter#breakContainer
	 * @param positionOrRange The position where to break attribute elements.
	 * @returns The new position or range, after breaking the attribute elements.
	 */ breakAttributes(positionOrRange) {
        if (positionOrRange instanceof Position$1) {
            return this._breakAttributes(positionOrRange);
        } else {
            return this._breakAttributesRange(positionOrRange);
        }
    }
    /**
	 * Breaks a {@link module:engine/view/containerelement~ContainerElement container view element} into two, at the given position.
	 * The position has to be directly inside the container element and cannot be in the root. It does not break the conrainer view element
	 * if the position is at the beginning or at the end of its parent element.
	 *
	 * ```html
	 * <p>foo^bar</p> -> <p>foo</p><p>bar</p>
	 * <div><p>foo</p>^<p>bar</p></div> -> <div><p>foo</p></div><div><p>bar</p></div>
	 * <p>^foobar</p> -> ^<p>foobar</p>
	 * <p>foobar^</p> -> <p>foobar</p>^
	 * ```
	 *
	 * **Note:** The difference between {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes breakAttributes()} and
	 * {@link module:engine/view/downcastwriter~DowncastWriter#breakContainer breakContainer()} is that `breakAttributes()` breaks all
	 * {@link module:engine/view/attributeelement~AttributeElement attribute elements} that are ancestors of a given `position`,
	 * up to the first encountered {@link module:engine/view/containerelement~ContainerElement container element}.
	 * `breakContainer()` assumes that the given `position` is directly in the container element and breaks that container element.
	 *
	 * @see module:engine/view/attributeelement~AttributeElement
	 * @see module:engine/view/containerelement~ContainerElement
	 * @see module:engine/view/downcastwriter~DowncastWriter#breakAttributes
	 * @param position The position where to break the element.
	 * @returns The position between broken elements. If an element has not been broken,
	 * the returned position is placed either before or after it.
	 */ breakContainer(position) {
        const element = position.parent;
        if (!element.is('containerElement')) {
            /**
			 * Trying to break an element which is not a container element.
			 *
			 * @error view-writer-break-non-container-element
			 */ throw new CKEditorError('view-writer-break-non-container-element', this.document);
        }
        if (!element.parent) {
            /**
			 * Trying to break root element.
			 *
			 * @error view-writer-break-root
			 */ throw new CKEditorError('view-writer-break-root', this.document);
        }
        if (position.isAtStart) {
            return Position$1._createBefore(element);
        } else if (!position.isAtEnd) {
            const newElement = element._clone(false);
            this.insert(Position$1._createAfter(element), newElement);
            const sourceRange = new Range$1(position, Position$1._createAt(element, 'end'));
            const targetPosition = new Position$1(newElement, 0);
            this.move(sourceRange, targetPosition);
        }
        return Position$1._createAfter(element);
    }
    /**
	 * Merges {@link module:engine/view/attributeelement~AttributeElement attribute elements}. It also merges text nodes if needed.
	 * Only {@link module:engine/view/attributeelement~AttributeElement#isSimilar similar} attribute elements can be merged.
	 *
	 * In following examples `<p>` is a container and `<b>` is an attribute element:
	 *
	 * ```html
	 * <p>foo[]bar</p> -> <p>foo{}bar</p>
	 * <p><b>foo</b>[]<b>bar</b></p> -> <p><b>foo{}bar</b></p>
	 * <p><b foo="bar">a</b>[]<b foo="baz">b</b></p> -> <p><b foo="bar">a</b>[]<b foo="baz">b</b></p>
	 * ```
	 *
	 * It will also take care about empty attributes when merging:
	 *
	 * ```html
	 * <p><b>[]</b></p> -> <p>[]</p>
	 * <p><b>foo</b><i>[]</i><b>bar</b></p> -> <p><b>foo{}bar</b></p>
	 * ```
	 *
	 * **Note:** Difference between {@link module:engine/view/downcastwriter~DowncastWriter#mergeAttributes mergeAttributes} and
	 * {@link module:engine/view/downcastwriter~DowncastWriter#mergeContainers mergeContainers} is that `mergeAttributes` merges two
	 * {@link module:engine/view/attributeelement~AttributeElement attribute elements} or {@link module:engine/view/text~Text text nodes}
	 * while `mergeContainer` merges two {@link module:engine/view/containerelement~ContainerElement container elements}.
	 *
	 * @see module:engine/view/attributeelement~AttributeElement
	 * @see module:engine/view/containerelement~ContainerElement
	 * @see module:engine/view/downcastwriter~DowncastWriter#mergeContainers
	 * @param position Merge position.
	 * @returns Position after merge.
	 */ mergeAttributes(position) {
        const positionOffset = position.offset;
        const positionParent = position.parent;
        // When inside text node - nothing to merge.
        if (positionParent.is('$text')) {
            return position;
        }
        // When inside empty attribute - remove it.
        if (positionParent.is('attributeElement') && positionParent.childCount === 0) {
            const parent = positionParent.parent;
            const offset = positionParent.index;
            positionParent._remove();
            this._removeFromClonedElementsGroup(positionParent);
            return this.mergeAttributes(new Position$1(parent, offset));
        }
        const nodeBefore = positionParent.getChild(positionOffset - 1);
        const nodeAfter = positionParent.getChild(positionOffset);
        // Position should be placed between two nodes.
        if (!nodeBefore || !nodeAfter) {
            return position;
        }
        // When position is between two text nodes.
        if (nodeBefore.is('$text') && nodeAfter.is('$text')) {
            return mergeTextNodes(nodeBefore, nodeAfter);
        } else if (nodeBefore.is('attributeElement') && nodeAfter.is('attributeElement') && nodeBefore.isSimilar(nodeAfter)) {
            // Move all children nodes from node placed after selection and remove that node.
            const count = nodeBefore.childCount;
            nodeBefore._appendChild(nodeAfter.getChildren());
            nodeAfter._remove();
            this._removeFromClonedElementsGroup(nodeAfter);
            // New position is located inside the first node, before new nodes.
            // Call this method recursively to merge again if needed.
            return this.mergeAttributes(new Position$1(nodeBefore, count));
        }
        return position;
    }
    /**
	 * Merges two {@link module:engine/view/containerelement~ContainerElement container elements} that are before and after given position.
	 * Precisely, the element after the position is removed and it's contents are moved to element before the position.
	 *
	 * ```html
	 * <p>foo</p>^<p>bar</p> -> <p>foo^bar</p>
	 * <div>foo</div>^<p>bar</p> -> <div>foo^bar</div>
	 * ```
	 *
	 * **Note:** Difference between {@link module:engine/view/downcastwriter~DowncastWriter#mergeAttributes mergeAttributes} and
	 * {@link module:engine/view/downcastwriter~DowncastWriter#mergeContainers mergeContainers} is that `mergeAttributes` merges two
	 * {@link module:engine/view/attributeelement~AttributeElement attribute elements} or {@link module:engine/view/text~Text text nodes}
	 * while `mergeContainer` merges two {@link module:engine/view/containerelement~ContainerElement container elements}.
	 *
	 * @see module:engine/view/attributeelement~AttributeElement
	 * @see module:engine/view/containerelement~ContainerElement
	 * @see module:engine/view/downcastwriter~DowncastWriter#mergeAttributes
	 * @param position Merge position.
	 * @returns Position after merge.
	 */ mergeContainers(position) {
        const prev = position.nodeBefore;
        const next = position.nodeAfter;
        if (!prev || !next || !prev.is('containerElement') || !next.is('containerElement')) {
            /**
			 * Element before and after given position cannot be merged.
			 *
			 * @error view-writer-merge-containers-invalid-position
			 */ throw new CKEditorError('view-writer-merge-containers-invalid-position', this.document);
        }
        const lastChild = prev.getChild(prev.childCount - 1);
        const newPosition = lastChild instanceof Text$1 ? Position$1._createAt(lastChild, 'end') : Position$1._createAt(prev, 'end');
        this.move(Range$1._createIn(next), Position$1._createAt(prev, 'end'));
        this.remove(Range$1._createOn(next));
        return newPosition;
    }
    /**
	 * Inserts a node or nodes at specified position. Takes care about breaking attributes before insertion
	 * and merging them afterwards.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
	 * contains instances that are not {@link module:engine/view/text~Text Texts},
	 * {@link module:engine/view/attributeelement~AttributeElement AttributeElements},
	 * {@link module:engine/view/containerelement~ContainerElement ContainerElements},
	 * {@link module:engine/view/emptyelement~EmptyElement EmptyElements},
	 * {@link module:engine/view/rawelement~RawElement RawElements} or
	 * {@link module:engine/view/uielement~UIElement UIElements}.
	 *
	 * @param position Insertion position.
	 * @param nodes Node or nodes to insert.
	 * @returns Range around inserted nodes.
	 */ insert(position, nodes) {
        nodes = isIterable(nodes) ? [
            ...nodes
        ] : [
            nodes
        ];
        // Check if nodes to insert are instances of AttributeElements, ContainerElements, EmptyElements, UIElements or Text.
        validateNodesToInsert(nodes, this.document);
        // Group nodes in batches of nodes that require or do not require breaking an AttributeElements.
        const nodeGroups = nodes.reduce((groups, node)=>{
            const lastGroup = groups[groups.length - 1];
            // Break attributes on nodes that do exist in the model tree so they can have attributes, other elements
            // can't have an attribute in model and won't get wrapped with an AttributeElement while down-casted.
            const breakAttributes = !node.is('uiElement');
            if (!lastGroup || lastGroup.breakAttributes != breakAttributes) {
                groups.push({
                    breakAttributes,
                    nodes: [
                        node
                    ]
                });
            } else {
                lastGroup.nodes.push(node);
            }
            return groups;
        }, []);
        // Insert nodes in batches.
        let start = null;
        let end = position;
        for (const { nodes, breakAttributes } of nodeGroups){
            const range = this._insertNodes(end, nodes, breakAttributes);
            if (!start) {
                start = range.start;
            }
            end = range.end;
        }
        // When no nodes were inserted - return collapsed range.
        if (!start) {
            return new Range$1(position);
        }
        return new Range$1(start, end);
    }
    /**
	 * Removes provided range from the container.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
	 * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
	 * same parent container.
	 *
	 * @param rangeOrItem Range to remove from container
	 * or an {@link module:engine/view/item~Item item} to remove. If range is provided, after removing, it will be updated
	 * to a collapsed range showing the new position.
	 * @returns Document fragment containing removed nodes.
	 */ remove(rangeOrItem) {
        const range = rangeOrItem instanceof Range$1 ? rangeOrItem : Range$1._createOn(rangeOrItem);
        validateRangeContainer(range, this.document);
        // If range is collapsed - nothing to remove.
        if (range.isCollapsed) {
            return new DocumentFragment$1(this.document);
        }
        // Break attributes at range start and end.
        const { start: breakStart, end: breakEnd } = this._breakAttributesRange(range, true);
        const parentContainer = breakStart.parent;
        const count = breakEnd.offset - breakStart.offset;
        // Remove nodes in range.
        const removed = parentContainer._removeChildren(breakStart.offset, count);
        for (const node of removed){
            this._removeFromClonedElementsGroup(node);
        }
        // Merge after removing.
        const mergePosition = this.mergeAttributes(breakStart);
        range.start = mergePosition;
        range.end = mergePosition.clone();
        // Return removed nodes.
        return new DocumentFragment$1(this.document, removed);
    }
    /**
	 * Removes matching elements from given range.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
	 * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
	 * same parent container.
	 *
	 * @param range Range to clear.
	 * @param element Element to remove.
	 */ clear(range, element) {
        validateRangeContainer(range, this.document);
        // Create walker on given range.
        // We walk backward because when we remove element during walk it modifies range end position.
        const walker = range.getWalker({
            direction: 'backward',
            ignoreElementEnd: true
        });
        // Let's walk.
        for (const current of walker){
            const item = current.item;
            let rangeToRemove;
            // When current item matches to the given element.
            if (item.is('element') && element.isSimilar(item)) {
                // Create range on this element.
                rangeToRemove = Range$1._createOn(item);
            // When range starts inside Text or TextProxy element.
            } else if (!current.nextPosition.isAfter(range.start) && item.is('$textProxy')) {
                // We need to check if parent of this text matches to given element.
                const parentElement = item.getAncestors().find((ancestor)=>{
                    return ancestor.is('element') && element.isSimilar(ancestor);
                });
                // If it is then create range inside this element.
                if (parentElement) {
                    rangeToRemove = Range$1._createIn(parentElement);
                }
            }
            // If we have found element to remove.
            if (rangeToRemove) {
                // We need to check if element range stick out of the given range and truncate if it is.
                if (rangeToRemove.end.isAfter(range.end)) {
                    rangeToRemove.end = range.end;
                }
                if (rangeToRemove.start.isBefore(range.start)) {
                    rangeToRemove.start = range.start;
                }
                // At the end we remove range with found element.
                this.remove(rangeToRemove);
            }
        }
    }
    /**
	 * Moves nodes from provided range to target position.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
	 * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
	 * same parent container.
	 *
	 * @param sourceRange Range containing nodes to move.
	 * @param targetPosition Position to insert.
	 * @returns Range in target container. Inserted nodes are placed between
	 * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions.
	 */ move(sourceRange, targetPosition) {
        let nodes;
        if (targetPosition.isAfter(sourceRange.end)) {
            targetPosition = this._breakAttributes(targetPosition, true);
            const parent = targetPosition.parent;
            const countBefore = parent.childCount;
            sourceRange = this._breakAttributesRange(sourceRange, true);
            nodes = this.remove(sourceRange);
            targetPosition.offset += parent.childCount - countBefore;
        } else {
            nodes = this.remove(sourceRange);
        }
        return this.insert(targetPosition, nodes);
    }
    /**
	 * Wraps elements within range with provided {@link module:engine/view/attributeelement~AttributeElement AttributeElement}.
	 * If a collapsed range is provided, it will be wrapped only if it is equal to view selection.
	 *
	 * If a collapsed range was passed and is same as selection, the selection
	 * will be moved to the inside of the wrapped attribute element.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-invalid-range-container`
	 * when {@link module:engine/view/range~Range#start}
	 * and {@link module:engine/view/range~Range#end} positions are not placed inside same parent container.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
	 * an instance of {@link module:engine/view/attributeelement~AttributeElement AttributeElement}.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-nonselection-collapsed-range` when passed range
	 * is collapsed and different than view selection.
	 *
	 * @param range Range to wrap.
	 * @param attribute Attribute element to use as wrapper.
	 * @returns range Range after wrapping, spanning over wrapping attribute element.
	 */ wrap(range, attribute) {
        if (!(attribute instanceof AttributeElement)) {
            throw new CKEditorError('view-writer-wrap-invalid-attribute', this.document);
        }
        validateRangeContainer(range, this.document);
        if (!range.isCollapsed) {
            // Non-collapsed range. Wrap it with the attribute element.
            return this._wrapRange(range, attribute);
        } else {
            // Collapsed range. Wrap position.
            let position = range.start;
            if (position.parent.is('element') && !_hasNonUiChildren(position.parent)) {
                position = position.getLastMatchingPosition((value)=>value.item.is('uiElement'));
            }
            position = this._wrapPosition(position, attribute);
            const viewSelection = this.document.selection;
            // If wrapping position is equal to view selection, move view selection inside wrapping attribute element.
            if (viewSelection.isCollapsed && viewSelection.getFirstPosition().isEqual(range.start)) {
                this.setSelection(position);
            }
            return new Range$1(position);
        }
    }
    /**
	 * Unwraps nodes within provided range from attribute element.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
	 * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
	 * same parent container.
	 */ unwrap(range, attribute) {
        if (!(attribute instanceof AttributeElement)) {
            /**
			 * The `attribute` passed to {@link module:engine/view/downcastwriter~DowncastWriter#unwrap `DowncastWriter#unwrap()`}
			 * must be an instance of {@link module:engine/view/attributeelement~AttributeElement `AttributeElement`}.
			 *
			 * @error view-writer-unwrap-invalid-attribute
			 */ throw new CKEditorError('view-writer-unwrap-invalid-attribute', this.document);
        }
        validateRangeContainer(range, this.document);
        // If range is collapsed - nothing to unwrap.
        if (range.isCollapsed) {
            return range;
        }
        // Break attributes at range start and end.
        const { start: breakStart, end: breakEnd } = this._breakAttributesRange(range, true);
        const parentContainer = breakStart.parent;
        // Unwrap children located between break points.
        const newRange = this._unwrapChildren(parentContainer, breakStart.offset, breakEnd.offset, attribute);
        // Merge attributes at the both ends and return a new range.
        const start = this.mergeAttributes(newRange.start);
        // If start position was merged - move end position back.
        if (!start.isEqual(newRange.start)) {
            newRange.end.offset--;
        }
        const end = this.mergeAttributes(newRange.end);
        return new Range$1(start, end);
    }
    /**
	 * Renames element by creating a copy of renamed element but with changed name and then moving contents of the
	 * old element to the new one. Keep in mind that this will invalidate all {@link module:engine/view/position~Position positions} which
	 * has renamed element as {@link module:engine/view/position~Position#parent a parent}.
	 *
	 * New element has to be created because `Element#tagName` property in DOM is readonly.
	 *
	 * Since this function creates a new element and removes the given one, the new element is returned to keep reference.
	 *
	 * @param newName New name for element.
	 * @param viewElement Element to be renamed.
	 * @returns Element created due to rename.
	 */ rename(newName, viewElement) {
        const newElement = new ContainerElement(this.document, newName, viewElement.getAttributes());
        this.insert(Position$1._createAfter(viewElement), newElement);
        this.move(Range$1._createIn(viewElement), Position$1._createAt(newElement, 0));
        this.remove(Range$1._createOn(viewElement));
        return newElement;
    }
    /**
	 * Cleans up memory by removing obsolete cloned elements group from the writer.
	 *
	 * Should be used whenever all {@link module:engine/view/attributeelement~AttributeElement attribute elements}
	 * with the same {@link module:engine/view/attributeelement~AttributeElement#id id} are going to be removed from the view and
	 * the group will no longer be needed.
	 *
	 * Cloned elements group are not removed automatically in case if the group is still needed after all its elements
	 * were removed from the view.
	 *
	 * Keep in mind that group names are equal to the `id` property of the attribute element.
	 *
	 * @param groupName Name of the group to clear.
	 */ clearClonedElementsGroup(groupName) {
        this._cloneGroups.delete(groupName);
    }
    /**
	 * Creates position at the given location. The location can be specified as:
	 *
	 * * a {@link module:engine/view/position~Position position},
	 * * parent element and offset (offset defaults to `0`),
	 * * parent element and `'end'` (sets position at the end of that element),
	 * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
	 *
	 * This method is a shortcut to other constructors such as:
	 *
	 * * {@link #createPositionBefore},
	 * * {@link #createPositionAfter},
	 *
	 * @param offset Offset or one of the flags. Used only when the first parameter is a {@link module:engine/view/item~Item view item}.
	 */ createPositionAt(itemOrPosition, offset) {
        return Position$1._createAt(itemOrPosition, offset);
    }
    /**
	 * Creates a new position after given view item.
	 *
	 * @param item View item after which the position should be located.
	 */ createPositionAfter(item) {
        return Position$1._createAfter(item);
    }
    /**
	 * Creates a new position before given view item.
	 *
	 * @param item View item before which the position should be located.
	 */ createPositionBefore(item) {
        return Position$1._createBefore(item);
    }
    /**
	 * Creates a range spanning from `start` position to `end` position.
	 *
	 * **Note:** This factory method creates its own {@link module:engine/view/position~Position} instances basing on passed values.
	 *
	 * @param start Start position.
	 * @param end End position. If not set, range will be collapsed at `start` position.
	 */ createRange(start, end) {
        return new Range$1(start, end);
    }
    /**
	 * Creates a range that starts before given {@link module:engine/view/item~Item view item} and ends after it.
	 */ createRangeOn(item) {
        return Range$1._createOn(item);
    }
    /**
	 * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
	 * that element and ends after the last child of that element.
	 *
	 * @param element Element which is a parent for the range.
	 */ createRangeIn(element) {
        return Range$1._createIn(element);
    }
    createSelection(...args) {
        return new Selection$1(...args);
    }
    /**
	 * Creates placeholders for child elements of the {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToStructure
	 * `elementToStructure()`} conversion helper.
	 *
	 * ```ts
	 * const viewSlot = conversionApi.writer.createSlot();
	 * const viewPosition = conversionApi.writer.createPositionAt( viewElement, 0 );
	 *
	 * conversionApi.writer.insert( viewPosition, viewSlot );
	 * ```
	 *
	 * It could be filtered down to a specific subset of children (only `<foo>` model elements in this case):
	 *
	 * ```ts
	 * const viewSlot = conversionApi.writer.createSlot( node => node.is( 'element', 'foo' ) );
	 * const viewPosition = conversionApi.writer.createPositionAt( viewElement, 0 );
	 *
	 * conversionApi.writer.insert( viewPosition, viewSlot );
	 * ```
	 *
	 * While providing a filtered slot, make sure to provide slots for all child nodes. A single node can not be downcasted into
	 * multiple slots.
	 *
	 * **Note**: You should not change the order of nodes. View elements should be in the same order as model nodes.
	 *
	 * @param modeOrFilter The filter for child nodes.
	 * @returns The slot element to be placed in to the view structure while processing
	 * {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToStructure `elementToStructure()`}.
	 */ createSlot(modeOrFilter = 'children') {
        if (!this._slotFactory) {
            /**
			 * The `createSlot()` method is only allowed inside the `elementToStructure` downcast helper callback.
			 *
			 * @error view-writer-invalid-create-slot-context
			 */ throw new CKEditorError('view-writer-invalid-create-slot-context', this.document);
        }
        return this._slotFactory(this, modeOrFilter);
    }
    /**
	 * Registers a slot factory.
	 *
	 * @internal
	 * @param slotFactory The slot factory.
	 */ _registerSlotFactory(slotFactory) {
        this._slotFactory = slotFactory;
    }
    /**
	 * Clears the registered slot factory.
	 *
	 * @internal
	 */ _clearSlotFactory() {
        this._slotFactory = null;
    }
    /**
	 * Inserts a node or nodes at the specified position. Takes care of breaking attributes before insertion
	 * and merging them afterwards if requested by the breakAttributes param.
	 *
	 * @param position Insertion position.
	 * @param nodes Node or nodes to insert.
	 * @param breakAttributes Whether attributes should be broken.
	 * @returns Range around inserted nodes.
	 */ _insertNodes(position, nodes, breakAttributes) {
        let parentElement;
        // Break attributes on nodes that do exist in the model tree so they can have attributes, other elements
        // can't have an attribute in model and won't get wrapped with an AttributeElement while down-casted.
        if (breakAttributes) {
            parentElement = getParentContainer(position);
        } else {
            parentElement = position.parent.is('$text') ? position.parent.parent : position.parent;
        }
        if (!parentElement) {
            /**
			 * Position's parent container cannot be found.
			 *
			 * @error view-writer-invalid-position-container
			 */ throw new CKEditorError('view-writer-invalid-position-container', this.document);
        }
        let insertionPosition;
        if (breakAttributes) {
            insertionPosition = this._breakAttributes(position, true);
        } else {
            insertionPosition = position.parent.is('$text') ? breakTextNode(position) : position;
        }
        const length = parentElement._insertChild(insertionPosition.offset, nodes);
        for (const node of nodes){
            this._addToClonedElementsGroup(node);
        }
        const endPosition = insertionPosition.getShiftedBy(length);
        const start = this.mergeAttributes(insertionPosition);
        // If start position was merged - move end position.
        if (!start.isEqual(insertionPosition)) {
            endPosition.offset--;
        }
        const end = this.mergeAttributes(endPosition);
        return new Range$1(start, end);
    }
    /**
	 * Wraps children with provided `wrapElement`. Only children contained in `parent` element between
	 * `startOffset` and `endOffset` will be wrapped.
	 */ _wrapChildren(parent, startOffset, endOffset, wrapElement) {
        let i = startOffset;
        const wrapPositions = [];
        while(i < endOffset){
            const child = parent.getChild(i);
            const isText = child.is('$text');
            const isAttribute = child.is('attributeElement');
            //
            // (In all examples, assume that `wrapElement` is `<span class="foo">` element.)
            //
            // Check if `wrapElement` can be joined with the wrapped element. One of requirements is having same name.
            // If possible, join elements.
            //
            // <p><span class="bar">abc</span></p>  -->  <p><span class="foo bar">abc</span></p>
            //
            if (isAttribute && this._wrapAttributeElement(wrapElement, child)) {
                wrapPositions.push(new Position$1(parent, i));
            } else if (isText || !isAttribute || shouldABeOutsideB(wrapElement, child)) {
                // Clone attribute.
                const newAttribute = wrapElement._clone();
                // Wrap current node with new attribute.
                child._remove();
                newAttribute._appendChild(child);
                parent._insertChild(i, newAttribute);
                this._addToClonedElementsGroup(newAttribute);
                wrapPositions.push(new Position$1(parent, i));
            } else /* if ( isAttribute ) */ {
                this._wrapChildren(child, 0, child.childCount, wrapElement);
            }
            i++;
        }
        // Merge at each wrap.
        let offsetChange = 0;
        for (const position of wrapPositions){
            position.offset -= offsetChange;
            // Do not merge with elements outside selected children.
            if (position.offset == startOffset) {
                continue;
            }
            const newPosition = this.mergeAttributes(position);
            // If nodes were merged - other merge offsets will change.
            if (!newPosition.isEqual(position)) {
                offsetChange++;
                endOffset--;
            }
        }
        return Range$1._createFromParentsAndOffsets(parent, startOffset, parent, endOffset);
    }
    /**
	 * Unwraps children from provided `unwrapElement`. Only children contained in `parent` element between
	 * `startOffset` and `endOffset` will be unwrapped.
	 */ _unwrapChildren(parent, startOffset, endOffset, unwrapElement) {
        let i = startOffset;
        const unwrapPositions = [];
        // Iterate over each element between provided offsets inside parent.
        // We don't use tree walker or range iterator because we will be removing and merging potentially multiple nodes,
        // so it could get messy. It is safer to it manually in this case.
        while(i < endOffset){
            const child = parent.getChild(i);
            // Skip all text nodes. There should be no container element's here either.
            if (!child.is('attributeElement')) {
                i++;
                continue;
            }
            //
            // (In all examples, assume that `unwrapElement` is `<span class="foo">` element.)
            //
            // If the child is similar to the given attribute element, unwrap it - it will be completely removed.
            //
            // <p><span class="foo">abc</span>xyz</p>  -->  <p>abcxyz</p>
            //
            if (child.isSimilar(unwrapElement)) {
                const unwrapped = child.getChildren();
                const count = child.childCount;
                // Replace wrapper element with its children
                child._remove();
                parent._insertChild(i, unwrapped);
                this._removeFromClonedElementsGroup(child);
                // Save start and end position of moved items.
                unwrapPositions.push(new Position$1(parent, i), new Position$1(parent, i + count));
                // Skip elements that were unwrapped. Assuming there won't be another element to unwrap in child elements.
                i += count;
                endOffset += count - 1;
                continue;
            }
            //
            // If the child is not similar but is an attribute element, try partial unwrapping - remove the same attributes/styles/classes.
            // Partial unwrapping will happen only if the elements have the same name.
            //
            // <p><span class="foo bar">abc</span>xyz</p>  -->  <p><span class="bar">abc</span>xyz</p>
            // <p><i class="foo">abc</i>xyz</p>            -->  <p><i class="foo">abc</i>xyz</p>
            //
            if (this._unwrapAttributeElement(unwrapElement, child)) {
                unwrapPositions.push(new Position$1(parent, i), new Position$1(parent, i + 1));
                i++;
                continue;
            }
            //
            // If other nested attribute is found, look through it's children for elements to unwrap.
            //
            // <p><i><span class="foo">abc</span></i><p>  -->  <p><i>abc</i><p>
            //
            this._unwrapChildren(child, 0, child.childCount, unwrapElement);
            i++;
        }
        // Merge at each unwrap.
        let offsetChange = 0;
        for (const position of unwrapPositions){
            position.offset -= offsetChange;
            // Do not merge with elements outside selected children.
            if (position.offset == startOffset || position.offset == endOffset) {
                continue;
            }
            const newPosition = this.mergeAttributes(position);
            // If nodes were merged - other merge offsets will change.
            if (!newPosition.isEqual(position)) {
                offsetChange++;
                endOffset--;
            }
        }
        return Range$1._createFromParentsAndOffsets(parent, startOffset, parent, endOffset);
    }
    /**
	 * Helper function for `view.writer.wrap`. Wraps range with provided attribute element.
	 * This method will also merge newly added attribute element with its siblings whenever possible.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
	 * an instance of {@link module:engine/view/attributeelement~AttributeElement AttributeElement}.
	 *
	 * @returns New range after wrapping, spanning over wrapping attribute element.
	 */ _wrapRange(range, attribute) {
        // Break attributes at range start and end.
        const { start: breakStart, end: breakEnd } = this._breakAttributesRange(range, true);
        const parentContainer = breakStart.parent;
        // Wrap all children with attribute.
        const newRange = this._wrapChildren(parentContainer, breakStart.offset, breakEnd.offset, attribute);
        // Merge attributes at the both ends and return a new range.
        const start = this.mergeAttributes(newRange.start);
        // If start position was merged - move end position back.
        if (!start.isEqual(newRange.start)) {
            newRange.end.offset--;
        }
        const end = this.mergeAttributes(newRange.end);
        return new Range$1(start, end);
    }
    /**
	 * Helper function for {@link #wrap}. Wraps position with provided attribute element.
	 * This method will also merge newly added attribute element with its siblings whenever possible.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
	 * an instance of {@link module:engine/view/attributeelement~AttributeElement AttributeElement}.
	 *
	 * @returns New position after wrapping.
	 */ _wrapPosition(position, attribute) {
        // Return same position when trying to wrap with attribute similar to position parent.
        if (attribute.isSimilar(position.parent)) {
            return movePositionToTextNode(position.clone());
        }
        // When position is inside text node - break it and place new position between two text nodes.
        if (position.parent.is('$text')) {
            position = breakTextNode(position);
        }
        // Create fake element that will represent position, and will not be merged with other attributes.
        const fakeElement = this.createAttributeElement('_wrapPosition-fake-element');
        fakeElement._priority = Number.POSITIVE_INFINITY;
        fakeElement.isSimilar = ()=>false;
        // Insert fake element in position location.
        position.parent._insertChild(position.offset, fakeElement);
        // Range around inserted fake attribute element.
        const wrapRange = new Range$1(position, position.getShiftedBy(1));
        // Wrap fake element with attribute (it will also merge if possible).
        this.wrap(wrapRange, attribute);
        // Remove fake element and place new position there.
        const newPosition = new Position$1(fakeElement.parent, fakeElement.index);
        fakeElement._remove();
        // If position is placed between text nodes - merge them and return position inside.
        const nodeBefore = newPosition.nodeBefore;
        const nodeAfter = newPosition.nodeAfter;
        if (nodeBefore instanceof Text$1 && nodeAfter instanceof Text$1) {
            return mergeTextNodes(nodeBefore, nodeAfter);
        }
        // If position is next to text node - move position inside.
        return movePositionToTextNode(newPosition);
    }
    /**
	 * Wraps one {@link module:engine/view/attributeelement~AttributeElement AttributeElement} into another by
	 * merging them if possible. When merging is possible - all attributes, styles and classes are moved from wrapper
	 * element to element being wrapped.
	 *
	 * @param wrapper Wrapper AttributeElement.
	 * @param toWrap AttributeElement to wrap using wrapper element.
	 * @returns Returns `true` if elements are merged.
	 */ _wrapAttributeElement(wrapper, toWrap) {
        if (!canBeJoined(wrapper, toWrap)) {
            return false;
        }
        // Can't merge if name or priority differs.
        if (wrapper.name !== toWrap.name || wrapper.priority !== toWrap.priority) {
            return false;
        }
        // Check if attributes can be merged.
        for (const key of wrapper.getAttributeKeys()){
            // Classes and styles should be checked separately.
            if (key === 'class' || key === 'style') {
                continue;
            }
            // If some attributes are different we cannot wrap.
            if (toWrap.hasAttribute(key) && toWrap.getAttribute(key) !== wrapper.getAttribute(key)) {
                return false;
            }
        }
        // Check if styles can be merged.
        for (const key of wrapper.getStyleNames()){
            if (toWrap.hasStyle(key) && toWrap.getStyle(key) !== wrapper.getStyle(key)) {
                return false;
            }
        }
        // Move all attributes/classes/styles from wrapper to wrapped AttributeElement.
        for (const key of wrapper.getAttributeKeys()){
            // Classes and styles should be checked separately.
            if (key === 'class' || key === 'style') {
                continue;
            }
            // Move only these attributes that are not present - other are similar.
            if (!toWrap.hasAttribute(key)) {
                this.setAttribute(key, wrapper.getAttribute(key), toWrap);
            }
        }
        for (const key of wrapper.getStyleNames()){
            if (!toWrap.hasStyle(key)) {
                this.setStyle(key, wrapper.getStyle(key), toWrap);
            }
        }
        for (const key of wrapper.getClassNames()){
            if (!toWrap.hasClass(key)) {
                this.addClass(key, toWrap);
            }
        }
        return true;
    }
    /**
	 * Unwraps {@link module:engine/view/attributeelement~AttributeElement AttributeElement} from another by removing
	 * corresponding attributes, classes and styles. All attributes, classes and styles from wrapper should be present
	 * inside element being unwrapped.
	 *
	 * @param wrapper Wrapper AttributeElement.
	 * @param toUnwrap AttributeElement to unwrap using wrapper element.
	 * @returns Returns `true` if elements are unwrapped.
	 **/ _unwrapAttributeElement(wrapper, toUnwrap) {
        if (!canBeJoined(wrapper, toUnwrap)) {
            return false;
        }
        // Can't unwrap if name or priority differs.
        if (wrapper.name !== toUnwrap.name || wrapper.priority !== toUnwrap.priority) {
            return false;
        }
        // Check if AttributeElement has all wrapper attributes.
        for (const key of wrapper.getAttributeKeys()){
            // Classes and styles should be checked separately.
            if (key === 'class' || key === 'style') {
                continue;
            }
            // If some attributes are missing or different we cannot unwrap.
            if (!toUnwrap.hasAttribute(key) || toUnwrap.getAttribute(key) !== wrapper.getAttribute(key)) {
                return false;
            }
        }
        // Check if AttributeElement has all wrapper classes.
        if (!toUnwrap.hasClass(...wrapper.getClassNames())) {
            return false;
        }
        // Check if AttributeElement has all wrapper styles.
        for (const key of wrapper.getStyleNames()){
            // If some styles are missing or different we cannot unwrap.
            if (!toUnwrap.hasStyle(key) || toUnwrap.getStyle(key) !== wrapper.getStyle(key)) {
                return false;
            }
        }
        // Remove all wrapper's attributes from unwrapped element.
        for (const key of wrapper.getAttributeKeys()){
            // Classes and styles should be checked separately.
            if (key === 'class' || key === 'style') {
                continue;
            }
            this.removeAttribute(key, toUnwrap);
        }
        // Remove all wrapper's classes from unwrapped element.
        this.removeClass(Array.from(wrapper.getClassNames()), toUnwrap);
        // Remove all wrapper's styles from unwrapped element.
        this.removeStyle(Array.from(wrapper.getStyleNames()), toUnwrap);
        return true;
    }
    /**
	 * Helper function used by other `DowncastWriter` methods. Breaks attribute elements at the boundaries of given range.
	 *
	 * @param range Range which `start` and `end` positions will be used to break attributes.
	 * @param forceSplitText If set to `true`, will break text nodes even if they are directly in container element.
	 * This behavior will result in incorrect view state, but is needed by other view writing methods which then fixes view state.
	 * @returns New range with located at break positions.
	 */ _breakAttributesRange(range, forceSplitText = false) {
        const rangeStart = range.start;
        const rangeEnd = range.end;
        validateRangeContainer(range, this.document);
        // Break at the collapsed position. Return new collapsed range.
        if (range.isCollapsed) {
            const position = this._breakAttributes(range.start, forceSplitText);
            return new Range$1(position, position);
        }
        const breakEnd = this._breakAttributes(rangeEnd, forceSplitText);
        const count = breakEnd.parent.childCount;
        const breakStart = this._breakAttributes(rangeStart, forceSplitText);
        // Calculate new break end offset.
        breakEnd.offset += breakEnd.parent.childCount - count;
        return new Range$1(breakStart, breakEnd);
    }
    /**
	 * Helper function used by other `DowncastWriter` methods. Breaks attribute elements at given position.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-empty-element` when break position
	 * is placed inside {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-ui-element` when break position
	 * is placed inside {@link module:engine/view/uielement~UIElement UIElement}.
	 *
	 * @param position Position where to break attributes.
	 * @param forceSplitText If set to `true`, will break text nodes even if they are directly in container element.
	 * This behavior will result in incorrect view state, but is needed by other view writing methods which then fixes view state.
	 * @returns New position after breaking the attributes.
	 */ _breakAttributes(position, forceSplitText = false) {
        const positionOffset = position.offset;
        const positionParent = position.parent;
        // If position is placed inside EmptyElement - throw an exception as we cannot break inside.
        if (position.parent.is('emptyElement')) {
            /**
			 * Cannot break an `EmptyElement` instance.
			 *
			 * This error is thrown if
			 * {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes `DowncastWriter#breakAttributes()`}
			 * was executed in an incorrect position.
			 *
			 * @error view-writer-cannot-break-empty-element
			 */ throw new CKEditorError('view-writer-cannot-break-empty-element', this.document);
        }
        // If position is placed inside UIElement - throw an exception as we cannot break inside.
        if (position.parent.is('uiElement')) {
            /**
			 * Cannot break a `UIElement` instance.
			 *
			 * This error is thrown if
			 * {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes `DowncastWriter#breakAttributes()`}
			 * was executed in an incorrect position.
			 *
			 * @error view-writer-cannot-break-ui-element
			 */ throw new CKEditorError('view-writer-cannot-break-ui-element', this.document);
        }
        // If position is placed inside RawElement - throw an exception as we cannot break inside.
        if (position.parent.is('rawElement')) {
            /**
			 * Cannot break a `RawElement` instance.
			 *
			 * This error is thrown if
			 * {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes `DowncastWriter#breakAttributes()`}
			 * was executed in an incorrect position.
			 *
			 * @error view-writer-cannot-break-raw-element
			 */ throw new CKEditorError('view-writer-cannot-break-raw-element', this.document);
        }
        // There are no attributes to break and text nodes breaking is not forced.
        if (!forceSplitText && positionParent.is('$text') && isContainerOrFragment(positionParent.parent)) {
            return position.clone();
        }
        // Position's parent is container, so no attributes to break.
        if (isContainerOrFragment(positionParent)) {
            return position.clone();
        }
        // Break text and start again in new position.
        if (positionParent.is('$text')) {
            return this._breakAttributes(breakTextNode(position), forceSplitText);
        }
        const length = positionParent.childCount;
        // <p>foo<b><u>bar{}</u></b></p>
        // <p>foo<b><u>bar</u>[]</b></p>
        // <p>foo<b><u>bar</u></b>[]</p>
        if (positionOffset == length) {
            const newPosition = new Position$1(positionParent.parent, positionParent.index + 1);
            return this._breakAttributes(newPosition, forceSplitText);
        } else {
            // <p>foo<b><u>{}bar</u></b></p>
            // <p>foo<b>[]<u>bar</u></b></p>
            // <p>foo{}<b><u>bar</u></b></p>
            if (positionOffset === 0) {
                const newPosition = new Position$1(positionParent.parent, positionParent.index);
                return this._breakAttributes(newPosition, forceSplitText);
            } else {
                const offsetAfter = positionParent.index + 1;
                // Break element.
                const clonedNode = positionParent._clone();
                // Insert cloned node to position's parent node.
                positionParent.parent._insertChild(offsetAfter, clonedNode);
                this._addToClonedElementsGroup(clonedNode);
                // Get nodes to move.
                const count = positionParent.childCount - positionOffset;
                const nodesToMove = positionParent._removeChildren(positionOffset, count);
                // Move nodes to cloned node.
                clonedNode._appendChild(nodesToMove);
                // Create new position to work on.
                const newPosition = new Position$1(positionParent.parent, offsetAfter);
                return this._breakAttributes(newPosition, forceSplitText);
            }
        }
    }
    /**
	 * Stores the information that an {@link module:engine/view/attributeelement~AttributeElement attribute element} was
	 * added to the tree. Saves the reference to the group in the given element and updates the group, so other elements
	 * from the group now keep a reference to the given attribute element.
	 *
	 * The clones group can be obtained using {@link module:engine/view/attributeelement~AttributeElement#getElementsWithSameId}.
	 *
	 * Does nothing if added element has no {@link module:engine/view/attributeelement~AttributeElement#id id}.
	 *
	 * @param element Attribute element to save.
	 */ _addToClonedElementsGroup(element) {
        // Add only if the element is in document tree.
        if (!element.root.is('rootElement')) {
            return;
        }
        // Traverse the element's children recursively to find other attribute elements that also might got inserted.
        // The loop is at the beginning so we can make fast returns later in the code.
        if (element.is('element')) {
            for (const child of element.getChildren()){
                this._addToClonedElementsGroup(child);
            }
        }
        const id = element.id;
        if (!id) {
            return;
        }
        let group = this._cloneGroups.get(id);
        if (!group) {
            group = new Set();
            this._cloneGroups.set(id, group);
        }
        group.add(element);
        element._clonesGroup = group;
    }
    /**
	 * Removes all the information about the given {@link module:engine/view/attributeelement~AttributeElement attribute element}
	 * from its clones group.
	 *
	 * Keep in mind, that the element will still keep a reference to the group (but the group will not keep a reference to it).
	 * This allows to reference the whole group even if the element was already removed from the tree.
	 *
	 * Does nothing if the element has no {@link module:engine/view/attributeelement~AttributeElement#id id}.
	 *
	 * @param element Attribute element to remove.
	 */ _removeFromClonedElementsGroup(element) {
        // Traverse the element's children recursively to find other attribute elements that also got removed.
        // The loop is at the beginning so we can make fast returns later in the code.
        if (element.is('element')) {
            for (const child of element.getChildren()){
                this._removeFromClonedElementsGroup(child);
            }
        }
        const id = element.id;
        if (!id) {
            return;
        }
        const group = this._cloneGroups.get(id);
        if (!group) {
            return;
        }
        group.delete(element);
    // Not removing group from element on purpose!
    // If other parts of code have reference to this element, they will be able to get references to other elements from the group.
    }
}
// Helper function for `view.writer.wrap`. Checks if given element has any children that are not ui elements.
function _hasNonUiChildren(parent) {
    return Array.from(parent.getChildren()).some((child)=>!child.is('uiElement'));
}
/**
 * The `attribute` passed to {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#wrap()`}
 * must be an instance of {@link module:engine/view/attributeelement~AttributeElement `AttributeElement`}.
 *
 * @error view-writer-wrap-invalid-attribute
 */ /**
 * Returns first parent container of specified {@link module:engine/view/position~Position Position}.
 * Position's parent node is checked as first, then next parents are checked.
 * Note that {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container.
 *
 * @param position Position used as a start point to locate parent container.
 * @returns Parent container element or `undefined` if container is not found.
 */ function getParentContainer(position) {
    let parent = position.parent;
    while(!isContainerOrFragment(parent)){
        if (!parent) {
            return undefined;
        }
        parent = parent.parent;
    }
    return parent;
}
/**
 * Checks if first {@link module:engine/view/attributeelement~AttributeElement AttributeElement} provided to the function
 * can be wrapped outside second element. It is done by comparing elements'
 * {@link module:engine/view/attributeelement~AttributeElement#priority priorities}, if both have same priority
 * {@link module:engine/view/element~Element#getIdentity identities} are compared.
 */ function shouldABeOutsideB(a, b) {
    if (a.priority < b.priority) {
        return true;
    } else if (a.priority > b.priority) {
        return false;
    }
    // When priorities are equal and names are different - use identities.
    return a.getIdentity() < b.getIdentity();
}
/**
 * Returns new position that is moved to near text node. Returns same position if there is no text node before of after
 * specified position.
 *
 * ```html
 * <p>foo[]</p>  ->  <p>foo{}</p>
 * <p>[]foo</p>  ->  <p>{}foo</p>
 * ```
 *
 * @returns Position located inside text node or same position if there is no text nodes
 * before or after position location.
 */ function movePositionToTextNode(position) {
    const nodeBefore = position.nodeBefore;
    if (nodeBefore && nodeBefore.is('$text')) {
        return new Position$1(nodeBefore, nodeBefore.data.length);
    }
    const nodeAfter = position.nodeAfter;
    if (nodeAfter && nodeAfter.is('$text')) {
        return new Position$1(nodeAfter, 0);
    }
    return position;
}
/**
 * Breaks text node into two text nodes when possible.
 *
 * ```html
 * <p>foo{}bar</p> -> <p>foo[]bar</p>
 * <p>{}foobar</p> -> <p>[]foobar</p>
 * <p>foobar{}</p> -> <p>foobar[]</p>
 * ```
 *
 * @param position Position that need to be placed inside text node.
 * @returns New position after breaking text node.
 */ function breakTextNode(position) {
    if (position.offset == position.parent.data.length) {
        return new Position$1(position.parent.parent, position.parent.index + 1);
    }
    if (position.offset === 0) {
        return new Position$1(position.parent.parent, position.parent.index);
    }
    // Get part of the text that need to be moved.
    const textToMove = position.parent.data.slice(position.offset);
    // Leave rest of the text in position's parent.
    position.parent._data = position.parent.data.slice(0, position.offset);
    // Insert new text node after position's parent text node.
    position.parent.parent._insertChild(position.parent.index + 1, new Text$1(position.root.document, textToMove));
    // Return new position between two newly created text nodes.
    return new Position$1(position.parent.parent, position.parent.index + 1);
}
/**
 * Merges two text nodes into first node. Removes second node and returns merge position.
 *
 * @param t1 First text node to merge. Data from second text node will be moved at the end of this text node.
 * @param t2 Second text node to merge. This node will be removed after merging.
 * @returns Position after merging text nodes.
 */ function mergeTextNodes(t1, t2) {
    // Merge text data into first text node and remove second one.
    const nodeBeforeLength = t1.data.length;
    t1._data += t2.data;
    t2._remove();
    return new Position$1(t1, nodeBeforeLength);
}
const validNodesToInsert = [
    Text$1,
    AttributeElement,
    ContainerElement,
    EmptyElement,
    RawElement,
    UIElement
];
/**
 * Checks if provided nodes are valid to insert.
 *
 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
 * contains instances that are not supported ones (see error description for valid ones.
 */ function validateNodesToInsert(nodes, errorContext) {
    for (const node of nodes){
        if (!validNodesToInsert.some((validNode)=>node instanceof validNode)) {
            /**
			 * One of the nodes to be inserted is of an invalid type.
			 *
			 * Nodes to be inserted with {@link module:engine/view/downcastwriter~DowncastWriter#insert `DowncastWriter#insert()`} should be
			 * of the following types:
			 *
			 * * {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
			 * * {@link module:engine/view/containerelement~ContainerElement ContainerElement},
			 * * {@link module:engine/view/emptyelement~EmptyElement EmptyElement},
			 * * {@link module:engine/view/uielement~UIElement UIElement},
			 * * {@link module:engine/view/rawelement~RawElement RawElement},
			 * * {@link module:engine/view/text~Text Text}.
			 *
			 * @error view-writer-insert-invalid-node-type
			 */ throw new CKEditorError('view-writer-insert-invalid-node-type', errorContext);
        }
        if (!node.is('$text')) {
            validateNodesToInsert(node.getChildren(), errorContext);
        }
    }
}
/**
 * Checks if node is ContainerElement or DocumentFragment, because in most cases they should be treated the same way.
 *
 * @returns Returns `true` if node is instance of ContainerElement or DocumentFragment.
 */ function isContainerOrFragment(node) {
    return node && (node.is('containerElement') || node.is('documentFragment'));
}
/**
 * Checks if {@link module:engine/view/range~Range#start range start} and {@link module:engine/view/range~Range#end range end} are placed
 * inside same {@link module:engine/view/containerelement~ContainerElement container element}.
 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when validation fails.
 */ function validateRangeContainer(range, errorContext) {
    const startContainer = getParentContainer(range.start);
    const endContainer = getParentContainer(range.end);
    if (!startContainer || !endContainer || startContainer !== endContainer) {
        /**
		 * The container of the given range is invalid.
		 *
		 * This may happen if {@link module:engine/view/range~Range#start range start} and
		 * {@link module:engine/view/range~Range#end range end} positions are not placed inside the same container element or
		 * a parent container for these positions cannot be found.
		 *
		 * Methods like {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#remove()`},
		 * {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#clean()`},
		 * {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#wrap()`},
		 * {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#unwrap()`} need to be called
		 * on a range that has its start and end positions located in the same container element. Both positions can be
		 * nested within other elements (e.g. an attribute element) but the closest container ancestor must be the same.
		 *
		 * @error view-writer-invalid-range-container
		 */ throw new CKEditorError('view-writer-invalid-range-container', errorContext);
    }
}
/**
 * Checks if two attribute elements can be joined together. Elements can be joined together if, and only if
 * they do not have ids specified.
 */ function canBeJoined(a, b) {
    return a.id === null && b.id === null;
}

/**
 * Set of utilities related to handling block and inline fillers.
 *
 * Browsers do not allow to put caret in elements which does not have height. Because of it, we need to fill all
 * empty elements which should be selectable with elements or characters called "fillers". Unfortunately there is no one
 * universal filler, this is why two types are uses:
 *
 * * Block filler is an element which fill block elements, like `<p>`. CKEditor uses `<br>` as a block filler during the editing,
 * as browsers do natively. So instead of an empty `<p>` there will be `<p><br></p>`. The advantage of block filler is that
 * it is transparent for the selection, so when the caret is before the `<br>` and user presses right arrow he will be
 * moved to the next paragraph, not after the `<br>`. The disadvantage is that it breaks a block, so it can not be used
 * in the middle of a line of text. The {@link module:engine/view/filler~BR_FILLER `<br>` filler} can be replaced with any other
 * character in the data output, for instance {@link module:engine/view/filler~NBSP_FILLER non-breaking space} or
 * {@link module:engine/view/filler~MARKED_NBSP_FILLER marked non-breaking space}.
 *
 * * Inline filler is a filler which does not break a line of text, so it can be used inside the text, for instance in the empty
 * `<b>` surrendered by text: `foo<b></b>bar`, if we want to put the caret there. CKEditor uses a sequence of the zero-width
 * spaces as an {@link module:engine/view/filler~INLINE_FILLER inline filler} having the predetermined
 * {@link module:engine/view/filler~INLINE_FILLER_LENGTH length}. A sequence is used, instead of a single character to
 * avoid treating random zero-width spaces as the inline filler. Disadvantage of the inline filler is that it is not
 * transparent for the selection. The arrow key moves the caret between zero-width spaces characters, so the additional
 * code is needed to handle the caret.
 *
 * Both inline and block fillers are handled by the {@link module:engine/view/renderer~Renderer renderer} and are not present in the
 * view.
 *
 * @module engine/view/filler
 */ /**
 * Non-breaking space filler creator. This function creates the `&nbsp;` text node.
 * It defines how the filler is created.
 *
 * @see module:engine/view/filler~MARKED_NBSP_FILLER
 * @see module:engine/view/filler~BR_FILLER
 */ const NBSP_FILLER = (domDocument)=>domDocument.createTextNode('\u00A0');
/**
 * Marked non-breaking space filler creator. This function creates the `<span data-cke-filler="true">&nbsp;</span>` element.
 * It defines how the filler is created.
 *
 * @see module:engine/view/filler~NBSP_FILLER
 * @see module:engine/view/filler~BR_FILLER
 */ const MARKED_NBSP_FILLER = (domDocument)=>{
    const span = domDocument.createElement('span');
    span.dataset.ckeFiller = 'true';
    span.innerText = '\u00A0';
    return span;
};
/**
 * `<br>` filler creator. This function creates the `<br data-cke-filler="true">` element.
 * It defines how the filler is created.
 *
 * @see module:engine/view/filler~NBSP_FILLER
 * @see module:engine/view/filler~MARKED_NBSP_FILLER
 */ const BR_FILLER = (domDocument)=>{
    const fillerBr = domDocument.createElement('br');
    fillerBr.dataset.ckeFiller = 'true';
    return fillerBr;
};
/**
 * Length of the {@link module:engine/view/filler~INLINE_FILLER INLINE_FILLER}.
 */ const INLINE_FILLER_LENGTH = 7;
/**
 * Inline filler which is a sequence of the word joiners.
 */ const INLINE_FILLER = '\u2060'.repeat(INLINE_FILLER_LENGTH);
/**
 * Checks if the node is a text node which starts with the {@link module:engine/view/filler~INLINE_FILLER inline filler}.
 *
 * ```ts
 * startsWithFiller( document.createTextNode( INLINE_FILLER ) ); // true
 * startsWithFiller( document.createTextNode( INLINE_FILLER + 'foo' ) ); // true
 * startsWithFiller( document.createTextNode( 'foo' ) ); // false
 * startsWithFiller( document.createElement( 'p' ) ); // false
 * ```
 *
 * @param domNode DOM node.
 * @returns True if the text node starts with the {@link module:engine/view/filler~INLINE_FILLER inline filler}.
 */ function startsWithFiller(domNode) {
    if (typeof domNode == 'string') {
        return domNode.substr(0, INLINE_FILLER_LENGTH) === INLINE_FILLER;
    }
    return isText(domNode) && domNode.data.substr(0, INLINE_FILLER_LENGTH) === INLINE_FILLER;
}
/**
 * Checks if the text node contains only the {@link module:engine/view/filler~INLINE_FILLER inline filler}.
 *
 * ```ts
 * isInlineFiller( document.createTextNode( INLINE_FILLER ) ); // true
 * isInlineFiller( document.createTextNode( INLINE_FILLER + 'foo' ) ); // false
 * ```
 *
 * @param domText DOM text node.
 * @returns True if the text node contains only the {@link module:engine/view/filler~INLINE_FILLER inline filler}.
 */ function isInlineFiller(domText) {
    return domText.data.length == INLINE_FILLER_LENGTH && startsWithFiller(domText);
}
/**
 * Get string data from the text node, removing an {@link module:engine/view/filler~INLINE_FILLER inline filler} from it,
 * if text node contains it.
 *
 * ```ts
 * getDataWithoutFiller( document.createTextNode( INLINE_FILLER + 'foo' ) ) == 'foo' // true
 * getDataWithoutFiller( document.createTextNode( 'foo' ) ) == 'foo' // true
 * ```
 *
 * @param domText DOM text node, possible with inline filler.
 * @returns Data without filler.
 */ function getDataWithoutFiller(domText) {
    const data = typeof domText == 'string' ? domText : domText.data;
    if (startsWithFiller(domText)) {
        return data.slice(INLINE_FILLER_LENGTH);
    }
    return data;
}
/**
 * Assign key observer which move cursor from the end of the inline filler to the beginning of it when
 * the left arrow is pressed, so the filler does not break navigation.
 *
 * @param view View controller instance we should inject quirks handling on.
 */ function injectQuirksHandling(view) {
    view.document.on('arrowKey', jumpOverInlineFiller, {
        priority: 'low'
    });
}
/**
 * Move cursor from the end of the inline filler to the beginning of it when, so the filler does not break navigation.
 */ function jumpOverInlineFiller(evt, data) {
    if (data.keyCode == keyCodes.arrowleft) {
        const domSelection = data.domTarget.ownerDocument.defaultView.getSelection();
        if (domSelection.rangeCount == 1 && domSelection.getRangeAt(0).collapsed) {
            const domParent = domSelection.getRangeAt(0).startContainer;
            const domOffset = domSelection.getRangeAt(0).startOffset;
            if (startsWithFiller(domParent) && domOffset <= INLINE_FILLER_LENGTH) {
                domSelection.collapse(domParent, 0);
            }
        }
    }
}

/**
 * Renderer is responsible for updating the DOM structure and the DOM selection based on
 * the {@link module:engine/view/renderer~Renderer#markToSync information about updated view nodes}.
 * In other words, it renders the view to the DOM.
 *
 * Its main responsibility is to make only the necessary, minimal changes to the DOM. However, unlike in many
 * virtual DOM implementations, the primary reason for doing minimal changes is not the performance but ensuring
 * that native editing features such as text composition, autocompletion, spell checking, selection's x-index are
 * affected as little as possible.
 *
 * Renderer uses {@link module:engine/view/domconverter~DomConverter} to transform view nodes and positions
 * to and from the DOM.
 */ class Renderer extends /* #__PURE__ */ ObservableMixin() {
    /**
	 * Set of DOM Documents instances.
	 */ domDocuments = new Set();
    /**
	 * Converter instance.
	 */ domConverter;
    /**
	 * Set of nodes which attributes changed and may need to be rendered.
	 */ markedAttributes = new Set();
    /**
	 * Set of elements which child lists changed and may need to be rendered.
	 */ markedChildren = new Set();
    /**
	 * Set of text nodes which text data changed and may need to be rendered.
	 */ markedTexts = new Set();
    /**
	 * View selection. Renderer updates DOM selection based on the view selection.
	 */ selection;
    /**
	 * The text node in which the inline filler was rendered.
	 */ _inlineFiller = null;
    /**
	 * DOM element containing fake selection.
	 */ _fakeSelectionContainer = null;
    /**
	 * Creates a renderer instance.
	 *
	 * @param domConverter Converter instance.
	 * @param selection View selection.
	 */ constructor(domConverter, selection){
        super();
        this.domConverter = domConverter;
        this.selection = selection;
        this.set('isFocused', false);
        this.set('isSelecting', false);
        // Rendering the selection and inline filler manipulation should be postponed in (non-Android) Blink until the user finishes
        // creating the selection in DOM to avoid accidental selection collapsing
        // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
        // When the user stops selecting, all pending changes should be rendered ASAP, though.
        if (env.isBlink && !env.isAndroid) {
            this.on('change:isSelecting', ()=>{
                if (!this.isSelecting) {
                    this.render();
                }
            });
        }
        this.set('isComposing', false);
        this.on('change:isComposing', ()=>{
            if (!this.isComposing) {
                this.render();
            }
        });
    }
    /**
	 * Marks a view node to be updated in the DOM by {@link #render `render()`}.
	 *
	 * Note that only view nodes whose parents have corresponding DOM elements need to be marked to be synchronized.
	 *
	 * @see #markedAttributes
	 * @see #markedChildren
	 * @see #markedTexts
	 *
	 * @param type Type of the change.
	 * @param node ViewNode to be marked.
	 */ markToSync(type, node) {
        if (type === 'text') {
            if (this.domConverter.mapViewToDom(node.parent)) {
                this.markedTexts.add(node);
            }
        } else {
            // If the node has no DOM element it is not rendered yet,
            // its children/attributes do not need to be marked to be sync.
            if (!this.domConverter.mapViewToDom(node)) {
                return;
            }
            if (type === 'attributes') {
                this.markedAttributes.add(node);
            } else if (type === 'children') {
                this.markedChildren.add(node);
            } else {
                /**
				 * Unknown type passed to Renderer.markToSync.
				 *
				 * @error view-renderer-unknown-type
				 */ throw new CKEditorError('view-renderer-unknown-type', this);
            }
        }
    }
    /**
	 * Renders all buffered changes ({@link #markedAttributes}, {@link #markedChildren} and {@link #markedTexts}) and
	 * the current view selection (if needed) to the DOM by applying a minimal set of changes to it.
	 *
	 * Renderer tries not to break the text composition (e.g. IME) and x-index of the selection,
	 * so it does as little as it is needed to update the DOM.
	 *
	 * Renderer also handles {@link module:engine/view/filler fillers}. Especially, it checks if the inline filler is needed
	 * at the selection position and adds or removes it. To prevent breaking text composition inline filler will not be
	 * removed as long as the selection is in the text node which needed it at first.
	 */ render() {
        // Ignore rendering while in the composition mode. Composition events are not cancellable and browser will modify the DOM tree.
        // All marked elements, attributes, etc. will wait until next render after the composition ends.
        // On Android composition events are immediately applied to the model, so we don't need to skip rendering,
        // and we should not do it because the difference between view and DOM could lead to position mapping problems.
        if (this.isComposing && !env.isAndroid) {
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	console.info( '%c[Renderer]%c Rendering aborted while isComposing',
            // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', ''
            // @if CK_DEBUG_TYPING // 	);
            // @if CK_DEBUG_TYPING // }
            return;
        }
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.group( '%c[Renderer]%c Rendering',
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', ''
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        let inlineFillerPosition = null;
        const isInlineFillerRenderingPossible = env.isBlink && !env.isAndroid ? !this.isSelecting : true;
        // Refresh mappings.
        for (const element of this.markedChildren){
            this._updateChildrenMappings(element);
        }
        // Don't manipulate inline fillers while the selection is being made in (non-Android) Blink to prevent accidental
        // DOM selection collapsing
        // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
        if (isInlineFillerRenderingPossible) {
            // There was inline filler rendered in the DOM but it's not
            // at the selection position any more, so we can remove it
            // (cause even if it's needed, it must be placed in another location).
            if (this._inlineFiller && !this._isSelectionInInlineFiller()) {
                this._removeInlineFiller();
            }
            // If we've got the filler, let's try to guess its position in the view.
            if (this._inlineFiller) {
                inlineFillerPosition = this._getInlineFillerPosition();
            } else if (this._needsInlineFillerAtSelection()) {
                inlineFillerPosition = this.selection.getFirstPosition();
                // Do not use `markToSync` so it will be added even if the parent is already added.
                this.markedChildren.add(inlineFillerPosition.parent);
            }
        } else if (this._inlineFiller && this._inlineFiller.parentNode) {
            // While the user is making selection, preserve the inline filler at its original position.
            inlineFillerPosition = this.domConverter.domPositionToView(this._inlineFiller);
            // While down-casting the document selection attributes, all existing empty
            // attribute elements (for selection position) are removed from the view and DOM,
            // so make sure that we were able to map filler position.
            // https://github.com/ckeditor/ckeditor5/issues/12026
            if (inlineFillerPosition && inlineFillerPosition.parent.is('$text')) {
                // The inline filler position is expected to be before the text node.
                inlineFillerPosition = Position$1._createBefore(inlineFillerPosition.parent);
            }
        }
        for (const element of this.markedAttributes){
            this._updateAttrs(element);
        }
        for (const element of this.markedChildren){
            this._updateChildren(element, {
                inlineFillerPosition
            });
        }
        for (const node of this.markedTexts){
            if (!this.markedChildren.has(node.parent) && this.domConverter.mapViewToDom(node.parent)) {
                this._updateText(node, {
                    inlineFillerPosition
                });
            }
        }
        // * Check whether the inline filler is required and where it really is in the DOM.
        //   At this point in most cases it will be in the DOM, but there are exceptions.
        //   For example, if the inline filler was deep in the created DOM structure, it will not be created.
        //   Similarly, if it was removed at the beginning of this function and then neither text nor children were updated,
        //   it will not be present. Fix those and similar scenarios.
        // * Don't manipulate inline fillers while the selection is being made in (non-Android) Blink to prevent accidental
        //   DOM selection collapsing
        //   (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
        if (isInlineFillerRenderingPossible) {
            if (inlineFillerPosition) {
                const fillerDomPosition = this.domConverter.viewPositionToDom(inlineFillerPosition);
                const domDocument = fillerDomPosition.parent.ownerDocument;
                if (!startsWithFiller(fillerDomPosition.parent)) {
                    // Filler has not been created at filler position. Create it now.
                    this._inlineFiller = addInlineFiller(domDocument, fillerDomPosition.parent, fillerDomPosition.offset);
                } else {
                    // Filler has been found, save it.
                    this._inlineFiller = fillerDomPosition.parent;
                }
            } else {
                // There is no filler needed.
                this._inlineFiller = null;
            }
        }
        // First focus the new editing host, then update the selection.
        // Otherwise, FF may throw an error (https://github.com/ckeditor/ckeditor5/issues/721).
        this._updateFocus();
        this._updateSelection();
        this.domConverter._clearTemporaryCustomProperties();
        this.markedTexts.clear();
        this.markedAttributes.clear();
        this.markedChildren.clear();
    // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
    // @if CK_DEBUG_TYPING // 	console.groupEnd();
    // @if CK_DEBUG_TYPING // }
    }
    /**
	 * Updates mappings of view element's children.
	 *
	 * Children that were replaced in the view structure by similar elements (same tag name) are treated as 'replaced'.
	 * This means that their mappings can be updated so the new view elements are mapped to the existing DOM elements.
	 * Thanks to that these elements do not need to be re-rendered completely.
	 *
	 * @param viewElement The view element whose children mappings will be updated.
	 */ _updateChildrenMappings(viewElement) {
        const domElement = this.domConverter.mapViewToDom(viewElement);
        if (!domElement) {
            // If there is no `domElement` it means that it was already removed from DOM and there is no need to process it.
            return;
        }
        // Removing nodes from the DOM as we iterate can cause `actualDomChildren`
        // (which is a live-updating `NodeList`) to get out of sync with the
        // indices that we compute as we iterate over `actions`.
        // This would produce incorrect element mappings.
        //
        // Converting live list to an array to make the list static.
        const actualDomChildren = Array.from(domElement.childNodes);
        const expectedDomChildren = Array.from(this.domConverter.viewChildrenToDom(viewElement, {
            withChildren: false
        }));
        const diff = this._diffNodeLists(actualDomChildren, expectedDomChildren);
        const actions = this._findUpdateActions(diff, actualDomChildren, expectedDomChildren, areSimilarElements);
        if (actions.indexOf('update') !== -1) {
            const counter = {
                equal: 0,
                insert: 0,
                delete: 0
            };
            for (const action of actions){
                if (action === 'update') {
                    const insertIndex = counter.equal + counter.insert;
                    const deleteIndex = counter.equal + counter.delete;
                    const viewChild = viewElement.getChild(insertIndex);
                    // UIElement and RawElement are special cases. Their children are not stored in a view (#799)
                    // so we cannot use them with replacing flow (since they use view children during rendering
                    // which will always result in rendering empty elements).
                    if (viewChild && !viewChild.is('uiElement') && !viewChild.is('rawElement')) {
                        this._updateElementMappings(viewChild, actualDomChildren[deleteIndex]);
                    }
                    remove$1(expectedDomChildren[insertIndex]);
                    counter.equal++;
                } else {
                    counter[action]++;
                }
            }
        }
    }
    /**
	 * Updates mappings of a given view element.
	 *
	 * @param viewElement The view element whose mappings will be updated.
	 * @param domElement The DOM element representing the given view element.
	 */ _updateElementMappings(viewElement, domElement) {
        // Remap 'DomConverter' bindings.
        this.domConverter.unbindDomElement(domElement);
        this.domConverter.bindElements(domElement, viewElement);
        // View element may have children which needs to be updated, but are not marked, mark them to update.
        this.markedChildren.add(viewElement);
        // Because we replace new view element mapping with the existing one, the corresponding DOM element
        // will not be rerendered. The new view element may have different attributes than the previous one.
        // Since its corresponding DOM element will not be rerendered, new attributes will not be added
        // to the DOM, so we need to mark it here to make sure its attributes gets updated. See #1427 for more
        // detailed case study.
        // Also there are cases where replaced element is removed from the view structure and then has
        // its attributes changed or removed. In such cases the element will not be present in `markedAttributes`
        // and also may be the same (`element.isSimilar()`) as the reused element not having its attributes updated.
        // To prevent such situations we always mark reused element to have its attributes rerenderd (#1560).
        this.markedAttributes.add(viewElement);
    }
    /**
	 * Gets the position of the inline filler based on the current selection.
	 * Here, we assume that we know that the filler is needed and
	 * {@link #_isSelectionInInlineFiller is at the selection position}, and, since it is needed,
	 * it is somewhere at the selection position.
	 *
	 * Note: The filler position cannot be restored based on the filler's DOM text node, because
	 * when this method is called (before rendering), the bindings will often be broken. View-to-DOM
	 * bindings are only dependable after rendering.
	 */ _getInlineFillerPosition() {
        const firstPos = this.selection.getFirstPosition();
        if (firstPos.parent.is('$text')) {
            return Position$1._createBefore(firstPos.parent);
        } else {
            return firstPos;
        }
    }
    /**
	 * Returns `true` if the selection has not left the inline filler's text node.
	 * If it is `true`, it means that the filler had been added for a reason and the selection did not
	 * leave the filler's text node. For example, the user can be in the middle of a composition so it should not be touched.
	 *
	 * @returns `true` if the inline filler and selection are in the same place.
	 */ _isSelectionInInlineFiller() {
        if (this.selection.rangeCount != 1 || !this.selection.isCollapsed) {
            return false;
        }
        // Note, we can't check if selection's position equals position of the
        // this._inlineFiller node, because of #663. We may not be able to calculate
        // the filler's position in the view at this stage.
        // Instead, we check it the other way – whether selection is anchored in
        // that text node or next to it.
        // Possible options are:
        // "FILLER{}"
        // "FILLERadded-text{}"
        const selectionPosition = this.selection.getFirstPosition();
        const position = this.domConverter.viewPositionToDom(selectionPosition);
        if (position && isText(position.parent) && startsWithFiller(position.parent)) {
            return true;
        }
        return false;
    }
    /**
	 * Removes the inline filler.
	 */ _removeInlineFiller() {
        const domFillerNode = this._inlineFiller;
        // Something weird happened and the stored node doesn't contain the filler's text.
        if (!startsWithFiller(domFillerNode)) {
            /**
			 * The inline filler node was lost. Most likely, something overwrote the filler text node
			 * in the DOM.
			 *
			 * @error view-renderer-filler-was-lost
			 */ throw new CKEditorError('view-renderer-filler-was-lost', this);
        }
        if (isInlineFiller(domFillerNode)) {
            domFillerNode.remove();
        } else {
            domFillerNode.data = domFillerNode.data.substr(INLINE_FILLER_LENGTH);
        }
        this._inlineFiller = null;
    }
    /**
	 * Checks if the inline {@link module:engine/view/filler filler} should be added.
	 *
	 * @returns `true` if the inline filler should be added.
	 */ _needsInlineFillerAtSelection() {
        if (this.selection.rangeCount != 1 || !this.selection.isCollapsed) {
            return false;
        }
        const selectionPosition = this.selection.getFirstPosition();
        const selectionParent = selectionPosition.parent;
        const selectionOffset = selectionPosition.offset;
        // If there is no DOM root we do not care about fillers.
        if (!this.domConverter.mapViewToDom(selectionParent.root)) {
            return false;
        }
        if (!selectionParent.is('element')) {
            return false;
        }
        // Prevent adding inline filler inside elements with contenteditable=false.
        // https://github.com/ckeditor/ckeditor5-engine/issues/1170
        if (!isEditable(selectionParent)) {
            return false;
        }
        const nodeBefore = selectionPosition.nodeBefore;
        const nodeAfter = selectionPosition.nodeAfter;
        if (nodeBefore instanceof Text$1 || nodeAfter instanceof Text$1) {
            return false;
        }
        // We have block filler, we do not need inline one.
        if (selectionOffset === selectionParent.getFillerOffset() && (!nodeBefore || !nodeBefore.is('element', 'br'))) {
            return false;
        }
        // Do not use inline filler while typing outside inline elements on Android.
        // The deleteContentBackward would remove part of the inline filler instead of removing last letter in a link.
        if (env.isAndroid && (nodeBefore || nodeAfter)) {
            return false;
        }
        return true;
    }
    /**
	 * Checks if text needs to be updated and possibly updates it.
	 *
	 * @param viewText View text to update.
	 * @param options.inlineFillerPosition The position where the inline filler should be rendered.
	 */ _updateText(viewText, options) {
        const domText = this.domConverter.findCorrespondingDomText(viewText);
        const newDomText = this.domConverter.viewToDom(viewText);
        let expectedText = newDomText.data;
        const filler = options.inlineFillerPosition;
        if (filler && filler.parent == viewText.parent && filler.offset == viewText.index) {
            expectedText = INLINE_FILLER + expectedText;
        }
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.group( '%c[Renderer]%c Update text',
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', ''
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        updateTextNode(domText, expectedText);
    // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
    // @if CK_DEBUG_TYPING // 	console.groupEnd();
    // @if CK_DEBUG_TYPING // }
    }
    /**
	 * Checks if attribute list needs to be updated and possibly updates it.
	 *
	 * @param viewElement The view element to update.
	 */ _updateAttrs(viewElement) {
        const domElement = this.domConverter.mapViewToDom(viewElement);
        if (!domElement) {
            // If there is no `domElement` it means that 'viewElement' is outdated as its mapping was updated
            // in 'this._updateChildrenMappings()'. There is no need to process it as new view element which
            // replaced old 'viewElement' mapping was also added to 'this.markedAttributes'
            // in 'this._updateChildrenMappings()' so it will be processed separately.
            return;
        }
        const domAttrKeys = Array.from(domElement.attributes).map((attr)=>attr.name);
        const viewAttrKeys = viewElement.getAttributeKeys();
        // Add or overwrite attributes.
        for (const key of viewAttrKeys){
            this.domConverter.setDomElementAttribute(domElement, key, viewElement.getAttribute(key), viewElement);
        }
        // Remove from DOM attributes which do not exists in the view.
        for (const key of domAttrKeys){
            // All other attributes not present in the DOM should be removed.
            if (!viewElement.hasAttribute(key)) {
                this.domConverter.removeDomElementAttribute(domElement, key);
            }
        }
    }
    /**
	 * Checks if elements child list needs to be updated and possibly updates it.
	 *
	 * Note that on Android, to reduce the risk of composition breaks, it tries to update data of an existing
	 * child text nodes instead of replacing them completely.
	 *
	 * @param viewElement View element to update.
	 * @param options.inlineFillerPosition The position where the inline filler should be rendered.
	 */ _updateChildren(viewElement, options) {
        const domElement = this.domConverter.mapViewToDom(viewElement);
        if (!domElement) {
            // If there is no `domElement` it means that it was already removed from DOM.
            // There is no need to process it. It will be processed when re-inserted.
            return;
        }
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.group( '%c[Renderer]%c Update children',
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', ''
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        // IME on Android inserts a new text node while typing after a link
        // instead of updating an existing text node that follows the link.
        // We must normalize those text nodes so the diff won't get confused.
        // https://github.com/ckeditor/ckeditor5/issues/12574.
        if (env.isAndroid) {
            let previousDomNode = null;
            for (const domNode of Array.from(domElement.childNodes)){
                if (previousDomNode && isText(previousDomNode) && isText(domNode)) {
                    domElement.normalize();
                    break;
                }
                previousDomNode = domNode;
            }
        }
        const inlineFillerPosition = options.inlineFillerPosition;
        const actualDomChildren = domElement.childNodes;
        const expectedDomChildren = Array.from(this.domConverter.viewChildrenToDom(viewElement, {
            bind: true
        }));
        // Inline filler element has to be created as it is present in the DOM, but not in the view. It is required
        // during diffing so text nodes could be compared correctly and also during rendering to maintain
        // proper order and indexes while updating the DOM.
        if (inlineFillerPosition && inlineFillerPosition.parent === viewElement) {
            addInlineFiller(domElement.ownerDocument, expectedDomChildren, inlineFillerPosition.offset);
        }
        const diff = this._diffNodeLists(actualDomChildren, expectedDomChildren);
        // We need to make sure that we update the existing text node and not replace it with another one.
        // The composition and different "language" browser extensions are fragile to text node being completely replaced.
        const actions = this._findUpdateActions(diff, actualDomChildren, expectedDomChildren, areTextNodes);
        let i = 0;
        const nodesToUnbind = new Set();
        // Handle deletions first.
        // This is to prevent a situation where an element that already exists in `actualDomChildren` is inserted at a different
        // index in `actualDomChildren`. Since `actualDomChildren` is a `NodeList`, this works like move, not like an insert,
        // and it disrupts the whole algorithm. See https://github.com/ckeditor/ckeditor5/issues/6367.
        //
        // It doesn't matter in what order we remove or add nodes, as long as we remove and add correct nodes at correct indexes.
        for (const action of actions){
            if (action === 'delete') {
                // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
                // @if CK_DEBUG_TYPING // 	console.info( '%c[Renderer]%c Remove node',
                // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', '', actualDomChildren[ i ]
                // @if CK_DEBUG_TYPING // 	);
                // @if CK_DEBUG_TYPING // }
                nodesToUnbind.add(actualDomChildren[i]);
                remove$1(actualDomChildren[i]);
            } else if (action === 'equal' || action === 'update') {
                i++;
            }
        }
        i = 0;
        for (const action of actions){
            if (action === 'insert') {
                // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
                // @if CK_DEBUG_TYPING // 	console.info( '%c[Renderer]%c Insert node',
                // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', '', expectedDomChildren[ i ]
                // @if CK_DEBUG_TYPING // 	);
                // @if CK_DEBUG_TYPING // }
                insertAt(domElement, i, expectedDomChildren[i]);
                i++;
            } else if (action === 'update') {
                // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
                // @if CK_DEBUG_TYPING // 	console.group( '%c[Renderer]%c Update text node',
                // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', ''
                // @if CK_DEBUG_TYPING // 	);
                // @if CK_DEBUG_TYPING // }
                updateTextNode(actualDomChildren[i], expectedDomChildren[i].data);
                i++;
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	console.groupEnd();
            // @if CK_DEBUG_TYPING // }
            } else if (action === 'equal') {
                // Force updating text nodes inside elements which did not change and do not need to be re-rendered (#1125).
                // Do it here (not in the loop above) because only after insertions the `i` index is correct.
                this._markDescendantTextToSync(this.domConverter.domToView(expectedDomChildren[i]));
                i++;
            }
        }
        // Unbind removed nodes. When node does not have a parent it means that it was removed from DOM tree during
        // comparison with the expected DOM. We don't need to check child nodes, because if child node was reinserted,
        // it was moved to DOM tree out of the removed node.
        for (const node of nodesToUnbind){
            if (!node.parentNode) {
                this.domConverter.unbindDomElement(node);
            }
        }
    // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
    // @if CK_DEBUG_TYPING // 	console.groupEnd();
    // @if CK_DEBUG_TYPING // }
    }
    /**
	 * Shorthand for diffing two arrays or node lists of DOM nodes.
	 *
	 * @param actualDomChildren Actual DOM children
	 * @param expectedDomChildren Expected DOM children.
	 * @returns The list of actions based on the {@link module:utils/diff~diff} function.
	 */ _diffNodeLists(actualDomChildren, expectedDomChildren) {
        actualDomChildren = filterOutFakeSelectionContainer(actualDomChildren, this._fakeSelectionContainer);
        return diff(actualDomChildren, expectedDomChildren, sameNodes$1.bind(null, this.domConverter));
    }
    /**
	 * Finds DOM nodes that were replaced with the similar nodes (same tag name) in the view. All nodes are compared
	 * within one `insert`/`delete` action group, for example:
	 *
	 * ```
	 * Actual DOM:		<p><b>Foo</b>Bar<i>Baz</i><b>Bax</b></p>
	 * Expected DOM:	<p>Bar<b>123</b><i>Baz</i><b>456</b></p>
	 * Input actions:	[ insert, insert, delete, delete, equal, insert, delete ]
	 * Output actions:	[ insert, replace, delete, equal, replace ]
	 * ```
	 *
	 * @param actions Actions array which is a result of the {@link module:utils/diff~diff} function.
	 * @param actualDom Actual DOM children
	 * @param expectedDom Expected DOM children.
	 * @param comparator A comparator function that should return `true` if the given node should be reused
	 * (either by the update of a text node data or an element children list for similar elements).
	 * @returns Actions array modified with the `update` actions.
	 */ _findUpdateActions(actions, actualDom, expectedDom, comparator) {
        // If there is no both 'insert' and 'delete' actions, no need to check for replaced elements.
        if (actions.indexOf('insert') === -1 || actions.indexOf('delete') === -1) {
            return actions;
        }
        let newActions = [];
        let actualSlice = [];
        let expectedSlice = [];
        const counter = {
            equal: 0,
            insert: 0,
            delete: 0
        };
        for (const action of actions){
            if (action === 'insert') {
                expectedSlice.push(expectedDom[counter.equal + counter.insert]);
            } else if (action === 'delete') {
                actualSlice.push(actualDom[counter.equal + counter.delete]);
            } else {
                newActions = newActions.concat(diff(actualSlice, expectedSlice, comparator).map((action)=>action === 'equal' ? 'update' : action));
                newActions.push('equal');
                // Reset stored elements on 'equal'.
                actualSlice = [];
                expectedSlice = [];
            }
            counter[action]++;
        }
        return newActions.concat(diff(actualSlice, expectedSlice, comparator).map((action)=>action === 'equal' ? 'update' : action));
    }
    /**
	 * Marks text nodes to be synchronized.
	 *
	 * If a text node is passed, it will be marked. If an element is passed, all descendant text nodes inside it will be marked.
	 *
	 * @param viewNode View node to sync.
	 */ _markDescendantTextToSync(viewNode) {
        if (!viewNode) {
            return;
        }
        if (viewNode.is('$text')) {
            this.markedTexts.add(viewNode);
        } else if (viewNode.is('element')) {
            for (const child of viewNode.getChildren()){
                this._markDescendantTextToSync(child);
            }
        }
    }
    /**
	 * Checks if the selection needs to be updated and possibly updates it.
	 */ _updateSelection() {
        // Block updating DOM selection in (non-Android) Blink while the user is selecting to prevent accidental selection collapsing.
        // Note: Structural changes in DOM must trigger selection rendering, though. Nodes the selection was anchored
        // to, may disappear in DOM which would break the selection (e.g. in real-time collaboration scenarios).
        // https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723
        if (env.isBlink && !env.isAndroid && this.isSelecting && !this.markedChildren.size) {
            return;
        }
        // If there is no selection - remove DOM and fake selections.
        if (this.selection.rangeCount === 0) {
            this._removeDomSelection();
            this._removeFakeSelection();
            return;
        }
        const domRoot = this.domConverter.mapViewToDom(this.selection.editableElement);
        // Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.
        if (!this.isFocused || !domRoot) {
            return;
        }
        // Render fake selection - create the fake selection container (if needed) and move DOM selection to it.
        if (this.selection.isFake) {
            this._updateFakeSelection(domRoot);
        } else if (this._fakeSelectionContainer && this._fakeSelectionContainer.isConnected) {
            this._removeFakeSelection();
            this._updateDomSelection(domRoot);
        } else if (!(this.isComposing && env.isAndroid)) {
            this._updateDomSelection(domRoot);
        }
    }
    /**
	 * Updates the fake selection.
	 *
	 * @param domRoot A valid DOM root where the fake selection container should be added.
	 */ _updateFakeSelection(domRoot) {
        const domDocument = domRoot.ownerDocument;
        if (!this._fakeSelectionContainer) {
            this._fakeSelectionContainer = createFakeSelectionContainer(domDocument);
        }
        const container = this._fakeSelectionContainer;
        // Bind fake selection container with the current selection *position*.
        this.domConverter.bindFakeSelection(container, this.selection);
        if (!this._fakeSelectionNeedsUpdate(domRoot)) {
            return;
        }
        if (!container.parentElement || container.parentElement != domRoot) {
            domRoot.appendChild(container);
        }
        container.textContent = this.selection.fakeSelectionLabel || '\u00A0';
        const domSelection = domDocument.getSelection();
        const domRange = domDocument.createRange();
        domSelection.removeAllRanges();
        domRange.selectNodeContents(container);
        domSelection.addRange(domRange);
    }
    /**
	 * Updates the DOM selection.
	 *
	 * @param domRoot A valid DOM root where the DOM selection should be rendered.
	 */ _updateDomSelection(domRoot) {
        const domSelection = domRoot.ownerDocument.defaultView.getSelection();
        // Let's check whether DOM selection needs updating at all.
        if (!this._domSelectionNeedsUpdate(domSelection)) {
            return;
        }
        // Multi-range selection is not available in most browsers, and, at least in Chrome, trying to
        // set such selection, that is not continuous, throws an error. Because of that, we will just use anchor
        // and focus of view selection.
        // Since we are not supporting multi-range selection, we also do not need to check if proper editable is
        // selected. If there is any editable selected, it is okay (editable is taken from selection anchor).
        const anchor = this.domConverter.viewPositionToDom(this.selection.anchor);
        const focus = this.domConverter.viewPositionToDom(this.selection.focus);
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.info( '%c[Renderer]%c Update DOM selection:',
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', '', anchor, focus
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        domSelection.setBaseAndExtent(anchor.parent, anchor.offset, focus.parent, focus.offset);
        // Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439).
        if (env.isGecko) {
            fixGeckoSelectionAfterBr(focus, domSelection);
        }
    }
    /**
	 * Checks whether a given DOM selection needs to be updated.
	 *
	 * @param domSelection The DOM selection to check.
	 */ _domSelectionNeedsUpdate(domSelection) {
        if (!this.domConverter.isDomSelectionCorrect(domSelection)) {
            // Current DOM selection is in incorrect position. We need to update it.
            return true;
        }
        const oldViewSelection = domSelection && this.domConverter.domSelectionToView(domSelection);
        if (oldViewSelection && this.selection.isEqual(oldViewSelection)) {
            return false;
        }
        // If selection is not collapsed, it does not need to be updated if it is similar.
        if (!this.selection.isCollapsed && this.selection.isSimilar(oldViewSelection)) {
            // Selection did not changed and is correct, do not update.
            return false;
        }
        // Selections are not similar.
        return true;
    }
    /**
	 * Checks whether the fake selection needs to be updated.
	 *
	 * @param domRoot A valid DOM root where a new fake selection container should be added.
	 */ _fakeSelectionNeedsUpdate(domRoot) {
        const container = this._fakeSelectionContainer;
        const domSelection = domRoot.ownerDocument.getSelection();
        // Fake selection needs to be updated if there's no fake selection container, or the container currently sits
        // in a different root.
        if (!container || container.parentElement !== domRoot) {
            return true;
        }
        // Make sure that the selection actually is within the fake selection.
        if (domSelection.anchorNode !== container && !container.contains(domSelection.anchorNode)) {
            return true;
        }
        return container.textContent !== this.selection.fakeSelectionLabel;
    }
    /**
	 * Removes the DOM selection.
	 */ _removeDomSelection() {
        for (const doc of this.domDocuments){
            const domSelection = doc.getSelection();
            if (domSelection.rangeCount) {
                const activeDomElement = doc.activeElement;
                const viewElement = this.domConverter.mapDomToView(activeDomElement);
                if (activeDomElement && viewElement) {
                    domSelection.removeAllRanges();
                }
            }
        }
    }
    /**
	 * Removes the fake selection.
	 */ _removeFakeSelection() {
        const container = this._fakeSelectionContainer;
        if (container) {
            container.remove();
        }
    }
    /**
	 * Checks if focus needs to be updated and possibly updates it.
	 */ _updateFocus() {
        if (this.isFocused) {
            const editable = this.selection.editableElement;
            if (editable) {
                this.domConverter.focus(editable);
            }
        }
    }
}
/**
 * Checks if provided element is editable.
 */ function isEditable(element) {
    if (element.getAttribute('contenteditable') == 'false') {
        return false;
    }
    const parent = element.findAncestor((element)=>element.hasAttribute('contenteditable'));
    return !parent || parent.getAttribute('contenteditable') == 'true';
}
/**
 * Adds inline filler at a given position.
 *
 * The position can be given as an array of DOM nodes and an offset in that array,
 * or a DOM parent element and an offset in that element.
 *
 * @returns The DOM text node that contains an inline filler.
 */ function addInlineFiller(domDocument, domParentOrArray, offset) {
    const childNodes = domParentOrArray instanceof Array ? domParentOrArray : domParentOrArray.childNodes;
    const nodeAfterFiller = childNodes[offset];
    if (isText(nodeAfterFiller)) {
        nodeAfterFiller.data = INLINE_FILLER + nodeAfterFiller.data;
        return nodeAfterFiller;
    } else {
        const fillerNode = domDocument.createTextNode(INLINE_FILLER);
        if (Array.isArray(domParentOrArray)) {
            childNodes.splice(offset, 0, fillerNode);
        } else {
            insertAt(domParentOrArray, offset, fillerNode);
        }
        return fillerNode;
    }
}
/**
 * Whether two DOM nodes should be considered as similar.
 * Nodes are considered similar if they have the same tag name.
 */ function areSimilarElements(node1, node2) {
    return isNode(node1) && isNode(node2) && !isText(node1) && !isText(node2) && !isComment(node1) && !isComment(node2) && node1.tagName.toLowerCase() === node2.tagName.toLowerCase();
}
/**
 * Whether two DOM nodes are text nodes.
 */ function areTextNodes(node1, node2) {
    return isNode(node1) && isNode(node2) && isText(node1) && isText(node2);
}
/**
 * Whether two dom nodes should be considered as the same.
 * Two nodes which are considered the same are:
 *
 * * Text nodes with the same text.
 * * Element nodes represented by the same object.
 * * Two block filler elements.
 *
 * @param blockFillerMode Block filler mode, see {@link module:engine/view/domconverter~DomConverter#blockFillerMode}.
 */ function sameNodes$1(domConverter, actualDomChild, expectedDomChild) {
    // Elements.
    if (actualDomChild === expectedDomChild) {
        return true;
    } else if (isText(actualDomChild) && isText(expectedDomChild)) {
        return actualDomChild.data === expectedDomChild.data;
    } else if (domConverter.isBlockFiller(actualDomChild) && domConverter.isBlockFiller(expectedDomChild)) {
        return true;
    }
    // Not matching types.
    return false;
}
/**
 * The following is a Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439).
 * When the native DOM selection is at the end of the block and preceded by <br /> e.g.
 *
 * ```html
 * <p>foo<br/>[]</p>
 * ```
 *
 * which happens a lot when using the soft line break, the browser fails to (visually) move the
 * caret to the new line. A quick fix is as simple as force–refreshing the selection with the same range.
 */ function fixGeckoSelectionAfterBr(focus, domSelection) {
    let parent = focus.parent;
    let offset = focus.offset;
    if (isText(parent) && isInlineFiller(parent)) {
        offset = indexOf(parent) + 1;
        parent = parent.parentNode;
    }
    // This fix works only when the focus point is at the very end of an element.
    // There is no point in running it in cases unrelated to the browser bug.
    if (parent.nodeType != Node.ELEMENT_NODE || offset != parent.childNodes.length - 1) {
        return;
    }
    const childAtOffset = parent.childNodes[offset];
    // To stay on the safe side, the fix being as specific as possible, it targets only the
    // selection which is at the very end of the element and preceded by <br />.
    if (childAtOffset && childAtOffset.tagName == 'BR') {
        domSelection.addRange(domSelection.getRangeAt(0));
    }
}
function filterOutFakeSelectionContainer(domChildList, fakeSelectionContainer) {
    const childList = Array.from(domChildList);
    if (childList.length == 0 || !fakeSelectionContainer) {
        return childList;
    }
    const last = childList[childList.length - 1];
    if (last == fakeSelectionContainer) {
        childList.pop();
    }
    return childList;
}
/**
 * Creates a fake selection container for a given document.
 */ function createFakeSelectionContainer(domDocument) {
    const container = domDocument.createElement('div');
    container.className = 'ck-fake-selection-container';
    Object.assign(container.style, {
        position: 'fixed',
        top: 0,
        left: '-9999px',
        // See https://github.com/ckeditor/ckeditor5/issues/752.
        width: '42px'
    });
    // Fill it with a text node so we can update it later.
    container.textContent = '\u00A0';
    return container;
}
/**
 * Checks if text needs to be updated and possibly updates it by removing and inserting only parts
 * of the data from the existing text node to reduce impact on the IME composition.
 *
 * @param domText DOM text node to update.
 * @param expectedText The expected data of a text node.
 */ function updateTextNode(domText, expectedText) {
    const actualText = domText.data;
    if (actualText == expectedText) {
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.info( '%c[Renderer]%c Text node does not need update:',
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', '',
        // @if CK_DEBUG_TYPING // 		`"${ domText.data }" (${ domText.data.length })`
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        return;
    }
    // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
    // @if CK_DEBUG_TYPING // 	console.info( '%c[Renderer]%c Update text node:',
    // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', '',
    // @if CK_DEBUG_TYPING // 		`"${ domText.data }" (${ domText.data.length }) -> "${ expectedText }" (${ expectedText.length })`
    // @if CK_DEBUG_TYPING // 	);
    // @if CK_DEBUG_TYPING // }
    const actions = fastDiff(actualText, expectedText);
    for (const action of actions){
        if (action.type === 'insert') {
            domText.insertData(action.index, action.values.join(''));
        } else {
            domText.deleteData(action.index, action.howMany);
        }
    }
}

const BR_FILLER_REF = BR_FILLER(global.document); // eslint-disable-line new-cap
const NBSP_FILLER_REF = NBSP_FILLER(global.document); // eslint-disable-line new-cap
const MARKED_NBSP_FILLER_REF = MARKED_NBSP_FILLER(global.document); // eslint-disable-line new-cap
const UNSAFE_ATTRIBUTE_NAME_PREFIX = 'data-ck-unsafe-attribute-';
const UNSAFE_ELEMENT_REPLACEMENT_ATTRIBUTE = 'data-ck-unsafe-element';
/**
 * `DomConverter` is a set of tools to do transformations between DOM nodes and view nodes. It also handles
 * {@link module:engine/view/domconverter~DomConverter#bindElements bindings} between these nodes.
 *
 * An instance of the DOM converter is available under
 * {@link module:engine/view/view~View#domConverter `editor.editing.view.domConverter`}.
 *
 * The DOM converter does not check which nodes should be rendered (use {@link module:engine/view/renderer~Renderer}), does not keep the
 * state of a tree nor keeps the synchronization between the tree view and the DOM tree (use {@link module:engine/view/document~Document}).
 *
 * The DOM converter keeps DOM elements to view element bindings, so when the converter gets destroyed, the bindings are lost.
 * Two converters will keep separate binding maps, so one tree view can be bound with two DOM trees.
 */ class DomConverter {
    document;
    /**
	 * Whether to leave the View-to-DOM conversion result unchanged or improve editing experience by filtering out interactive data.
	 */ renderingMode;
    /**
	 * The mode of a block filler used by the DOM converter.
	 */ blockFillerMode;
    /**
	 * Elements which are considered pre-formatted elements.
	 */ preElements;
    /**
	 * Elements which are considered block elements (and hence should be filled with a
	 * {@link #isBlockFiller block filler}).
	 *
	 * Whether an element is considered a block element also affects handling of trailing whitespaces.
	 *
	 * You can extend this array if you introduce support for block elements which are not yet recognized here.
	 */ blockElements;
    /**
	 * A list of elements that exist inline (in text) but their inner structure cannot be edited because
	 * of the way they are rendered by the browser. They are mostly HTML form elements but there are other
	 * elements such as `<img>` or `<iframe>` that also have non-editable children or no children whatsoever.
	 *
	 * Whether an element is considered an inline object has an impact on white space rendering (trimming)
	 * around (and inside of it). In short, white spaces in text nodes next to inline objects are not trimmed.
	 *
	 * You can extend this array if you introduce support for inline object elements which are not yet recognized here.
	 */ inlineObjectElements;
    /**
	 * A list of elements which may affect the editing experience. To avoid this, those elements are replaced with
	 * `<span data-ck-unsafe-element="[element name]"></span>` while rendering in the editing mode.
	 */ unsafeElements;
    /**
	 * The DOM Document used to create DOM nodes.
	 */ _domDocument;
    /**
	 * The DOM-to-view mapping.
	 */ _domToViewMapping = new WeakMap();
    /**
	 * The view-to-DOM mapping.
	 */ _viewToDomMapping = new WeakMap();
    /**
	 * Holds the mapping between fake selection containers and corresponding view selections.
	 */ _fakeSelectionMapping = new WeakMap();
    /**
	 * Matcher for view elements whose content should be treated as raw data
	 * and not processed during the conversion from DOM nodes to view elements.
	 */ _rawContentElementMatcher = new Matcher();
    /**
	 * Matcher for inline object view elements. This is an extension of a simple {@link #inlineObjectElements} array of element names.
	 */ _inlineObjectElementMatcher = new Matcher();
    /**
	 * Set of elements with temporary custom properties that require clearing after render.
	 */ _elementsWithTemporaryCustomProperties = new Set();
    /**
	 * Creates a DOM converter.
	 *
	 * @param document The view document instance.
	 * @param options An object with configuration options.
	 * @param options.blockFillerMode The type of the block filler to use.
	 * Default value depends on the options.renderingMode:
	 *  'nbsp' when options.renderingMode == 'data',
	 *  'br' when options.renderingMode == 'editing'.
	 * @param options.renderingMode Whether to leave the View-to-DOM conversion result unchanged
	 * or improve editing experience by filtering out interactive data.
	 */ constructor(document, { blockFillerMode, renderingMode = 'editing' } = {}){
        this.document = document;
        this.renderingMode = renderingMode;
        this.blockFillerMode = blockFillerMode || (renderingMode === 'editing' ? 'br' : 'nbsp');
        this.preElements = [
            'pre'
        ];
        this.blockElements = [
            'address',
            'article',
            'aside',
            'blockquote',
            'caption',
            'center',
            'dd',
            'details',
            'dir',
            'div',
            'dl',
            'dt',
            'fieldset',
            'figcaption',
            'figure',
            'footer',
            'form',
            'h1',
            'h2',
            'h3',
            'h4',
            'h5',
            'h6',
            'header',
            'hgroup',
            'legend',
            'li',
            'main',
            'menu',
            'nav',
            'ol',
            'p',
            'pre',
            'section',
            'summary',
            'table',
            'tbody',
            'td',
            'tfoot',
            'th',
            'thead',
            'tr',
            'ul'
        ];
        this.inlineObjectElements = [
            'object',
            'iframe',
            'input',
            'button',
            'textarea',
            'select',
            'option',
            'video',
            'embed',
            'audio',
            'img',
            'canvas'
        ];
        this.unsafeElements = [
            'script',
            'style'
        ];
        this._domDocument = this.renderingMode === 'editing' ? global.document : global.document.implementation.createHTMLDocument('');
    }
    /**
	 * Binds a given DOM element that represents fake selection to a **position** of a
	 * {@link module:engine/view/documentselection~DocumentSelection document selection}.
	 * Document selection copy is stored and can be retrieved by the
	 * {@link module:engine/view/domconverter~DomConverter#fakeSelectionToView} method.
	 */ bindFakeSelection(domElement, viewDocumentSelection) {
        this._fakeSelectionMapping.set(domElement, new Selection$1(viewDocumentSelection));
    }
    /**
	 * Returns a {@link module:engine/view/selection~Selection view selection} instance corresponding to a given
	 * DOM element that represents fake selection. Returns `undefined` if binding to the given DOM element does not exist.
	 */ fakeSelectionToView(domElement) {
        return this._fakeSelectionMapping.get(domElement);
    }
    /**
	 * Binds DOM and view elements, so it will be possible to get corresponding elements using
	 * {@link module:engine/view/domconverter~DomConverter#mapDomToView} and
	 * {@link module:engine/view/domconverter~DomConverter#mapViewToDom}.
	 *
	 * @param domElement The DOM element to bind.
	 * @param viewElement The view element to bind.
	 */ bindElements(domElement, viewElement) {
        this._domToViewMapping.set(domElement, viewElement);
        this._viewToDomMapping.set(viewElement, domElement);
    }
    /**
	 * Unbinds a given DOM element from the view element it was bound to. Unbinding is deep, meaning that all children of
	 * the DOM element will be unbound too.
	 *
	 * @param domElement The DOM element to unbind.
	 */ unbindDomElement(domElement) {
        const viewElement = this._domToViewMapping.get(domElement);
        if (viewElement) {
            this._domToViewMapping.delete(domElement);
            this._viewToDomMapping.delete(viewElement);
            for (const child of Array.from(domElement.children)){
                this.unbindDomElement(child);
            }
        }
    }
    /**
	 * Binds DOM and view document fragments, so it will be possible to get corresponding document fragments using
	 * {@link module:engine/view/domconverter~DomConverter#mapDomToView} and
	 * {@link module:engine/view/domconverter~DomConverter#mapViewToDom}.
	 *
	 * @param domFragment The DOM document fragment to bind.
	 * @param viewFragment The view document fragment to bind.
	 */ bindDocumentFragments(domFragment, viewFragment) {
        this._domToViewMapping.set(domFragment, viewFragment);
        this._viewToDomMapping.set(viewFragment, domFragment);
    }
    /**
	 * Decides whether a given pair of attribute key and value should be passed further down the pipeline.
	 *
	 * @param elementName Element name in lower case.
	 */ shouldRenderAttribute(attributeKey, attributeValue, elementName) {
        if (this.renderingMode === 'data') {
            return true;
        }
        attributeKey = attributeKey.toLowerCase();
        if (attributeKey.startsWith('on')) {
            return false;
        }
        if (attributeKey === 'srcdoc' && attributeValue.match(/\bon\S+\s*=|javascript:|<\s*\/*script/i)) {
            return false;
        }
        if (elementName === 'img' && (attributeKey === 'src' || attributeKey === 'srcset')) {
            return true;
        }
        if (elementName === 'source' && attributeKey === 'srcset') {
            return true;
        }
        if (attributeValue.match(/^\s*(javascript:|data:(image\/svg|text\/x?html))/i)) {
            return false;
        }
        return true;
    }
    /**
	 * Set `domElement`'s content using provided `html` argument. Apply necessary filtering for the editing pipeline.
	 *
	 * @param domElement DOM element that should have `html` set as its content.
	 * @param html Textual representation of the HTML that will be set on `domElement`.
	 */ setContentOf(domElement, html) {
        // For data pipeline we pass the HTML as-is.
        if (this.renderingMode === 'data') {
            domElement.innerHTML = html;
            return;
        }
        const document = new DOMParser().parseFromString(html, 'text/html');
        const fragment = document.createDocumentFragment();
        const bodyChildNodes = document.body.childNodes;
        while(bodyChildNodes.length > 0){
            fragment.appendChild(bodyChildNodes[0]);
        }
        const treeWalker = document.createTreeWalker(fragment, NodeFilter.SHOW_ELEMENT);
        const nodes = [];
        let currentNode;
        // eslint-disable-next-line no-cond-assign
        while(currentNode = treeWalker.nextNode()){
            nodes.push(currentNode);
        }
        for (const currentNode of nodes){
            // Go through nodes to remove those that are prohibited in editing pipeline.
            for (const attributeName of currentNode.getAttributeNames()){
                this.setDomElementAttribute(currentNode, attributeName, currentNode.getAttribute(attributeName));
            }
            const elementName = currentNode.tagName.toLowerCase();
            // There are certain nodes, that should be renamed to <span> in editing pipeline.
            if (this._shouldRenameElement(elementName)) {
                _logUnsafeElement(elementName);
                currentNode.replaceWith(this._createReplacementDomElement(elementName, currentNode));
            }
        }
        // Empty the target element.
        while(domElement.firstChild){
            domElement.firstChild.remove();
        }
        domElement.append(fragment);
    }
    /**
	 * Converts the view to the DOM. For all text nodes, not bound elements and document fragments new items will
	 * be created. For bound elements and document fragments the method will return corresponding items.
	 *
	 * @param viewNode View node or document fragment to transform.
	 * @param options Conversion options.
	 * @param options.bind Determines whether new elements will be bound.
	 * @param options.withChildren If `false`, node's and document fragment's children will not be converted.
	 * @returns Converted node or DocumentFragment.
	 */ viewToDom(viewNode, options = {}) {
        if (viewNode.is('$text')) {
            const textData = this._processDataFromViewText(viewNode);
            return this._domDocument.createTextNode(textData);
        } else {
            const viewElementOrFragment = viewNode;
            if (this.mapViewToDom(viewElementOrFragment)) {
                // Do not reuse element that is marked to not reuse (for example an IMG element
                // so it can immediately display a placeholder background instead of waiting for the new src to load).
                if (viewElementOrFragment.getCustomProperty('editingPipeline:doNotReuseOnce')) {
                    this._elementsWithTemporaryCustomProperties.add(viewElementOrFragment);
                } else {
                    return this.mapViewToDom(viewElementOrFragment);
                }
            }
            let domElement;
            if (viewElementOrFragment.is('documentFragment')) {
                // Create DOM document fragment.
                domElement = this._domDocument.createDocumentFragment();
                if (options.bind) {
                    this.bindDocumentFragments(domElement, viewElementOrFragment);
                }
            } else if (viewElementOrFragment.is('uiElement')) {
                if (viewElementOrFragment.name === '$comment') {
                    domElement = this._domDocument.createComment(viewElementOrFragment.getCustomProperty('$rawContent'));
                } else {
                    // UIElement has its own render() method (see #799).
                    domElement = viewElementOrFragment.render(this._domDocument, this);
                }
                if (options.bind) {
                    this.bindElements(domElement, viewElementOrFragment);
                }
                return domElement;
            } else {
                // Create DOM element.
                if (this._shouldRenameElement(viewElementOrFragment.name)) {
                    _logUnsafeElement(viewElementOrFragment.name);
                    domElement = this._createReplacementDomElement(viewElementOrFragment.name);
                } else if (viewElementOrFragment.hasAttribute('xmlns')) {
                    domElement = this._domDocument.createElementNS(viewElementOrFragment.getAttribute('xmlns'), viewElementOrFragment.name);
                } else {
                    domElement = this._domDocument.createElement(viewElementOrFragment.name);
                }
                // RawElement take care of their children in RawElement#render() method which can be customized
                // (see https://github.com/ckeditor/ckeditor5/issues/4469).
                if (viewElementOrFragment.is('rawElement')) {
                    viewElementOrFragment.render(domElement, this);
                }
                if (options.bind) {
                    this.bindElements(domElement, viewElementOrFragment);
                }
                // Copy element's attributes.
                for (const key of viewElementOrFragment.getAttributeKeys()){
                    this.setDomElementAttribute(domElement, key, viewElementOrFragment.getAttribute(key), viewElementOrFragment);
                }
            }
            if (options.withChildren !== false) {
                for (const child of this.viewChildrenToDom(viewElementOrFragment, options)){
                    if (domElement instanceof HTMLTemplateElement) {
                        domElement.content.appendChild(child);
                    } else {
                        domElement.appendChild(child);
                    }
                }
            }
            return domElement;
        }
    }
    /**
	 * Sets the attribute on a DOM element.
	 *
	 * **Note**: To remove the attribute, use {@link #removeDomElementAttribute}.
	 *
	 * @param domElement The DOM element the attribute should be set on.
	 * @param key The name of the attribute.
	 * @param value The value of the attribute.
	 * @param relatedViewElement The view element related to the `domElement` (if there is any).
	 * It helps decide whether the attribute set is unsafe. For instance, view elements created via the
	 * {@link module:engine/view/downcastwriter~DowncastWriter} methods can allow certain attributes that would normally be filtered out.
	 */ setDomElementAttribute(domElement, key, value, relatedViewElement) {
        const shouldRenderAttribute = this.shouldRenderAttribute(key, value, domElement.tagName.toLowerCase()) || relatedViewElement && relatedViewElement.shouldRenderUnsafeAttribute(key);
        if (!shouldRenderAttribute) {
            logWarning('domconverter-unsafe-attribute-detected', {
                domElement,
                key,
                value
            });
        }
        if (!isValidAttributeName(key)) {
            /**
			 * Invalid attribute name was ignored during rendering.
			 *
			 * @error domconverter-invalid-attribute-detected
			 */ logWarning('domconverter-invalid-attribute-detected', {
                domElement,
                key,
                value
            });
            return;
        }
        // The old value was safe but the new value is unsafe.
        if (domElement.hasAttribute(key) && !shouldRenderAttribute) {
            domElement.removeAttribute(key);
        } else if (domElement.hasAttribute(UNSAFE_ATTRIBUTE_NAME_PREFIX + key) && shouldRenderAttribute) {
            domElement.removeAttribute(UNSAFE_ATTRIBUTE_NAME_PREFIX + key);
        }
        // If the attribute should not be rendered, rename it (instead of removing) to give developers some idea of what
        // is going on (https://github.com/ckeditor/ckeditor5/issues/10801).
        domElement.setAttribute(shouldRenderAttribute ? key : UNSAFE_ATTRIBUTE_NAME_PREFIX + key, value);
    }
    /**
	 * Removes an attribute from a DOM element.
	 *
	 * **Note**: To set the attribute, use {@link #setDomElementAttribute}.
	 *
	 * @param domElement The DOM element the attribute should be removed from.
	 * @param key The name of the attribute.
	 */ removeDomElementAttribute(domElement, key) {
        // See #_createReplacementDomElement() to learn what this is.
        if (key == UNSAFE_ELEMENT_REPLACEMENT_ATTRIBUTE) {
            return;
        }
        domElement.removeAttribute(key);
        // See setDomElementAttribute() to learn what this is.
        domElement.removeAttribute(UNSAFE_ATTRIBUTE_NAME_PREFIX + key);
    }
    /**
	 * Converts children of the view element to DOM using the
	 * {@link module:engine/view/domconverter~DomConverter#viewToDom} method.
	 * Additionally, this method adds block {@link module:engine/view/filler filler} to the list of children, if needed.
	 *
	 * @param viewElement Parent view element.
	 * @param options See {@link module:engine/view/domconverter~DomConverter#viewToDom} options parameter.
	 * @returns DOM nodes.
	 */ *viewChildrenToDom(viewElement, options = {}) {
        const fillerPositionOffset = viewElement.getFillerOffset && viewElement.getFillerOffset();
        let offset = 0;
        for (const childView of viewElement.getChildren()){
            if (fillerPositionOffset === offset) {
                yield this._getBlockFiller();
            }
            const transparentRendering = childView.is('element') && !!childView.getCustomProperty('dataPipeline:transparentRendering') && !first(childView.getAttributes());
            if (transparentRendering && this.renderingMode == 'data') {
                yield* this.viewChildrenToDom(childView, options);
            } else {
                if (transparentRendering) {
                    /**
					 * The `dataPipeline:transparentRendering` flag is supported only in the data pipeline.
					 *
					 * @error domconverter-transparent-rendering-unsupported-in-editing-pipeline
					 */ logWarning('domconverter-transparent-rendering-unsupported-in-editing-pipeline', {
                        viewElement: childView
                    });
                }
                yield this.viewToDom(childView, options);
            }
            offset++;
        }
        if (fillerPositionOffset === offset) {
            yield this._getBlockFiller();
        }
    }
    /**
	 * Converts view {@link module:engine/view/range~Range} to DOM range.
	 * Inline and block {@link module:engine/view/filler fillers} are handled during the conversion.
	 *
	 * @param viewRange View range.
	 * @returns DOM range.
	 */ viewRangeToDom(viewRange) {
        const domStart = this.viewPositionToDom(viewRange.start);
        const domEnd = this.viewPositionToDom(viewRange.end);
        const domRange = this._domDocument.createRange();
        domRange.setStart(domStart.parent, domStart.offset);
        domRange.setEnd(domEnd.parent, domEnd.offset);
        return domRange;
    }
    /**
	 * Converts view {@link module:engine/view/position~Position} to DOM parent and offset.
	 *
	 * Inline and block {@link module:engine/view/filler fillers} are handled during the conversion.
	 * If the converted position is directly before inline filler it is moved inside the filler.
	 *
	 * @param viewPosition View position.
	 * @returns DOM position or `null` if view position could not be converted to DOM.
	 * DOM position has two properties:
	 * * `parent` - DOM position parent.
	 * * `offset` - DOM position offset.
	 */ viewPositionToDom(viewPosition) {
        const viewParent = viewPosition.parent;
        if (viewParent.is('$text')) {
            const domParent = this.findCorrespondingDomText(viewParent);
            if (!domParent) {
                // Position is in a view text node that has not been rendered to DOM yet.
                return null;
            }
            let offset = viewPosition.offset;
            if (startsWithFiller(domParent)) {
                offset += INLINE_FILLER_LENGTH;
            }
            return {
                parent: domParent,
                offset
            };
        } else {
            // viewParent is instance of ViewElement.
            let domParent, domBefore, domAfter;
            if (viewPosition.offset === 0) {
                domParent = this.mapViewToDom(viewParent);
                if (!domParent) {
                    // Position is in a view element that has not been rendered to DOM yet.
                    return null;
                }
                domAfter = domParent.childNodes[0];
            } else {
                const nodeBefore = viewPosition.nodeBefore;
                domBefore = nodeBefore.is('$text') ? this.findCorrespondingDomText(nodeBefore) : this.mapViewToDom(nodeBefore);
                if (!domBefore) {
                    // Position is after a view element that has not been rendered to DOM yet.
                    return null;
                }
                domParent = domBefore.parentNode;
                domAfter = domBefore.nextSibling;
            }
            // If there is an inline filler at position return position inside the filler. We should never return
            // the position before the inline filler.
            if (isText(domAfter) && startsWithFiller(domAfter)) {
                return {
                    parent: domAfter,
                    offset: INLINE_FILLER_LENGTH
                };
            }
            const offset = domBefore ? indexOf(domBefore) + 1 : 0;
            return {
                parent: domParent,
                offset
            };
        }
    }
    /**
	 * Converts DOM to view. For all text nodes, not bound elements and document fragments new items will
	 * be created. For bound elements and document fragments function will return corresponding items. For
	 * {@link module:engine/view/filler fillers} `null` will be returned.
	 * For all DOM elements rendered by {@link module:engine/view/uielement~UIElement} that UIElement will be returned.
	 *
	 * @param domNode DOM node or document fragment to transform.
	 * @param options Conversion options.
	 * @param options.bind Determines whether new elements will be bound. False by default.
	 * @param options.withChildren If `true`, node's and document fragment's children will be converted too. True by default.
	 * @param options.keepOriginalCase If `false`, node's tag name will be converted to lower case. False by default.
	 * @param options.skipComments If `false`, comment nodes will be converted to `$comment`
	 * {@link module:engine/view/uielement~UIElement view UI elements}. False by default.
	 * @returns Converted node or document fragment or `null` if DOM node is a {@link module:engine/view/filler filler}
	 * or the given node is an empty text node.
	 */ domToView(domNode, options = {}) {
        const inlineNodes = [];
        const generator = this._domToView(domNode, options, inlineNodes);
        // Get the first yielded value or a returned value.
        const node = generator.next().value;
        if (!node) {
            return null;
        }
        // Trigger children handling.
        generator.next();
        // Whitespace cleaning.
        this._processDomInlineNodes(null, inlineNodes, options);
        // Text not got trimmed to an empty string so there is no result node.
        if (node.is('$text') && node.data.length == 0) {
            return null;
        }
        return node;
    }
    /**
	 * Converts children of the DOM element to view nodes using
	 * the {@link module:engine/view/domconverter~DomConverter#domToView} method.
	 * Additionally this method omits block {@link module:engine/view/filler filler}, if it exists in the DOM parent.
	 *
	 * @param domElement Parent DOM element.
	 * @param options See {@link module:engine/view/domconverter~DomConverter#domToView} options parameter.
	 * @param inlineNodes An array that will be populated with inline nodes. It's used internally for whitespace processing.
	 * @returns View nodes.
	 */ *domChildrenToView(domElement, options = {}, inlineNodes = []) {
        // Get child nodes from content document fragment if element is template
        let childNodes = [];
        if (domElement instanceof HTMLTemplateElement) {
            childNodes = [
                ...domElement.content.childNodes
            ];
        } else {
            childNodes = [
                ...domElement.childNodes
            ];
        }
        for(let i = 0; i < childNodes.length; i++){
            const domChild = childNodes[i];
            const generator = this._domToView(domChild, options, inlineNodes);
            // Get the first yielded value or a returned value.
            const viewChild = generator.next().value;
            if (viewChild !== null) {
                // Whitespace cleaning before entering a block element (between block elements).
                if (this._isBlockViewElement(viewChild)) {
                    this._processDomInlineNodes(domElement, inlineNodes, options);
                }
                yield viewChild;
                // Trigger children handling.
                generator.next();
            }
        }
        // Whitespace cleaning before leaving a block element (content of block element).
        this._processDomInlineNodes(domElement, inlineNodes, options);
    }
    /**
	 * Converts DOM selection to view {@link module:engine/view/selection~Selection}.
	 * Ranges which cannot be converted will be omitted.
	 *
	 * @param domSelection DOM selection.
	 * @returns View selection.
	 */ domSelectionToView(domSelection) {
        // See: https://github.com/ckeditor/ckeditor5/issues/9635.
        if (isGeckoRestrictedDomSelection(domSelection)) {
            return new Selection$1([]);
        }
        // DOM selection might be placed in fake selection container.
        // If container contains fake selection - return corresponding view selection.
        if (domSelection.rangeCount === 1) {
            let container = domSelection.getRangeAt(0).startContainer;
            // The DOM selection might be moved to the text node inside the fake selection container.
            if (isText(container)) {
                container = container.parentNode;
            }
            const viewSelection = this.fakeSelectionToView(container);
            if (viewSelection) {
                return viewSelection;
            }
        }
        const isBackward = this.isDomSelectionBackward(domSelection);
        const viewRanges = [];
        for(let i = 0; i < domSelection.rangeCount; i++){
            // DOM Range have correct start and end, no matter what is the DOM Selection direction. So we don't have to fix anything.
            const domRange = domSelection.getRangeAt(i);
            const viewRange = this.domRangeToView(domRange);
            if (viewRange) {
                viewRanges.push(viewRange);
            }
        }
        return new Selection$1(viewRanges, {
            backward: isBackward
        });
    }
    /**
	 * Converts DOM Range to view {@link module:engine/view/range~Range}.
	 * If the start or end position can not be converted `null` is returned.
	 *
	 * @param domRange DOM range.
	 * @returns View range.
	 */ domRangeToView(domRange) {
        const viewStart = this.domPositionToView(domRange.startContainer, domRange.startOffset);
        const viewEnd = this.domPositionToView(domRange.endContainer, domRange.endOffset);
        if (viewStart && viewEnd) {
            return new Range$1(viewStart, viewEnd);
        }
        return null;
    }
    /**
	 * Converts DOM parent and offset to view {@link module:engine/view/position~Position}.
	 *
	 * If the position is inside a {@link module:engine/view/filler filler} which has no corresponding view node,
	 * position of the filler will be converted and returned.
	 *
	 * If the position is inside DOM element rendered by {@link module:engine/view/uielement~UIElement}
	 * that position will be converted to view position before that UIElement.
	 *
	 * If structures are too different and it is not possible to find corresponding position then `null` will be returned.
	 *
	 * @param domParent DOM position parent.
	 * @param domOffset DOM position offset. You can skip it when converting the inline filler node.
	 * @returns View position.
	 */ domPositionToView(domParent, domOffset = 0) {
        if (this.isBlockFiller(domParent)) {
            return this.domPositionToView(domParent.parentNode, indexOf(domParent));
        }
        // If position is somewhere inside UIElement or a RawElement - return position before that element.
        const viewElement = this.mapDomToView(domParent);
        if (viewElement && (viewElement.is('uiElement') || viewElement.is('rawElement'))) {
            return Position$1._createBefore(viewElement);
        }
        if (isText(domParent)) {
            if (isInlineFiller(domParent)) {
                return this.domPositionToView(domParent.parentNode, indexOf(domParent));
            }
            const viewParent = this.findCorrespondingViewText(domParent);
            let offset = domOffset;
            if (!viewParent) {
                return null;
            }
            if (startsWithFiller(domParent)) {
                offset -= INLINE_FILLER_LENGTH;
                offset = offset < 0 ? 0 : offset;
            }
            return new Position$1(viewParent, offset);
        } else {
            if (domOffset === 0) {
                const viewParent = this.mapDomToView(domParent);
                if (viewParent) {
                    return new Position$1(viewParent, 0);
                }
            } else {
                const domBefore = domParent.childNodes[domOffset - 1];
                // Jump over an inline filler (and also on Firefox jump over a block filler while pressing backspace in an empty paragraph).
                if (isText(domBefore) && isInlineFiller(domBefore) || domBefore && this.isBlockFiller(domBefore)) {
                    return this.domPositionToView(domBefore.parentNode, indexOf(domBefore));
                }
                const viewBefore = isText(domBefore) ? this.findCorrespondingViewText(domBefore) : this.mapDomToView(domBefore);
                // TODO #663
                if (viewBefore && viewBefore.parent) {
                    return new Position$1(viewBefore.parent, viewBefore.index + 1);
                }
            }
            return null;
        }
    }
    /**
	 * Returns corresponding view {@link module:engine/view/element~Element Element} or
	 * {@link module:engine/view/documentfragment~DocumentFragment} for provided DOM element or
	 * document fragment. If there is no view item {@link module:engine/view/domconverter~DomConverter#bindElements bound}
	 * to the given DOM - `undefined` is returned.
	 *
	 * For all DOM elements rendered by a {@link module:engine/view/uielement~UIElement} or
	 * a {@link module:engine/view/rawelement~RawElement}, the parent `UIElement` or `RawElement` will be returned.
	 *
	 * @param domElementOrDocumentFragment DOM element or document fragment.
	 * @returns Corresponding view element, document fragment or `undefined` if no element was bound.
	 */ mapDomToView(domElementOrDocumentFragment) {
        const hostElement = this.getHostViewElement(domElementOrDocumentFragment);
        return hostElement || this._domToViewMapping.get(domElementOrDocumentFragment);
    }
    /**
	 * Finds corresponding text node. Text nodes are not {@link module:engine/view/domconverter~DomConverter#bindElements bound},
	 * corresponding text node is returned based on the sibling or parent.
	 *
	 * If the directly previous sibling is a {@link module:engine/view/domconverter~DomConverter#bindElements bound} element, it is used
	 * to find the corresponding text node.
	 *
	 * If this is a first child in the parent and the parent is a {@link module:engine/view/domconverter~DomConverter#bindElements bound}
	 * element, it is used to find the corresponding text node.
	 *
	 * For all text nodes rendered by a {@link module:engine/view/uielement~UIElement} or
	 * a {@link module:engine/view/rawelement~RawElement}, the parent `UIElement` or `RawElement` will be returned.
	 *
	 * Otherwise `null` is returned.
	 *
	 * Note that for the block or inline {@link module:engine/view/filler filler} this method returns `null`.
	 *
	 * @param domText DOM text node.
	 * @returns Corresponding view text node or `null`, if it was not possible to find a corresponding node.
	 */ findCorrespondingViewText(domText) {
        if (isInlineFiller(domText)) {
            return null;
        }
        // If DOM text was rendered by a UIElement or a RawElement - return this parent element.
        const hostElement = this.getHostViewElement(domText);
        if (hostElement) {
            return hostElement;
        }
        const previousSibling = domText.previousSibling;
        // Try to use previous sibling to find the corresponding text node.
        if (previousSibling) {
            if (!this.isElement(previousSibling)) {
                // The previous is text or comment.
                return null;
            }
            const viewElement = this.mapDomToView(previousSibling);
            if (viewElement) {
                const nextSibling = viewElement.nextSibling;
                // It might be filler which has no corresponding view node.
                if (nextSibling instanceof Text$1) {
                    return nextSibling;
                } else {
                    return null;
                }
            }
        } else {
            const viewElement = this.mapDomToView(domText.parentNode);
            if (viewElement) {
                const firstChild = viewElement.getChild(0);
                // It might be filler which has no corresponding view node.
                if (firstChild instanceof Text$1) {
                    return firstChild;
                } else {
                    return null;
                }
            }
        }
        return null;
    }
    mapViewToDom(documentFragmentOrElement) {
        return this._viewToDomMapping.get(documentFragmentOrElement);
    }
    /**
	 * Finds corresponding text node. Text nodes are not {@link module:engine/view/domconverter~DomConverter#bindElements bound},
	 * corresponding text node is returned based on the sibling or parent.
	 *
	 * If the directly previous sibling is a {@link module:engine/view/domconverter~DomConverter#bindElements bound} element, it is used
	 * to find the corresponding text node.
	 *
	 * If this is a first child in the parent and the parent is a {@link module:engine/view/domconverter~DomConverter#bindElements bound}
	 * element, it is used to find the corresponding text node.
	 *
	 * Otherwise `null` is returned.
	 *
	 * @param viewText View text node.
	 * @returns Corresponding DOM text node or `null`, if it was not possible to find a corresponding node.
	 */ findCorrespondingDomText(viewText) {
        const previousSibling = viewText.previousSibling;
        // Try to use previous sibling to find the corresponding text node.
        if (previousSibling && this.mapViewToDom(previousSibling)) {
            return this.mapViewToDom(previousSibling).nextSibling;
        }
        // If this is a first node, try to use parent to find the corresponding text node.
        if (!previousSibling && viewText.parent && this.mapViewToDom(viewText.parent)) {
            return this.mapViewToDom(viewText.parent).childNodes[0];
        }
        return null;
    }
    /**
	 * Focuses DOM editable that is corresponding to provided {@link module:engine/view/editableelement~EditableElement}.
	 */ focus(viewEditable) {
        const domEditable = this.mapViewToDom(viewEditable);
        if (domEditable && domEditable.ownerDocument.activeElement !== domEditable) {
            // Save the scrollX and scrollY positions before the focus.
            const { scrollX, scrollY } = global.window;
            const scrollPositions = [];
            // Save all scrollLeft and scrollTop values starting from domEditable up to
            // document#documentElement.
            forEachDomElementAncestor(domEditable, (node)=>{
                const { scrollLeft, scrollTop } = node;
                scrollPositions.push([
                    scrollLeft,
                    scrollTop
                ]);
            });
            domEditable.focus();
            // Restore scrollLeft and scrollTop values starting from domEditable up to
            // document#documentElement.
            // https://github.com/ckeditor/ckeditor5-engine/issues/951
            // https://github.com/ckeditor/ckeditor5-engine/issues/957
            forEachDomElementAncestor(domEditable, (node)=>{
                const [scrollLeft, scrollTop] = scrollPositions.shift();
                node.scrollLeft = scrollLeft;
                node.scrollTop = scrollTop;
            });
            // Restore the scrollX and scrollY positions after the focus.
            // https://github.com/ckeditor/ckeditor5-engine/issues/951
            global.window.scrollTo(scrollX, scrollY);
        }
    }
    /**
	 * Remove DOM selection from blurred editable, so it won't interfere with clicking on dropdowns (especially on iOS).
	 *
	 * @internal
	 */ _clearDomSelection() {
        const domEditable = this.mapViewToDom(this.document.selection.editableElement);
        if (!domEditable) {
            return;
        }
        // Check if DOM selection is inside editor editable element.
        const domSelection = domEditable.ownerDocument.defaultView.getSelection();
        const newViewSelection = this.domSelectionToView(domSelection);
        const selectionInEditable = newViewSelection && newViewSelection.rangeCount > 0;
        if (selectionInEditable) {
            domSelection.removeAllRanges();
        }
    }
    /**
	 * Returns `true` when `node.nodeType` equals `Node.ELEMENT_NODE`.
	 *
	 * @param node Node to check.
	 */ isElement(node) {
        return node && node.nodeType == Node.ELEMENT_NODE;
    }
    /**
	 * Returns `true` when `node.nodeType` equals `Node.DOCUMENT_FRAGMENT_NODE`.
	 *
	 * @param node Node to check.
	 */ isDocumentFragment(node) {
        return node && node.nodeType == Node.DOCUMENT_FRAGMENT_NODE;
    }
    /**
	 * Checks if the node is an instance of the block filler for this DOM converter.
	 *
	 * ```ts
	 * const converter = new DomConverter( viewDocument, { blockFillerMode: 'br' } );
	 *
	 * converter.isBlockFiller( BR_FILLER( document ) ); // true
	 * converter.isBlockFiller( NBSP_FILLER( document ) ); // false
	 * ```
	 *
	 * **Note:**: For the `'nbsp'` mode the method also checks context of a node so it cannot be a detached node.
	 *
	 * **Note:** A special case in the `'nbsp'` mode exists where the `<br>` in `<p><br></p>` is treated as a block filler.
	 *
	 * @param domNode DOM node to check.
	 * @returns True if a node is considered a block filler for given mode.
	 */ isBlockFiller(domNode) {
        if (this.blockFillerMode == 'br') {
            return domNode.isEqualNode(BR_FILLER_REF);
        }
        // Special case for <p><br></p> in which <br> should be treated as filler even when we are not in the 'br' mode. See ckeditor5#5564.
        if (domNode.tagName === 'BR' && hasBlockParent(domNode, this.blockElements) && domNode.parentNode.childNodes.length === 1) {
            return true;
        }
        // If not in 'br' mode, try recognizing both marked and regular nbsp block fillers.
        return domNode.isEqualNode(MARKED_NBSP_FILLER_REF) || isNbspBlockFiller(domNode, this.blockElements);
    }
    /**
	 * Returns `true` if given selection is a backward selection, that is, if it's `focus` is before `anchor`.
	 *
	 * @param DOM Selection instance to check.
	 */ isDomSelectionBackward(selection) {
        if (selection.isCollapsed) {
            return false;
        }
        // Since it takes multiple lines of code to check whether a "DOM Position" is before/after another "DOM Position",
        // we will use the fact that range will collapse if it's end is before it's start.
        const range = this._domDocument.createRange();
        try {
            range.setStart(selection.anchorNode, selection.anchorOffset);
            range.setEnd(selection.focusNode, selection.focusOffset);
        } catch (e) {
            // Safari sometimes gives us a selection that makes Range.set{Start,End} throw.
            // See https://github.com/ckeditor/ckeditor5/issues/12375.
            return false;
        }
        const backward = range.collapsed;
        range.detach();
        return backward;
    }
    /**
	 * Returns a parent {@link module:engine/view/uielement~UIElement} or {@link module:engine/view/rawelement~RawElement}
	 * that hosts the provided DOM node. Returns `null` if there is no such parent.
	 */ getHostViewElement(domNode) {
        const ancestors = getAncestors(domNode);
        // Remove domNode from the list.
        ancestors.pop();
        while(ancestors.length){
            const domNode = ancestors.pop();
            const viewNode = this._domToViewMapping.get(domNode);
            if (viewNode && (viewNode.is('uiElement') || viewNode.is('rawElement'))) {
                return viewNode;
            }
        }
        return null;
    }
    /**
	 * Checks if the given selection's boundaries are at correct places.
	 *
	 * The following places are considered as incorrect for selection boundaries:
	 *
	 * * before or in the middle of an inline filler sequence,
	 * * inside a DOM element which represents {@link module:engine/view/uielement~UIElement a view UI element},
	 * * inside a DOM element which represents {@link module:engine/view/rawelement~RawElement a view raw element}.
	 *
	 * @param domSelection The DOM selection object to be checked.
	 * @returns `true` if the given selection is at a correct place, `false` otherwise.
	 */ isDomSelectionCorrect(domSelection) {
        return this._isDomSelectionPositionCorrect(domSelection.anchorNode, domSelection.anchorOffset) && this._isDomSelectionPositionCorrect(domSelection.focusNode, domSelection.focusOffset);
    }
    /**
	 * Registers a {@link module:engine/view/matcher~MatcherPattern} for view elements whose content should be treated as raw data
	 * and not processed during the conversion from DOM nodes to view elements.
	 *
	 * This is affecting how {@link module:engine/view/domconverter~DomConverter#domToView} and
	 * {@link module:engine/view/domconverter~DomConverter#domChildrenToView} process DOM nodes.
	 *
	 * The raw data can be later accessed by a
	 * {@link module:engine/view/element~Element#getCustomProperty custom property of a view element} called `"$rawContent"`.
	 *
	 * @param pattern Pattern matching a view element whose content should
	 * be treated as raw data.
	 */ registerRawContentMatcher(pattern) {
        this._rawContentElementMatcher.add(pattern);
    }
    /**
	 * Registers a {@link module:engine/view/matcher~MatcherPattern} for inline object view elements.
	 *
	 * This is affecting how {@link module:engine/view/domconverter~DomConverter#domToView} and
	 * {@link module:engine/view/domconverter~DomConverter#domChildrenToView} process DOM nodes.
	 *
	 * This is an extension of a simple {@link #inlineObjectElements} array of element names.
	 *
	 * @param pattern Pattern matching a view element which should be treated as an inline object.
	 */ registerInlineObjectMatcher(pattern) {
        this._inlineObjectElementMatcher.add(pattern);
    }
    /**
	 * Clear temporary custom properties.
	 *
	 * @internal
	 */ _clearTemporaryCustomProperties() {
        for (const element of this._elementsWithTemporaryCustomProperties){
            element._removeCustomProperty('editingPipeline:doNotReuseOnce');
        }
        this._elementsWithTemporaryCustomProperties.clear();
    }
    /**
	 * Returns the block {@link module:engine/view/filler filler} node based on the current {@link #blockFillerMode} setting.
	 */ _getBlockFiller() {
        switch(this.blockFillerMode){
            case 'nbsp':
                return NBSP_FILLER(this._domDocument); // eslint-disable-line new-cap
            case 'markedNbsp':
                return MARKED_NBSP_FILLER(this._domDocument); // eslint-disable-line new-cap
            case 'br':
                return BR_FILLER(this._domDocument); // eslint-disable-line new-cap
        }
    }
    /**
	 * Checks if the given DOM position is a correct place for selection boundary. See {@link #isDomSelectionCorrect}.
	 *
	 * @param domParent Position parent.
	 * @param offset Position offset.
	 * @returns `true` if given position is at a correct place for selection boundary, `false` otherwise.
	 */ _isDomSelectionPositionCorrect(domParent, offset) {
        // If selection is before or in the middle of inline filler string, it is incorrect.
        if (isText(domParent) && startsWithFiller(domParent) && offset < INLINE_FILLER_LENGTH) {
            // Selection in a text node, at wrong position (before or in the middle of filler).
            return false;
        }
        if (this.isElement(domParent) && startsWithFiller(domParent.childNodes[offset])) {
            // Selection in an element node, before filler text node.
            return false;
        }
        const viewParent = this.mapDomToView(domParent);
        // The position is incorrect when anchored inside a UIElement or a RawElement.
        // Note: In case of UIElement and RawElement, mapDomToView() returns a parent element for any DOM child
        // so there's no need to perform any additional checks.
        if (viewParent && (viewParent.is('uiElement') || viewParent.is('rawElement'))) {
            return false;
        }
        return true;
    }
    /**
	 * Internal generator for {@link #domToView}. Also used by {@link #domChildrenToView}.
	 * Separates DOM nodes conversion from whitespaces processing.
	 *
	 * @param domNode DOM node or document fragment to transform.
	 * @param inlineNodes An array of recently encountered inline nodes truncated to the block element boundaries.
	 * Used later to process whitespaces.
	 */ *_domToView(domNode, options, inlineNodes) {
        if (this.isBlockFiller(domNode)) {
            return null;
        }
        // When node is inside a UIElement or a RawElement return that parent as it's view representation.
        const hostElement = this.getHostViewElement(domNode);
        if (hostElement) {
            return hostElement;
        }
        if (isComment(domNode) && options.skipComments) {
            return null;
        }
        if (isText(domNode)) {
            if (isInlineFiller(domNode)) {
                return null;
            } else {
                const textData = domNode.data;
                if (textData === '') {
                    return null;
                }
                const textNode = new Text$1(this.document, textData);
                inlineNodes.push(textNode);
                return textNode;
            }
        } else {
            let viewElement = this.mapDomToView(domNode);
            if (viewElement) {
                if (this._isInlineObjectElement(viewElement)) {
                    inlineNodes.push(viewElement);
                }
                return viewElement;
            }
            if (this.isDocumentFragment(domNode)) {
                // Create view document fragment.
                viewElement = new DocumentFragment$1(this.document);
                if (options.bind) {
                    this.bindDocumentFragments(domNode, viewElement);
                }
            } else {
                // Create view element.
                viewElement = this._createViewElement(domNode, options);
                if (options.bind) {
                    this.bindElements(domNode, viewElement);
                }
                // Copy element's attributes.
                const attrs = domNode.attributes;
                if (attrs) {
                    for(let l = attrs.length, i = 0; i < l; i++){
                        viewElement._setAttribute(attrs[i].name, attrs[i].value);
                    }
                }
                // Treat this element's content as a raw data if it was registered as such.
                if (this._isViewElementWithRawContent(viewElement, options)) {
                    viewElement._setCustomProperty('$rawContent', domNode.innerHTML);
                    if (!this._isBlockViewElement(viewElement)) {
                        inlineNodes.push(viewElement);
                    }
                    return viewElement;
                }
                // Comment node is also treated as an element with raw data.
                if (isComment(domNode)) {
                    viewElement._setCustomProperty('$rawContent', domNode.data);
                    return viewElement;
                }
            }
            // Yield the element first so the flow of nested inline nodes is not reversed inside elements.
            yield viewElement;
            const nestedInlineNodes = [];
            if (options.withChildren !== false) {
                for (const child of this.domChildrenToView(domNode, options, nestedInlineNodes)){
                    viewElement._appendChild(child);
                }
            }
            // Check if this is an inline object after processing child nodes so matcher
            // for inline objects can verify if the element is empty.
            if (this._isInlineObjectElement(viewElement)) {
                inlineNodes.push(viewElement);
            } else {
                // It's an inline element that is not an object (like <b>, <i>) or a block element.
                for (const inlineNode of nestedInlineNodes){
                    inlineNodes.push(inlineNode);
                }
            }
        }
    }
    /**
	 * Internal helper that walks the list of inline view nodes already generated from DOM nodes
	 * and handles whitespaces and NBSPs.
	 *
	 * @param domParent The DOM parent of the given inline nodes. This should be a document fragment or
	 * a block element to whitespace processing start cleaning.
	 * @param inlineNodes An array of recently encountered inline nodes truncated to the block element boundaries.
	 */ _processDomInlineNodes(domParent, inlineNodes, options) {
        if (!inlineNodes.length) {
            return;
        }
        // Process text nodes only after reaching a block or document fragment,
        // do not alter whitespaces while processing an inline element like <b> or <i>.
        if (domParent && !this.isDocumentFragment(domParent) && !this._isBlockDomElement(domParent)) {
            return;
        }
        let prevNodeEndsWithSpace = false;
        for(let i = 0; i < inlineNodes.length; i++){
            const node = inlineNodes[i];
            if (!node.is('$text')) {
                prevNodeEndsWithSpace = false;
                continue;
            }
            let data;
            let nodeEndsWithSpace = false;
            if (this._isPreFormatted(node)) {
                data = getDataWithoutFiller(node.data);
            } else {
                // Change all consecutive whitespace characters (from the [ \n\t\r] set –
                // see https://github.com/ckeditor/ckeditor5-engine/issues/822#issuecomment-311670249) to a single space character.
                // That's how multiple whitespaces are treated when rendered, so we normalize those whitespaces.
                // We're replacing 1+ (and not 2+) to also normalize singular \n\t\r characters (#822).
                data = node.data.replace(/[ \n\t\r]{1,}/g, ' ');
                nodeEndsWithSpace = /[^\S\u00A0]/.test(data.charAt(data.length - 1));
                const prevNode = i > 0 ? inlineNodes[i - 1] : null;
                const nextNode = i + 1 < inlineNodes.length ? inlineNodes[i + 1] : null;
                const shouldLeftTrim = !prevNode || prevNode.is('element') && prevNode.name == 'br' || prevNodeEndsWithSpace;
                const shouldRightTrim = nextNode ? false : !startsWithFiller(node.data);
                // Do not try to clear whitespaces if this is flat mapping for the purpose of mutation observer and differ in rendering.
                if (options.withChildren !== false) {
                    // If the previous dom text node does not exist or it ends by whitespace character, remove space character from the
                    // beginning of this text node. Such space character is treated as a whitespace.
                    if (shouldLeftTrim) {
                        data = data.replace(/^ /, '');
                    }
                    // If the next text node does not exist remove space character from the end of this text node.
                    if (shouldRightTrim) {
                        data = data.replace(/ $/, '');
                    }
                }
                // At the beginning and end of a block element, Firefox inserts normal space + <br> instead of non-breaking space.
                // This means that the text node starts/end with normal space instead of non-breaking space.
                // This causes a problem because the normal space would be removed in `.replace` calls above. To prevent that,
                // the inline filler is removed only after the data is initially processed (by the `.replace` above). See ckeditor5#692.
                data = getDataWithoutFiller(data);
                // At this point we should have removed all whitespaces from DOM text data.
                //
                // Now, We will reverse the process that happens in `_processDataFromViewText`.
                //
                // We have to change &nbsp; chars, that were in DOM text data because of rendering reasons, to spaces.
                // First, change all ` \u00A0` pairs (space + &nbsp;) to two spaces. DOM converter changes two spaces from model/view to
                // ` \u00A0` to ensure proper rendering. Since here we convert back, we recognize those pairs and change them back to `  `.
                data = data.replace(/ \u00A0/g, '  ');
                const isNextNodeInlineObjectElement = nextNode && nextNode.is('element') && nextNode.name != 'br';
                const isNextNodeStartingWithSpace = nextNode && nextNode.is('$text') && nextNode.data.charAt(0) == ' ';
                // Then, let's change the last nbsp to a space.
                if (/[ \u00A0]\u00A0$/.test(data) || !nextNode || isNextNodeInlineObjectElement || isNextNodeStartingWithSpace) {
                    data = data.replace(/\u00A0$/, ' ');
                }
                // Then, change &nbsp; character that is at the beginning of the text node to space character.
                // We do that replacement only if this is the first node or the previous node ends on whitespace character.
                if (shouldLeftTrim || prevNode && prevNode.is('element') && prevNode.name != 'br') {
                    data = data.replace(/^\u00A0/, ' ');
                }
            }
            // At this point, all whitespaces should be removed and all &nbsp; created for rendering reasons should be
            // changed to normal space. All left &nbsp; are &nbsp; inserted intentionally.
            if (data.length == 0 && node.parent) {
                node._remove();
                inlineNodes.splice(i, 1);
                i--;
            } else {
                node._data = data;
                prevNodeEndsWithSpace = nodeEndsWithSpace;
            }
        }
        inlineNodes.length = 0;
    }
    /**
	 * Takes text data from a given {@link module:engine/view/text~Text#data} and processes it so
	 * it is correctly displayed in the DOM.
	 *
	 * Following changes are done:
	 *
	 * * a space at the beginning is changed to `&nbsp;` if this is the first text node in its container
	 * element or if a previous text node ends with a space character,
	 * * space at the end of the text node is changed to `&nbsp;` if there are two spaces at the end of a node or if next node
	 * starts with a space or if it is the last text node in its container,
	 * * remaining spaces are replaced to a chain of spaces and `&nbsp;` (e.g. `'x   x'` becomes `'x &nbsp; x'`).
	 *
	 * Content of {@link #preElements} is not processed.
	 *
	 * @param node View text node to process.
	 * @returns Processed text data.
	 */ _processDataFromViewText(node) {
        let data = node.data;
        // If the currently processed view text node is preformatted, we should not change whitespaces.
        if (this._isPreFormatted(node)) {
            return data;
        }
        // 1. Replace the first space with a nbsp if the previous node ends with a space or there is no previous node
        // (container element boundary).
        if (data.charAt(0) == ' ') {
            const prevNode = this._getTouchingInlineViewNode(node, false);
            const prevEndsWithSpace = prevNode && prevNode.is('$textProxy') && this._nodeEndsWithSpace(prevNode);
            if (prevEndsWithSpace || !prevNode) {
                data = '\u00A0' + data.substr(1);
            }
        }
        // 2. Replace the last space with nbsp if there are two spaces at the end or if the next node starts with space or there is no
        // next node (container element boundary).
        //
        // Keep in mind that Firefox prefers $nbsp; before tag, not inside it:
        //
        // Foo <span>&nbsp;bar</span>  <-- bad.
        // Foo&nbsp;<span> bar</span>  <-- good.
        //
        // More here: https://github.com/ckeditor/ckeditor5-engine/issues/1747.
        if (data.charAt(data.length - 1) == ' ') {
            const nextNode = this._getTouchingInlineViewNode(node, true);
            const nextStartsWithSpace = nextNode && nextNode.is('$textProxy') && nextNode.data.charAt(0) == ' ';
            if (data.charAt(data.length - 2) == ' ' || !nextNode || nextStartsWithSpace) {
                data = data.substr(0, data.length - 1) + '\u00A0';
            }
        }
        // 3. Create space+nbsp pairs.
        return data.replace(/ {2}/g, ' \u00A0');
    }
    /**
	 * Checks whether given node ends with a space character after changing appropriate space characters to `&nbsp;`s.
	 *
	 * @param  node Node to check.
	 * @returns `true` if given `node` ends with space, `false` otherwise.
	 */ _nodeEndsWithSpace(node) {
        if (this._isPreFormatted(node)) {
            return false;
        }
        const data = this._processDataFromViewText(node);
        return data.charAt(data.length - 1) == ' ';
    }
    /**
	 * Checks whether given text contains preformatted white space. This is the case if
	 * * any of node ancestors has a name which is in `preElements` array, or
	 * * the closest ancestor that has the `white-space` CSS property sets it to a value that preserves spaces
	 *
	 * @param node Node to check
	 * @returns `true` if given node contains preformatted white space, `false` otherwise.
	 */ _isPreFormatted(node) {
        if (_hasViewParentOfType(node, this.preElements)) {
            return true;
        }
        for (const ancestor of node.getAncestors({
            parentFirst: true
        })){
            if (!ancestor.is('element') || !ancestor.hasStyle('white-space') || ancestor.getStyle('white-space') === 'inherit') {
                continue;
            }
            // If the node contains the `white-space` property with a value that does not preserve spaces, it will take
            // precedence over any white-space settings its ancestors contain, so no further parent checking needs to
            // be done.
            return [
                'pre',
                'pre-wrap',
                'break-spaces'
            ].includes(ancestor.getStyle('white-space'));
        }
        return false;
    }
    /**
	 * Helper function. For given {@link module:engine/view/text~Text view text node}, it finds previous or next sibling
	 * that is contained in the same container element. If there is no such sibling, `null` is returned.
	 *
	 * @param node Reference node.
	 * @returns Touching text node, an inline object
	 * or `null` if there is no next or previous touching text node.
	 */ _getTouchingInlineViewNode(node, getNext) {
        const treeWalker = new TreeWalker$1({
            startPosition: getNext ? Position$1._createAfter(node) : Position$1._createBefore(node),
            direction: getNext ? 'forward' : 'backward'
        });
        for (const value of treeWalker){
            // <br> found – it works like a block boundary, so do not scan further.
            if (value.item.is('element', 'br')) {
                return null;
            } else if (this._isInlineObjectElement(value.item)) {
                return value.item;
            } else if (value.item.is('containerElement')) {
                return null;
            } else if (value.item.is('$textProxy')) {
                return value.item;
            }
        }
        return null;
    }
    /**
	 * Returns `true` if a DOM node belongs to {@link #blockElements}. `false` otherwise.
	 */ _isBlockDomElement(node) {
        return this.isElement(node) && this.blockElements.includes(node.tagName.toLowerCase());
    }
    /**
	 * Returns `true` if a view node belongs to {@link #blockElements}. `false` otherwise.
	 */ _isBlockViewElement(node) {
        return node.is('element') && this.blockElements.includes(node.name);
    }
    /**
	 * Returns `true` if a DOM node belongs to {@link #inlineObjectElements}. `false` otherwise.
	 */ _isInlineObjectElement(node) {
        if (!node.is('element')) {
            return false;
        }
        return node.name == 'br' || this.inlineObjectElements.includes(node.name) || !!this._inlineObjectElementMatcher.match(node);
    }
    /**
	 * Creates view element basing on the node type.
	 *
	 * @param node DOM node to check.
	 * @param options Conversion options. See {@link module:engine/view/domconverter~DomConverter#domToView} options parameter.
	 */ _createViewElement(node, options) {
        if (isComment(node)) {
            return new UIElement(this.document, '$comment');
        }
        const viewName = options.keepOriginalCase ? node.tagName : node.tagName.toLowerCase();
        return new Element$1(this.document, viewName);
    }
    /**
	 * Checks if view element's content should be treated as a raw data.
	 *
	 * @param viewElement View element to check.
	 * @param options Conversion options. See {@link module:engine/view/domconverter~DomConverter#domToView} options parameter.
	 */ _isViewElementWithRawContent(viewElement, options) {
        return options.withChildren !== false && viewElement.is('element') && !!this._rawContentElementMatcher.match(viewElement);
    }
    /**
	 * Checks whether a given element name should be renamed in a current rendering mode.
	 *
	 * @param elementName The name of view element.
	 */ _shouldRenameElement(elementName) {
        const name = elementName.toLowerCase();
        return this.renderingMode === 'editing' && this.unsafeElements.includes(name);
    }
    /**
	 * Return a <span> element with a special attribute holding the name of the original element.
	 * Optionally, copy all the attributes of the original element if that element is provided.
	 *
	 * @param elementName The name of view element.
	 * @param originalDomElement The original DOM element to copy attributes and content from.
	 */ _createReplacementDomElement(elementName, originalDomElement) {
        const newDomElement = this._domDocument.createElement('span');
        // Mark the span replacing a script as hidden.
        newDomElement.setAttribute(UNSAFE_ELEMENT_REPLACEMENT_ATTRIBUTE, elementName);
        if (originalDomElement) {
            while(originalDomElement.firstChild){
                newDomElement.appendChild(originalDomElement.firstChild);
            }
            for (const attributeName of originalDomElement.getAttributeNames()){
                newDomElement.setAttribute(attributeName, originalDomElement.getAttribute(attributeName));
            }
        }
        return newDomElement;
    }
}
/**
 * Helper function.
 * Used to check if given native `Element` or `Text` node has parent with tag name from `types` array.
 *
 * @returns`true` if such parent exists or `false` if it does not.
 */ function _hasViewParentOfType(node, types) {
    return node.getAncestors().some((parent)=>parent.is('element') && types.includes(parent.name));
}
/**
 * A helper that executes given callback for each DOM node's ancestor, starting from the given node
 * and ending in document#documentElement.
 *
 * @param callback A callback to be executed for each ancestor.
 */ function forEachDomElementAncestor(element, callback) {
    let node = element;
    while(node){
        callback(node);
        node = node.parentElement;
    }
}
/**
 * Checks if given node is a nbsp block filler.
 *
 * A &nbsp; is a block filler only if it is a single child of a block element.
 *
 * @param domNode DOM node.
 */ function isNbspBlockFiller(domNode, blockElements) {
    const isNBSP = domNode.isEqualNode(NBSP_FILLER_REF);
    return isNBSP && hasBlockParent(domNode, blockElements) && domNode.parentNode.childNodes.length === 1;
}
/**
 * Checks if domNode has block parent.
 *
 * @param domNode DOM node.
 */ function hasBlockParent(domNode, blockElements) {
    const parent = domNode.parentNode;
    return !!parent && !!parent.tagName && blockElements.includes(parent.tagName.toLowerCase());
}
/**
 * Log to console the information about element that was replaced.
 * Check UNSAFE_ELEMENTS for all recognized unsafe elements.
 *
 * @param elementName The name of the view element.
 */ function _logUnsafeElement(elementName) {
    if (elementName === 'script') {
        logWarning('domconverter-unsafe-script-element-detected');
    }
    if (elementName === 'style') {
        logWarning('domconverter-unsafe-style-element-detected');
    }
}
/**
 * In certain cases, Firefox mysteriously assigns so called "restricted objects" to native DOM Range properties.
 * Any attempt at accessing restricted object's properties causes errors.
 * See: https://github.com/ckeditor/ckeditor5/issues/9635.
 */ function isGeckoRestrictedDomSelection(domSelection) {
    if (!env.isGecko) {
        return false;
    }
    if (!domSelection.rangeCount) {
        return false;
    }
    const container = domSelection.getRangeAt(0).startContainer;
    try {
        Object.prototype.toString.call(container);
    } catch (error) {
        return true;
    }
    return false;
}
 /**
 * While rendering the editor content, the {@link module:engine/view/domconverter~DomConverter} detected a `<script>` element that may
 * disrupt the editing experience. To avoid this, the `<script>` element was replaced with `<span data-ck-unsafe-element="script"></span>`.
 *
 * @error domconverter-unsafe-script-element-detected
 */  /**
 * While rendering the editor content, the {@link module:engine/view/domconverter~DomConverter} detected a `<style>` element that may affect
 * the editing experience. To avoid this, the `<style>` element was replaced with `<span data-ck-unsafe-element="style"></span>`.
 *
 * @error domconverter-unsafe-style-element-detected
 */  /**
 * The {@link module:engine/view/domconverter~DomConverter} detected an interactive attribute in the
 * {@glink framework/architecture/editing-engine#editing-pipeline editing pipeline}. For the best
 * editing experience, the attribute was renamed to `data-ck-unsafe-attribute-[original attribute name]`.
 *
 * If you are the author of the plugin that generated this attribute and you want it to be preserved
 * in the editing pipeline, you can configure this when creating the element
 * using {@link module:engine/view/downcastwriter~DowncastWriter} during the
 * {@glink framework/architecture/editing-engine#conversion model–view conversion}. Methods such as
 * {@link module:engine/view/downcastwriter~DowncastWriter#createContainerElement},
 * {@link module:engine/view/downcastwriter~DowncastWriter#createAttributeElement}, or
 * {@link module:engine/view/downcastwriter~DowncastWriter#createEmptyElement}
 * accept an option that will disable filtering of specific attributes:
 *
 * ```ts
 * const paragraph = writer.createContainerElement( 'p',
 * 	{
 * 		class: 'clickable-paragraph',
 * 		onclick: 'alert( "Paragraph clicked!" )'
 * 	},
 * 	{
 * 		// Make sure the "onclick" attribute will pass through.
 * 		renderUnsafeAttributes: [ 'onclick' ]
 * 	}
 * );
 * ```
 *
 * @error domconverter-unsafe-attribute-detected
 * @param domElement The DOM element the attribute was set on.
 * @param key The original name of the attribute
 * @param value The value of the original attribute
 */

/**
 * Abstract base observer class. Observers are classes which listen to DOM events, do the preliminary
 * processing and fire events on the {@link module:engine/view/document~Document} objects.
 * Observers can also add features to the view, for instance by updating its status or marking elements
 * which need a refresh on DOM events.
 */ class Observer extends /* #__PURE__ */ DomEmitterMixin() {
    /**
	 * An instance of the view controller.
	 */ view;
    /**
	 * A reference to the {@link module:engine/view/document~Document} object.
	 */ document;
    /**
	 * The state of the observer. If it is disabled, no events will be fired.
	 */ _isEnabled = false;
    /**
	 * Creates an instance of the observer.
	 */ constructor(view){
        super();
        this.view = view;
        this.document = view.document;
    }
    /**
	 * The state of the observer. If it is disabled, no events will be fired.
	 */ get isEnabled() {
        return this._isEnabled;
    }
    /**
	 * Enables the observer. This method is called when the observer is registered to the
	 * {@link module:engine/view/view~View} and after {@link module:engine/view/view~View#forceRender rendering}
	 * (all observers are {@link #disable disabled} before rendering).
	 *
	 * A typical use case for disabling observers is that mutation observers need to be disabled for the rendering.
	 * However, a child class may not need to be disabled, so it can implement an empty method.
	 *
	 * @see module:engine/view/observer/observer~Observer#disable
	 */ enable() {
        this._isEnabled = true;
    }
    /**
	 * Disables the observer. This method is called before
	 * {@link module:engine/view/view~View#forceRender rendering} to prevent firing events during rendering.
	 *
	 * @see module:engine/view/observer/observer~Observer#enable
	 */ disable() {
        this._isEnabled = false;
    }
    /**
	 * Disables and destroys the observer, among others removes event listeners created by the observer.
	 */ destroy() {
        this.disable();
        this.stopListening();
    }
    /**
	 * Checks whether a given DOM event should be ignored (should not be turned into a synthetic view document event).
	 *
	 * Currently, an event will be ignored only if its target or any of its ancestors has the `data-cke-ignore-events` attribute.
	 * This attribute can be used inside the structures generated by
	 * {@link module:engine/view/downcastwriter~DowncastWriter#createUIElement `DowncastWriter#createUIElement()`} to ignore events
	 * fired within a UI that should be excluded from CKEditor 5's realms.
	 *
	 * @param domTarget The DOM event target to check (usually an element, sometimes a text node and
	 * potentially sometimes a document, too).
	 * @returns Whether this event should be ignored by the observer.
	 */ checkShouldIgnoreEventFromTarget(domTarget) {
        if (domTarget && domTarget.nodeType === 3) {
            domTarget = domTarget.parentNode;
        }
        if (!domTarget || domTarget.nodeType !== 1) {
            return false;
        }
        return domTarget.matches('[data-cke-ignore-events], [data-cke-ignore-events] *');
    }
}

/**
 * Information about a DOM event in context of the {@link module:engine/view/document~Document}.
 * It wraps the native event, which usually should not be used as the wrapper contains
 * additional data (like key code for keyboard events).
 *
 * @typeParam TEvent The type of DOM Event that this class represents.
 */ class DomEventData {
    /**
	 * Instance of the view controller.
	 */ view;
    /**
	 * The instance of the document.
	 */ document;
    /**
	 * The DOM event.
	 */ domEvent;
    /**
	 * The DOM target.
	 */ domTarget;
    /**
	 * @param view The instance of the view controller.
	 * @param domEvent The DOM event.
	 * @param additionalData Additional properties that the instance should contain.
	 */ constructor(view, domEvent, additionalData){
        this.view = view;
        this.document = view.document;
        this.domEvent = domEvent;
        this.domTarget = domEvent.target;
        extend(this, additionalData);
    }
    /**
	 * The tree view element representing the target.
	 */ get target() {
        return this.view.domConverter.mapDomToView(this.domTarget);
    }
    /**
	 * Prevents the native's event default action.
	 */ preventDefault() {
        this.domEvent.preventDefault();
    }
    /**
	 * Stops native event propagation.
	 */ stopPropagation() {
        this.domEvent.stopPropagation();
    }
}

/**
 * Base class for DOM event observers. This class handles
 * {@link module:engine/view/observer/observer~Observer#observe adding} listeners to DOM elements,
 * {@link module:engine/view/observer/observer~Observer#disable disabling} and
 * {@link module:engine/view/observer/observer~Observer#enable re-enabling} events.
 * Child class needs to define
 * {@link module:engine/view/observer/domeventobserver~DomEventObserver#domEventType DOM event type} and
 * {@link module:engine/view/observer/domeventobserver~DomEventObserver#onDomEvent callback}.
 *
 * For instance:
 *
 * ```ts
 * class ClickObserver extends DomEventObserver<'click'> {
 * 	// It can also be defined as a normal property in the constructor.
 * 	get domEventType(): 'click' {
 * 		return 'click';
 * 	}
 *
 * 	onDomEvent( domEvent: MouseEvent ): void {
 * 		this.fire( 'click', domEvent );
 * 	}
 * }
 * ```
 *
 * @typeParam EventType DOM Event type name or an union of those.
 * @typeParam AdditionalData Additional data passed along with the event.
 */ class DomEventObserver extends Observer {
    /**
	 * If set to `true` DOM events will be listened on the capturing phase.
	 * Default value is `false`.
	 */ useCapture = false;
    /**
	 * @inheritDoc
	 */ observe(domElement) {
        const types = typeof this.domEventType == 'string' ? [
            this.domEventType
        ] : this.domEventType;
        types.forEach((type)=>{
            this.listenTo(domElement, type, (eventInfo, domEvent)=>{
                if (this.isEnabled && !this.checkShouldIgnoreEventFromTarget(domEvent.target)) {
                    this.onDomEvent(domEvent);
                }
            }, {
                useCapture: this.useCapture
            });
        });
    }
    /**
	 * @inheritDoc
	 */ stopObserving(domElement) {
        this.stopListening(domElement);
    }
    /**
	 * Calls `Document#fire()` if observer {@link #isEnabled is enabled}.
	 *
	 * @see module:utils/emittermixin~Emitter#fire
	 * @param eventType The event type (name).
	 * @param domEvent The DOM event.
	 * @param additionalData The additional data which should extend the
	 * {@link module:engine/view/observer/domeventdata~DomEventData event data} object.
	 */ fire(eventType, domEvent, additionalData) {
        if (this.isEnabled) {
            this.document.fire(eventType, new DomEventData(this.view, domEvent, additionalData));
        }
    }
}

/**
 * Observer for events connected with pressing keyboard keys.
 *
 * Note that this observer is attached by the {@link module:engine/view/view~View} and is available by default.
 */ class KeyObserver extends DomEventObserver {
    /**
	 * @inheritDoc
	 */ domEventType = [
        'keydown',
        'keyup'
    ];
    /**
	 * @inheritDoc
	 */ onDomEvent(domEvt) {
        const data = {
            keyCode: domEvt.keyCode,
            altKey: domEvt.altKey,
            ctrlKey: domEvt.ctrlKey,
            shiftKey: domEvt.shiftKey,
            metaKey: domEvt.metaKey,
            get keystroke () {
                return getCode(this);
            }
        };
        this.fire(domEvt.type, domEvt, data);
    }
}

/**
 * Fake selection observer class. If view selection is fake it is placed in dummy DOM container. This observer listens
 * on {@link module:engine/view/document~Document#event:keydown keydown} events and handles moving fake view selection to the correct place
 * if arrow keys are pressed.
 * Fires {@link module:engine/view/document~Document#event:selectionChange selectionChange event} simulating natural behaviour of
 * {@link module:engine/view/observer/selectionobserver~SelectionObserver SelectionObserver}.
 */ class FakeSelectionObserver extends Observer {
    /**
	 * Fires debounced event `selectionChangeDone`. It uses `lodash#debounce` method to delay function call.
	 */ _fireSelectionChangeDoneDebounced;
    /**
	 * Creates new FakeSelectionObserver instance.
	 */ constructor(view){
        super(view);
        this._fireSelectionChangeDoneDebounced = debounce((data)=>{
            this.document.fire('selectionChangeDone', data);
        }, 200);
    }
    /**
	 * @inheritDoc
	 */ observe() {
        const document = this.document;
        document.on('arrowKey', (eventInfo, data)=>{
            const selection = document.selection;
            if (selection.isFake && this.isEnabled) {
                // Prevents default key down handling - no selection change will occur.
                data.preventDefault();
            }
        }, {
            context: '$capture'
        });
        document.on('arrowKey', (eventInfo, data)=>{
            const selection = document.selection;
            if (selection.isFake && this.isEnabled) {
                this._handleSelectionMove(data.keyCode);
            }
        }, {
            priority: 'lowest'
        });
    }
    /**
	 * @inheritDoc
	 */ stopObserving() {}
    /**
	 * @inheritDoc
	 */ destroy() {
        super.destroy();
        this._fireSelectionChangeDoneDebounced.cancel();
    }
    /**
	 * Handles collapsing view selection according to given key code. If left or up key is provided - new selection will be
	 * collapsed to left. If right or down key is pressed - new selection will be collapsed to right.
	 *
	 * This method fires {@link module:engine/view/document~Document#event:selectionChange} and
	 * {@link module:engine/view/document~Document#event:selectionChangeDone} events imitating behaviour of
	 * {@link module:engine/view/observer/selectionobserver~SelectionObserver}.
	 */ _handleSelectionMove(keyCode) {
        const selection = this.document.selection;
        const newSelection = new Selection$1(selection.getRanges(), {
            backward: selection.isBackward,
            fake: false
        });
        // Left or up arrow pressed - move selection to start.
        if (keyCode == keyCodes.arrowleft || keyCode == keyCodes.arrowup) {
            newSelection.setTo(newSelection.getFirstPosition());
        }
        // Right or down arrow pressed - move selection to end.
        if (keyCode == keyCodes.arrowright || keyCode == keyCodes.arrowdown) {
            newSelection.setTo(newSelection.getLastPosition());
        }
        const data = {
            oldSelection: selection,
            newSelection,
            domSelection: null
        };
        // Fire dummy selection change event.
        this.document.fire('selectionChange', data);
        // Call` #_fireSelectionChangeDoneDebounced` every time when `selectionChange` event is fired.
        // This function is debounced what means that `selectionChangeDone` event will be fired only when
        // defined int the function time will elapse since the last time the function was called.
        // So `selectionChangeDone` will be fired when selection will stop changing.
        this._fireSelectionChangeDoneDebounced(data);
    }
}

/**
 * Mutation observer's role is to watch for any DOM changes inside the editor that weren't
 * done by the editor's {@link module:engine/view/renderer~Renderer} itself and reverting these changes.
 *
 * It does this by observing all mutations in the DOM, marking related view elements as changed and calling
 * {@link module:engine/view/renderer~Renderer#render}. Because all mutated nodes are marked as
 * "to be rendered" and the {@link module:engine/view/renderer~Renderer#render `render()`} method is called,
 * all changes are reverted in the DOM (the DOM is synced with the editor's view structure).
 *
 * Note that this observer is attached by the {@link module:engine/view/view~View} and is available by default.
 */ class MutationObserver extends Observer {
    /**
	 * Reference to the {@link module:engine/view/view~View#domConverter}.
	 */ domConverter;
    /**
	 * Reference to the {@link module:engine/view/view~View#_renderer}.
	 */ renderer;
    /**
	 * Native mutation observer config.
	 */ _config;
    /**
	 * Observed DOM elements.
	 */ _domElements;
    /**
	 * Native mutation observer.
	 */ _mutationObserver;
    /**
	 * @inheritDoc
	 */ constructor(view){
        super(view);
        this._config = {
            childList: true,
            characterData: true,
            subtree: true
        };
        this.domConverter = view.domConverter;
        this.renderer = view._renderer;
        this._domElements = new Set();
        this._mutationObserver = new window.MutationObserver(this._onMutations.bind(this));
    }
    /**
	 * Synchronously handles mutations and empties the queue.
	 */ flush() {
        this._onMutations(this._mutationObserver.takeRecords());
    }
    /**
	 * @inheritDoc
	 */ observe(domElement) {
        this._domElements.add(domElement);
        if (this.isEnabled) {
            this._mutationObserver.observe(domElement, this._config);
        }
    }
    /**
	 * @inheritDoc
	 */ stopObserving(domElement) {
        this._domElements.delete(domElement);
        if (this.isEnabled) {
            // Unfortunately, it is not possible to stop observing particular DOM element.
            // In order to stop observing one of multiple DOM elements, we need to re-connect the mutation observer.
            this._mutationObserver.disconnect();
            for (const domElement of this._domElements){
                this._mutationObserver.observe(domElement, this._config);
            }
        }
    }
    /**
	 * @inheritDoc
	 */ enable() {
        super.enable();
        for (const domElement of this._domElements){
            this._mutationObserver.observe(domElement, this._config);
        }
    }
    /**
	 * @inheritDoc
	 */ disable() {
        super.disable();
        this._mutationObserver.disconnect();
    }
    /**
	 * @inheritDoc
	 */ destroy() {
        super.destroy();
        this._mutationObserver.disconnect();
    }
    /**
	 * Handles mutations. Mark view elements to sync and call render.
	 *
	 * @param domMutations Array of native mutations.
	 */ _onMutations(domMutations) {
        // As a result of this.flush() we can have an empty collection.
        if (domMutations.length === 0) {
            return;
        }
        const domConverter = this.domConverter;
        // Use map and set for deduplication.
        const mutatedTextNodes = new Set();
        const elementsWithMutatedChildren = new Set();
        // Handle `childList` mutations first, so we will be able to check if the `characterData` mutation is in the
        // element with changed structure anyway.
        for (const mutation of domMutations){
            const element = domConverter.mapDomToView(mutation.target);
            if (!element) {
                continue;
            }
            // Do not collect mutations from UIElements and RawElements.
            if (element.is('uiElement') || element.is('rawElement')) {
                continue;
            }
            if (mutation.type === 'childList' && !this._isBogusBrMutation(mutation)) {
                elementsWithMutatedChildren.add(element);
            }
        }
        // Handle `characterData` mutations later, when we have the full list of nodes which changed structure.
        for (const mutation of domMutations){
            const element = domConverter.mapDomToView(mutation.target);
            // Do not collect mutations from UIElements and RawElements.
            if (element && (element.is('uiElement') || element.is('rawElement'))) {
                continue;
            }
            if (mutation.type === 'characterData') {
                const text = domConverter.findCorrespondingViewText(mutation.target);
                if (text && !elementsWithMutatedChildren.has(text.parent)) {
                    mutatedTextNodes.add(text);
                } else if (!text && startsWithFiller(mutation.target)) {
                    elementsWithMutatedChildren.add(domConverter.mapDomToView(mutation.target.parentNode));
                }
            }
        }
        // Now we build the list of mutations to mark elements. We did not do it earlier to avoid marking the
        // same node multiple times in case of duplication.
        let hasMutations = false;
        for (const textNode of mutatedTextNodes){
            hasMutations = true;
            this.renderer.markToSync('text', textNode);
        }
        for (const viewElement of elementsWithMutatedChildren){
            const domElement = domConverter.mapViewToDom(viewElement);
            const viewChildren = Array.from(viewElement.getChildren());
            const newViewChildren = Array.from(domConverter.domChildrenToView(domElement, {
                withChildren: false
            }));
            // It may happen that as a result of many changes (sth was inserted and then removed),
            // both elements haven't really changed. #1031
            if (!isEqualWith(viewChildren, newViewChildren, sameNodes)) {
                hasMutations = true;
                this.renderer.markToSync('children', viewElement);
            }
        }
        // In case only non-relevant mutations were recorded it skips the event and force render (#5600).
        if (hasMutations) {
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	console.group( '%c[MutationObserver]%c Mutations detected',
            // @if CK_DEBUG_TYPING // 		'font-weight:bold;color:green', ''
            // @if CK_DEBUG_TYPING // 	);
            // @if CK_DEBUG_TYPING // }
            // At this point we have "dirty DOM" (changed) and de-synched view (which has not been changed).
            // In order to "reset DOM" we render the view again.
            this.view.forceRender();
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.groupEnd();
        // @if CK_DEBUG_TYPING // }
        }
    }
    /**
	 * Checks if mutation was generated by the browser inserting bogus br on the end of the block element.
	 * Such mutations are generated while pressing space or performing native spellchecker correction
	 * on the end of the block element in Firefox browser.
	 *
	 * @param mutation Native mutation object.
	 */ _isBogusBrMutation(mutation) {
        let addedNode = null;
        // Check if mutation added only one node on the end of its parent.
        if (mutation.nextSibling === null && mutation.removedNodes.length === 0 && mutation.addedNodes.length == 1) {
            addedNode = this.domConverter.domToView(mutation.addedNodes[0], {
                withChildren: false
            });
        }
        return addedNode && addedNode.is('element', 'br');
    }
}
function sameNodes(child1, child2) {
    // First level of comparison (array of children vs array of children) – use the Lodash's default behavior.
    if (Array.isArray(child1)) {
        return;
    }
    // Elements.
    if (child1 === child2) {
        return true;
    } else if (child1.is('$text') && child2.is('$text')) {
        return child1.data === child2.data;
    }
    // Not matching types.
    return false;
}

/**
 * {@link module:engine/view/document~Document#event:focus Focus}
 * and {@link module:engine/view/document~Document#event:blur blur} events observer.
 * Focus observer handle also {@link module:engine/view/rooteditableelement~RootEditableElement#isFocused isFocused} property of the
 * {@link module:engine/view/rooteditableelement~RootEditableElement root elements}.
 *
 * Note that this observer is attached by the {@link module:engine/view/view~View} and is available by default.
 */ class FocusObserver extends DomEventObserver {
    /**
	 * Identifier of the timeout currently used by focus listener to delay rendering execution.
	 */ _renderTimeoutId;
    /**
	 * Set to `true` if the document is in the process of setting the focus.
	 *
	 * The flag is used to indicate that setting the focus is in progress.
	 */ _isFocusChanging = false;
    /**
	 * @inheritDoc
	 */ domEventType = [
        'focus',
        'blur'
    ];
    /**
	 * @inheritDoc
	 */ constructor(view){
        super(view);
        this.useCapture = true;
        const document = this.document;
        document.on('focus', ()=>{
            this._isFocusChanging = true;
            // Unfortunately native `selectionchange` event is fired asynchronously.
            // We need to wait until `SelectionObserver` handle the event and then render. Otherwise rendering will
            // overwrite new DOM selection with selection from the view.
            // See https://github.com/ckeditor/ckeditor5-engine/issues/795 for more details.
            // Long timeout is needed to solve #676 and https://github.com/ckeditor/ckeditor5-engine/issues/1157 issues.
            //
            // Using `view.change()` instead of `view.forceRender()` to prevent double rendering
            // in a situation where `selectionchange` already caused selection change.
            this._renderTimeoutId = setTimeout(()=>{
                this.flush();
                view.change(()=>{});
            }, 50);
        });
        document.on('blur', (evt, data)=>{
            const selectedEditable = document.selection.editableElement;
            if (selectedEditable === null || selectedEditable === data.target) {
                document.isFocused = false;
                this._isFocusChanging = false;
                // Re-render the document to update view elements
                // (changing document.isFocused already marked view as changed since last rendering).
                view.change(()=>{});
            }
        });
    }
    /**
	 * Finishes setting the document focus state.
	 */ flush() {
        if (this._isFocusChanging) {
            this._isFocusChanging = false;
            this.document.isFocused = true;
        }
    }
    /**
	 * @inheritDoc
	 */ onDomEvent(domEvent) {
        this.fire(domEvent.type, domEvent);
    }
    /**
	 * @inheritDoc
	 */ destroy() {
        if (this._renderTimeoutId) {
            clearTimeout(this._renderTimeoutId);
        }
        super.destroy();
    }
}

/**
 * Selection observer class observes selection changes in the document. If a selection changes on the document this
 * observer checks if the DOM selection is different from the {@link module:engine/view/document~Document#selection view selection}.
 * The selection observer fires {@link module:engine/view/document~Document#event:selectionChange} event only if
 * a selection change was the only change in the document and the DOM selection is different from the view selection.
 *
 * This observer also manages the {@link module:engine/view/document~Document#isSelecting} property of the view document.
 *
 * Note that this observer is attached by the {@link module:engine/view/view~View} and is available by default.
 */ class SelectionObserver extends Observer {
    /**
	 * Instance of the mutation observer. Selection observer calls
	 * {@link module:engine/view/observer/mutationobserver~MutationObserver#flush} to ensure that the mutations will be handled
	 * before the {@link module:engine/view/document~Document#event:selectionChange} event is fired.
	 */ mutationObserver;
    /**
	 * Instance of the focus observer. Focus observer calls
	 * {@link module:engine/view/observer/focusobserver~FocusObserver#flush} to mark the latest focus change as complete.
	 */ focusObserver;
    /**
	 * Reference to the view {@link module:engine/view/documentselection~DocumentSelection} object used to compare
	 * new selection with it.
	 */ selection;
    /**
	 * Reference to the {@link module:engine/view/view~View#domConverter}.
	 */ domConverter;
    /**
	 * A set of documents which have added `selectionchange` listener to avoid adding a listener twice to the same
	 * document.
	 */ _documents;
    /**
	 * Fires debounced event `selectionChangeDone`. It uses `lodash#debounce` method to delay function call.
	 */ _fireSelectionChangeDoneDebounced;
    /**
	 * When called, starts clearing the {@link #_loopbackCounter} counter in time intervals. When the number of selection
	 * changes exceeds a certain limit within the interval of time, the observer will not fire `selectionChange` but warn about
	 * possible infinite selection loop.
	 */ _clearInfiniteLoopInterval;
    /**
	 * Unlocks the `isSelecting` state of the view document in case the selection observer did not record this fact
	 * correctly (for whatever reason). It is a safeguard (paranoid check), that returns document to the normal state
	 * after a certain period of time (debounced, postponed by each selectionchange event).
	 */ _documentIsSelectingInactivityTimeoutDebounced;
    /**
	 * Private property to check if the code does not enter infinite loop.
	 */ _loopbackCounter;
    constructor(view){
        super(view);
        this.mutationObserver = view.getObserver(MutationObserver);
        this.focusObserver = view.getObserver(FocusObserver);
        this.selection = this.document.selection;
        this.domConverter = view.domConverter;
        this._documents = new WeakSet();
        this._fireSelectionChangeDoneDebounced = debounce((data)=>{
            this.document.fire('selectionChangeDone', data);
        }, 200);
        this._clearInfiniteLoopInterval = setInterval(()=>this._clearInfiniteLoop(), 1000);
        this._documentIsSelectingInactivityTimeoutDebounced = debounce(()=>this.document.isSelecting = false, 5000);
        this._loopbackCounter = 0;
    }
    /**
	 * @inheritDoc
	 */ observe(domElement) {
        const domDocument = domElement.ownerDocument;
        const startDocumentIsSelecting = ()=>{
            this.document.isSelecting = true;
            // Let's activate the safety timeout each time the document enters the "is selecting" state.
            this._documentIsSelectingInactivityTimeoutDebounced();
        };
        const endDocumentIsSelecting = ()=>{
            if (!this.document.isSelecting) {
                return;
            }
            // Make sure that model selection is up-to-date at the end of selecting process.
            // Sometimes `selectionchange` events could arrive after the `mouseup` event and that selection could be already outdated.
            this._handleSelectionChange(null, domDocument);
            this.document.isSelecting = false;
            // The safety timeout can be canceled when the document leaves the "is selecting" state.
            this._documentIsSelectingInactivityTimeoutDebounced.cancel();
        };
        // The document has the "is selecting" state while the user keeps making (extending) the selection
        // (e.g. by holding the mouse button and moving the cursor). The state resets when they either released
        // the mouse button or interrupted the process by pressing or releasing any key.
        this.listenTo(domElement, 'selectstart', startDocumentIsSelecting, {
            priority: 'highest'
        });
        this.listenTo(domElement, 'keydown', endDocumentIsSelecting, {
            priority: 'highest',
            useCapture: true
        });
        this.listenTo(domElement, 'keyup', endDocumentIsSelecting, {
            priority: 'highest',
            useCapture: true
        });
        // Add document-wide listeners only once. This method could be called for multiple editing roots.
        if (this._documents.has(domDocument)) {
            return;
        }
        // This listener is using capture mode to make sure that selection is upcasted before any other
        // handler would like to check it and update (for example table multi cell selection).
        this.listenTo(domDocument, 'mouseup', endDocumentIsSelecting, {
            priority: 'highest',
            useCapture: true
        });
        this.listenTo(domDocument, 'selectionchange', (evt, domEvent)=>{
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	const domSelection = domDocument.defaultView!.getSelection();
            // @if CK_DEBUG_TYPING // 	console.group( '%c[SelectionObserver]%c selectionchange', 'color:green', ''
            // @if CK_DEBUG_TYPING // 	);
            // @if CK_DEBUG_TYPING // 	console.info( '%c[SelectionObserver]%c DOM Selection:', 'font-weight:bold;color:green', '',
            // @if CK_DEBUG_TYPING // 		{ node: domSelection!.anchorNode, offset: domSelection!.anchorOffset },
            // @if CK_DEBUG_TYPING // 		{ node: domSelection!.focusNode, offset: domSelection!.focusOffset }
            // @if CK_DEBUG_TYPING // 	);
            // @if CK_DEBUG_TYPING // }
            // The Renderer is disabled while composing on non-android browsers, so we can't update the view selection
            // because the DOM and view tree drifted apart. Position mapping could fail because of it.
            if (this.document.isComposing && !env.isAndroid) {
                // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
                // @if CK_DEBUG_TYPING // 	console.info( '%c[SelectionObserver]%c Selection change ignored (isComposing)',
                // @if CK_DEBUG_TYPING // 		'font-weight:bold;color:green', ''
                // @if CK_DEBUG_TYPING // 	);
                // @if CK_DEBUG_TYPING // 	console.groupEnd();
                // @if CK_DEBUG_TYPING // }
                return;
            }
            this._handleSelectionChange(domEvent, domDocument);
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	console.groupEnd();
            // @if CK_DEBUG_TYPING // }
            // Defer the safety timeout when the selection changes (e.g. the user keeps extending the selection
            // using their mouse).
            this._documentIsSelectingInactivityTimeoutDebounced();
        });
        this._documents.add(domDocument);
    }
    /**
	 * @inheritDoc
	 */ stopObserving(domElement) {
        this.stopListening(domElement);
    }
    /**
	 * @inheritDoc
	 */ destroy() {
        super.destroy();
        clearInterval(this._clearInfiniteLoopInterval);
        this._fireSelectionChangeDoneDebounced.cancel();
        this._documentIsSelectingInactivityTimeoutDebounced.cancel();
    }
    /* istanbul ignore next -- @preserve */ _reportInfiniteLoop() {
    // @if CK_DEBUG //		throw new Error(
    // @if CK_DEBUG //			'Selection change observer detected an infinite rendering loop.\n\n' +
    // @if CK_DEBUG //	 		'⚠️⚠️ Report this error on https://github.com/ckeditor/ckeditor5/issues/11658.'
    // @if CK_DEBUG //		);
    }
    /**
	 * Selection change listener. {@link module:engine/view/observer/mutationobserver~MutationObserver#flush Flush} mutations, check if
	 * a selection changes and fires {@link module:engine/view/document~Document#event:selectionChange} event on every change
	 * and {@link module:engine/view/document~Document#event:selectionChangeDone} when a selection stop changing.
	 *
	 * @param domEvent DOM event.
	 * @param domDocument DOM document.
	 */ _handleSelectionChange(domEvent, domDocument) {
        if (!this.isEnabled) {
            return;
        }
        const domSelection = domDocument.defaultView.getSelection();
        if (this.checkShouldIgnoreEventFromTarget(domSelection.anchorNode)) {
            return;
        }
        // Ensure the mutation event will be before selection event on all browsers.
        this.mutationObserver.flush();
        const newViewSelection = this.domConverter.domSelectionToView(domSelection);
        // Do not convert selection change if the new view selection has no ranges in it.
        //
        // It means that the DOM selection is in some way incorrect. Ranges that were in the DOM selection could not be
        // converted to the view. This happens when the DOM selection was moved outside of the editable element.
        if (newViewSelection.rangeCount == 0) {
            this.view.hasDomSelection = false;
            return;
        }
        this.view.hasDomSelection = true;
        // Mark the latest focus change as complete (we got new selection after the focus so the selection is in the focused element).
        this.focusObserver.flush();
        if (this.selection.isEqual(newViewSelection) && this.domConverter.isDomSelectionCorrect(domSelection)) {
            return;
        }
        // Ensure we are not in the infinite loop (#400).
        // This counter is reset each second. 60 selection changes in 1 second is enough high number
        // to be very difficult (impossible) to achieve using just keyboard keys (during normal editor use).
        if (++this._loopbackCounter > 60) {
            // Selection change observer detected an infinite rendering loop.
            // Most probably you try to put the selection in the position which is not allowed
            // by the browser and browser fixes it automatically what causes `selectionchange` event on
            // which a loopback through a model tries to re-render the wrong selection and again.
            this._reportInfiniteLoop();
            return;
        }
        if (this.selection.isSimilar(newViewSelection)) {
            // If selection was equal and we are at this point of algorithm, it means that it was incorrect.
            // Just re-render it, no need to fire any events, etc.
            this.view.forceRender();
        } else {
            const data = {
                oldSelection: this.selection,
                newSelection: newViewSelection,
                domSelection
            };
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	console.info( '%c[SelectionObserver]%c Fire selection change:',
            // @if CK_DEBUG_TYPING // 		'font-weight:bold;color:green', '',
            // @if CK_DEBUG_TYPING // 		newViewSelection.getFirstRange()
            // @if CK_DEBUG_TYPING // 	);
            // @if CK_DEBUG_TYPING // }
            // Prepare data for new selection and fire appropriate events.
            this.document.fire('selectionChange', data);
            // Call `#_fireSelectionChangeDoneDebounced` every time when `selectionChange` event is fired.
            // This function is debounced what means that `selectionChangeDone` event will be fired only when
            // defined int the function time will elapse since the last time the function was called.
            // So `selectionChangeDone` will be fired when selection will stop changing.
            this._fireSelectionChangeDoneDebounced(data);
        }
    }
    /**
	 * Clears `SelectionObserver` internal properties connected with preventing infinite loop.
	 */ _clearInfiniteLoop() {
        this._loopbackCounter = 0;
    }
}

/**
 * {@link module:engine/view/document~Document#event:compositionstart Compositionstart},
 * {@link module:engine/view/document~Document#event:compositionupdate compositionupdate} and
 * {@link module:engine/view/document~Document#event:compositionend compositionend} events observer.
 *
 * Note that this observer is attached by the {@link module:engine/view/view~View} and is available by default.
 */ class CompositionObserver extends DomEventObserver {
    /**
	 * @inheritDoc
	 */ domEventType = [
        'compositionstart',
        'compositionupdate',
        'compositionend'
    ];
    /**
	 * @inheritDoc
	 */ constructor(view){
        super(view);
        const document = this.document;
        document.on('compositionstart', ()=>{
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	console.log( '%c[CompositionObserver] ' +
            // @if CK_DEBUG_TYPING // 		'┌───────────────────────────── isComposing = true ─────────────────────────────┐',
            // @if CK_DEBUG_TYPING // 		'font-weight: bold; color: green'
            // @if CK_DEBUG_TYPING // 	);
            // @if CK_DEBUG_TYPING // }
            document.isComposing = true;
        }, {
            priority: 'low'
        });
        document.on('compositionend', ()=>{
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	console.log( '%c[CompositionObserver] ' +
            // @if CK_DEBUG_TYPING // 		'└───────────────────────────── isComposing = false ─────────────────────────────┘',
            // @if CK_DEBUG_TYPING // 		'font-weight: bold; color: green'
            // @if CK_DEBUG_TYPING // 	);
            // @if CK_DEBUG_TYPING // }
            document.isComposing = false;
        }, {
            priority: 'low'
        });
    }
    /**
	 * @inheritDoc
	 */ onDomEvent(domEvent) {
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.group( `%c[CompositionObserver]%c ${ domEvent.type }`, 'color: green', '' );
        // @if CK_DEBUG_TYPING // }
        this.fire(domEvent.type, domEvent, {
            data: domEvent.data
        });
    // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
    // @if CK_DEBUG_TYPING // 	console.groupEnd();
    // @if CK_DEBUG_TYPING // }
    }
}

/**
 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */ /**
 * @module engine/view/datatransfer
 */ /**
 * A facade over the native [`DataTransfer`](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer) object.
 */ class DataTransfer {
    /**
	 * The array of files created from the native `DataTransfer#files` or `DataTransfer#items`.
	 */ _files;
    /**
	 * The native DataTransfer object.
	 */ _native;
    /**
	 * @param nativeDataTransfer The native [`DataTransfer`](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer) object.
	 * @param options.cacheFiles Whether `files` list should be initialized in the constructor.
	 */ constructor(nativeDataTransfer, options = {}){
        // We should store references to the File instances in case someone would like to process this files
        // outside the event handler. Files are stored only for `drop` and `paste` events because they are not usable
        // in other events and are generating a huge delay on Firefox while dragging.
        // See https://github.com/ckeditor/ckeditor5/issues/13366.
        this._files = options.cacheFiles ? getFiles(nativeDataTransfer) : null;
        this._native = nativeDataTransfer;
    }
    /**
	 * The array of files created from the native `DataTransfer#files` or `DataTransfer#items`.
	 */ get files() {
        if (!this._files) {
            this._files = getFiles(this._native);
        }
        return this._files;
    }
    /**
	 * Returns an array of available native content types.
	 */ get types() {
        return this._native.types;
    }
    /**
	 * Gets the data from the data transfer by its MIME type.
	 *
	 * ```ts
	 * dataTransfer.getData( 'text/plain' );
	 * ```
	 *
	 * @param type The MIME type. E.g. `text/html` or `text/plain`.
	 */ getData(type) {
        return this._native.getData(type);
    }
    /**
	 * Sets the data in the data transfer.
	 *
	 * @param type The MIME type. E.g. `text/html` or `text/plain`.
	 */ setData(type, data) {
        this._native.setData(type, data);
    }
    /**
	 * The effect that is allowed for a drag operation.
	 */ set effectAllowed(value) {
        this._native.effectAllowed = value;
    }
    get effectAllowed() {
        return this._native.effectAllowed;
    }
    /**
	 * The actual drop effect.
	 */ set dropEffect(value) {
        this._native.dropEffect = value;
    }
    get dropEffect() {
        return this._native.dropEffect;
    }
    /**
	 * Set a preview image of the dragged content.
	 */ setDragImage(image, x, y) {
        this._native.setDragImage(image, x, y);
    }
    /**
	 * Whether the dragging operation was canceled.
	 */ get isCanceled() {
        return this._native.dropEffect == 'none' || !!this._native.mozUserCancelled;
    }
}
function getFiles(nativeDataTransfer) {
    // DataTransfer.files and items are array-like and might not have an iterable interface.
    const files = Array.from(nativeDataTransfer.files || []);
    const items = Array.from(nativeDataTransfer.items || []);
    if (files.length) {
        return files;
    }
    // Chrome has empty DataTransfer.files, but allows getting files through the items interface.
    return items.filter((item)=>item.kind === 'file').map((item)=>item.getAsFile());
}

/**
 * Observer for events connected with data input.
 *
 * **Note**: This observer is attached by {@link module:engine/view/view~View} and available by default in all
 * editor instances.
 */ class InputObserver extends DomEventObserver {
    /**
	 * @inheritDoc
	 */ domEventType = 'beforeinput';
    /**
	 * @inheritDoc
	 */ onDomEvent(domEvent) {
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.group( `%c[InputObserver]%c ${ domEvent.type }: ${ domEvent.inputType }`,
        // @if CK_DEBUG_TYPING // 		'color: green', 'color: default'
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        const domTargetRanges = domEvent.getTargetRanges();
        const view = this.view;
        const viewDocument = view.document;
        let dataTransfer = null;
        let data = null;
        let targetRanges = [];
        if (domEvent.dataTransfer) {
            dataTransfer = new DataTransfer(domEvent.dataTransfer);
        }
        if (domEvent.data !== null) {
            data = domEvent.data;
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.info( `%c[InputObserver]%c event data: %c${ JSON.stringify( data ) }`,
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', 'font-weight:bold', 'color: blue;'
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        } else if (dataTransfer) {
            data = dataTransfer.getData('text/plain');
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.info( `%c[InputObserver]%c event data transfer: %c${ JSON.stringify( data ) }`,
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', 'font-weight:bold', 'color: blue;'
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        }
        // If the editor selection is fake (an object is selected), the DOM range does not make sense because it is anchored
        // in the fake selection container.
        if (viewDocument.selection.isFake) {
            // Future-proof: in case of multi-range fake selections being possible.
            targetRanges = Array.from(viewDocument.selection.getRanges());
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.info( '%c[InputObserver]%c using fake selection:',
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', 'font-weight:bold', targetRanges,
        // @if CK_DEBUG_TYPING // 		viewDocument.selection.isFake ? 'fake view selection' : 'fake DOM parent'
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        } else if (domTargetRanges.length) {
            targetRanges = domTargetRanges.map((domRange)=>{
                // Sometimes browser provides range that starts before editable node.
                // We try to fall back to collapsed range at the valid end position.
                // See https://github.com/ckeditor/ckeditor5/issues/14411.
                // See https://github.com/ckeditor/ckeditor5/issues/14050.
                const viewStart = view.domConverter.domPositionToView(domRange.startContainer, domRange.startOffset);
                const viewEnd = view.domConverter.domPositionToView(domRange.endContainer, domRange.endOffset);
                if (viewStart) {
                    return view.createRange(viewStart, viewEnd);
                } else if (viewEnd) {
                    return view.createRange(viewEnd);
                }
            }).filter((range)=>!!range);
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.info( '%c[InputObserver]%c using target ranges:',
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', 'font-weight:bold', targetRanges
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        } else if (env.isAndroid) {
            const domSelection = domEvent.target.ownerDocument.defaultView.getSelection();
            targetRanges = Array.from(view.domConverter.domSelectionToView(domSelection).getRanges());
        // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
        // @if CK_DEBUG_TYPING // 	console.info( '%c[InputObserver]%c using selection ranges:',
        // @if CK_DEBUG_TYPING // 		'color: green;font-weight: bold', 'font-weight:bold', targetRanges
        // @if CK_DEBUG_TYPING // 	);
        // @if CK_DEBUG_TYPING // }
        }
        // Android sometimes fires insertCompositionText with a new-line character at the end of the data
        // instead of firing insertParagraph beforeInput event.
        // Fire the correct type of beforeInput event and ignore the replaced fragment of text because
        // it wants to replace "test" with "test\n".
        // https://github.com/ckeditor/ckeditor5/issues/12368.
        if (env.isAndroid && domEvent.inputType == 'insertCompositionText' && data && data.endsWith('\n')) {
            this.fire(domEvent.type, domEvent, {
                inputType: 'insertParagraph',
                targetRanges: [
                    view.createRange(targetRanges[0].end)
                ]
            });
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	console.groupEnd();
            // @if CK_DEBUG_TYPING // }
            return;
        }
        // Normalize the insertText data that includes new-line characters.
        // https://github.com/ckeditor/ckeditor5/issues/2045.
        if (domEvent.inputType == 'insertText' && data && data.includes('\n')) {
            // There might be a single new-line or double for new paragraph, but we translate
            // it to paragraphs as it is our default action for enter handling.
            const parts = data.split(/\n{1,2}/g);
            let partTargetRanges = targetRanges;
            for(let i = 0; i < parts.length; i++){
                const dataPart = parts[i];
                if (dataPart != '') {
                    this.fire(domEvent.type, domEvent, {
                        data: dataPart,
                        dataTransfer,
                        targetRanges: partTargetRanges,
                        inputType: domEvent.inputType,
                        isComposing: domEvent.isComposing
                    });
                    // Use the result view selection so following events will be added one after another.
                    partTargetRanges = [
                        viewDocument.selection.getFirstRange()
                    ];
                }
                if (i + 1 < parts.length) {
                    this.fire(domEvent.type, domEvent, {
                        inputType: 'insertParagraph',
                        targetRanges: partTargetRanges
                    });
                    // Use the result view selection so following events will be added one after another.
                    partTargetRanges = [
                        viewDocument.selection.getFirstRange()
                    ];
                }
            }
            // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
            // @if CK_DEBUG_TYPING // 	console.groupEnd();
            // @if CK_DEBUG_TYPING // }
            return;
        }
        // Fire the normalized beforeInput event.
        this.fire(domEvent.type, domEvent, {
            data,
            dataTransfer,
            targetRanges,
            inputType: domEvent.inputType,
            isComposing: domEvent.isComposing
        });
    // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
    // @if CK_DEBUG_TYPING // 	console.groupEnd();
    // @if CK_DEBUG_TYPING // }
    }
}

/**
 * Arrow keys observer introduces the {@link module:engine/view/document~Document#event:arrowKey `Document#arrowKey`} event.
 *
 * Note that this observer is attached by the {@link module:engine/view/view~View} and is available by default.
 */ class ArrowKeysObserver extends Observer {
    /**
	 * @inheritDoc
	 */ constructor(view){
        super(view);
        this.document.on('keydown', (event, data)=>{
            if (this.isEnabled && isArrowKeyCode(data.keyCode)) {
                const eventInfo = new BubblingEventInfo(this.document, 'arrowKey', this.document.selection.getFirstRange());
                this.document.fire(eventInfo, data);
                if (eventInfo.stop.called) {
                    event.stop();
                }
            }
        });
    }
    /**
	 * @inheritDoc
	 */ observe() {}
    /**
	 * @inheritDoc
	 */ stopObserving() {}
}

/**
 * Tab observer introduces the {@link module:engine/view/document~Document#event:tab `Document#tab`} event.
 *
 * Note that because {@link module:engine/view/observer/tabobserver~TabObserver} is attached by the
 * {@link module:engine/view/view~View}, this event is available by default.
 */ class TabObserver extends Observer {
    /**
	 * @inheritDoc
	 */ constructor(view){
        super(view);
        const doc = this.document;
        doc.on('keydown', (evt, data)=>{
            if (!this.isEnabled || data.keyCode != keyCodes.tab || data.ctrlKey) {
                return;
            }
            const event = new BubblingEventInfo(doc, 'tab', doc.selection.getFirstRange());
            doc.fire(event, data);
            if (event.stop.called) {
                evt.stop();
            }
        });
    }
    /**
	 * @inheritDoc
	 */ observe() {}
    /**
	 * @inheritDoc
	 */ stopObserving() {}
}

/**
 * Editor's view controller class. Its main responsibility is DOM - View management for editing purposes, to provide
 * abstraction over the DOM structure and events and hide all browsers quirks.
 *
 * View controller renders view document to DOM whenever view structure changes. To determine when view can be rendered,
 * all changes need to be done using the {@link module:engine/view/view~View#change} method, using
 * {@link module:engine/view/downcastwriter~DowncastWriter}:
 *
 * ```ts
 * view.change( writer => {
 * 	writer.insert( position, writer.createText( 'foo' ) );
 * } );
 * ```
 *
 * View controller also register {@link module:engine/view/observer/observer~Observer observers} which observes changes
 * on DOM and fire events on the {@link module:engine/view/document~Document Document}.
 * Note that the following observers are added by the class constructor and are always available:
 *
 * * {@link module:engine/view/observer/selectionobserver~SelectionObserver},
 * * {@link module:engine/view/observer/focusobserver~FocusObserver},
 * * {@link module:engine/view/observer/keyobserver~KeyObserver},
 * * {@link module:engine/view/observer/fakeselectionobserver~FakeSelectionObserver}.
 * * {@link module:engine/view/observer/compositionobserver~CompositionObserver}.
 * * {@link module:engine/view/observer/inputobserver~InputObserver}.
 * * {@link module:engine/view/observer/arrowkeysobserver~ArrowKeysObserver}.
 * * {@link module:engine/view/observer/tabobserver~TabObserver}.
 *
 * This class also {@link module:engine/view/view~View#attachDomRoot binds the DOM and the view elements}.
 *
 * If you do not need full a DOM - view management, and only want to transform a tree of view elements to a tree of DOM
 * elements you do not need this controller. You can use the {@link module:engine/view/domconverter~DomConverter DomConverter} instead.
 */ class View extends /* #__PURE__ */ ObservableMixin() {
    /**
	 * Instance of the {@link module:engine/view/document~Document} associated with this view controller.
	 */ document;
    /**
	 * Instance of the {@link module:engine/view/domconverter~DomConverter domConverter} used by
	 * {@link module:engine/view/view~View#_renderer renderer}
	 * and {@link module:engine/view/observer/observer~Observer observers}.
	 */ domConverter;
    /**
	 * Roots of the DOM tree. Map on the `HTMLElement`s with roots names as keys.
	 */ domRoots = new Map();
    /**
	 * Instance of the {@link module:engine/view/renderer~Renderer renderer}.
	 *
	 * @internal
	 */ _renderer;
    /**
	 * A DOM root attributes cache. It saves the initial values of DOM root attributes before the DOM element
	 * is {@link module:engine/view/view~View#attachDomRoot attached} to the view so later on, when
	 * the view is destroyed ({@link module:engine/view/view~View#detachDomRoot}), they can be easily restored.
	 * This way, the DOM element can go back to the (clean) state as if the editing view never used it.
	 */ _initialDomRootAttributes = new WeakMap();
    /**
	 * Map of registered {@link module:engine/view/observer/observer~Observer observers}.
	 */ _observers = new Map();
    /**
	 * DowncastWriter instance used in {@link #change change method} callbacks.
	 */ _writer;
    /**
	 * Is set to `true` when {@link #change view changes} are currently in progress.
	 */ _ongoingChange = false;
    /**
	 * Used to prevent calling {@link #forceRender} and {@link #change} during rendering view to the DOM.
	 */ _postFixersInProgress = false;
    /**
	 * Internal flag to temporary disable rendering. See the usage in the {@link #_disableRendering}.
	 */ _renderingDisabled = false;
    /**
	 * Internal flag that disables rendering when there are no changes since the last rendering.
	 * It stores information about changed selection and changed elements from attached document roots.
	 */ _hasChangedSinceTheLastRendering = false;
    /**
	 * @param stylesProcessor The styles processor instance.
	 */ constructor(stylesProcessor){
        super();
        this.document = new Document$1(stylesProcessor);
        this.domConverter = new DomConverter(this.document);
        this.set('isRenderingInProgress', false);
        this.set('hasDomSelection', false);
        this._renderer = new Renderer(this.domConverter, this.document.selection);
        this._renderer.bind('isFocused', 'isSelecting', 'isComposing').to(this.document, 'isFocused', 'isSelecting', 'isComposing');
        this._writer = new DowncastWriter(this.document);
        // Add default observers.
        // Make sure that this list matches AlwaysRegisteredObservers type.
        this.addObserver(MutationObserver);
        this.addObserver(FocusObserver);
        this.addObserver(SelectionObserver);
        this.addObserver(KeyObserver);
        this.addObserver(FakeSelectionObserver);
        this.addObserver(CompositionObserver);
        this.addObserver(ArrowKeysObserver);
        this.addObserver(InputObserver);
        this.addObserver(TabObserver);
        // Inject quirks handlers.
        injectQuirksHandling(this);
        injectUiElementHandling(this);
        // Use 'normal' priority so that rendering is performed as first when using that priority.
        this.on('render', ()=>{
            this._render();
            // Informs that layout has changed after render.
            this.document.fire('layoutChanged');
            // Reset the `_hasChangedSinceTheLastRendering` flag after rendering.
            this._hasChangedSinceTheLastRendering = false;
        });
        // Listen to the document selection changes directly.
        this.listenTo(this.document.selection, 'change', ()=>{
            this._hasChangedSinceTheLastRendering = true;
        });
        // Trigger re-render if only the focus changed.
        this.listenTo(this.document, 'change:isFocused', ()=>{
            this._hasChangedSinceTheLastRendering = true;
        });
        // Remove ranges from DOM selection if editor is blurred.
        // See https://github.com/ckeditor/ckeditor5/issues/5753.
        if (env.isiOS) {
            this.listenTo(this.document, 'blur', (evt, data)=>{
                const relatedViewElement = this.domConverter.mapDomToView(data.domEvent.relatedTarget);
                // Do not modify DOM selection if focus is moved to other editable of the same editor.
                if (!relatedViewElement) {
                    this.domConverter._clearDomSelection();
                }
            });
        }
    }
    /**
	 * Attaches a DOM root element to the view element and enable all observers on that element.
	 * Also {@link module:engine/view/renderer~Renderer#markToSync mark element} to be synchronized
	 * with the view what means that all child nodes will be removed and replaced with content of the view root.
	 *
	 * This method also will change view element name as the same as tag name of given dom root.
	 * Name is always transformed to lower case.
	 *
	 * **Note:** Use {@link #detachDomRoot `detachDomRoot()`} to revert this action.
	 *
	 * @param domRoot DOM root element.
	 * @param name Name of the root.
	 */ attachDomRoot(domRoot, name = 'main') {
        const viewRoot = this.document.getRoot(name);
        // Set view root name the same as DOM root tag name.
        viewRoot._name = domRoot.tagName.toLowerCase();
        const initialDomRootAttributes = {};
        // 1. Copy and cache the attributes to remember the state of the element before attaching.
        //    The cached attributes will be restored in detachDomRoot() so the element goes to the
        //    clean state as if the editing view never used it.
        // 2. Apply the attributes using the view writer, so they all go under the control of the engine.
        //    The editing view takes over the attribute management completely because various
        //    features (e.g. addPlaceholder()) require dynamic changes of those attributes and they
        //    cannot be managed by the engine and the UI library at the same time.
        for (const { name, value } of Array.from(domRoot.attributes)){
            initialDomRootAttributes[name] = value;
            // Do not use writer.setAttribute() for the class attribute. The EditableUIView class
            // and its descendants could have already set some using the writer.addClass() on the view
            // document root. They haven't been rendered yet so they are not present in the DOM root.
            // Using writer.setAttribute( 'class', ... ) would override them completely.
            if (name === 'class') {
                this._writer.addClass(value.split(' '), viewRoot);
            } else {
                this._writer.setAttribute(name, value, viewRoot);
            }
        }
        this._initialDomRootAttributes.set(domRoot, initialDomRootAttributes);
        const updateContenteditableAttribute = ()=>{
            this._writer.setAttribute('contenteditable', (!viewRoot.isReadOnly).toString(), viewRoot);
            if (viewRoot.isReadOnly) {
                this._writer.addClass('ck-read-only', viewRoot);
            } else {
                this._writer.removeClass('ck-read-only', viewRoot);
            }
        };
        // Set initial value.
        updateContenteditableAttribute();
        this.domRoots.set(name, domRoot);
        this.domConverter.bindElements(domRoot, viewRoot);
        this._renderer.markToSync('children', viewRoot);
        this._renderer.markToSync('attributes', viewRoot);
        this._renderer.domDocuments.add(domRoot.ownerDocument);
        viewRoot.on('change:children', (evt, node)=>this._renderer.markToSync('children', node));
        viewRoot.on('change:attributes', (evt, node)=>this._renderer.markToSync('attributes', node));
        viewRoot.on('change:text', (evt, node)=>this._renderer.markToSync('text', node));
        viewRoot.on('change:isReadOnly', ()=>this.change(updateContenteditableAttribute));
        viewRoot.on('change', ()=>{
            this._hasChangedSinceTheLastRendering = true;
        });
        for (const observer of this._observers.values()){
            observer.observe(domRoot, name);
        }
    }
    /**
	 * Detaches a DOM root element from the view element and restores its attributes to the state before
	 * {@link #attachDomRoot `attachDomRoot()`}.
	 *
	 * @param name Name of the root to detach.
	 */ detachDomRoot(name) {
        const domRoot = this.domRoots.get(name);
        // Remove all root attributes so the DOM element is "bare".
        Array.from(domRoot.attributes).forEach(({ name })=>domRoot.removeAttribute(name));
        const initialDomRootAttributes = this._initialDomRootAttributes.get(domRoot);
        // Revert all view root attributes back to the state before attachDomRoot was called.
        for(const attribute in initialDomRootAttributes){
            domRoot.setAttribute(attribute, initialDomRootAttributes[attribute]);
        }
        this.domRoots.delete(name);
        this.domConverter.unbindDomElement(domRoot);
        for (const observer of this._observers.values()){
            observer.stopObserving(domRoot);
        }
    }
    /**
	 * Gets DOM root element.
	 *
	 * @param name  Name of the root.
	 * @returns DOM root element instance.
	 */ getDomRoot(name = 'main') {
        return this.domRoots.get(name);
    }
    /**
	 * Creates observer of the given type if not yet created, {@link module:engine/view/observer/observer~Observer#enable enables} it
	 * and {@link module:engine/view/observer/observer~Observer#observe attaches} to all existing and future
	 * {@link #domRoots DOM roots}.
	 *
	 * Note: Observers are recognized by their constructor (classes). A single observer will be instantiated and used only
	 * when registered for the first time. This means that features and other components can register a single observer
	 * multiple times without caring whether it has been already added or not.
	 *
	 * @param ObserverConstructor The constructor of an observer to add.
	 * Should create an instance inheriting from {@link module:engine/view/observer/observer~Observer}.
	 * @returns Added observer instance.
	 */ addObserver(ObserverConstructor) {
        let observer = this._observers.get(ObserverConstructor);
        if (observer) {
            return observer;
        }
        observer = new ObserverConstructor(this);
        this._observers.set(ObserverConstructor, observer);
        for (const [name, domElement] of this.domRoots){
            observer.observe(domElement, name);
        }
        observer.enable();
        return observer;
    }
    /**
	 * Returns observer of the given type or `undefined` if such observer has not been added yet.
	 *
	 * @param ObserverConstructor The constructor of an observer to get.
	 * @returns Observer instance or undefined.
	 */ getObserver(ObserverConstructor) {
        return this._observers.get(ObserverConstructor);
    }
    /**
	 * Disables all added observers.
	 */ disableObservers() {
        for (const observer of this._observers.values()){
            observer.disable();
        }
    }
    /**
	 * Enables all added observers.
	 */ enableObservers() {
        for (const observer of this._observers.values()){
            observer.enable();
        }
    }
    /**
	 * Scrolls the page viewport and {@link #domRoots} with their ancestors to reveal the
	 * caret, **if not already visible to the user**.
	 *
	 * **Note**: Calling this method fires the {@link module:engine/view/view~ViewScrollToTheSelectionEvent} event that
	 * allows custom behaviors.
	 *
	 * @param options Additional configuration of the scrolling behavior.
	 * @param options.viewportOffset A distance between the DOM selection and the viewport boundary to be maintained
	 * while scrolling to the selection (default is 20px). Setting this value to `0` will reveal the selection precisely at
	 * the viewport boundary.
	 * @param options.ancestorOffset A distance between the DOM selection and scrollable DOM root ancestor(s) to be maintained
	 * while scrolling to the selection (default is 20px). Setting this value to `0` will reveal the selection precisely at
	 * the scrollable ancestor(s) boundary.
	 * @param options.alignToTop When set `true`, the DOM selection will be aligned to the top of the viewport if not already visible
	 * (see `forceScroll` to learn more).
	 * @param options.forceScroll When set `true`, the DOM selection will be aligned to the top of the viewport and scrollable ancestors
	 * whether it is already visible or not. This option will only work when `alignToTop` is `true`.
	 */ scrollToTheSelection({ alignToTop, forceScroll, viewportOffset = 20, ancestorOffset = 20 } = {}) {
        const range = this.document.selection.getFirstRange();
        if (!range) {
            return;
        }
        // Clone to make sure properties like `viewportOffset` are not mutated in the event listeners.
        const originalArgs = cloneDeep({
            alignToTop,
            forceScroll,
            viewportOffset,
            ancestorOffset
        });
        if (typeof viewportOffset === 'number') {
            viewportOffset = {
                top: viewportOffset,
                bottom: viewportOffset,
                left: viewportOffset,
                right: viewportOffset
            };
        }
        const options = {
            target: this.domConverter.viewRangeToDom(range),
            viewportOffset,
            ancestorOffset,
            alignToTop,
            forceScroll
        };
        this.fire('scrollToTheSelection', options, originalArgs);
        scrollViewportToShowTarget(options);
    }
    /**
	 * It will focus DOM element representing {@link module:engine/view/editableelement~EditableElement EditableElement}
	 * that is currently having selection inside.
	 */ focus() {
        if (!this.document.isFocused) {
            const editable = this.document.selection.editableElement;
            if (editable) {
                this.domConverter.focus(editable);
                this.forceRender();
            }
        }
    }
    /**
	 * The `change()` method is the primary way of changing the view. You should use it to modify any node in the view tree.
	 * It makes sure that after all changes are made the view is rendered to the DOM (assuming that the view will be changed
	 * inside the callback). It prevents situations when the DOM is updated when the view state is not yet correct. It allows
	 * to nest calls one inside another and still performs a single rendering after all those changes are made.
	 * It also returns the return value of its callback.
	 *
	 * ```ts
	 * const text = view.change( writer => {
	 * 	const newText = writer.createText( 'foo' );
	 * 	writer.insert( position1, newText );
	 *
	 * 	view.change( writer => {
	 * 		writer.insert( position2, writer.createText( 'bar' ) );
	 * 	} );
	 *
	 * 	writer.remove( range );
	 *
	 * 	return newText;
	 * } );
	 * ```
	 *
	 * When the outermost change block is done and rendering to the DOM is over the
	 * {@link module:engine/view/view~View#event:render `View#render`} event is fired.
	 *
	 * This method throws a `applying-view-changes-on-rendering` error when
	 * the change block is used after rendering to the DOM has started.
	 *
	 * @param callback Callback function which may modify the view.
	 * @returns Value returned by the callback.
	 */ change(callback) {
        if (this.isRenderingInProgress || this._postFixersInProgress) {
            /**
			 * Thrown when there is an attempt to make changes to the view tree when it is in incorrect state. This may
			 * cause some unexpected behaviour and inconsistency between the DOM and the view.
			 * This may be caused by:
			 *
			 * * calling {@link module:engine/view/view~View#change} or {@link module:engine/view/view~View#forceRender} during rendering
			 * process,
			 * * calling {@link module:engine/view/view~View#change} or {@link module:engine/view/view~View#forceRender} inside of
			 *   {@link module:engine/view/document~Document#registerPostFixer post-fixer function}.
			 *
			 * @error cannot-change-view-tree
			 */ throw new CKEditorError('cannot-change-view-tree', this);
        }
        try {
            // Recursive call to view.change() method - execute listener immediately.
            if (this._ongoingChange) {
                return callback(this._writer);
            }
            // This lock will assure that all recursive calls to view.change() will end up in same block - one "render"
            // event for all nested calls.
            this._ongoingChange = true;
            const callbackResult = callback(this._writer);
            this._ongoingChange = false;
            // This lock is used by editing controller to render changes from outer most model.change() once. As plugins might call
            // view.change() inside model.change() block - this will ensures that postfixers and rendering are called once after all
            // changes. Also, we don't need to render anything if there're no changes since last rendering.
            if (!this._renderingDisabled && this._hasChangedSinceTheLastRendering) {
                this._postFixersInProgress = true;
                this.document._callPostFixers(this._writer);
                this._postFixersInProgress = false;
                this.fire('render');
            }
            return callbackResult;
        } catch (err) {
            // @if CK_DEBUG // throw err;
            /* istanbul ignore next -- @preserve */ CKEditorError.rethrowUnexpectedError(err, this);
        }
    }
    /**
	 * Forces rendering {@link module:engine/view/document~Document view document} to DOM. If any view changes are
	 * currently in progress, rendering will start after all {@link #change change blocks} are processed.
	 *
	 * Note that this method is dedicated for special cases. All view changes should be wrapped in the {@link #change}
	 * block and the view will automatically check whether it needs to render DOM or not.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `applying-view-changes-on-rendering` when
	 * trying to re-render when rendering to DOM has already started.
	 */ forceRender() {
        this._hasChangedSinceTheLastRendering = true;
        this.getObserver(FocusObserver).flush();
        this.change(()=>{});
    }
    /**
	 * Destroys this instance. Makes sure that all observers are destroyed and listeners removed.
	 */ destroy() {
        for (const observer of this._observers.values()){
            observer.destroy();
        }
        this.document.destroy();
        this.stopListening();
    }
    /**
	 * Creates position at the given location. The location can be specified as:
	 *
	 * * a {@link module:engine/view/position~Position position},
	 * * parent element and offset (offset defaults to `0`),
	 * * parent element and `'end'` (sets position at the end of that element),
	 * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
	 *
	 * This method is a shortcut to other constructors such as:
	 *
	 * * {@link #createPositionBefore},
	 * * {@link #createPositionAfter},
	 *
	 * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/view/item~Item view item}.
	 */ createPositionAt(itemOrPosition, offset) {
        return Position$1._createAt(itemOrPosition, offset);
    }
    /**
	 * Creates a new position after given view item.
	 *
	 * @param item View item after which the position should be located.
	 */ createPositionAfter(item) {
        return Position$1._createAfter(item);
    }
    /**
	 * Creates a new position before given view item.
	 *
	 * @param item View item before which the position should be located.
	 */ createPositionBefore(item) {
        return Position$1._createBefore(item);
    }
    /**
	 * Creates a range spanning from `start` position to `end` position.
	 *
	 * **Note:** This factory method creates it's own {@link module:engine/view/position~Position} instances basing on passed values.
	 *
	 * @param start Start position.
	 * @param end End position. If not set, range will be collapsed at `start` position.
	 */ createRange(start, end) {
        return new Range$1(start, end);
    }
    /**
	 * Creates a range that starts before given {@link module:engine/view/item~Item view item} and ends after it.
	 */ createRangeOn(item) {
        return Range$1._createOn(item);
    }
    /**
	 * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
	 * that element and ends after the last child of that element.
	 *
	 * @param element Element which is a parent for the range.
	 */ createRangeIn(element) {
        return Range$1._createIn(element);
    }
    createSelection(...args) {
        return new Selection$1(...args);
    }
    /**
	 * Disables or enables rendering. If the flag is set to `true` then the rendering will be disabled.
	 * If the flag is set to `false` and if there was some change in the meantime, then the rendering action will be performed.
	 *
	 * @internal
	 * @param flag A flag indicates whether the rendering should be disabled.
	 */ _disableRendering(flag) {
        this._renderingDisabled = flag;
        if (flag == false) {
            // Render when you stop blocking rendering.
            this.change(()=>{});
        }
    }
    /**
	 * Renders all changes. In order to avoid triggering the observers (e.g. selection) all observers are disabled
	 * before rendering and re-enabled after that.
	 */ _render() {
        this.isRenderingInProgress = true;
        this.disableObservers();
        this._renderer.render();
        this.enableObservers();
        this.isRenderingInProgress = false;
    }
}

/**
 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */ /**
 * @module engine/model/typecheckable
 */ class TypeCheckable {
    /* istanbul ignore next -- @preserve */ is() {
        // There are a lot of overloads above.
        // Overriding method in derived classes remove them and only `is( type: string ): boolean` is visible which we don't want.
        // One option would be to copy them all to all classes, but that's ugly.
        // It's best when TypeScript compiler doesn't see those overloads, except the one in the top base class.
        // To overload a method, but not let the compiler see it, do after class definition:
        // `MyClass.prototype.is = function( type: string ) {...}`
        throw new Error('is() method is abstract');
    }
}

/**
 * Model node. Most basic structure of model tree.
 *
 * This is an abstract class that is a base for other classes representing different nodes in model.
 *
 * **Note:** If a node is detached from the model tree, you can manipulate it using it's API.
 * However, it is **very important** that nodes already attached to model tree should be only changed through
 * {@link module:engine/model/writer~Writer Writer API}.
 *
 * Changes done by `Node` methods, like {@link module:engine/model/element~Element#_insertChild _insertChild} or
 * {@link module:engine/model/node~Node#_setAttribute _setAttribute}
 * do not generate {@link module:engine/model/operation/operation~Operation operations}
 * which are essential for correct editor work if you modify nodes in {@link module:engine/model/document~Document document} root.
 *
 * The flow of working on `Node` (and classes that inherits from it) is as such:
 * 1. You can create a `Node` instance, modify it using it's API.
 * 2. Add `Node` to the model using `Batch` API.
 * 3. Change `Node` that was already added to the model using `Batch` API.
 *
 * Similarly, you cannot use `Batch` API on a node that has not been added to the model tree, with the exception
 * of {@link module:engine/model/writer~Writer#insert inserting} that node to the model tree.
 *
 * Be aware that using {@link module:engine/model/writer~Writer#remove remove from Batch API} does not allow to use `Node` API because
 * the information about `Node` is still kept in model document.
 *
 * In case of {@link module:engine/model/element~Element element node}, adding and removing children also counts as changing a node and
 * follows same rules.
 */ let Node$1 = class Node extends TypeCheckable {
    /**
	 * Parent of this node. It could be {@link module:engine/model/element~Element}
	 * or {@link module:engine/model/documentfragment~DocumentFragment}.
	 * Equals to `null` if the node has no parent.
	 */ parent = null;
    /**
	 * Attributes set on this node.
	 */ _attrs;
    /**
	 * Creates a model node.
	 *
	 * This is an abstract class, so this constructor should not be used directly.
	 *
	 * @param attrs Node's attributes. See {@link module:utils/tomap~toMap} for a list of accepted values.
	 */ constructor(attrs){
        super();
        this._attrs = toMap(attrs);
    }
    /**
	 * {@link module:engine/model/document~Document Document} that owns this root element.
	 */ get document() {
        return null;
    }
    /**
	 * Index of this node in its parent or `null` if the node has no parent.
	 *
	 * Accessing this property throws an error if this node's parent element does not contain it.
	 * This means that model tree got broken.
	 */ get index() {
        let pos;
        if (!this.parent) {
            return null;
        }
        if ((pos = this.parent.getChildIndex(this)) === null) {
            throw new CKEditorError('model-node-not-found-in-parent', this);
        }
        return pos;
    }
    /**
	 * Offset at which this node starts in its parent. It is equal to the sum of {@link #offsetSize offsetSize}
	 * of all its previous siblings. Equals to `null` if node has no parent.
	 *
	 * Accessing this property throws an error if this node's parent element does not contain it.
	 * This means that model tree got broken.
	 */ get startOffset() {
        let pos;
        if (!this.parent) {
            return null;
        }
        if ((pos = this.parent.getChildStartOffset(this)) === null) {
            throw new CKEditorError('model-node-not-found-in-parent', this);
        }
        return pos;
    }
    /**
	 * Offset size of this node. Represents how much "offset space" is occupied by the node in it's parent.
	 * It is important for {@link module:engine/model/position~Position position}. When node has `offsetSize` greater than `1`, position
	 * can be placed between that node start and end. `offsetSize` greater than `1` is for nodes that represents more
	 * than one entity, i.e. {@link module:engine/model/text~Text text node}.
	 */ get offsetSize() {
        return 1;
    }
    /**
	 * Offset at which this node ends in it's parent. It is equal to the sum of this node's
	 * {@link module:engine/model/node~Node#startOffset start offset} and {@link #offsetSize offset size}.
	 * Equals to `null` if the node has no parent.
	 */ get endOffset() {
        if (!this.parent) {
            return null;
        }
        return this.startOffset + this.offsetSize;
    }
    /**
	 * Node's next sibling or `null` if the node is a last child of it's parent or if the node has no parent.
	 */ get nextSibling() {
        const index = this.index;
        return index !== null && this.parent.getChild(index + 1) || null;
    }
    /**
	 * Node's previous sibling or `null` if the node is a first child of it's parent or if the node has no parent.
	 */ get previousSibling() {
        const index = this.index;
        return index !== null && this.parent.getChild(index - 1) || null;
    }
    /**
	 * The top-most ancestor of the node. If node has no parent it is the root itself. If the node is a part
	 * of {@link module:engine/model/documentfragment~DocumentFragment}, it's `root` is equal to that `DocumentFragment`.
	 */ get root() {
        // eslint-disable-next-line @typescript-eslint/no-this-alias, consistent-this
        let root = this;
        while(root.parent){
            root = root.parent;
        }
        return root;
    }
    /**
	 * Returns `true` if the node is inside a document root that is attached to the document.
	 */ isAttached() {
        // If the node has no parent it means that it is a root.
        // But this is not a `RootElement`, so it means that it is not attached.
        //
        // If this is not the root, check if this element's root is attached.
        return this.parent === null ? false : this.root.isAttached();
    }
    /**
	 * Gets path to the node. The path is an array containing starting offsets of consecutive ancestors of this node,
	 * beginning from {@link module:engine/model/node~Node#root root}, down to this node's starting offset. The path can be used to
	 * create {@link module:engine/model/position~Position Position} instance.
	 *
	 * ```ts
	 * const abc = new Text( 'abc' );
	 * const foo = new Text( 'foo' );
	 * const h1 = new Element( 'h1', null, new Text( 'header' ) );
	 * const p = new Element( 'p', null, [ abc, foo ] );
	 * const div = new Element( 'div', null, [ h1, p ] );
	 * foo.getPath(); // Returns [ 1, 3 ]. `foo` is in `p` which is in `div`. `p` starts at offset 1, while `foo` at 3.
	 * h1.getPath(); // Returns [ 0 ].
	 * div.getPath(); // Returns [].
	 * ```
	 */ getPath() {
        const path = [];
        // eslint-disable-next-line @typescript-eslint/no-this-alias, consistent-this
        let node = this;
        while(node.parent){
            path.unshift(node.startOffset);
            node = node.parent;
        }
        return path;
    }
    /**
	 * Returns ancestors array of this node.
	 *
	 * @param options Options object.
	 * @param options.includeSelf When set to `true` this node will be also included in parent's array.
	 * @param options.parentFirst When set to `true`, array will be sorted from node's parent to root element,
	 * otherwise root element will be the first item in the array.
	 * @returns Array with ancestors.
	 */ getAncestors(options = {}) {
        const ancestors = [];
        let parent = options.includeSelf ? this : this.parent;
        while(parent){
            ancestors[options.parentFirst ? 'push' : 'unshift'](parent);
            parent = parent.parent;
        }
        return ancestors;
    }
    /**
	 * Returns a {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
	 * which is a common ancestor of both nodes.
	 *
	 * @param node The second node.
	 * @param options Options object.
	 * @param options.includeSelf When set to `true` both nodes will be considered "ancestors" too.
	 * Which means that if e.g. node A is inside B, then their common ancestor will be B.
	 */ getCommonAncestor(node, options = {}) {
        const ancestorsA = this.getAncestors(options);
        const ancestorsB = node.getAncestors(options);
        let i = 0;
        while(ancestorsA[i] == ancestorsB[i] && ancestorsA[i]){
            i++;
        }
        return i === 0 ? null : ancestorsA[i - 1];
    }
    /**
	 * Returns whether this node is before given node. `false` is returned if nodes are in different trees (for example,
	 * in different {@link module:engine/model/documentfragment~DocumentFragment}s).
	 *
	 * @param node Node to compare with.
	 */ isBefore(node) {
        // Given node is not before this node if they are same.
        if (this == node) {
            return false;
        }
        // Return `false` if it is impossible to compare nodes.
        if (this.root !== node.root) {
            return false;
        }
        const thisPath = this.getPath();
        const nodePath = node.getPath();
        const result = compareArrays(thisPath, nodePath);
        switch(result){
            case 'prefix':
                return true;
            case 'extension':
                return false;
            default:
                return thisPath[result] < nodePath[result];
        }
    }
    /**
	 * Returns whether this node is after given node. `false` is returned if nodes are in different trees (for example,
	 * in different {@link module:engine/model/documentfragment~DocumentFragment}s).
	 *
	 * @param node Node to compare with.
	 */ isAfter(node) {
        // Given node is not before this node if they are same.
        if (this == node) {
            return false;
        }
        // Return `false` if it is impossible to compare nodes.
        if (this.root !== node.root) {
            return false;
        }
        // In other cases, just check if the `node` is before, and return the opposite.
        return !this.isBefore(node);
    }
    /**
	 * Checks if the node has an attribute with given key.
	 *
	 * @param key Key of attribute to check.
	 * @returns `true` if attribute with given key is set on node, `false` otherwise.
	 */ hasAttribute(key) {
        return this._attrs.has(key);
    }
    /**
	 * Gets an attribute value for given key or `undefined` if that attribute is not set on node.
	 *
	 * @param key Key of attribute to look for.
	 * @returns Attribute value or `undefined`.
	 */ getAttribute(key) {
        return this._attrs.get(key);
    }
    /**
	 * Returns iterator that iterates over this node's attributes.
	 *
	 * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
	 * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
	 */ getAttributes() {
        return this._attrs.entries();
    }
    /**
	 * Returns iterator that iterates over this node's attribute keys.
	 */ getAttributeKeys() {
        return this._attrs.keys();
    }
    /**
	 * Converts `Node` to plain object and returns it.
	 *
	 * @returns `Node` converted to plain object.
	 */ toJSON() {
        const json = {};
        // Serializes attributes to the object.
        // attributes = { a: 'foo', b: 1, c: true }.
        if (this._attrs.size) {
            json.attributes = Array.from(this._attrs).reduce((result, attr)=>{
                result[attr[0]] = attr[1];
                return result;
            }, {});
        }
        return json;
    }
    /**
	 * Creates a copy of this node, that is a node with exactly same attributes, and returns it.
	 *
	 * @internal
	 * @returns Node with same attributes as this node.
	 */ _clone(_deep) {
        return new this.constructor(this._attrs);
    }
    /**
	 * Removes this node from it's parent.
	 *
	 * @internal
	 * @see module:engine/model/writer~Writer#remove
	 */ _remove() {
        this.parent._removeChildren(this.index);
    }
    /**
	 * Sets attribute on the node. If attribute with the same key already is set, it's value is overwritten.
	 *
	 * @see module:engine/model/writer~Writer#setAttribute
	 * @internal
	 * @param key Key of attribute to set.
	 * @param value Attribute value.
	 */ _setAttribute(key, value) {
        this._attrs.set(key, value);
    }
    /**
	 * Removes all attributes from the node and sets given attributes.
	 *
	 * @see module:engine/model/writer~Writer#setAttributes
	 * @internal
	 * @param attrs Attributes to set. See {@link module:utils/tomap~toMap} for a list of accepted values.
	 */ _setAttributesTo(attrs) {
        this._attrs = toMap(attrs);
    }
    /**
	 * Removes an attribute with given key from the node.
	 *
	 * @see module:engine/model/writer~Writer#removeAttribute
	 * @internal
	 * @param key Key of attribute to remove.
	 * @returns `true` if the attribute was set on the element, `false` otherwise.
	 */ _removeAttribute(key) {
        return this._attrs.delete(key);
    }
    /**
	 * Removes all attributes from the node.
	 *
	 * @see module:engine/model/writer~Writer#clearAttributes
	 * @internal
	 */ _clearAttributes() {
        this._attrs.clear();
    }
};
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Node$1.prototype.is = function(type) {
    return type === 'node' || type === 'model:node';
};

/**
 * Provides an interface to operate on a list of {@link module:engine/model/node~Node nodes}. `NodeList` is used internally
 * in classes like {@link module:engine/model/element~Element Element}
 * or {@link module:engine/model/documentfragment~DocumentFragment DocumentFragment}.
 */ class NodeList {
    /**
	 * Nodes contained in this node list.
	 */ _nodes = [];
    /**
	 * Creates an empty node list.
	 *
	 * @internal
	 * @param nodes Nodes contained in this node list.
	 */ constructor(nodes){
        if (nodes) {
            this._insertNodes(0, nodes);
        }
    }
    /**
	 * Iterable interface.
	 *
	 * Iterates over all nodes contained inside this node list.
	 */ [Symbol.iterator]() {
        return this._nodes[Symbol.iterator]();
    }
    /**
	 * Number of nodes contained inside this node list.
	 */ get length() {
        return this._nodes.length;
    }
    /**
	 * Sum of {@link module:engine/model/node~Node#offsetSize offset sizes} of all nodes contained inside this node list.
	 */ get maxOffset() {
        return this._nodes.reduce((sum, node)=>sum + node.offsetSize, 0);
    }
    /**
	 * Gets the node at the given index. Returns `null` if incorrect index was passed.
	 */ getNode(index) {
        return this._nodes[index] || null;
    }
    /**
	 * Returns an index of the given node. Returns `null` if given node is not inside this node list.
	 */ getNodeIndex(node) {
        const index = this._nodes.indexOf(node);
        return index == -1 ? null : index;
    }
    /**
	 * Returns the starting offset of given node. Starting offset is equal to the sum of
	 * {@link module:engine/model/node~Node#offsetSize offset sizes} of all nodes that are before this node in this node list.
	 */ getNodeStartOffset(node) {
        const index = this.getNodeIndex(node);
        return index === null ? null : this._nodes.slice(0, index).reduce((sum, node)=>sum + node.offsetSize, 0);
    }
    /**
	 * Converts index to offset in node list.
	 *
	 * Returns starting offset of a node that is at given index. Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError}
	 * `model-nodelist-index-out-of-bounds` if given index is less than `0` or more than {@link #length}.
	 */ indexToOffset(index) {
        if (index == this._nodes.length) {
            return this.maxOffset;
        }
        const node = this._nodes[index];
        if (!node) {
            /**
			 * Given index cannot be found in the node list.
			 *
			 * @error model-nodelist-index-out-of-bounds
			 */ throw new CKEditorError('model-nodelist-index-out-of-bounds', this);
        }
        return this.getNodeStartOffset(node);
    }
    /**
	 * Converts offset in node list to index.
	 *
	 * Returns index of a node that occupies given offset. Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError}
	 * `model-nodelist-offset-out-of-bounds` if given offset is less than `0` or more than {@link #maxOffset}.
	 */ offsetToIndex(offset) {
        let totalOffset = 0;
        for (const node of this._nodes){
            if (offset >= totalOffset && offset < totalOffset + node.offsetSize) {
                return this.getNodeIndex(node);
            }
            totalOffset += node.offsetSize;
        }
        if (totalOffset != offset) {
            /**
			 * Given offset cannot be found in the node list.
			 *
			 * @error model-nodelist-offset-out-of-bounds
			 * @param offset
			 * @param nodeList Stringified node list.
			 */ throw new CKEditorError('model-nodelist-offset-out-of-bounds', this, {
                offset,
                nodeList: this
            });
        }
        return this.length;
    }
    /**
	 * Inserts given nodes at given index.
	 *
	 * @internal
	 * @param index Index at which nodes should be inserted.
	 * @param nodes Nodes to be inserted.
	 */ _insertNodes(index, nodes) {
        // Validation.
        for (const node of nodes){
            if (!(node instanceof Node$1)) {
                /**
				 * Trying to insert an object which is not a Node instance.
				 *
				 * @error model-nodelist-insertnodes-not-node
				 */ throw new CKEditorError('model-nodelist-insertnodes-not-node', this);
            }
        }
        this._nodes = spliceArray(this._nodes, Array.from(nodes), index, 0);
    }
    /**
	 * Removes one or more nodes starting at the given index.
	 *
	 * @internal
	 * @param indexStart Index of the first node to remove.
	 * @param howMany Number of nodes to remove.
	 * @returns Array containing removed nodes.
	 */ _removeNodes(indexStart, howMany = 1) {
        return this._nodes.splice(indexStart, howMany);
    }
    /**
	 * Converts `NodeList` instance to an array containing nodes that were inserted in the node list. Nodes
	 * are also converted to their plain object representation.
	 *
	 * @returns `NodeList` instance converted to `Array`.
	 */ toJSON() {
        return this._nodes.map((node)=>node.toJSON());
    }
}

// @if CK_DEBUG_ENGINE // const { convertMapToStringifiedObject } = require( '../dev-utils/utils' );
/**
 * Model text node. Type of {@link module:engine/model/node~Node node} that contains {@link module:engine/model/text~Text#data text data}.
 *
 * **Important:** see {@link module:engine/model/node~Node} to read about restrictions using `Text` and `Node` API.
 *
 * **Note:** keep in mind that `Text` instances might indirectly got removed from model tree when model is changed.
 * This happens when {@link module:engine/model/writer~Writer model writer} is used to change model and the text node is merged with
 * another text node. Then, both text nodes are removed and a new text node is inserted into the model. Because of
 * this behavior, keeping references to `Text` is not recommended. Instead, consider creating
 * {@link module:engine/model/liveposition~LivePosition live position} placed before the text node.
 */ class Text extends Node$1 {
    /**
	 * Text data contained in this text node.
	 *
	 * @internal
	 */ _data;
    /**
	 * Creates a text node.
	 *
	 * **Note:** Constructor of this class shouldn't be used directly in the code.
	 * Use the {@link module:engine/model/writer~Writer#createText} method instead.
	 *
	 * @internal
	 * @param data Node's text.
	 * @param attrs Node's attributes. See {@link module:utils/tomap~toMap} for a list of accepted values.
	 */ constructor(data, attrs){
        super(attrs);
        this._data = data || '';
    }
    /**
	 * @inheritDoc
	 */ get offsetSize() {
        return this.data.length;
    }
    /**
	 * Returns a text data contained in the node.
	 */ get data() {
        return this._data;
    }
    /**
	 * Converts `Text` instance to plain object and returns it.
	 *
	 * @returns`Text` instance converted to plain object.
	 */ toJSON() {
        const json = super.toJSON();
        json.data = this.data;
        return json;
    }
    /**
	 * Creates a copy of this text node and returns it. Created text node has same text data and attributes as original text node.
	 *
	 * @internal
	 * @returns `Text` instance created using given plain object.
	 */ _clone() {
        return new Text(this.data, this.getAttributes());
    }
    /**
	 * Creates a `Text` instance from given plain object (i.e. parsed JSON string).
	 *
	 * @param json Plain object to be converted to `Text`.
	 * @returns `Text` instance created using given plain object.
	 */ static fromJSON(json) {
        return new Text(json.data, json.attributes);
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Text.prototype.is = function(type) {
    return type === '$text' || type === 'model:$text' || // This are legacy values kept for backward compatibility.
    type === 'text' || type === 'model:text' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
    type === 'node' || type === 'model:node';
};

// @if CK_DEBUG_ENGINE // const { convertMapToStringifiedObject } = require( '../dev-utils/utils' );
/**
 * `TextProxy` represents a part of {@link module:engine/model/text~Text text node}.
 *
 * Since {@link module:engine/model/position~Position positions} can be placed between characters of a text node,
 * {@link module:engine/model/range~Range ranges} may contain only parts of text nodes. When {@link module:engine/model/range~Range#getItems
 * getting items}
 * contained in such range, we need to represent a part of that text node, since returning the whole text node would be incorrect.
 * `TextProxy` solves this issue.
 *
 * `TextProxy` has an API similar to {@link module:engine/model/text~Text Text} and allows to do most of the common tasks performed
 * on model nodes.
 *
 * **Note:** Some `TextProxy` instances may represent whole text node, not just a part of it.
 * See {@link module:engine/model/textproxy~TextProxy#isPartial}.
 *
 * **Note:** `TextProxy` is not an instance of {@link module:engine/model/node~Node node}. Keep this in mind when using it as a
 * parameter of methods.
 *
 * **Note:** `TextProxy` is a readonly interface. If you want to perform changes on model data represented by a `TextProxy`
 * use {@link module:engine/model/writer~Writer model writer API}.
 *
 * **Note:** `TextProxy` instances are created on the fly, basing on the current state of model. Because of this, it is
 * highly unrecommended to store references to `TextProxy` instances. `TextProxy` instances are not refreshed when
 * model changes, so they might get invalidated. Instead, consider creating {@link module:engine/model/liveposition~LivePosition live
 * position}.
 *
 * `TextProxy` instances are created by {@link module:engine/model/treewalker~TreeWalker model tree walker}. You should not need to create
 * an instance of this class by your own.
 */ class TextProxy extends TypeCheckable {
    /**
	 * Text node which part is represented by this text proxy.
	 */ textNode;
    /**
	 * Text data represented by this text proxy.
	 */ data;
    /**
	 * Offset in {@link module:engine/model/textproxy~TextProxy#textNode text node} from which the text proxy starts.
	 */ offsetInText;
    /**
	 * Creates a text proxy.
	 *
	 * @internal
	 * @param textNode Text node which part is represented by this text proxy.
	 * @param offsetInText Offset in {@link module:engine/model/textproxy~TextProxy#textNode text node} from which the text proxy
	 * starts.
	 * @param length Text proxy length, that is how many text node's characters, starting from `offsetInText` it represents.
	 */ constructor(textNode, offsetInText, length){
        super();
        this.textNode = textNode;
        if (offsetInText < 0 || offsetInText > textNode.offsetSize) {
            /**
			 * Given `offsetInText` value is incorrect.
			 *
			 * @error model-textproxy-wrong-offsetintext
			 */ throw new CKEditorError('model-textproxy-wrong-offsetintext', this);
        }
        if (length < 0 || offsetInText + length > textNode.offsetSize) {
            /**
			 * Given `length` value is incorrect.
			 *
			 * @error model-textproxy-wrong-length
			 */ throw new CKEditorError('model-textproxy-wrong-length', this);
        }
        this.data = textNode.data.substring(offsetInText, offsetInText + length);
        this.offsetInText = offsetInText;
    }
    /**
	 * Offset at which this text proxy starts in it's parent.
	 *
	 * @see module:engine/model/node~Node#startOffset
	 */ get startOffset() {
        return this.textNode.startOffset !== null ? this.textNode.startOffset + this.offsetInText : null;
    }
    /**
	 * Offset size of this text proxy. Equal to the number of characters represented by the text proxy.
	 *
	 * @see module:engine/model/node~Node#offsetSize
	 */ get offsetSize() {
        return this.data.length;
    }
    /**
	 * Offset at which this text proxy ends in it's parent.
	 *
	 * @see module:engine/model/node~Node#endOffset
	 */ get endOffset() {
        return this.startOffset !== null ? this.startOffset + this.offsetSize : null;
    }
    /**
	 * Flag indicating whether `TextProxy` instance covers only part of the original {@link module:engine/model/text~Text text node}
	 * (`true`) or the whole text node (`false`).
	 *
	 * This is `false` when text proxy starts at the very beginning of {@link module:engine/model/textproxy~TextProxy#textNode textNode}
	 * ({@link module:engine/model/textproxy~TextProxy#offsetInText offsetInText} equals `0`) and text proxy sizes is equal to
	 * text node size.
	 */ get isPartial() {
        return this.offsetSize !== this.textNode.offsetSize;
    }
    /**
	 * Parent of this text proxy, which is same as parent of text node represented by this text proxy.
	 */ get parent() {
        return this.textNode.parent;
    }
    /**
	 * Root of this text proxy, which is same as root of text node represented by this text proxy.
	 */ get root() {
        return this.textNode.root;
    }
    /**
	 * Gets path to this text proxy.
	 *
	 * @see module:engine/model/node~Node#getPath
	 */ getPath() {
        const path = this.textNode.getPath();
        if (path.length > 0) {
            path[path.length - 1] += this.offsetInText;
        }
        return path;
    }
    /**
	 * Returns ancestors array of this text proxy.
	 *
	 * @param options Options object.
	 * @param options.includeSelf When set to `true` this text proxy will be also included in parent's array.
	 * @param options.parentFirst When set to `true`, array will be sorted from text proxy parent to root element,
	 * otherwise root element will be the first item in the array.
	 * @returns Array with ancestors.
	 */ getAncestors(options = {}) {
        const ancestors = [];
        let parent = options.includeSelf ? this : this.parent;
        while(parent){
            ancestors[options.parentFirst ? 'push' : 'unshift'](parent);
            parent = parent.parent;
        }
        return ancestors;
    }
    /**
	 * Checks if this text proxy has an attribute for given key.
	 *
	 * @param key Key of attribute to check.
	 * @returns `true` if attribute with given key is set on text proxy, `false` otherwise.
	 */ hasAttribute(key) {
        return this.textNode.hasAttribute(key);
    }
    /**
	 * Gets an attribute value for given key or `undefined` if that attribute is not set on text proxy.
	 *
	 * @param key Key of attribute to look for.
	 * @returns Attribute value or `undefined`.
	 */ getAttribute(key) {
        return this.textNode.getAttribute(key);
    }
    /**
	 * Returns iterator that iterates over this node's attributes. Attributes are returned as arrays containing two
	 * items. First one is attribute key and second is attribute value.
	 *
	 * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
	 */ getAttributes() {
        return this.textNode.getAttributes();
    }
    /**
	 * Returns iterator that iterates over this node's attribute keys.
	 */ getAttributeKeys() {
        return this.textNode.getAttributeKeys();
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
TextProxy.prototype.is = function(type) {
    return type === '$textProxy' || type === 'model:$textProxy' || // This are legacy values kept for backward compatibility.
    type === 'textProxy' || type === 'model:textProxy';
};

// @if CK_DEBUG_ENGINE // const { stringifyMap, convertMapToStringifiedObject, convertMapToTags } = require( '../dev-utils/utils' );
/**
 * Model element. Type of {@link module:engine/model/node~Node node} that has a {@link module:engine/model/element~Element#name name} and
 * {@link module:engine/model/element~Element#getChildren child nodes}.
 *
 * **Important**: see {@link module:engine/model/node~Node} to read about restrictions using `Element` and `Node` API.
 */ class Element extends Node$1 {
    /**
	 * Element name.
	 */ name;
    /**
	 * List of children nodes.
	 */ _children = new NodeList();
    /**
	 * Creates a model element.
	 *
	 * **Note:** Constructor of this class shouldn't be used directly in the code.
	 * Use the {@link module:engine/model/writer~Writer#createElement} method instead.
	 *
	 * @internal
	 * @param name Element's name.
	 * @param attrs Element's attributes. See {@link module:utils/tomap~toMap} for a list of accepted values.
	 * @param children One or more nodes to be inserted as children of created element.
	 */ constructor(name, attrs, children){
        super(attrs);
        this.name = name;
        if (children) {
            this._insertChild(0, children);
        }
    }
    /**
	 * Number of this element's children.
	 */ get childCount() {
        return this._children.length;
    }
    /**
	 * Sum of {@link module:engine/model/node~Node#offsetSize offset sizes} of all of this element's children.
	 */ get maxOffset() {
        return this._children.maxOffset;
    }
    /**
	 * Is `true` if there are no nodes inside this element, `false` otherwise.
	 */ get isEmpty() {
        return this.childCount === 0;
    }
    /**
	 * Gets the child at the given index.
	 */ getChild(index) {
        return this._children.getNode(index);
    }
    /**
	 * Returns an iterator that iterates over all of this element's children.
	 */ getChildren() {
        return this._children[Symbol.iterator]();
    }
    /**
	 * Returns an index of the given child node. Returns `null` if given node is not a child of this element.
	 *
	 * @param node Child node to look for.
	 * @returns Child node's index in this element.
	 */ getChildIndex(node) {
        return this._children.getNodeIndex(node);
    }
    /**
	 * Returns the starting offset of given child. Starting offset is equal to the sum of
	 * {@link module:engine/model/node~Node#offsetSize offset sizes} of all node's siblings that are before it. Returns `null` if
	 * given node is not a child of this element.
	 *
	 * @param node Child node to look for.
	 * @returns Child node's starting offset.
	 */ getChildStartOffset(node) {
        return this._children.getNodeStartOffset(node);
    }
    /**
	 * Returns index of a node that occupies given offset. If given offset is too low, returns `0`. If given offset is
	 * too high, returns {@link module:engine/model/element~Element#getChildIndex index after last child}.
	 *
	 * ```ts
	 * const textNode = new Text( 'foo' );
	 * const pElement = new Element( 'p' );
	 * const divElement = new Element( [ textNode, pElement ] );
	 * divElement.offsetToIndex( -1 ); // Returns 0, because offset is too low.
	 * divElement.offsetToIndex( 0 ); // Returns 0, because offset 0 is taken by `textNode` which is at index 0.
	 * divElement.offsetToIndex( 1 ); // Returns 0, because `textNode` has `offsetSize` equal to 3, so it occupies offset 1 too.
	 * divElement.offsetToIndex( 2 ); // Returns 0.
	 * divElement.offsetToIndex( 3 ); // Returns 1.
	 * divElement.offsetToIndex( 4 ); // Returns 2. There are no nodes at offset 4, so last available index is returned.
	 * ```
	 */ offsetToIndex(offset) {
        return this._children.offsetToIndex(offset);
    }
    /**
	 * Returns a descendant node by its path relative to this element.
	 *
	 * ```ts
	 * // <this>a<b>c</b></this>
	 * this.getNodeByPath( [ 0 ] );     // -> "a"
	 * this.getNodeByPath( [ 1 ] );     // -> <b>
	 * this.getNodeByPath( [ 1, 0 ] );  // -> "c"
	 * ```
	 *
	 * @param relativePath Path of the node to find, relative to this element.
	 */ getNodeByPath(relativePath) {
        // eslint-disable-next-line @typescript-eslint/no-this-alias, consistent-this
        let node = this;
        for (const index of relativePath){
            node = node.getChild(node.offsetToIndex(index));
        }
        return node;
    }
    /**
	 * Returns the parent element of the given name. Returns null if the element is not inside the desired parent.
	 *
	 * @param parentName The name of the parent element to find.
	 * @param options Options object.
	 * @param options.includeSelf When set to `true` this node will be also included while searching.
	 */ findAncestor(parentName, options = {}) {
        let parent = options.includeSelf ? this : this.parent;
        while(parent){
            if (parent.name === parentName) {
                return parent;
            }
            parent = parent.parent;
        }
        return null;
    }
    /**
	 * Converts `Element` instance to plain object and returns it. Takes care of converting all of this element's children.
	 *
	 * @returns `Element` instance converted to plain object.
	 */ toJSON() {
        const json = super.toJSON();
        json.name = this.name;
        if (this._children.length > 0) {
            json.children = [];
            for (const node of this._children){
                json.children.push(node.toJSON());
            }
        }
        return json;
    }
    /**
	 * Creates a copy of this element and returns it. Created element has the same name and attributes as the original element.
	 * If clone is deep, the original element's children are also cloned. If not, then empty element is returned.
	 *
	 * @internal
	 * @param deep If set to `true` clones element and all its children recursively. When set to `false`,
	 * element will be cloned without any child.
	 */ _clone(deep = false) {
        const children = deep ? Array.from(this._children).map((node)=>node._clone(true)) : undefined;
        return new Element(this.name, this.getAttributes(), children);
    }
    /**
	 * {@link module:engine/model/element~Element#_insertChild Inserts} one or more nodes at the end of this element.
	 *
	 * @see module:engine/model/writer~Writer#append
	 * @internal
	 * @param nodes Nodes to be inserted.
	 */ _appendChild(nodes) {
        this._insertChild(this.childCount, nodes);
    }
    /**
	 * Inserts one or more nodes at the given index and sets {@link module:engine/model/node~Node#parent parent} of these nodes
	 * to this element.
	 *
	 * @see module:engine/model/writer~Writer#insert
	 * @internal
	 * @param index Index at which nodes should be inserted.
	 * @param items Items to be inserted.
	 */ _insertChild(index, items) {
        const nodes = normalize$1(items);
        for (const node of nodes){
            // If node that is being added to this element is already inside another element, first remove it from the old parent.
            if (node.parent !== null) {
                node._remove();
            }
            node.parent = this;
        }
        this._children._insertNodes(index, nodes);
    }
    /**
	 * Removes one or more nodes starting at the given index and sets
	 * {@link module:engine/model/node~Node#parent parent} of these nodes to `null`.
	 *
	 * @see module:engine/model/writer~Writer#remove
	 * @internal
	 * @param index Index of the first node to remove.
	 * @param howMany Number of nodes to remove.
	 * @returns Array containing removed nodes.
	 */ _removeChildren(index, howMany = 1) {
        const nodes = this._children._removeNodes(index, howMany);
        for (const node of nodes){
            node.parent = null;
        }
        return nodes;
    }
    /**
	 * Creates an `Element` instance from given plain object (i.e. parsed JSON string).
	 * Converts `Element` children to proper nodes.
	 *
	 * @param json Plain object to be converted to `Element`.
	 * @returns `Element` instance created using given plain object.
	 */ static fromJSON(json) {
        let children;
        if (json.children) {
            children = [];
            for (const child of json.children){
                if (child.name) {
                    // If child has name property, it is an Element.
                    children.push(Element.fromJSON(child));
                } else {
                    // Otherwise, it is a Text node.
                    children.push(Text.fromJSON(child));
                }
            }
        }
        return new Element(json.name, json.attributes, children);
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Element.prototype.is = function(type, name) {
    if (!name) {
        return type === 'element' || type === 'model:element' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'node' || type === 'model:node';
    }
    return name === this.name && (type === 'element' || type === 'model:element');
};
/**
 * Converts strings to Text and non-iterables to arrays.
 */ function normalize$1(nodes) {
    // Separate condition because string is iterable.
    if (typeof nodes == 'string') {
        return [
            new Text(nodes)
        ];
    }
    if (!isIterable(nodes)) {
        nodes = [
            nodes
        ];
    }
    // Array.from to enable .map() on non-arrays.
    return Array.from(nodes).map((node)=>{
        if (typeof node == 'string') {
            return new Text(node);
        }
        if (node instanceof TextProxy) {
            return new Text(node.data, node.getAttributes());
        }
        return node;
    });
}

/**
 * Position iterator class. It allows to iterate forward and backward over the document.
 */ class TreeWalker {
    /**
	 * Walking direction. Defaults `'forward'`.
	 */ direction;
    /**
	 * Iterator boundaries.
	 *
	 * When the iterator is walking `'forward'` on the end of boundary or is walking `'backward'`
	 * on the start of boundary, then `{ done: true }` is returned.
	 *
	 * If boundaries are not defined they are set before first and after last child of the root node.
	 */ boundaries;
    /**
	 * Flag indicating whether all consecutive characters with the same attributes should be
	 * returned as one {@link module:engine/model/textproxy~TextProxy} (`true`) or one by one (`false`).
	 */ singleCharacters;
    /**
	 * Flag indicating whether iterator should enter elements or not. If the iterator is shallow child nodes of any
	 * iterated node will not be returned along with `elementEnd` tag.
	 */ shallow;
    /**
	 * Flag indicating whether iterator should ignore `elementEnd` tags. If the option is true walker will not
	 * return a parent node of the start position. If this option is `true` each {@link module:engine/model/element~Element} will
	 * be returned once, while if the option is `false` they might be returned twice:
	 * for `'elementStart'` and `'elementEnd'`.
	 */ ignoreElementEnd;
    /**
	 * Iterator position. This is always static position, even if the initial position was a
	 * {@link module:engine/model/liveposition~LivePosition live position}. If start position is not defined then position depends
	 * on {@link #direction}. If direction is `'forward'` position starts form the beginning, when direction
	 * is `'backward'` position starts from the end.
	 */ _position;
    /**
	 * Start boundary cached for optimization purposes.
	 */ _boundaryStartParent;
    /**
	 * End boundary cached for optimization purposes.
	 */ _boundaryEndParent;
    /**
	 * Parent of the most recently visited node. Cached for optimization purposes.
	 */ _visitedParent;
    /**
	 * Creates a range iterator. All parameters are optional, but you have to specify either `boundaries` or `startPosition`.
	 *
	 * @param options Object with configuration.
	 */ constructor(options){
        if (!options || !options.boundaries && !options.startPosition) {
            /**
			 * Neither boundaries nor starting position of a `TreeWalker` have been defined.
			 *
			 * @error model-tree-walker-no-start-position
			 */ throw new CKEditorError('model-tree-walker-no-start-position', null);
        }
        const direction = options.direction || 'forward';
        if (direction != 'forward' && direction != 'backward') {
            /**
			 * Only `backward` and `forward` direction allowed.
			 *
			 * @error model-tree-walker-unknown-direction
			 */ throw new CKEditorError('model-tree-walker-unknown-direction', options, {
                direction
            });
        }
        this.direction = direction;
        this.boundaries = options.boundaries || null;
        if (options.startPosition) {
            this._position = options.startPosition.clone();
        } else {
            this._position = Position._createAt(this.boundaries[this.direction == 'backward' ? 'end' : 'start']);
        }
        // Reset position stickiness in case it was set to other value, as the stickiness is kept after cloning.
        this.position.stickiness = 'toNone';
        this.singleCharacters = !!options.singleCharacters;
        this.shallow = !!options.shallow;
        this.ignoreElementEnd = !!options.ignoreElementEnd;
        this._boundaryStartParent = this.boundaries ? this.boundaries.start.parent : null;
        this._boundaryEndParent = this.boundaries ? this.boundaries.end.parent : null;
        this._visitedParent = this.position.parent;
    }
    /**
	 * Iterable interface.
	 *
	 * @returns {Iterable.<module:engine/model/treewalker~TreeWalkerValue>}
	 */ [Symbol.iterator]() {
        return this;
    }
    /**
	 * Iterator position. This is always static position, even if the initial position was a
	 * {@link module:engine/model/liveposition~LivePosition live position}. If start position is not defined then position depends
	 * on {@link #direction}. If direction is `'forward'` position starts form the beginning, when direction
	 * is `'backward'` position starts from the end.
	 */ get position() {
        return this._position;
    }
    /**
	 * Moves {@link #position} in the {@link #direction} skipping values as long as the callback function returns `true`.
	 *
	 * For example:
	 *
	 * ```ts
	 * walker.skip( value => value.type == 'text' ); // <paragraph>[]foo</paragraph> -> <paragraph>foo[]</paragraph>
	 * walker.skip( () => true ); // Move the position to the end: <paragraph>[]foo</paragraph> -> <paragraph>foo</paragraph>[]
	 * walker.skip( () => false ); // Do not move the position.
	 * ```
	 *
	 * @param skip Callback function. Gets {@link module:engine/model/treewalker~TreeWalkerValue} and should
	 * return `true` if the value should be skipped or `false` if not.
	 */ skip(skip) {
        let done, value, prevPosition, prevVisitedParent;
        do {
            prevPosition = this.position;
            prevVisitedParent = this._visitedParent;
            ({ done, value } = this.next());
        }while (!done && skip(value))
        if (!done) {
            this._position = prevPosition;
            this._visitedParent = prevVisitedParent;
        }
    }
    /**
	 * Gets the next tree walker's value.
	 */ next() {
        if (this.direction == 'forward') {
            return this._next();
        } else {
            return this._previous();
        }
    }
    /**
	 * Makes a step forward in model. Moves the {@link #position} to the next position and returns the encountered value.
	 */ _next() {
        const previousPosition = this.position;
        const position = this.position.clone();
        const parent = this._visitedParent;
        // We are at the end of the root.
        if (parent.parent === null && position.offset === parent.maxOffset) {
            return {
                done: true,
                value: undefined
            };
        }
        // We reached the walker boundary.
        if (parent === this._boundaryEndParent && position.offset == this.boundaries.end.offset) {
            return {
                done: true,
                value: undefined
            };
        }
        // Get node just after the current position.
        // Use a highly optimized version instead of checking the text node first and then getting the node after. See #6582.
        const textNodeAtPosition = getTextNodeAtPosition(position, parent);
        const node = textNodeAtPosition || getNodeAfterPosition(position, parent, textNodeAtPosition);
        if (node instanceof Element) {
            if (!this.shallow) {
                // Manual operations on path internals for optimization purposes. Here and in the rest of the method.
                position.path.push(0);
                this._visitedParent = node;
            } else {
                // We are past the walker boundaries.
                if (this.boundaries && this.boundaries.end.isBefore(position)) {
                    return {
                        done: true,
                        value: undefined
                    };
                }
                position.offset++;
            }
            this._position = position;
            return formatReturnValue('elementStart', node, previousPosition, position, 1);
        }
        if (node instanceof Text) {
            let charactersCount;
            if (this.singleCharacters) {
                charactersCount = 1;
            } else {
                let offset = node.endOffset;
                if (this._boundaryEndParent == parent && this.boundaries.end.offset < offset) {
                    offset = this.boundaries.end.offset;
                }
                charactersCount = offset - position.offset;
            }
            const offsetInTextNode = position.offset - node.startOffset;
            const item = new TextProxy(node, offsetInTextNode, charactersCount);
            position.offset += charactersCount;
            this._position = position;
            return formatReturnValue('text', item, previousPosition, position, charactersCount);
        }
        // `node` is not set, we reached the end of current `parent`.
        position.path.pop();
        position.offset++;
        this._position = position;
        this._visitedParent = parent.parent;
        if (this.ignoreElementEnd) {
            return this._next();
        }
        return formatReturnValue('elementEnd', parent, previousPosition, position);
    }
    /**
	 * Makes a step backward in model. Moves the {@link #position} to the previous position and returns the encountered value.
	 */ _previous() {
        const previousPosition = this.position;
        const position = this.position.clone();
        const parent = this._visitedParent;
        // We are at the beginning of the root.
        if (parent.parent === null && position.offset === 0) {
            return {
                done: true,
                value: undefined
            };
        }
        // We reached the walker boundary.
        if (parent == this._boundaryStartParent && position.offset == this.boundaries.start.offset) {
            return {
                done: true,
                value: undefined
            };
        }
        // Get node just before the current position.
        // Use a highly optimized version instead of checking the text node first and then getting the node before. See #6582.
        const positionParent = position.parent;
        const textNodeAtPosition = getTextNodeAtPosition(position, positionParent);
        const node = textNodeAtPosition || getNodeBeforePosition(position, positionParent, textNodeAtPosition);
        if (node instanceof Element) {
            position.offset--;
            if (this.shallow) {
                this._position = position;
                return formatReturnValue('elementStart', node, previousPosition, position, 1);
            }
            position.path.push(node.maxOffset);
            this._position = position;
            this._visitedParent = node;
            if (this.ignoreElementEnd) {
                return this._previous();
            }
            return formatReturnValue('elementEnd', node, previousPosition, position);
        }
        if (node instanceof Text) {
            let charactersCount;
            if (this.singleCharacters) {
                charactersCount = 1;
            } else {
                let offset = node.startOffset;
                if (this._boundaryStartParent == parent && this.boundaries.start.offset > offset) {
                    offset = this.boundaries.start.offset;
                }
                charactersCount = position.offset - offset;
            }
            const offsetInTextNode = position.offset - node.startOffset;
            const item = new TextProxy(node, offsetInTextNode - charactersCount, charactersCount);
            position.offset -= charactersCount;
            this._position = position;
            return formatReturnValue('text', item, previousPosition, position, charactersCount);
        }
        // `node` is not set, we reached the beginning of current `parent`.
        position.path.pop();
        this._position = position;
        this._visitedParent = parent.parent;
        return formatReturnValue('elementStart', parent, previousPosition, position, 1);
    }
}
function formatReturnValue(type, item, previousPosition, nextPosition, length) {
    return {
        done: false,
        value: {
            type,
            item,
            previousPosition,
            nextPosition,
            length
        }
    };
}

/**
 * Represents a position in the model tree.
 *
 * A position is represented by its {@link module:engine/model/position~Position#root} and
 * a {@link module:engine/model/position~Position#path} in that root.
 *
 * You can create position instances via its constructor or the `createPosition*()` factory methods of
 * {@link module:engine/model/model~Model} and {@link module:engine/model/writer~Writer}.
 *
 * **Note:** Position is based on offsets, not indexes. This means that a position between two text nodes
 * `foo` and `bar` has offset `3`, not `1`. See {@link module:engine/model/position~Position#path} for more information.
 *
 * Since a position in the model is represented by a {@link module:engine/model/position~Position#root position root} and
 * {@link module:engine/model/position~Position#path position path} it is possible to create positions placed in non-existing places.
 * This requirement is important for operational transformation algorithms.
 *
 * Also, {@link module:engine/model/operation/operation~Operation operations}
 * kept in the {@link module:engine/model/document~Document#history document history}
 * are storing positions (and ranges) which were correct when those operations were applied, but may not be correct
 * after the document has changed.
 *
 * When changes are applied to the model, it may also happen that {@link module:engine/model/position~Position#parent position parent}
 * will change even if position path has not changed. Keep in mind, that if a position leads to non-existing element,
 * {@link module:engine/model/position~Position#parent} and some other properties and methods will throw errors.
 *
 * In most cases, position with wrong path is caused by an error in code, but it is sometimes needed, as described above.
 */ class Position extends TypeCheckable {
    /**
	 * Root of the position path.
	 */ root;
    /**
	 * Position of the node in the tree. **Path contains offsets, not indexes.**
	 *
	 * Position can be placed before, after or in a {@link module:engine/model/node~Node node} if that node has
	 * {@link module:engine/model/node~Node#offsetSize} greater than `1`. Items in position path are
	 * {@link module:engine/model/node~Node#startOffset starting offsets} of position ancestors, starting from direct root children,
	 * down to the position offset in it's parent.
	 *
	 * ```
	 * ROOT
	 *  |- P            before: [ 0 ]         after: [ 1 ]
	 *  |- UL           before: [ 1 ]         after: [ 2 ]
	 *     |- LI        before: [ 1, 0 ]      after: [ 1, 1 ]
	 *     |  |- foo    before: [ 1, 0, 0 ]   after: [ 1, 0, 3 ]
	 *     |- LI        before: [ 1, 1 ]      after: [ 1, 2 ]
	 *        |- bar    before: [ 1, 1, 0 ]   after: [ 1, 1, 3 ]
	 * ```
	 *
	 * `foo` and `bar` are representing {@link module:engine/model/text~Text text nodes}. Since text nodes has offset size
	 * greater than `1` you can place position offset between their start and end:
	 *
	 * ```
	 * ROOT
	 *  |- P
	 *  |- UL
	 *     |- LI
	 *     |  |- f^o|o  ^ has path: [ 1, 0, 1 ]   | has path: [ 1, 0, 2 ]
	 *     |- LI
	 *        |- b^a|r  ^ has path: [ 1, 1, 1 ]   | has path: [ 1, 1, 2 ]
	 * ```
	 */ path;
    /**
	 * Position stickiness. See {@link module:engine/model/position~PositionStickiness}.
	 */ stickiness;
    /**
	 * Creates a position.
	 *
	 * @param root Root of the position.
	 * @param path Position path. See {@link module:engine/model/position~Position#path}.
	 * @param stickiness Position stickiness. See {@link module:engine/model/position~PositionStickiness}.
	 */ constructor(root, path, stickiness = 'toNone'){
        super();
        if (!root.is('element') && !root.is('documentFragment')) {
            /**
			 * Position root is invalid.
			 *
			 * Positions can only be anchored in elements or document fragments.
			 *
			 * @error model-position-root-invalid
			 */ throw new CKEditorError('model-position-root-invalid', root);
        }
        if (!(path instanceof Array) || path.length === 0) {
            /**
			 * Position path must be an array with at least one item.
			 *
			 * @error model-position-path-incorrect-format
			 * @param path
			 */ throw new CKEditorError('model-position-path-incorrect-format', root, {
                path
            });
        }
        // Normalize the root and path when element (not root) is passed.
        if (root.is('rootElement')) {
            path = path.slice();
        } else {
            path = [
                ...root.getPath(),
                ...path
            ];
            root = root.root;
        }
        this.root = root;
        this.path = path;
        this.stickiness = stickiness;
    }
    /**
	 * Offset at which this position is located in its {@link module:engine/model/position~Position#parent parent}. It is equal
	 * to the last item in position {@link module:engine/model/position~Position#path path}.
	 *
	 * @type {Number}
	 */ get offset() {
        return this.path[this.path.length - 1];
    }
    set offset(newOffset) {
        this.path[this.path.length - 1] = newOffset;
    }
    /**
	 * Parent element of this position.
	 *
	 * Keep in mind that `parent` value is calculated when the property is accessed.
	 * If {@link module:engine/model/position~Position#path position path}
	 * leads to a non-existing element, `parent` property will throw error.
	 *
	 * Also it is a good idea to cache `parent` property if it is used frequently in an algorithm (i.e. in a long loop).
	 */ get parent() {
        let parent = this.root;
        for(let i = 0; i < this.path.length - 1; i++){
            parent = parent.getChild(parent.offsetToIndex(this.path[i]));
            if (!parent) {
                /**
				 * The position's path is incorrect. This means that a position does not point to
				 * a correct place in the tree and hence, some of its methods and getters cannot work correctly.
				 *
				 * **Note**: Unlike DOM and view positions, in the model, the
				 * {@link module:engine/model/position~Position#parent position's parent} is always an element or a document fragment.
				 * The last offset in the {@link module:engine/model/position~Position#path position's path} is the point in this element
				 * where this position points.
				 *
				 * Read more about model positions and offsets in
				 * the {@glink framework/architecture/editing-engine#indexes-and-offsets Editing engine architecture} guide.
				 *
				 * @error model-position-path-incorrect
				 * @param position The incorrect position.
				 */ throw new CKEditorError('model-position-path-incorrect', this, {
                    position: this
                });
            }
        }
        if (parent.is('$text')) {
            throw new CKEditorError('model-position-path-incorrect', this, {
                position: this
            });
        }
        return parent;
    }
    /**
	 * Position {@link module:engine/model/position~Position#offset offset} converted to an index in position's parent node. It is
	 * equal to the {@link module:engine/model/node~Node#index index} of a node after this position. If position is placed
	 * in text node, position index is equal to the index of that text node.
	 */ get index() {
        return this.parent.offsetToIndex(this.offset);
    }
    /**
	 * Returns {@link module:engine/model/text~Text text node} instance in which this position is placed or `null` if this
	 * position is not in a text node.
	 */ get textNode() {
        return getTextNodeAtPosition(this, this.parent);
    }
    /**
	 * Node directly after this position or `null` if this position is in text node.
	 */ get nodeAfter() {
        // Cache the parent and reuse for performance reasons. See #6579 and #6582.
        const parent = this.parent;
        return getNodeAfterPosition(this, parent, getTextNodeAtPosition(this, parent));
    }
    /**
	 * Node directly before this position or `null` if this position is in text node.
	 */ get nodeBefore() {
        // Cache the parent and reuse for performance reasons. See #6579 and #6582.
        const parent = this.parent;
        return getNodeBeforePosition(this, parent, getTextNodeAtPosition(this, parent));
    }
    /**
	 * Is `true` if position is at the beginning of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
	 */ get isAtStart() {
        return this.offset === 0;
    }
    /**
	 * Is `true` if position is at the end of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
	 */ get isAtEnd() {
        return this.offset == this.parent.maxOffset;
    }
    /**
	 * Checks whether this position is before or after given position.
	 *
	 * This method is safe to use it on non-existing positions (for example during operational transformation).
	 */ compareWith(otherPosition) {
        if (this.root != otherPosition.root) {
            return 'different';
        }
        const result = compareArrays(this.path, otherPosition.path);
        switch(result){
            case 'same':
                return 'same';
            case 'prefix':
                return 'before';
            case 'extension':
                return 'after';
            default:
                return this.path[result] < otherPosition.path[result] ? 'before' : 'after';
        }
    }
    /**
	 * Gets the farthest position which matches the callback using
	 * {@link module:engine/model/treewalker~TreeWalker TreeWalker}.
	 *
	 * For example:
	 *
	 * ```ts
	 * getLastMatchingPosition( value => value.type == 'text' );
	 * // <paragraph>[]foo</paragraph> -> <paragraph>foo[]</paragraph>
	 *
	 * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } );
	 * // <paragraph>foo[]</paragraph> -> <paragraph>[]foo</paragraph>
	 *
	 * getLastMatchingPosition( value => false );
	 * // Do not move the position.
	 * ```
	 *
	 * @param skip Callback function. Gets {@link module:engine/model/treewalker~TreeWalkerValue} and should
	 * return `true` if the value should be skipped or `false` if not.
	 * @param options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
	 *
	 * @returns The position after the last item which matches the `skip` callback test.
	 */ getLastMatchingPosition(skip, options = {}) {
        options.startPosition = this;
        const treeWalker = new TreeWalker(options);
        treeWalker.skip(skip);
        return treeWalker.position;
    }
    /**
	 * Returns a path to this position's parent. Parent path is equal to position {@link module:engine/model/position~Position#path path}
	 * but without the last item.
	 *
	 * This method is safe to use it on non-existing positions (for example during operational transformation).
	 *
	 * @returns Path to the parent.
	 */ getParentPath() {
        return this.path.slice(0, -1);
    }
    /**
	 * Returns ancestors array of this position, that is this position's parent and its ancestors.
	 *
	 * @returns Array with ancestors.
	 */ getAncestors() {
        const parent = this.parent;
        if (parent.is('documentFragment')) {
            return [
                parent
            ];
        } else {
            return parent.getAncestors({
                includeSelf: true
            });
        }
    }
    /**
	 * Returns the parent element of the given name. Returns null if the position is not inside the desired parent.
	 *
	 * @param parentName The name of the parent element to find.
	 */ findAncestor(parentName) {
        const parent = this.parent;
        if (parent.is('element')) {
            return parent.findAncestor(parentName, {
                includeSelf: true
            });
        }
        return null;
    }
    /**
	 * Returns the slice of two position {@link #path paths} which is identical. The {@link #root roots}
	 * of these two paths must be identical.
	 *
	 * This method is safe to use it on non-existing positions (for example during operational transformation).
	 *
	 * @param position The second position.
	 * @returns The common path.
	 */ getCommonPath(position) {
        if (this.root != position.root) {
            return [];
        }
        // We find on which tree-level start and end have the lowest common ancestor
        const cmp = compareArrays(this.path, position.path);
        // If comparison returned string it means that arrays are same.
        const diffAt = typeof cmp == 'string' ? Math.min(this.path.length, position.path.length) : cmp;
        return this.path.slice(0, diffAt);
    }
    /**
	 * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
	 * which is a common ancestor of both positions. The {@link #root roots} of these two positions must be identical.
	 *
	 * @param position The second position.
	 */ getCommonAncestor(position) {
        const ancestorsA = this.getAncestors();
        const ancestorsB = position.getAncestors();
        let i = 0;
        while(ancestorsA[i] == ancestorsB[i] && ancestorsA[i]){
            i++;
        }
        return i === 0 ? null : ancestorsA[i - 1];
    }
    /**
	 * Returns a new instance of `Position`, that has same {@link #parent parent} but it's offset
	 * is shifted by `shift` value (can be a negative value).
	 *
	 * This method is safe to use it on non-existing positions (for example during operational transformation).
	 *
	 * @param shift Offset shift. Can be a negative value.
	 * @returns Shifted position.
	 */ getShiftedBy(shift) {
        const shifted = this.clone();
        const offset = shifted.offset + shift;
        shifted.offset = offset < 0 ? 0 : offset;
        return shifted;
    }
    /**
	 * Checks whether this position is after given position.
	 *
	 * This method is safe to use it on non-existing positions (for example during operational transformation).
	 *
	 * @see module:engine/model/position~Position#isBefore
	 * @param  otherPosition Position to compare with.
	 * @returns True if this position is after given position.
	 */ isAfter(otherPosition) {
        return this.compareWith(otherPosition) == 'after';
    }
    /**
	 * Checks whether this position is before given position.
	 *
	 * **Note:** watch out when using negation of the value returned by this method, because the negation will also
	 * be `true` if positions are in different roots and you might not expect this. You should probably use
	 * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
	 * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
	 *
	 * ```ts
	 * if ( a.isBefore( b ) && c.isAfter( d ) ) {
	 * 	// do A.
	 * } else {
	 * 	// do B.
	 * }
	 * ```
	 *
	 * or, if you have only one if-branch:
	 *
	 * ```ts
	 * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
	 * 	// do B.
	 * }
	 * ```
	 *
	 * rather than:
	 *
	 * ```ts
	 * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
	 * 	// do B.
	 * } else {
	 * 	// do A.
	 * }
	 * ```
	 *
	 * This method is safe to use it on non-existing positions (for example during operational transformation).
	 *
	 * @param otherPosition Position to compare with.
	 * @returns True if this position is before given position.
	 */ isBefore(otherPosition) {
        return this.compareWith(otherPosition) == 'before';
    }
    /**
	 * Checks whether this position is equal to given position.
	 *
	 * This method is safe to use it on non-existing positions (for example during operational transformation).
	 *
	 * @param otherPosition Position to compare with.
	 * @returns True if positions are same.
	 */ isEqual(otherPosition) {
        return this.compareWith(otherPosition) == 'same';
    }
    /**
	 * Checks whether this position is touching given position. Positions touch when there are no text nodes
	 * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
	 * they are very similar or even indistinguishable.
	 *
	 * @param otherPosition Position to compare with.
	 * @returns True if positions touch.
	 */ isTouching(otherPosition) {
        if (this.root !== otherPosition.root) {
            return false;
        }
        const commonLevel = Math.min(this.path.length, otherPosition.path.length);
        for(let level = 0; level < commonLevel; level++){
            const diff = this.path[level] - otherPosition.path[level];
            // Positions are spread by a node, so they are not touching.
            if (diff < -1 || diff > 1) {
                return false;
            } else if (diff === 1) {
                // `otherPosition` is on the left.
                // `this` is on the right.
                return checkTouchingBranch(otherPosition, this, level);
            } else if (diff === -1) {
                // `this` is on the left.
                // `otherPosition` is on the right.
                return checkTouchingBranch(this, otherPosition, level);
            }
        // `diff === 0`.
        // Positions are inside the same element on this level, compare deeper.
        }
        // If we ended up here, it means that positions paths have the same beginning.
        // If the paths have the same length, then it means that they are identical, so the positions are same.
        if (this.path.length === otherPosition.path.length) {
            return true;
        } else if (this.path.length > otherPosition.path.length) {
            return checkOnlyZeroes(this.path, commonLevel);
        } else {
            return checkOnlyZeroes(otherPosition.path, commonLevel);
        }
    }
    /**
	 * Checks if two positions are in the same parent.
	 *
	 * This method is safe to use it on non-existing positions (for example during operational transformation).
	 *
	 * @param position Position to compare with.
	 * @returns `true` if positions have the same parent, `false` otherwise.
	 */ hasSameParentAs(position) {
        if (this.root !== position.root) {
            return false;
        }
        const thisParentPath = this.getParentPath();
        const posParentPath = position.getParentPath();
        return compareArrays(thisParentPath, posParentPath) == 'same';
    }
    /**
	 * Returns a copy of this position that is transformed by given `operation`.
	 *
	 * The new position's parameters are updated accordingly to the effect of the `operation`.
	 *
	 * For example, if `n` nodes are inserted before the position, the returned position {@link ~Position#offset} will be
	 * increased by `n`. If the position was in a merged element, it will be accordingly moved to the new element, etc.
	 *
	 * This method is safe to use it on non-existing positions (for example during operational transformation).
	 *
	 * @param operation Operation to transform by.
	 * @returns Transformed position.
	 */ getTransformedByOperation(operation) {
        let result;
        switch(operation.type){
            case 'insert':
                result = this._getTransformedByInsertOperation(operation);
                break;
            case 'move':
            case 'remove':
            case 'reinsert':
                result = this._getTransformedByMoveOperation(operation);
                break;
            case 'split':
                result = this._getTransformedBySplitOperation(operation);
                break;
            case 'merge':
                result = this._getTransformedByMergeOperation(operation);
                break;
            default:
                result = Position._createAt(this);
                break;
        }
        return result;
    }
    /**
	 * Returns a copy of this position transformed by an insert operation.
	 *
	 * @internal
	 */ _getTransformedByInsertOperation(operation) {
        return this._getTransformedByInsertion(operation.position, operation.howMany);
    }
    /**
	 * Returns a copy of this position transformed by a move operation.
	 *
	 * @internal
	 */ _getTransformedByMoveOperation(operation) {
        return this._getTransformedByMove(operation.sourcePosition, operation.targetPosition, operation.howMany);
    }
    /**
	 * Returns a copy of this position transformed by a split operation.
	 *
	 * @internal
	 */ _getTransformedBySplitOperation(operation) {
        const movedRange = operation.movedRange;
        const isContained = movedRange.containsPosition(this) || movedRange.start.isEqual(this) && this.stickiness == 'toNext';
        if (isContained) {
            return this._getCombined(operation.splitPosition, operation.moveTargetPosition);
        } else {
            if (operation.graveyardPosition) {
                return this._getTransformedByMove(operation.graveyardPosition, operation.insertionPosition, 1);
            } else {
                return this._getTransformedByInsertion(operation.insertionPosition, 1);
            }
        }
    }
    /**
	 * Returns a copy of this position transformed by merge operation.
	 *
	 * @internal
	 */ _getTransformedByMergeOperation(operation) {
        const movedRange = operation.movedRange;
        const isContained = movedRange.containsPosition(this) || movedRange.start.isEqual(this);
        let pos;
        if (isContained) {
            pos = this._getCombined(operation.sourcePosition, operation.targetPosition);
            if (operation.sourcePosition.isBefore(operation.targetPosition)) {
                // Above happens during OT when the merged element is moved before the merged-to element.
                pos = pos._getTransformedByDeletion(operation.deletionPosition, 1);
            }
        } else if (this.isEqual(operation.deletionPosition)) {
            pos = Position._createAt(operation.deletionPosition);
        } else {
            pos = this._getTransformedByMove(operation.deletionPosition, operation.graveyardPosition, 1);
        }
        return pos;
    }
    /**
	 * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
	 * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
	 *
	 * @internal
	 * @param deletePosition Position before the first removed node.
	 * @param howMany How many nodes are removed.
	 * @returns Transformed position or `null`.
	 */ _getTransformedByDeletion(deletePosition, howMany) {
        const transformed = Position._createAt(this);
        // This position can't be affected if deletion was in a different root.
        if (this.root != deletePosition.root) {
            return transformed;
        }
        if (compareArrays(deletePosition.getParentPath(), this.getParentPath()) == 'same') {
            // If nodes are removed from the node that is pointed by this position...
            if (deletePosition.offset < this.offset) {
                // And are removed from before an offset of that position...
                if (deletePosition.offset + howMany > this.offset) {
                    // Position is in removed range, it's no longer in the tree.
                    return null;
                } else {
                    // Decrement the offset accordingly.
                    transformed.offset -= howMany;
                }
            }
        } else if (compareArrays(deletePosition.getParentPath(), this.getParentPath()) == 'prefix') {
            // If nodes are removed from a node that is on a path to this position...
            const i = deletePosition.path.length - 1;
            if (deletePosition.offset <= this.path[i]) {
                // And are removed from before next node of that path...
                if (deletePosition.offset + howMany > this.path[i]) {
                    // If the next node of that path is removed return null
                    // because the node containing this position got removed.
                    return null;
                } else {
                    // Otherwise, decrement index on that path.
                    transformed.path[i] -= howMany;
                }
            }
        }
        return transformed;
    }
    /**
	 * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
	 *
	 * @internal
	 * @param insertPosition Position where nodes are inserted.
	 * @param howMany How many nodes are inserted.
	 * @returns Transformed position.
	 */ _getTransformedByInsertion(insertPosition, howMany) {
        const transformed = Position._createAt(this);
        // This position can't be affected if insertion was in a different root.
        if (this.root != insertPosition.root) {
            return transformed;
        }
        if (compareArrays(insertPosition.getParentPath(), this.getParentPath()) == 'same') {
            // If nodes are inserted in the node that is pointed by this position...
            if (insertPosition.offset < this.offset || insertPosition.offset == this.offset && this.stickiness != 'toPrevious') {
                // And are inserted before an offset of that position...
                // "Push" this positions offset.
                transformed.offset += howMany;
            }
        } else if (compareArrays(insertPosition.getParentPath(), this.getParentPath()) == 'prefix') {
            // If nodes are inserted in a node that is on a path to this position...
            const i = insertPosition.path.length - 1;
            if (insertPosition.offset <= this.path[i]) {
                // And are inserted before next node of that path...
                // "Push" the index on that path.
                transformed.path[i] += howMany;
            }
        }
        return transformed;
    }
    /**
	 * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
	 *
	 * @internal
	 * @param sourcePosition Position before the first element to move.
	 * @param targetPosition Position where moved elements will be inserted.
	 * @param howMany How many consecutive nodes to move, starting from `sourcePosition`.
	 * @returns Transformed position.
	 */ _getTransformedByMove(sourcePosition, targetPosition, howMany) {
        // Update target position, as it could be affected by nodes removal.
        targetPosition = targetPosition._getTransformedByDeletion(sourcePosition, howMany);
        if (sourcePosition.isEqual(targetPosition)) {
            // If `targetPosition` is equal to `sourcePosition` this isn't really any move. Just return position as it is.
            return Position._createAt(this);
        }
        // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
        const transformed = this._getTransformedByDeletion(sourcePosition, howMany);
        const isMoved = transformed === null || sourcePosition.isEqual(this) && this.stickiness == 'toNext' || sourcePosition.getShiftedBy(howMany).isEqual(this) && this.stickiness == 'toPrevious';
        if (isMoved) {
            // This position is inside moved range (or sticks to it).
            // In this case, we calculate a combination of this position, move source position and target position.
            return this._getCombined(sourcePosition, targetPosition);
        } else {
            // This position is not inside a removed range.
            //
            // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
            return transformed._getTransformedByInsertion(targetPosition, howMany);
        }
    }
    /**
	 * Returns a new position that is a combination of this position and given positions.
	 *
	 * The combined position is a copy of this position transformed by moving a range starting at `source` position
	 * to the `target` position. It is expected that this position is inside the moved range.
	 *
	 * Example:
	 *
	 * ```ts
	 * let original = model.createPositionFromPath( root, [ 2, 3, 1 ] );
	 * let source = model.createPositionFromPath( root, [ 2, 2 ] );
	 * let target = model.createPositionFromPath( otherRoot, [ 1, 1, 3 ] );
	 * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
	 * ```
	 *
	 * Explanation:
	 *
	 * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
	 * was inside moved nodes and now should point to the new place. The moved nodes will be after
	 * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
	 * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
	 * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
	 * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
	 *
	 * @internal
	 * @param source Beginning of the moved range.
	 * @param target Position where the range is moved.
	 * @returns Combined position.
	 */ _getCombined(source, target) {
        const i = source.path.length - 1;
        // The first part of a path to combined position is a path to the place where nodes were moved.
        const combined = Position._createAt(target);
        combined.stickiness = this.stickiness;
        // Then we have to update the rest of the path.
        // Fix the offset because this position might be after `from` position and we have to reflect that.
        combined.offset = combined.offset + this.path[i] - source.offset;
        // Then, add the rest of the path.
        // If this position is at the same level as `from` position nothing will get added.
        combined.path = [
            ...combined.path,
            ...this.path.slice(i + 1)
        ];
        return combined;
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        return {
            root: this.root.toJSON(),
            path: Array.from(this.path),
            stickiness: this.stickiness
        };
    }
    /**
	 * Returns a new position that is equal to current position.
	 */ clone() {
        return new this.constructor(this.root, this.path, this.stickiness);
    }
    /**
	 * Creates position at the given location. The location can be specified as:
	 *
	 * * a {@link module:engine/model/position~Position position},
	 * * parent element and offset (offset defaults to `0`),
	 * * parent element and `'end'` (sets position at the end of that element),
	 * * {@link module:engine/model/item~Item model item} and `'before'` or `'after'` (sets position before or after given model item).
	 *
	 * This method is a shortcut to other factory methods such as:
	 *
	 * * {@link module:engine/model/position~Position._createBefore},
	 * * {@link module:engine/model/position~Position._createAfter}.
	 *
	 * @internal
	 * @param offset Offset or one of the flags. Used only when the first parameter is a {@link module:engine/model/item~Item model item}.
	 * @param stickiness Position stickiness. Used only when the first parameter is a {@link module:engine/model/item~Item model item}.
	 */ static _createAt(itemOrPosition, offset, stickiness = 'toNone') {
        if (itemOrPosition instanceof Position) {
            return new Position(itemOrPosition.root, itemOrPosition.path, itemOrPosition.stickiness);
        } else {
            const node = itemOrPosition;
            if (offset == 'end') {
                offset = node.maxOffset;
            } else if (offset == 'before') {
                return this._createBefore(node, stickiness);
            } else if (offset == 'after') {
                return this._createAfter(node, stickiness);
            } else if (offset !== 0 && !offset) {
                /**
				 * {@link module:engine/model/model~Model#createPositionAt `Model#createPositionAt()`}
				 * requires the offset to be specified when the first parameter is a model item.
				 *
				 * @error model-createpositionat-offset-required
				 */ throw new CKEditorError('model-createpositionat-offset-required', [
                    this,
                    itemOrPosition
                ]);
            }
            if (!node.is('element') && !node.is('documentFragment')) {
                /**
				 * Position parent have to be a model element or model document fragment.
				 *
				 * @error model-position-parent-incorrect
				 */ throw new CKEditorError('model-position-parent-incorrect', [
                    this,
                    itemOrPosition
                ]);
            }
            const path = node.getPath();
            path.push(offset);
            return new this(node.root, path, stickiness);
        }
    }
    /**
	 * Creates a new position, after given {@link module:engine/model/item~Item model item}.
	 *
	 * @internal
	 * @param item Item after which the position should be placed.
	 * @param stickiness Position stickiness.
	 */ static _createAfter(item, stickiness) {
        if (!item.parent) {
            /**
			 * You can not make a position after a root element.
			 *
			 * @error model-position-after-root
			 * @param root
			 */ throw new CKEditorError('model-position-after-root', [
                this,
                item
            ], {
                root: item
            });
        }
        return this._createAt(item.parent, item.endOffset, stickiness);
    }
    /**
	 * Creates a new position, before the given {@link module:engine/model/item~Item model item}.
	 *
	 * @internal
	 * @param item Item before which the position should be placed.
	 * @param stickiness Position stickiness.
	 */ static _createBefore(item, stickiness) {
        if (!item.parent) {
            /**
			 * You can not make a position before a root element.
			 *
			 * @error model-position-before-root
			 * @param root
			 */ throw new CKEditorError('model-position-before-root', item, {
                root: item
            });
        }
        return this._createAt(item.parent, item.startOffset, stickiness);
    }
    /**
	 * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
	 *
	 * @param json Plain object to be converted to `Position`.
	 * @param doc Document object that will be position owner.
	 * @returns `Position` instance created using given plain object.
	 */ static fromJSON(json, doc) {
        if (json.root === '$graveyard') {
            const pos = new Position(doc.graveyard, json.path);
            pos.stickiness = json.stickiness;
            return pos;
        }
        if (!doc.getRoot(json.root)) {
            /**
			 * Cannot create position for document. Root with specified name does not exist.
			 *
			 * @error model-position-fromjson-no-root
			 * @param rootName
			 */ throw new CKEditorError('model-position-fromjson-no-root', doc, {
                rootName: json.root
            });
        }
        return new Position(doc.getRoot(json.root), json.path, json.stickiness);
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Position.prototype.is = function(type) {
    return type === 'position' || type === 'model:position';
};
/**
 * Returns a text node at the given position.
 *
 * This is a helper function optimized to reuse the position parent instance for performance reasons.
 *
 * Normally, you should use {@link module:engine/model/position~Position#textNode `Position#textNode`}.
 * If you start hitting performance issues with {@link module:engine/model/position~Position#parent `Position#parent`}
 * check if your algorithm does not access it multiple times (which can happen directly or indirectly via other position properties).
 *
 * See https://github.com/ckeditor/ckeditor5/issues/6579.
 *
 * See also:
 *
 * * {@link module:engine/model/position~getNodeAfterPosition}
 * * {@link module:engine/model/position~getNodeBeforePosition}
 *
 * @param positionParent The parent of the given position.
 */ function getTextNodeAtPosition(position, positionParent) {
    const node = positionParent.getChild(positionParent.offsetToIndex(position.offset));
    if (node && node.is('$text') && node.startOffset < position.offset) {
        return node;
    }
    return null;
}
/**
 * Returns the node after the given position.
 *
 * This is a helper function optimized to reuse the position parent instance and the calculation of the text node at the
 * specific position for performance reasons.
 *
 * Normally, you should use {@link module:engine/model/position~Position#nodeAfter `Position#nodeAfter`}.
 * If you start hitting performance issues with {@link module:engine/model/position~Position#parent `Position#parent`} and/or
 * {@link module:engine/model/position~Position#textNode `Position#textNode`}
 * check if your algorithm does not access those properties multiple times
 * (which can happen directly or indirectly via other position properties).
 *
 * See https://github.com/ckeditor/ckeditor5/issues/6579 and https://github.com/ckeditor/ckeditor5/issues/6582.
 *
 * See also:
 *
 * * {@link module:engine/model/position~getTextNodeAtPosition}
 * * {@link module:engine/model/position~getNodeBeforePosition}
 *
 * @param positionParent The parent of the given position.
 * @param textNode Text node at the given position.
 */ function getNodeAfterPosition(position, positionParent, textNode) {
    if (textNode !== null) {
        return null;
    }
    return positionParent.getChild(positionParent.offsetToIndex(position.offset));
}
/**
 * Returns the node before the given position.
 *
 * Refer to {@link module:engine/model/position~getNodeBeforePosition} for documentation on when to use this util method.
 *
 * See also:
 *
 * * {@link module:engine/model/position~getTextNodeAtPosition}
 * * {@link module:engine/model/position~getNodeAfterPosition}
 *
 * @param positionParent The parent of the given position.
 * @param textNode Text node at the given position.
 */ function getNodeBeforePosition(position, positionParent, textNode) {
    if (textNode !== null) {
        return null;
    }
    return positionParent.getChild(positionParent.offsetToIndex(position.offset) - 1);
}
/**
 * This is a helper function for `Position#isTouching()`.
 *
 * It checks whether to given positions are touching, considering that they have the same root and paths
 * until given level, and at given level they differ by 1 (so they are branching at `level` point).
 *
 * The exact requirements for touching positions are described in `Position#isTouching()` and also
 * in the body of this function.
 *
 * @param left Position "on the left" (it is before `right`).
 * @param right Position "on the right" (it is after `left`).
 * @param level Level on which the positions are different.
 */ function checkTouchingBranch(left, right, level) {
    if (level + 1 === left.path.length) {
        // Left position does not have any more entries after the point where the positions differ.
        // [ 2 ] vs [ 3 ]
        // [ 2 ] vs [ 3, 0, 0 ]
        // The positions are spread by node at [ 2 ].
        return false;
    }
    if (!checkOnlyZeroes(right.path, level + 1)) {
        // Right position does not have only zeroes, so we have situation like:
        // [ 2, maxOffset ] vs [ 3, 1 ]
        // [ 2, maxOffset ] vs [ 3, 1, 0, 0 ]
        // The positions are spread by node at [ 3, 0 ].
        return false;
    }
    if (!checkOnlyMaxOffset(left, level + 1)) {
        // Left position does not have only max offsets, so we have situation like:
        // [ 2, 4 ] vs [ 3 ]
        // [ 2, 4 ] vs [ 3, 0, 0 ]
        // The positions are spread by node at [ 2, 5 ].
        return false;
    }
    // Left position has only max offsets and right position has only zeroes or nothing.
    // [ 2, maxOffset ] vs [ 3 ]
    // [ 2, maxOffset, maxOffset ] vs [ 3, 0 ]
    // There are not elements between positions. The positions are touching.
    return true;
}
/**
 * Checks whether for given array, starting from given index until the end of the array, all items are `0`s.
 *
 * This is a helper function for `Position#isTouching()`.
 */ function checkOnlyZeroes(arr, idx) {
    while(idx < arr.length){
        if (arr[idx] !== 0) {
            return false;
        }
        idx++;
    }
    return true;
}
/**
 * Checks whether for given position, starting from given path level, whether the position is at the end of
 * its parent and whether each element on the path to the position is also at at the end of its parent.
 *
 * This is a helper function for `Position#isTouching()`.
 */ function checkOnlyMaxOffset(pos, level) {
    let parent = pos.parent;
    let idx = pos.path.length - 1;
    let add = 0;
    while(idx >= level){
        if (pos.path[idx] + add !== parent.maxOffset) {
            return false;
        }
        // After the first check, we "go up", and check whether the position's parent-parent is the last element.
        // However, we need to add 1 to the value in the path to "simulate" moving the path after the parent.
        // It happens just once.
        add = 1;
        idx--;
        parent = parent.parent;
    }
    return true;
}

/**
 * Represents a range in the model tree.
 *
 * A range is defined by its {@link module:engine/model/range~Range#start} and {@link module:engine/model/range~Range#end}
 * positions.
 *
 * You can create range instances via its constructor or the `createRange*()` factory methods of
 * {@link module:engine/model/model~Model} and {@link module:engine/model/writer~Writer}.
 */ class Range extends TypeCheckable {
    /**
	 * Start position.
	 */ start;
    /**
	 * End position.
	 */ end;
    /**
	 * Creates a range spanning from `start` position to `end` position.
	 *
	 * @param start The start position.
	 * @param end The end position. If not set, the range will be collapsed at the `start` position.
	 */ constructor(start, end){
        super();
        this.start = Position._createAt(start);
        this.end = end ? Position._createAt(end) : Position._createAt(start);
        // If the range is collapsed, treat in a similar way as a position and set its boundaries stickiness to 'toNone'.
        // In other case, make the boundaries stick to the "inside" of the range.
        this.start.stickiness = this.isCollapsed ? 'toNone' : 'toNext';
        this.end.stickiness = this.isCollapsed ? 'toNone' : 'toPrevious';
    }
    /**
	 * Iterable interface.
	 *
	 * Iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
	 * them together with additional information like length or {@link module:engine/model/position~Position positions},
	 * grouped as {@link module:engine/model/treewalker~TreeWalkerValue}.
	 * It iterates over all {@link module:engine/model/textproxy~TextProxy text contents} that are inside the range
	 * and all the {@link module:engine/model/element~Element}s that are entered into when iterating over this range.
	 *
	 * This iterator uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range
	 * and `ignoreElementEnd` option set to `true`.
	 */ *[Symbol.iterator]() {
        yield* new TreeWalker({
            boundaries: this,
            ignoreElementEnd: true
        });
    }
    /**
	 * Describes whether the range is collapsed, that is if {@link #start} and
	 * {@link #end} positions are equal.
	 */ get isCollapsed() {
        return this.start.isEqual(this.end);
    }
    /**
	 * Describes whether this range is flat, that is if {@link #start} position and
	 * {@link #end} position are in the same {@link module:engine/model/position~Position#parent}.
	 */ get isFlat() {
        const startParentPath = this.start.getParentPath();
        const endParentPath = this.end.getParentPath();
        return compareArrays(startParentPath, endParentPath) == 'same';
    }
    /**
	 * Range root element.
	 */ get root() {
        return this.start.root;
    }
    /**
	 * Checks whether this range contains given {@link module:engine/model/position~Position position}.
	 *
	 * @param position Position to check.
	 * @returns `true` if given {@link module:engine/model/position~Position position} is contained
	 * in this range,`false` otherwise.
	 */ containsPosition(position) {
        return position.isAfter(this.start) && position.isBefore(this.end);
    }
    /**
	 * Checks whether this range contains given {@link ~Range range}.
	 *
	 * @param otherRange Range to check.
	 * @param loose Whether the check is loose or strict. If the check is strict (`false`), compared range cannot
	 * start or end at the same position as this range boundaries. If the check is loose (`true`), compared range can start, end or
	 * even be equal to this range. Note that collapsed ranges are always compared in strict mode.
	 * @returns {Boolean} `true` if given {@link ~Range range} boundaries are contained by this range, `false` otherwise.
	 */ containsRange(otherRange, loose = false) {
        if (otherRange.isCollapsed) {
            loose = false;
        }
        const containsStart = this.containsPosition(otherRange.start) || loose && this.start.isEqual(otherRange.start);
        const containsEnd = this.containsPosition(otherRange.end) || loose && this.end.isEqual(otherRange.end);
        return containsStart && containsEnd;
    }
    /**
	 * Checks whether given {@link module:engine/model/item~Item} is inside this range.
	 */ containsItem(item) {
        const pos = Position._createBefore(item);
        return this.containsPosition(pos) || this.start.isEqual(pos);
    }
    /**
	 * Two ranges are equal if their {@link #start} and {@link #end} positions are equal.
	 *
	 * @param otherRange Range to compare with.
	 * @returns `true` if ranges are equal, `false` otherwise.
	 */ isEqual(otherRange) {
        return this.start.isEqual(otherRange.start) && this.end.isEqual(otherRange.end);
    }
    /**
	 * Checks and returns whether this range intersects with given range.
	 *
	 * @param otherRange Range to compare with.
	 * @returns `true` if ranges intersect, `false` otherwise.
	 */ isIntersecting(otherRange) {
        return this.start.isBefore(otherRange.end) && this.end.isAfter(otherRange.start);
    }
    /**
	 * Computes which part(s) of this {@link ~Range range} is not a part of given {@link ~Range range}.
	 * Returned array contains zero, one or two {@link ~Range ranges}.
	 *
	 * Examples:
	 *
	 * ```ts
	 * let range = model.createRange(
	 * 	model.createPositionFromPath( root, [ 2, 7 ] ),
	 * 	model.createPositionFromPath( root, [ 4, 0, 1 ] )
	 * );
	 * let otherRange = model.createRange( model.createPositionFromPath( root, [ 1 ] ), model.createPositionFromPath( root, [ 5 ] ) );
	 * let transformed = range.getDifference( otherRange );
	 * // transformed array has no ranges because `otherRange` contains `range`
	 *
	 * otherRange = model.createRange( model.createPositionFromPath( root, [ 1 ] ), model.createPositionFromPath( root, [ 3 ] ) );
	 * transformed = range.getDifference( otherRange );
	 * // transformed array has one range: from [ 3 ] to [ 4, 0, 1 ]
	 *
	 * otherRange = model.createRange( model.createPositionFromPath( root, [ 3 ] ), model.createPositionFromPath( root, [ 4 ] ) );
	 * transformed = range.getDifference( otherRange );
	 * // transformed array has two ranges: from [ 2, 7 ] to [ 3 ] and from [ 4 ] to [ 4, 0, 1 ]
	 * ```
	 *
	 * @param otherRange Range to differentiate against.
	 * @returns The difference between ranges.
	 */ getDifference(otherRange) {
        const ranges = [];
        if (this.isIntersecting(otherRange)) {
            // Ranges intersect.
            if (this.containsPosition(otherRange.start)) {
                // Given range start is inside this range. This means that we have to
                // add shrunken range - from the start to the middle of this range.
                ranges.push(new Range(this.start, otherRange.start));
            }
            if (this.containsPosition(otherRange.end)) {
                // Given range end is inside this range. This means that we have to
                // add shrunken range - from the middle of this range to the end.
                ranges.push(new Range(otherRange.end, this.end));
            }
        } else {
            // Ranges do not intersect, return the original range.
            ranges.push(new Range(this.start, this.end));
        }
        return ranges;
    }
    /**
	 * Returns an intersection of this {@link ~Range range} and given {@link ~Range range}.
	 * Intersection is a common part of both of those ranges. If ranges has no common part, returns `null`.
	 *
	 * Examples:
	 *
	 * ```ts
	 * let range = model.createRange(
	 * 	model.createPositionFromPath( root, [ 2, 7 ] ),
	 * 	model.createPositionFromPath( root, [ 4, 0, 1 ] )
	 * );
	 * let otherRange = model.createRange( model.createPositionFromPath( root, [ 1 ] ), model.createPositionFromPath( root, [ 2 ] ) );
	 * let transformed = range.getIntersection( otherRange ); // null - ranges have no common part
	 *
	 * otherRange = model.createRange( model.createPositionFromPath( root, [ 3 ] ), model.createPositionFromPath( root, [ 5 ] ) );
	 * transformed = range.getIntersection( otherRange ); // range from [ 3 ] to [ 4, 0, 1 ]
	 * ```
	 *
	 * @param otherRange Range to check for intersection.
	 * @returns A common part of given ranges or `null` if ranges have no common part.
	 */ getIntersection(otherRange) {
        if (this.isIntersecting(otherRange)) {
            // Ranges intersect, so a common range will be returned.
            // At most, it will be same as this range.
            let commonRangeStart = this.start;
            let commonRangeEnd = this.end;
            if (this.containsPosition(otherRange.start)) {
                // Given range start is inside this range. This means thaNt we have to
                // shrink common range to the given range start.
                commonRangeStart = otherRange.start;
            }
            if (this.containsPosition(otherRange.end)) {
                // Given range end is inside this range. This means that we have to
                // shrink common range to the given range end.
                commonRangeEnd = otherRange.end;
            }
            return new Range(commonRangeStart, commonRangeEnd);
        }
        // Ranges do not intersect, so they do not have common part.
        return null;
    }
    /**
	 * Returns a range created by joining this {@link ~Range range} with the given {@link ~Range range}.
	 * If ranges have no common part, returns `null`.
	 *
	 * Examples:
	 *
	 * ```ts
	 * let range = model.createRange(
	 * 	model.createPositionFromPath( root, [ 2, 7 ] ),
	 * 	model.createPositionFromPath( root, [ 4, 0, 1 ] )
	 * );
	 * let otherRange = model.createRange(
	 * 	model.createPositionFromPath( root, [ 1 ] ),
	 * 	model.createPositionFromPath( root, [ 2 ] )
 	 * );
	 * let transformed = range.getJoined( otherRange ); // null - ranges have no common part
	 *
	 * otherRange = model.createRange(
	 * 	model.createPositionFromPath( root, [ 3 ] ),
	 * 	model.createPositionFromPath( root, [ 5 ] )
	 * );
	 * transformed = range.getJoined( otherRange ); // range from [ 2, 7 ] to [ 5 ]
	 * ```
	 *
	 * @param otherRange Range to be joined.
	 * @param loose Whether the intersection check is loose or strict. If the check is strict (`false`),
	 * ranges are tested for intersection or whether start/end positions are equal. If the check is loose (`true`),
	 * compared range is also checked if it's {@link module:engine/model/position~Position#isTouching touching} current range.
	 * @returns A sum of given ranges or `null` if ranges have no common part.
	 */ getJoined(otherRange, loose = false) {
        let shouldJoin = this.isIntersecting(otherRange);
        if (!shouldJoin) {
            if (this.start.isBefore(otherRange.start)) {
                shouldJoin = loose ? this.end.isTouching(otherRange.start) : this.end.isEqual(otherRange.start);
            } else {
                shouldJoin = loose ? otherRange.end.isTouching(this.start) : otherRange.end.isEqual(this.start);
            }
        }
        if (!shouldJoin) {
            return null;
        }
        let startPosition = this.start;
        let endPosition = this.end;
        if (otherRange.start.isBefore(startPosition)) {
            startPosition = otherRange.start;
        }
        if (otherRange.end.isAfter(endPosition)) {
            endPosition = otherRange.end;
        }
        return new Range(startPosition, endPosition);
    }
    /**
	 * Computes and returns the smallest set of {@link #isFlat flat} ranges, that covers this range in whole.
	 *
	 * See an example of a model structure (`[` and `]` are range boundaries):
	 *
	 * ```
	 * root                                                            root
	 *  |- element DIV                         DIV             P2              P3             DIV
	 *  |   |- element H                   H        P1        f o o           b a r       H         P4
	 *  |   |   |- "fir[st"             fir[st     lorem                               se]cond     ipsum
	 *  |   |- element P1
	 *  |   |   |- "lorem"                                              ||
	 *  |- element P2                                                   ||
	 *  |   |- "foo"                                                    VV
	 *  |- element P3
	 *  |   |- "bar"                                                   root
	 *  |- element DIV                         DIV             [P2             P3]             DIV
	 *  |   |- element H                   H       [P1]       f o o           b a r        H         P4
	 *  |   |   |- "se]cond"            fir[st]    lorem                               [se]cond     ipsum
	 *  |   |- element P4
	 *  |   |   |- "ipsum"
	 * ```
	 *
	 * As it can be seen, letters contained in the range are: `stloremfoobarse`, spread across different parents.
	 * We are looking for minimal set of flat ranges that contains the same nodes.
	 *
	 * Minimal flat ranges for above range `( [ 0, 0, 3 ], [ 3, 0, 2 ] )` will be:
	 *
	 * ```
	 * ( [ 0, 0, 3 ], [ 0, 0, 5 ] ) = "st"
	 * ( [ 0, 1 ], [ 0, 2 ] ) = element P1 ("lorem")
	 * ( [ 1 ], [ 3 ] ) = element P2, element P3 ("foobar")
	 * ( [ 3, 0, 0 ], [ 3, 0, 2 ] ) = "se"
	 * ```
	 *
	 * **Note:** if an {@link module:engine/model/element~Element element} is not wholly contained in this range, it won't be returned
	 * in any of the returned flat ranges. See in the example how `H` elements at the beginning and at the end of the range
	 * were omitted. Only their parts that were wholly in the range were returned.
	 *
	 * **Note:** this method is not returning flat ranges that contain no nodes.
	 *
	 * @returns Array of flat ranges covering this range.
	 */ getMinimalFlatRanges() {
        const ranges = [];
        const diffAt = this.start.getCommonPath(this.end).length;
        const pos = Position._createAt(this.start);
        let posParent = pos.parent;
        // Go up.
        while(pos.path.length > diffAt + 1){
            const howMany = posParent.maxOffset - pos.offset;
            if (howMany !== 0) {
                ranges.push(new Range(pos, pos.getShiftedBy(howMany)));
            }
            pos.path = pos.path.slice(0, -1);
            pos.offset++;
            posParent = posParent.parent;
        }
        // Go down.
        while(pos.path.length <= this.end.path.length){
            const offset = this.end.path[pos.path.length - 1];
            const howMany = offset - pos.offset;
            if (howMany !== 0) {
                ranges.push(new Range(pos, pos.getShiftedBy(howMany)));
            }
            pos.offset = offset;
            pos.path.push(0);
        }
        return ranges;
    }
    /**
	 * Creates a {@link module:engine/model/treewalker~TreeWalker TreeWalker} instance with this range as a boundary.
	 *
	 * For example, to iterate over all items in the entire document root:
	 *
	 * ```ts
	 * // Create a range spanning over the entire root content:
	 * const range = editor.model.createRangeIn( editor.model.document.getRoot() );
	 *
	 * // Iterate over all items in this range:
	 * for ( const value of range.getWalker() ) {
	 * 	console.log( value.item );
	 * }
	 * ```
	 *
	 * @param options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
	 */ getWalker(options = {}) {
        options.boundaries = this;
        return new TreeWalker(options);
    }
    /**
	 * Returns an iterator that iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
	 * them.
	 *
	 * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range and `ignoreElementEnd` option
	 * set to `true`. However it returns only {@link module:engine/model/item~Item model items},
	 * not {@link module:engine/model/treewalker~TreeWalkerValue}.
	 *
	 * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
	 * a full list of available options.
	 *
	 * @param options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
	 */ *getItems(options = {}) {
        options.boundaries = this;
        options.ignoreElementEnd = true;
        const treeWalker = new TreeWalker(options);
        for (const value of treeWalker){
            yield value.item;
        }
    }
    /**
	 * Returns an iterator that iterates over all {@link module:engine/model/position~Position positions} that are boundaries or
	 * contained in this range.
	 *
	 * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range. However it returns only
	 * {@link module:engine/model/position~Position positions}, not {@link module:engine/model/treewalker~TreeWalkerValue}.
	 *
	 * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
	 * a full list of available options.
	 *
	 * @param options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
	 */ *getPositions(options = {}) {
        options.boundaries = this;
        const treeWalker = new TreeWalker(options);
        yield treeWalker.position;
        for (const value of treeWalker){
            yield value.nextPosition;
        }
    }
    /**
	 * Returns a range that is a result of transforming this range by given `operation`.
	 *
	 * **Note:** transformation may break one range into multiple ranges (for example, when a part of the range is
	 * moved to a different part of document tree). For this reason, an array is returned by this method and it
	 * may contain one or more `Range` instances.
	 *
	 * @param operation Operation to transform range by.
	 * @returns Range which is the result of transformation.
	 */ getTransformedByOperation(operation) {
        switch(operation.type){
            case 'insert':
                return this._getTransformedByInsertOperation(operation);
            case 'move':
            case 'remove':
            case 'reinsert':
                return this._getTransformedByMoveOperation(operation);
            case 'split':
                return [
                    this._getTransformedBySplitOperation(operation)
                ];
            case 'merge':
                return [
                    this._getTransformedByMergeOperation(operation)
                ];
        }
        return [
            new Range(this.start, this.end)
        ];
    }
    /**
	 * Returns a range that is a result of transforming this range by multiple `operations`.
	 *
	 * @see ~Range#getTransformedByOperation
	 * @param operations Operations to transform the range by.
	 * @returns Range which is the result of transformation.
	 */ getTransformedByOperations(operations) {
        const ranges = [
            new Range(this.start, this.end)
        ];
        for (const operation of operations){
            for(let i = 0; i < ranges.length; i++){
                const result = ranges[i].getTransformedByOperation(operation);
                ranges.splice(i, 1, ...result);
                i += result.length - 1;
            }
        }
        // It may happen that a range is split into two, and then the part of second "piece" is moved into first
        // "piece". In this case we will have incorrect third range, which should not be included in the result --
        // because it is already included in the first "piece". In this loop we are looking for all such ranges that
        // are inside other ranges and we simply remove them.
        for(let i = 0; i < ranges.length; i++){
            const range = ranges[i];
            for(let j = i + 1; j < ranges.length; j++){
                const next = ranges[j];
                if (range.containsRange(next) || next.containsRange(range) || range.isEqual(next)) {
                    ranges.splice(j, 1);
                }
            }
        }
        return ranges;
    }
    /**
	 * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
	 * which is a common ancestor of the range's both ends (in which the entire range is contained).
	 */ getCommonAncestor() {
        return this.start.getCommonAncestor(this.end);
    }
    /**
	 * Returns an {@link module:engine/model/element~Element Element} contained by the range.
	 * The element will be returned when it is the **only** node within the range and **fully–contained**
	 * at the same time.
	 */ getContainedElement() {
        if (this.isCollapsed) {
            return null;
        }
        const nodeAfterStart = this.start.nodeAfter;
        const nodeBeforeEnd = this.end.nodeBefore;
        if (nodeAfterStart && nodeAfterStart.is('element') && nodeAfterStart === nodeBeforeEnd) {
            return nodeAfterStart;
        }
        return null;
    }
    /**
	 * Converts `Range` to plain object and returns it.
	 *
	 * @returns `Node` converted to plain object.
	 */ toJSON() {
        return {
            start: this.start.toJSON(),
            end: this.end.toJSON()
        };
    }
    /**
	 * Returns a new range that is equal to current range.
	 */ clone() {
        return new this.constructor(this.start, this.end);
    }
    /**
	 * Returns a result of transforming a copy of this range by insert operation.
	 *
	 * One or more ranges may be returned as a result of this transformation.
	 *
	 * @internal
	 */ _getTransformedByInsertOperation(operation, spread = false) {
        return this._getTransformedByInsertion(operation.position, operation.howMany, spread);
    }
    /**
	 * Returns a result of transforming a copy of this range by move operation.
	 *
	 * One or more ranges may be returned as a result of this transformation.
	 *
	 * @internal
	 */ _getTransformedByMoveOperation(operation, spread = false) {
        const sourcePosition = operation.sourcePosition;
        const howMany = operation.howMany;
        const targetPosition = operation.targetPosition;
        return this._getTransformedByMove(sourcePosition, targetPosition, howMany, spread);
    }
    /**
	 * Returns a result of transforming a copy of this range by split operation.
	 *
	 * Always one range is returned. The transformation is done in a way to not break the range.
	 *
	 * @internal
	 */ _getTransformedBySplitOperation(operation) {
        const start = this.start._getTransformedBySplitOperation(operation);
        let end = this.end._getTransformedBySplitOperation(operation);
        if (this.end.isEqual(operation.insertionPosition)) {
            end = this.end.getShiftedBy(1);
        }
        // Below may happen when range contains graveyard element used by split operation.
        if (start.root != end.root) {
            // End position was next to the moved graveyard element and was moved with it.
            // Fix it by using old `end` which has proper `root`.
            end = this.end.getShiftedBy(-1);
        }
        return new Range(start, end);
    }
    /**
	 * Returns a result of transforming a copy of this range by merge operation.
	 *
	 * Always one range is returned. The transformation is done in a way to not break the range.
	 *
	 * @internal
	 */ _getTransformedByMergeOperation(operation) {
        // Special case when the marker is set on "the closing tag" of an element. Marker can be set like that during
        // transformations, especially when a content of a few block elements were removed. For example:
        //
        // {} is the transformed range, [] is the removed range.
        // <p>F[o{o</p><p>B}ar</p><p>Xy]z</p>
        //
        // <p>Fo{o</p><p>B}ar</p><p>z</p>
        // <p>F{</p><p>B}ar</p><p>z</p>
        // <p>F{</p>}<p>z</p>
        // <p>F{}z</p>
        //
        if (this.start.isEqual(operation.targetPosition) && this.end.isEqual(operation.deletionPosition)) {
            return new Range(this.start);
        }
        let start = this.start._getTransformedByMergeOperation(operation);
        let end = this.end._getTransformedByMergeOperation(operation);
        if (start.root != end.root) {
            // This happens when the end position was next to the merged (deleted) element.
            // Then, the end position was moved to the graveyard root. In this case we need to fix
            // the range cause its boundaries would be in different roots.
            end = this.end.getShiftedBy(-1);
        }
        if (start.isAfter(end)) {
            // This happens in three following cases:
            //
            // Case 1: Merge operation source position is before the target position (due to some transformations, OT, etc.)
            //         This means that start can be moved before the end of the range.
            //
            // Before: <p>a{a</p><p>b}b</p><p>cc</p>
            // Merge:  <p>b}b</p><p>cca{a</p>
            // Fix:    <p>{b}b</p><p>ccaa</p>
            //
            // Case 2: Range start is before merged node but not directly.
            //         Result should include all nodes that were in the original range.
            //
            // Before: <p>aa</p>{<p>cc</p><p>b}b</p>
            // Merge:  <p>aab}b</p>{<p>cc</p>
            // Fix:    <p>aa{bb</p><p>cc</p>}
            //
            //         The range is expanded by an additional `b` letter but it is better than dropping the whole `cc` paragraph.
            //
            // Case 3: Range start is directly before merged node.
            //         Resulting range should include only nodes from the merged element:
            //
            // Before: <p>aa</p>{<p>b}b</p><p>cc</p>
            // Merge:  <p>aab}b</p>{<p>cc</p>
            // Fix:    <p>aa{b}b</p><p>cc</p>
            //
            if (operation.sourcePosition.isBefore(operation.targetPosition)) {
                // Case 1.
                start = Position._createAt(end);
                start.offset = 0;
            } else {
                if (!operation.deletionPosition.isEqual(start)) {
                    // Case 2.
                    end = operation.deletionPosition;
                }
                // In both case 2 and 3 start is at the end of the merge-to element.
                start = operation.targetPosition;
            }
            return new Range(start, end);
        }
        return new Range(start, end);
    }
    /**
	 * Returns an array containing one or two {@link ~Range ranges} that are a result of transforming this
	 * {@link ~Range range} by inserting `howMany` nodes at `insertPosition`. Two {@link ~Range ranges} are
	 * returned if the insertion was inside this {@link ~Range range} and `spread` is set to `true`.
	 *
	 * Examples:
	 *
	 * ```ts
	 * let range = model.createRange(
	 * 	model.createPositionFromPath( root, [ 2, 7 ] ),
	 * 	model.createPositionFromPath( root, [ 4, 0, 1 ] )
	 * );
	 * let transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 1 ] ), 2 );
	 * // transformed array has one range from [ 4, 7 ] to [ 6, 0, 1 ]
	 *
	 * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 4, 0, 0 ] ), 4 );
	 * // transformed array has one range from [ 2, 7 ] to [ 4, 0, 5 ]
	 *
	 * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 3, 2 ] ), 4 );
	 * // transformed array has one range, which is equal to original range
	 *
	 * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 3, 2 ] ), 4, true );
	 * // transformed array has two ranges: from [ 2, 7 ] to [ 3, 2 ] and from [ 3, 6 ] to [ 4, 0, 1 ]
	 * ```
	 *
	 * @internal
	 * @param insertPosition Position where nodes are inserted.
	 * @param howMany How many nodes are inserted.
	 * @param spread Flag indicating whether this range should be spread if insertion
	 * was inside the range. Defaults to `false`.
	 * @returns Result of the transformation.
	 */ _getTransformedByInsertion(insertPosition, howMany, spread = false) {
        if (spread && this.containsPosition(insertPosition)) {
            // Range has to be spread. The first part is from original start to the spread point.
            // The other part is from spread point to the original end, but transformed by
            // insertion to reflect insertion changes.
            return [
                new Range(this.start, insertPosition),
                new Range(insertPosition.getShiftedBy(howMany), this.end._getTransformedByInsertion(insertPosition, howMany))
            ];
        } else {
            const range = new Range(this.start, this.end);
            range.start = range.start._getTransformedByInsertion(insertPosition, howMany);
            range.end = range.end._getTransformedByInsertion(insertPosition, howMany);
            return [
                range
            ];
        }
    }
    /**
	 * Returns an array containing {@link ~Range ranges} that are a result of transforming this
	 * {@link ~Range range} by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
	 *
	 * @internal
	 * @param sourcePosition Position from which nodes are moved.
	 * @param targetPosition Position to where nodes are moved.
	 * @param howMany How many nodes are moved.
	 * @param spread Whether the range should be spread if the move points inside the range.
	 * @returns  Result of the transformation.
	 */ _getTransformedByMove(sourcePosition, targetPosition, howMany, spread = false) {
        // Special case for transforming a collapsed range. Just transform it like a position.
        if (this.isCollapsed) {
            const newPos = this.start._getTransformedByMove(sourcePosition, targetPosition, howMany);
            return [
                new Range(newPos)
            ];
        }
        // Special case for transformation when a part of the range is moved towards the range.
        //
        // Examples:
        //
        // <div><p>ab</p><p>c[d</p></div><p>e]f</p> --> <div><p>ab</p></div><p>c[d</p><p>e]f</p>
        // <p>e[f</p><div><p>a]b</p><p>cd</p></div> --> <p>e[f</p><p>a]b</p><div><p>cd</p></div>
        //
        // Without this special condition, the default algorithm leaves an "artifact" range from one of `differenceSet` parts:
        //
        // <div><p>ab</p><p>c[d</p></div><p>e]f</p> --> <div><p>ab</p>{</div>}<p>c[d</p><p>e]f</p>
        //
        // This special case is applied only if the range is to be kept together (not spread).
        const moveRange = Range._createFromPositionAndShift(sourcePosition, howMany);
        const insertPosition = targetPosition._getTransformedByDeletion(sourcePosition, howMany);
        if (this.containsPosition(targetPosition) && !spread) {
            if (moveRange.containsPosition(this.start) || moveRange.containsPosition(this.end)) {
                const start = this.start._getTransformedByMove(sourcePosition, targetPosition, howMany);
                const end = this.end._getTransformedByMove(sourcePosition, targetPosition, howMany);
                return [
                    new Range(start, end)
                ];
            }
        }
        // Default algorithm.
        let result;
        const differenceSet = this.getDifference(moveRange);
        let difference = null;
        const common = this.getIntersection(moveRange);
        if (differenceSet.length == 1) {
            // `moveRange` and this range may intersect but may be separate.
            difference = new Range(differenceSet[0].start._getTransformedByDeletion(sourcePosition, howMany), differenceSet[0].end._getTransformedByDeletion(sourcePosition, howMany));
        } else if (differenceSet.length == 2) {
            // `moveRange` is inside this range.
            difference = new Range(this.start, this.end._getTransformedByDeletion(sourcePosition, howMany));
        } // else, `moveRange` contains this range.
        if (difference) {
            result = difference._getTransformedByInsertion(insertPosition, howMany, common !== null || spread);
        } else {
            result = [];
        }
        if (common) {
            const transformedCommon = new Range(common.start._getCombined(moveRange.start, insertPosition), common.end._getCombined(moveRange.start, insertPosition));
            if (result.length == 2) {
                result.splice(1, 0, transformedCommon);
            } else {
                result.push(transformedCommon);
            }
        }
        return result;
    }
    /**
	 * Returns a copy of this range that is transformed by deletion of `howMany` nodes from `deletePosition`.
	 *
	 * If the deleted range is intersecting with the transformed range, the transformed range will be shrank.
	 *
	 * If the deleted range contains transformed range, `null` will be returned.
	 *
	 * @internal
	 * @param deletionPosition Position from which nodes are removed.
	 * @param howMany How many nodes are removed.
	 * @returns Result of the transformation.
	 */ _getTransformedByDeletion(deletePosition, howMany) {
        let newStart = this.start._getTransformedByDeletion(deletePosition, howMany);
        let newEnd = this.end._getTransformedByDeletion(deletePosition, howMany);
        if (newStart == null && newEnd == null) {
            return null;
        }
        if (newStart == null) {
            newStart = deletePosition;
        }
        if (newEnd == null) {
            newEnd = deletePosition;
        }
        return new Range(newStart, newEnd);
    }
    /**
	 * Creates a new range, spreading from specified {@link module:engine/model/position~Position position} to a position moved by
	 * given `shift`. If `shift` is a negative value, shifted position is treated as the beginning of the range.
	 *
	 * @internal
	 * @param position Beginning of the range.
	 * @param shift How long the range should be.
	 */ static _createFromPositionAndShift(position, shift) {
        const start = position;
        const end = position.getShiftedBy(shift);
        return shift > 0 ? new this(start, end) : new this(end, start);
    }
    /**
	 * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
	 * that element and ends after the last child of that element.
	 *
	 * @internal
	 * @param element Element which is a parent for the range.
	 */ static _createIn(element) {
        return new this(Position._createAt(element, 0), Position._createAt(element, element.maxOffset));
    }
    /**
	 * Creates a range that starts before given {@link module:engine/model/item~Item model item} and ends after it.
	 *
	 * @internal
	 */ static _createOn(item) {
        return this._createFromPositionAndShift(Position._createBefore(item), item.offsetSize);
    }
    /**
	 * Combines all ranges from the passed array into a one range. At least one range has to be passed.
	 * Passed ranges must not have common parts.
	 *
	 * The first range from the array is a reference range. If other ranges start or end on the exactly same position where
	 * the reference range, they get combined into one range.
	 *
	 * ```
	 * [  ][]  [    ][ ][             ][ ][]  [  ]  // Passed ranges, shown sorted
	 * [    ]                                       // The result of the function if the first range was a reference range.
	 *         [                           ]        // The result of the function if the third-to-seventh range was a reference range.
	 *                                        [  ]  // The result of the function if the last range was a reference range.
	 * ```
	 *
	 * @internal
	 * @param ranges Ranges to combine.
	 * @returns Combined range.
	 */ static _createFromRanges(ranges) {
        if (ranges.length === 0) {
            /**
			 * At least one range has to be passed to
			 * {@link module:engine/model/range~Range._createFromRanges `Range._createFromRanges()`}.
			 *
			 * @error range-create-from-ranges-empty-array
			 */ throw new CKEditorError('range-create-from-ranges-empty-array', null);
        } else if (ranges.length == 1) {
            return ranges[0].clone();
        }
        // 1. Set the first range in `ranges` array as a reference range.
        // If we are going to return just a one range, one of the ranges need to be the reference one.
        // Other ranges will be stuck to that range, if possible.
        const ref = ranges[0];
        // 2. Sort all the ranges so it's easier to process them.
        ranges.sort((a, b)=>{
            return a.start.isAfter(b.start) ? 1 : -1;
        });
        // 3. Check at which index the reference range is now.
        const refIndex = ranges.indexOf(ref);
        // 4. At this moment we don't need the original range.
        // We are going to modify the result and we need to return a new instance of Range.
        // We have to create a copy of the reference range.
        const result = new this(ref.start, ref.end);
        // 5. Ranges should be checked and glued starting from the range that is closest to the reference range.
        // Since ranges are sorted, start with the range with index that is closest to reference range index.
        if (refIndex > 0) {
            // eslint-disable-next-line no-constant-condition
            for(let i = refIndex - 1; true; i++){
                if (ranges[i].end.isEqual(result.start)) {
                    result.start = Position._createAt(ranges[i].start);
                } else {
                    break;
                }
            }
        }
        // 6. Ranges should be checked and glued starting from the range that is closest to the reference range.
        // Since ranges are sorted, start with the range with index that is closest to reference range index.
        for(let i = refIndex + 1; i < ranges.length; i++){
            if (ranges[i].start.isEqual(result.end)) {
                result.end = Position._createAt(ranges[i].end);
            } else {
                break;
            }
        }
        return result;
    }
    /**
	 * Creates a `Range` instance from given plain object (i.e. parsed JSON string).
	 *
	 * @param json Plain object to be converted to `Range`.
	 * @param doc Document object that will be range owner.
	 * @returns `Range` instance created using given plain object.
	 */ static fromJSON(json, doc) {
        return new this(Position.fromJSON(json.start, doc), Position.fromJSON(json.end, doc));
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Range.prototype.is = function(type) {
    return type === 'range' || type === 'model:range';
};

/**
 * Maps elements, positions and markers between the {@link module:engine/view/document~Document view} and
 * the {@link module:engine/model/model model}.
 *
 * The instance of the Mapper used for the editing pipeline is available in
 * {@link module:engine/controller/editingcontroller~EditingController#mapper `editor.editing.mapper`}.
 *
 * Mapper uses bound elements to find corresponding elements and positions, so, to get proper results,
 * all model elements should be {@link module:engine/conversion/mapper~Mapper#bindElements bound}.
 *
 * To map the complex model to/from view relations, you may provide custom callbacks for the
 * {@link module:engine/conversion/mapper~Mapper#event:modelToViewPosition modelToViewPosition event} and
 * {@link module:engine/conversion/mapper~Mapper#event:viewToModelPosition viewToModelPosition event} that are fired whenever
 * a position mapping request occurs.
 * Those events are fired by the {@link module:engine/conversion/mapper~Mapper#toViewPosition toViewPosition}
 * and {@link module:engine/conversion/mapper~Mapper#toModelPosition toModelPosition} methods. `Mapper` adds its own default callbacks
 * with `'lowest'` priority. To override default `Mapper` mapping, add custom callback with higher priority and
 * stop the event.
 */ class Mapper extends /* #__PURE__ */ EmitterMixin() {
    /**
	 * Model element to view element mapping.
	 */ _modelToViewMapping = new WeakMap();
    /**
	 * View element to model element mapping.
	 */ _viewToModelMapping = new WeakMap();
    /**
	 * A map containing callbacks between view element names and functions evaluating length of view elements
	 * in model.
	 */ _viewToModelLengthCallbacks = new Map();
    /**
	 * Model marker name to view elements mapping.
	 *
	 * Keys are `String`s while values are `Set`s with {@link module:engine/view/element~Element view elements}.
	 * One marker (name) can be mapped to multiple elements.
	 */ _markerNameToElements = new Map();
    /**
	 * View element to model marker names mapping.
	 *
	 * This is reverse to {@link ~Mapper#_markerNameToElements} map.
	 */ _elementToMarkerNames = new Map();
    /**
	 * The map of removed view elements with their current root (used for deferred unbinding).
	 */ _deferredBindingRemovals = new Map();
    /**
	 * Stores marker names of markers which have changed due to unbinding a view element (so it is assumed that the view element
	 * has been removed, moved or renamed).
	 */ _unboundMarkerNames = new Set();
    /**
	 * Creates an instance of the mapper.
	 */ constructor(){
        super();
        // Default mapper algorithm for mapping model position to view position.
        this.on('modelToViewPosition', (evt, data)=>{
            if (data.viewPosition) {
                return;
            }
            const viewContainer = this._modelToViewMapping.get(data.modelPosition.parent);
            if (!viewContainer) {
                /**
				 * A model position could not be mapped to the view because the parent of the model position
				 * does not have a mapped view element (might have not been converted yet or it has no converter).
				 *
				 * Make sure that the model element is correctly converted to the view.
				 *
				 * @error mapping-model-position-view-parent-not-found
				 */ throw new CKEditorError('mapping-model-position-view-parent-not-found', this, {
                    modelPosition: data.modelPosition
                });
            }
            data.viewPosition = this.findPositionIn(viewContainer, data.modelPosition.offset);
        }, {
            priority: 'low'
        });
        // Default mapper algorithm for mapping view position to model position.
        this.on('viewToModelPosition', (evt, data)=>{
            if (data.modelPosition) {
                return;
            }
            const viewBlock = this.findMappedViewAncestor(data.viewPosition);
            const modelParent = this._viewToModelMapping.get(viewBlock);
            const modelOffset = this._toModelOffset(data.viewPosition.parent, data.viewPosition.offset, viewBlock);
            data.modelPosition = Position._createAt(modelParent, modelOffset);
        }, {
            priority: 'low'
        });
    }
    /**
	 * Marks model and view elements as corresponding. Corresponding elements can be retrieved by using
	 * the {@link module:engine/conversion/mapper~Mapper#toModelElement toModelElement} and
	 * {@link module:engine/conversion/mapper~Mapper#toViewElement toViewElement} methods.
	 * The information that elements are bound is also used to translate positions.
	 *
	 * @param modelElement Model element.
	 * @param viewElement View element.
	 */ bindElements(modelElement, viewElement) {
        this._modelToViewMapping.set(modelElement, viewElement);
        this._viewToModelMapping.set(viewElement, modelElement);
    }
    /**
	 * Unbinds the given {@link module:engine/view/element~Element view element} from the map.
	 *
	 * **Note:** view-to-model binding will be removed, if it existed. However, corresponding model-to-view binding
	 * will be removed only if model element is still bound to the passed `viewElement`.
	 *
	 * This behavior allows for re-binding model element to another view element without fear of losing the new binding
	 * when the previously bound view element is unbound.
	 *
	 * @param viewElement View element to unbind.
	 * @param options The options object.
	 * @param options.defer Controls whether the binding should be removed immediately or deferred until a
	 * {@link #flushDeferredBindings `flushDeferredBindings()`} call.
	 */ unbindViewElement(viewElement, options = {}) {
        const modelElement = this.toModelElement(viewElement);
        if (this._elementToMarkerNames.has(viewElement)) {
            for (const markerName of this._elementToMarkerNames.get(viewElement)){
                this._unboundMarkerNames.add(markerName);
            }
        }
        if (options.defer) {
            this._deferredBindingRemovals.set(viewElement, viewElement.root);
        } else {
            this._viewToModelMapping.delete(viewElement);
            if (this._modelToViewMapping.get(modelElement) == viewElement) {
                this._modelToViewMapping.delete(modelElement);
            }
        }
    }
    /**
	 * Unbinds the given {@link module:engine/model/element~Element model element} from the map.
	 *
	 * **Note:** the model-to-view binding will be removed, if it existed. However, the corresponding view-to-model binding
	 * will be removed only if the view element is still bound to the passed `modelElement`.
	 *
	 * This behavior lets for re-binding view element to another model element without fear of losing the new binding
	 * when the previously bound model element is unbound.
	 *
	 * @param modelElement Model element to unbind.
	 */ unbindModelElement(modelElement) {
        const viewElement = this.toViewElement(modelElement);
        this._modelToViewMapping.delete(modelElement);
        if (this._viewToModelMapping.get(viewElement) == modelElement) {
            this._viewToModelMapping.delete(viewElement);
        }
    }
    /**
	 * Binds the given marker name with the given {@link module:engine/view/element~Element view element}. The element
	 * will be added to the current set of elements bound with the given marker name.
	 *
	 * @param element Element to bind.
	 * @param name Marker name.
	 */ bindElementToMarker(element, name) {
        const elements = this._markerNameToElements.get(name) || new Set();
        elements.add(element);
        const names = this._elementToMarkerNames.get(element) || new Set();
        names.add(name);
        this._markerNameToElements.set(name, elements);
        this._elementToMarkerNames.set(element, names);
    }
    /**
	 * Unbinds an element from given marker name.
	 *
	 * @param element Element to unbind.
	 * @param name Marker name.
	 */ unbindElementFromMarkerName(element, name) {
        const nameToElements = this._markerNameToElements.get(name);
        if (nameToElements) {
            nameToElements.delete(element);
            if (nameToElements.size == 0) {
                this._markerNameToElements.delete(name);
            }
        }
        const elementToNames = this._elementToMarkerNames.get(element);
        if (elementToNames) {
            elementToNames.delete(name);
            if (elementToNames.size == 0) {
                this._elementToMarkerNames.delete(element);
            }
        }
    }
    /**
	 * Returns all marker names of markers which have changed due to unbinding a view element (so it is assumed that the view element
	 * has been removed, moved or renamed) since the last flush. After returning, the marker names list is cleared.
	 */ flushUnboundMarkerNames() {
        const markerNames = Array.from(this._unboundMarkerNames);
        this._unboundMarkerNames.clear();
        return markerNames;
    }
    /**
	 * Unbinds all deferred binding removals of view elements that in the meantime were not re-attached to some root or document fragment.
	 *
	 * See: {@link #unbindViewElement `unbindViewElement()`}.
	 */ flushDeferredBindings() {
        for (const [viewElement, root] of this._deferredBindingRemovals){
            // Unbind it only if it wasn't re-attached to some root or document fragment.
            if (viewElement.root == root) {
                this.unbindViewElement(viewElement);
            }
        }
        this._deferredBindingRemovals = new Map();
    }
    /**
	 * Removes all model to view and view to model bindings.
	 */ clearBindings() {
        this._modelToViewMapping = new WeakMap();
        this._viewToModelMapping = new WeakMap();
        this._markerNameToElements = new Map();
        this._elementToMarkerNames = new Map();
        this._unboundMarkerNames = new Set();
        this._deferredBindingRemovals = new Map();
    }
    toModelElement(viewElement) {
        return this._viewToModelMapping.get(viewElement);
    }
    toViewElement(modelElement) {
        return this._modelToViewMapping.get(modelElement);
    }
    /**
	 * Gets the corresponding model range.
	 *
	 * @param viewRange View range.
	 * @returns Corresponding model range.
	 */ toModelRange(viewRange) {
        return new Range(this.toModelPosition(viewRange.start), this.toModelPosition(viewRange.end));
    }
    /**
	 * Gets the corresponding view range.
	 *
	 * @param modelRange Model range.
	 * @returns Corresponding view range.
	 */ toViewRange(modelRange) {
        return new Range$1(this.toViewPosition(modelRange.start), this.toViewPosition(modelRange.end));
    }
    /**
	 * Gets the corresponding model position.
	 *
	 * @fires viewToModelPosition
	 * @param viewPosition View position.
	 * @returns Corresponding model position.
	 */ toModelPosition(viewPosition) {
        const data = {
            viewPosition,
            mapper: this
        };
        this.fire('viewToModelPosition', data);
        return data.modelPosition;
    }
    /**
	 * Gets the corresponding view position.
	 *
	 * @fires modelToViewPosition
	 * @param modelPosition Model position.
	 * @param options Additional options for position mapping process.
	 * @param options.isPhantom Should be set to `true` if the model position to map is pointing to a place
	 * in model tree which no longer exists. For example, it could be an end of a removed model range.
	 * @returns Corresponding view position.
	 */ toViewPosition(modelPosition, options = {}) {
        const data = {
            modelPosition,
            mapper: this,
            isPhantom: options.isPhantom
        };
        this.fire('modelToViewPosition', data);
        return data.viewPosition;
    }
    /**
	 * Gets all view elements bound to the given marker name.
	 *
	 * @param name Marker name.
	 * @returns View elements bound with the given marker name or `null`
	 * if no elements are bound to the given marker name.
	 */ markerNameToElements(name) {
        const boundElements = this._markerNameToElements.get(name);
        if (!boundElements) {
            return null;
        }
        const elements = new Set();
        for (const element of boundElements){
            if (element.is('attributeElement')) {
                for (const clone of element.getElementsWithSameId()){
                    elements.add(clone);
                }
            } else {
                elements.add(element);
            }
        }
        return elements;
    }
    /**
	 * Registers a callback that evaluates the length in the model of a view element with the given name.
	 *
	 * The callback is fired with one argument, which is a view element instance. The callback is expected to return
	 * a number representing the length of the view element in the model.
	 *
	 * ```ts
	 * // List item in view may contain nested list, which have other list items. In model though,
	 * // the lists are represented by flat structure. Because of those differences, length of list view element
	 * // may be greater than one. In the callback it's checked how many nested list items are in evaluated list item.
	 *
	 * function getViewListItemLength( element ) {
	 * 	let length = 1;
	 *
	 * 	for ( let child of element.getChildren() ) {
	 * 		if ( child.name == 'ul' || child.name == 'ol' ) {
	 * 			for ( let item of child.getChildren() ) {
	 * 				length += getViewListItemLength( item );
	 * 			}
	 * 		}
	 * 	}
	 *
	 * 	return length;
	 * }
	 *
	 * mapper.registerViewToModelLength( 'li', getViewListItemLength );
	 * ```
	 *
	 * @param viewElementName Name of view element for which callback is registered.
	 * @param lengthCallback Function return a length of view element instance in model.
	 */ registerViewToModelLength(viewElementName, lengthCallback) {
        this._viewToModelLengthCallbacks.set(viewElementName, lengthCallback);
    }
    /**
	 * For the given `viewPosition`, finds and returns the closest ancestor of this position that has a mapping to
	 * the model.
	 *
	 * @param viewPosition Position for which a mapped ancestor should be found.
	 */ findMappedViewAncestor(viewPosition) {
        let parent = viewPosition.parent;
        while(!this._viewToModelMapping.has(parent)){
            parent = parent.parent;
        }
        return parent;
    }
    /**
	 * Calculates model offset based on the view position and the block element.
	 *
	 * Example:
	 *
	 * ```html
	 * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, p ) -> 5
	 * ```
	 *
	 * Is a sum of:
	 *
	 * ```html
	 * <p>foo|<b>bar</b></p> // _toModelOffset( p, 3, p ) -> 3
	 * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, b ) -> 2
	 * ```
	 *
	 * @param viewParent Position parent.
	 * @param viewOffset Position offset.
	 * @param viewBlock Block used as a base to calculate offset.
	 * @returns Offset in the model.
	 */ _toModelOffset(viewParent, viewOffset, viewBlock) {
        if (viewBlock != viewParent) {
            // See example.
            const offsetToParentStart = this._toModelOffset(viewParent.parent, viewParent.index, viewBlock);
            const offsetInParent = this._toModelOffset(viewParent, viewOffset, viewParent);
            return offsetToParentStart + offsetInParent;
        }
        // viewBlock == viewParent, so we need to calculate the offset in the parent element.
        // If the position is a text it is simple ("ba|r" -> 2).
        if (viewParent.is('$text')) {
            return viewOffset;
        }
        // If the position is in an element we need to sum lengths of siblings ( <b> bar </b> foo | -> 3 + 3 = 6 ).
        let modelOffset = 0;
        for(let i = 0; i < viewOffset; i++){
            modelOffset += this.getModelLength(viewParent.getChild(i));
        }
        return modelOffset;
    }
    /**
	 * Gets the length of the view element in the model.
	 *
	 * The length is calculated as follows:
	 * * if a {@link #registerViewToModelLength length mapping callback} is provided for the given `viewNode`, it is used to
	 * evaluate the model length (`viewNode` is used as first and only parameter passed to the callback),
	 * * length of a {@link module:engine/view/text~Text text node} is equal to the length of its
	 * {@link module:engine/view/text~Text#data data},
	 * * length of a {@link module:engine/view/uielement~UIElement ui element} is equal to 0,
	 * * length of a mapped {@link module:engine/view/element~Element element} is equal to 1,
	 * * length of a non-mapped {@link module:engine/view/element~Element element} is equal to the length of its children.
	 *
	 * Examples:
	 *
	 * ```
	 * foo                          -> 3 // Text length is equal to its data length.
	 * <p>foo</p>                   -> 1 // Length of an element which is mapped is by default equal to 1.
	 * <b>foo</b>                   -> 3 // Length of an element which is not mapped is a length of its children.
	 * <div><p>x</p><p>y</p></div>  -> 2 // Assuming that <div> is not mapped and <p> are mapped.
	 * ```
	 *
	 * @param viewNode View node.
	 * @returns Length of the node in the tree model.
	 */ getModelLength(viewNode) {
        if (this._viewToModelLengthCallbacks.get(viewNode.name)) {
            const callback = this._viewToModelLengthCallbacks.get(viewNode.name);
            return callback(viewNode);
        } else if (this._viewToModelMapping.has(viewNode)) {
            return 1;
        } else if (viewNode.is('$text')) {
            return viewNode.data.length;
        } else if (viewNode.is('uiElement')) {
            return 0;
        } else {
            let len = 0;
            for (const child of viewNode.getChildren()){
                len += this.getModelLength(child);
            }
            return len;
        }
    }
    /**
	 * Finds the position in the view node (or in its children) with the expected model offset.
	 *
	 * Example:
	 *
	 * ```
	 * <p>fo<b>bar</b>bom</p> -> expected offset: 4
	 *
	 * findPositionIn( p, 4 ):
	 * <p>|fo<b>bar</b>bom</p> -> expected offset: 4, actual offset: 0
	 * <p>fo|<b>bar</b>bom</p> -> expected offset: 4, actual offset: 2
	 * <p>fo<b>bar</b>|bom</p> -> expected offset: 4, actual offset: 5 -> we are too far
	 *
	 * findPositionIn( b, 4 - ( 5 - 3 ) ):
	 * <p>fo<b>|bar</b>bom</p> -> expected offset: 2, actual offset: 0
	 * <p>fo<b>bar|</b>bom</p> -> expected offset: 2, actual offset: 3 -> we are too far
	 *
	 * findPositionIn( bar, 2 - ( 3 - 3 ) ):
	 * We are in the text node so we can simple find the offset.
	 * <p>fo<b>ba|r</b>bom</p> -> expected offset: 2, actual offset: 2 -> position found
	 * ```
	 *
	 * @param viewParent Tree view element in which we are looking for the position.
	 * @param expectedOffset Expected offset.
	 * @returns Found position.
	 */ findPositionIn(viewParent, expectedOffset) {
        // Last scanned view node.
        let viewNode;
        // Length of the last scanned view node.
        let lastLength = 0;
        let modelOffset = 0;
        let viewOffset = 0;
        // In the text node it is simple: the offset in the model equals the offset in the text.
        if (viewParent.is('$text')) {
            return new Position$1(viewParent, expectedOffset);
        }
        // In other cases we add lengths of child nodes to find the proper offset.
        // If it is smaller we add the length.
        while(modelOffset < expectedOffset){
            viewNode = viewParent.getChild(viewOffset);
            lastLength = this.getModelLength(viewNode);
            modelOffset += lastLength;
            viewOffset++;
        }
        // If it equals we found the position.
        if (modelOffset == expectedOffset) {
            return this._moveViewPositionToTextNode(new Position$1(viewParent, viewOffset));
        } else {
            // ( modelOffset - lastLength ) is the offset to the child we enter,
            // so we subtract it from the expected offset to fine the offset in the child.
            return this.findPositionIn(viewNode, expectedOffset - (modelOffset - lastLength));
        }
    }
    /**
	 * Because we prefer positions in the text nodes over positions next to text nodes, if the view position was next to a text node,
	 * it moves it into the text node instead.
	 *
	 * ```
	 * <p>[]<b>foo</b></p> -> <p>[]<b>foo</b></p> // do not touch if position is not directly next to text
	 * <p>foo[]<b>foo</b></p> -> <p>foo{}<b>foo</b></p> // move to text node
	 * <p><b>[]foo</b></p> -> <p><b>{}foo</b></p> // move to text node
	 * ```
	 *
	 * @param viewPosition Position potentially next to the text node.
	 * @returns Position in the text node if possible.
	 */ _moveViewPositionToTextNode(viewPosition) {
        // If the position is just after a text node, put it at the end of that text node.
        // If the position is just before a text node, put it at the beginning of that text node.
        const nodeBefore = viewPosition.nodeBefore;
        const nodeAfter = viewPosition.nodeAfter;
        if (nodeBefore instanceof Text$1) {
            return new Position$1(nodeBefore, nodeBefore.data.length);
        } else if (nodeAfter instanceof Text$1) {
            return new Position$1(nodeAfter, 0);
        }
        // Otherwise, just return the given position.
        return viewPosition;
    }
}

/**
 * Manages a list of consumable values for the {@link module:engine/model/item~Item model items}.
 *
 * Consumables are various aspects of the model. A model item can be broken down into separate, single properties that might be
 * taken into consideration when converting that item.
 *
 * `ModelConsumable` is used by {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher} while analyzing the changed
 * parts of {@link module:engine/model/document~Document the document}. The added / changed / removed model items are broken down
 * into singular properties (the item itself and its attributes). All those parts are saved in `ModelConsumable`. Then,
 * during conversion, when the given part of a model item is converted (i.e. the view element has been inserted into the view,
 * but without attributes), the consumable value is removed from `ModelConsumable`.
 *
 * For model items, `ModelConsumable` stores consumable values of one of following types: `insert`, `addattribute:<attributeKey>`,
 * `changeattributes:<attributeKey>`, `removeattributes:<attributeKey>`.
 *
 * In most cases, it is enough to let th {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}
 * gather consumable values, so there is no need to use
 * the {@link module:engine/conversion/modelconsumable~ModelConsumable#add add method} directly.
 * However, it is important to understand how consumable values can be
 * {@link module:engine/conversion/modelconsumable~ModelConsumable#consume consumed}.
 * See {@link module:engine/conversion/downcasthelpers default downcast converters} for more information.
 *
 * Keep in mind that one conversion event may have multiple callbacks (converters) attached to it. Each of those is
 * able to convert one or more parts of the model. However, when one of those callbacks actually converts
 * something, the others should not, because they would duplicate the results. Using `ModelConsumable` helps to avoid
 * this situation, because callbacks should only convert these values that were not yet consumed from `ModelConsumable`.
 *
 * Consuming multiple values in a single callback:
 *
 * ```ts
 * // Converter for custom `imageBlock` element that might have a `caption` element inside which changes
 * // how the image is displayed in the view:
 * //
 * // Model:
 * //
 * // [imageBlock]
 * //   └─ [caption]
 * //       └─ foo
 * //
 * // View:
 * //
 * // <figure>
 * //   ├─ <img />
 * //   └─ <caption>
 * //       └─ foo
 * modelConversionDispatcher.on( 'insert:imageBlock', ( evt, data, conversionApi ) => {
 * 	// First, consume the `imageBlock` element.
 * 	conversionApi.consumable.consume( data.item, 'insert' );
 *
 * 	// Just create normal image element for the view.
 * 	// Maybe it will be "decorated" later.
 * 	const viewImage = new ViewElement( 'img' );
 * 	const insertPosition = conversionApi.mapper.toViewPosition( data.range.start );
 * 	const viewWriter = conversionApi.writer;
 *
 * 	// Check if the `imageBlock` element has children.
 * 	if ( data.item.childCount > 0 ) {
 * 		const modelCaption = data.item.getChild( 0 );
 *
 * 		// `modelCaption` insertion change is consumed from consumable values.
 * 		// It will not be converted by other converters, but it's children (probably some text) will be.
 * 		// Through mapping, converters for text will know where to insert contents of `modelCaption`.
 * 		if ( conversionApi.consumable.consume( modelCaption, 'insert' ) ) {
 * 			const viewCaption = new ViewElement( 'figcaption' );
 *
 * 			const viewImageHolder = new ViewElement( 'figure', null, [ viewImage, viewCaption ] );
 *
 * 			conversionApi.mapper.bindElements( modelCaption, viewCaption );
 * 			conversionApi.mapper.bindElements( data.item, viewImageHolder );
 * 			viewWriter.insert( insertPosition, viewImageHolder );
 * 		}
 * 	} else {
 * 		conversionApi.mapper.bindElements( data.item, viewImage );
 * 		viewWriter.insert( insertPosition, viewImage );
 * 	}
 *
 * 	evt.stop();
 * } );
 * ```
 */ class ModelConsumable {
    /**
	 * Contains list of consumable values.
	 */ _consumable = new Map();
    /**
	 * For each {@link module:engine/model/textproxy~TextProxy} added to `ModelConsumable`, this registry holds a parent
	 * of that `TextProxy` and the start and end indices of that `TextProxy`. This allows identification of the `TextProxy`
	 * instances that point to the same part of the model but are different instances. Each distinct `TextProxy`
	 * is given a unique `Symbol` which is then registered as consumable. This process is transparent for the `ModelConsumable`
	 * API user because whenever `TextProxy` is added, tested, consumed or reverted, the internal mechanisms of
	 * `ModelConsumable` translate `TextProxy` to that unique `Symbol`.
	 */ _textProxyRegistry = new Map();
    /**
	 * Adds a consumable value to the consumables list and links it with a given model item.
	 *
	 * ```ts
	 * modelConsumable.add( modelElement, 'insert' ); // Add `modelElement` insertion change to consumable values.
	 * modelConsumable.add( modelElement, 'addAttribute:bold' ); // Add `bold` attribute insertion on `modelElement` change.
	 * modelConsumable.add( modelElement, 'removeAttribute:bold' ); // Add `bold` attribute removal on `modelElement` change.
	 * modelConsumable.add( modelSelection, 'selection' ); // Add `modelSelection` to consumable values.
	 * modelConsumable.add( modelRange, 'range' ); // Add `modelRange` to consumable values.
	 * ```
	 *
	 * @param item Model item, range or selection that has the consumable.
	 * @param type Consumable type. Will be normalized to a proper form, that is either `<word>` or `<part>:<part>`.
	 * Second colon and everything after will be cut. Passing event name is a safe and good practice.
	 */ add(item, type) {
        type = _normalizeConsumableType(type);
        if (item instanceof TextProxy) {
            item = this._getSymbolForTextProxy(item);
        }
        if (!this._consumable.has(item)) {
            this._consumable.set(item, new Map());
        }
        this._consumable.get(item).set(type, true);
    }
    /**
	 * Removes a given consumable value from a given model item.
	 *
	 * ```ts
	 * modelConsumable.consume( modelElement, 'insert' ); // Remove `modelElement` insertion change from consumable values.
	 * modelConsumable.consume( modelElement, 'addAttribute:bold' ); // Remove `bold` attribute insertion on `modelElement` change.
	 * modelConsumable.consume( modelElement, 'removeAttribute:bold' ); // Remove `bold` attribute removal on `modelElement` change.
	 * modelConsumable.consume( modelSelection, 'selection' ); // Remove `modelSelection` from consumable values.
	 * modelConsumable.consume( modelRange, 'range' ); // Remove 'modelRange' from consumable values.
	 * ```
	 *
	 * @param item Model item, range or selection from which consumable will be consumed.
	 * @param type Consumable type. Will be normalized to a proper form, that is either `<word>` or `<part>:<part>`.
	 * Second colon and everything after will be cut. Passing event name is a safe and good practice.
	 * @returns `true` if consumable value was available and was consumed, `false` otherwise.
	 */ consume(item, type) {
        type = _normalizeConsumableType(type);
        if (item instanceof TextProxy) {
            item = this._getSymbolForTextProxy(item);
        }
        if (this.test(item, type)) {
            this._consumable.get(item).set(type, false);
            return true;
        } else {
            return false;
        }
    }
    /**
	 * Tests whether there is a consumable value of a given type connected with a given model item.
	 *
	 * ```ts
	 * modelConsumable.test( modelElement, 'insert' ); // Check for `modelElement` insertion change.
	 * modelConsumable.test( modelElement, 'addAttribute:bold' ); // Check for `bold` attribute insertion on `modelElement` change.
	 * modelConsumable.test( modelElement, 'removeAttribute:bold' ); // Check for `bold` attribute removal on `modelElement` change.
	 * modelConsumable.test( modelSelection, 'selection' ); // Check if `modelSelection` is consumable.
	 * modelConsumable.test( modelRange, 'range' ); // Check if `modelRange` is consumable.
	 * ```
	 *
	 * @param item Model item, range or selection to be tested.
	 * @param type Consumable type. Will be normalized to a proper form, that is either `<word>` or `<part>:<part>`.
	 * Second colon and everything after will be cut. Passing event name is a safe and good practice.
	 * @returns `null` if such consumable was never added, `false` if the consumable values was
	 * already consumed or `true` if it was added and not consumed yet.
	 */ test(item, type) {
        type = _normalizeConsumableType(type);
        if (item instanceof TextProxy) {
            item = this._getSymbolForTextProxy(item);
        }
        const itemConsumables = this._consumable.get(item);
        if (itemConsumables === undefined) {
            return null;
        }
        const value = itemConsumables.get(type);
        if (value === undefined) {
            return null;
        }
        return value;
    }
    /**
	 * Reverts consuming of a consumable value.
	 *
	 * ```ts
	 * modelConsumable.revert( modelElement, 'insert' ); // Revert consuming `modelElement` insertion change.
	 * modelConsumable.revert( modelElement, 'addAttribute:bold' ); // Revert consuming `bold` attribute insert from `modelElement`.
	 * modelConsumable.revert( modelElement, 'removeAttribute:bold' ); // Revert consuming `bold` attribute remove from `modelElement`.
	 * modelConsumable.revert( modelSelection, 'selection' ); // Revert consuming `modelSelection`.
	 * modelConsumable.revert( modelRange, 'range' ); // Revert consuming `modelRange`.
	 * ```
	 *
	 * @param item Model item, range or selection to be reverted.
	 * @param type Consumable type.
	 * @returns `true` if consumable has been reversed, `false` otherwise. `null` if the consumable has
	 * never been added.
	 */ revert(item, type) {
        type = _normalizeConsumableType(type);
        if (item instanceof TextProxy) {
            item = this._getSymbolForTextProxy(item);
        }
        const test = this.test(item, type);
        if (test === false) {
            this._consumable.get(item).set(type, true);
            return true;
        } else if (test === true) {
            return false;
        }
        return null;
    }
    /**
	 * Verifies if all events from the specified group were consumed.
	 *
	 * @param eventGroup The events group to verify.
	 */ verifyAllConsumed(eventGroup) {
        const items = [];
        for (const [item, consumables] of this._consumable){
            for (const [event, canConsume] of consumables){
                const eventPrefix = event.split(':')[0];
                if (canConsume && eventGroup == eventPrefix) {
                    items.push({
                        event,
                        item: item.name || item.description
                    });
                }
            }
        }
        if (items.length) {
            /**
			 * Some of the {@link module:engine/model/item~Item model items} were not consumed while downcasting the model to view.
			 *
			 * This might be the effect of:
			 *
			 * * A missing converter for some model elements. Make sure that you registered downcast converters for all model elements.
			 * * A custom converter that does not consume converted items. Make sure that you
			 * {@link module:engine/conversion/modelconsumable~ModelConsumable#consume consumed} all model elements that you converted
			 * from the model to the view.
			 * * A custom converter that called `event.stop()`. When providing a custom converter, keep in mind that you should not stop
			 * the event. If you stop it then the default converter at the `lowest` priority will not trigger the conversion of this node's
			 * attributes and child nodes.
			 *
			 * @error conversion-model-consumable-not-consumed
			 * @param {Array.<module:engine/model/item~Item>} items Items that were not consumed.
			 */ throw new CKEditorError('conversion-model-consumable-not-consumed', null, {
                items
            });
        }
    }
    /**
	 * Gets a unique symbol for the passed {@link module:engine/model/textproxy~TextProxy} instance. All `TextProxy` instances that
	 * have same parent, same start index and same end index will get the same symbol.
	 *
	 * Used internally to correctly consume `TextProxy` instances.
	 *
	 * @internal
	 * @param textProxy `TextProxy` instance to get a symbol for.
	 * @returns Symbol representing all equal instances of `TextProxy`.
	 */ _getSymbolForTextProxy(textProxy) {
        let symbol = null;
        const startMap = this._textProxyRegistry.get(textProxy.startOffset);
        if (startMap) {
            const endMap = startMap.get(textProxy.endOffset);
            if (endMap) {
                symbol = endMap.get(textProxy.parent);
            }
        }
        if (!symbol) {
            symbol = this._addSymbolForTextProxy(textProxy);
        }
        return symbol;
    }
    /**
	 * Adds a symbol for the given {@link module:engine/model/textproxy~TextProxy} instance.
	 *
	 * Used internally to correctly consume `TextProxy` instances.
	 *
	 * @param textProxy Text proxy instance.
	 * @returns Symbol generated for given `TextProxy`.
	 */ _addSymbolForTextProxy(textProxy) {
        const start = textProxy.startOffset;
        const end = textProxy.endOffset;
        const parent = textProxy.parent;
        const symbol = Symbol('$textProxy:' + textProxy.data);
        let startMap;
        let endMap;
        startMap = this._textProxyRegistry.get(start);
        if (!startMap) {
            startMap = new Map();
            this._textProxyRegistry.set(start, startMap);
        }
        endMap = startMap.get(end);
        if (!endMap) {
            endMap = new Map();
            startMap.set(end, endMap);
        }
        endMap.set(parent, symbol);
        return symbol;
    }
}
/**
 * Returns a normalized consumable type name from the given string. A normalized consumable type name is a string that has
 * at most one colon, for example: `insert` or `addMarker:highlight`. If a string to normalize has more "parts" (more colons),
 * the further parts are dropped, for example: `addattribute:bold:$text` -> `addattributes:bold`.
 *
 * @param type Consumable type.
 * @returns Normalized consumable type.
 */ function _normalizeConsumableType(type) {
    const parts = type.split(':');
    // For inserts allow passing event name, it's stored in the context of a specified element so the element name is not needed.
    if (parts[0] == 'insert') {
        return parts[0];
    }
    // Markers are identified by the whole name (otherwise we would consume the whole markers group).
    if (parts[0] == 'addMarker' || parts[0] == 'removeMarker') {
        return type;
    }
    return parts.length > 1 ? parts[0] + ':' + parts[1] : parts[0];
}

/**
 * The downcast dispatcher is a central point of downcasting (conversion from the model to the view), which is a process of reacting
 * to changes in the model and firing a set of events. The callbacks listening to these events are called converters. The
 * converters' role is to convert the model changes to changes in view (for example, adding view nodes or
 * changing attributes on view elements).
 *
 * During the conversion process, downcast dispatcher fires events basing on the state of the model and prepares
 * data for these events. It is important to understand that the events are connected with the changes done on the model,
 * for example: "a node has been inserted" or "an attribute has changed". This is in contrary to upcasting (a view-to-model conversion)
 * where you convert the view state (view nodes) to a model tree.
 *
 * The events are prepared basing on a diff created by the {@link module:engine/model/differ~Differ Differ}, which buffers them
 * and then passes to the downcast dispatcher as a diff between the old model state and the new model state.
 *
 * Note that because the changes are converted, there is a need to have a mapping between the model structure and the view structure.
 * To map positions and elements during the downcast (a model-to-view conversion), use {@link module:engine/conversion/mapper~Mapper}.
 *
 * Downcast dispatcher fires the following events for model tree changes:
 *
 * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert `insert`} &ndash;
 * If a range of nodes was inserted to the model tree.
 * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:remove `remove`} &ndash;
 * If a range of nodes was removed from the model tree.
 * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute`} &ndash;
 * If an attribute was added, changed or removed from a model node.
 *
 * For {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert `insert`}
 * and {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute`},
 * the downcast dispatcher generates {@link module:engine/conversion/modelconsumable~ModelConsumable consumables}.
 * These are used to have control over which changes have already been consumed. It is useful when some converters
 * overwrite others or convert multiple changes (for example, it converts an insertion of an element and also converts that
 * element's attributes during the insertion).
 *
 * Additionally, downcast dispatcher fires events for {@link module:engine/model/markercollection~Marker marker} changes:
 *
 * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker `addMarker`} &ndash; If a marker was added.
 * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:removeMarker `removeMarker`} &ndash; If a marker was
 * removed.
 *
 * Note that changing a marker is done through removing the marker from the old range and adding it to the new range,
 * so both of these events are fired.
 *
 * Finally, a downcast dispatcher also handles firing events for the {@link module:engine/model/selection model selection}
 * conversion:
 *
 * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:selection `selection`}
 * &ndash; Converts the selection from the model to the view.
 * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute`}
 * &ndash; Fired for every selection attribute.
 * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker `addMarker`}
 * &ndash; Fired for every marker that contains a selection.
 *
 * Unlike the model tree and the markers, the events for selection are not fired for changes but for a selection state.
 *
 * When providing custom listeners for a downcast dispatcher, remember to check whether a given change has not been
 * {@link module:engine/conversion/modelconsumable~ModelConsumable#consume consumed} yet.
 *
 * When providing custom listeners for a downcast dispatcher, keep in mind that you **should not** stop the event. If you stop it,
 * then the default converter at the `lowest` priority will not trigger the conversion of this node's attributes and child nodes.
 *
 * When providing custom listeners for a downcast dispatcher, remember to use the provided
 * {@link module:engine/view/downcastwriter~DowncastWriter view downcast writer} to apply changes to the view document.
 *
 * You can read more about conversion in the following guide:
 *
 * * {@glink framework/deep-dive/conversion/downcast Downcast conversion}
 *
 * An example of a custom converter for the downcast dispatcher:
 *
 * ```ts
 * // You will convert inserting a "paragraph" model element into the model.
 * downcastDispatcher.on( 'insert:paragraph', ( evt, data, conversionApi ) => {
 * 	// Remember to check whether the change has not been consumed yet and consume it.
 * 	if ( !conversionApi.consumable.consume( data.item, 'insert' ) ) {
 * 		return;
 * 	}
 *
 * 	// Translate the position in the model to a position in the view.
 * 	const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
 *
 * 	// Create a <p> element that will be inserted into the view at the `viewPosition`.
 * 	const viewElement = conversionApi.writer.createContainerElement( 'p' );
 *
 * 	// Bind the newly created view element to the model element so positions will map accordingly in the future.
 * 	conversionApi.mapper.bindElements( data.item, viewElement );
 *
 * 	// Add the newly created view element to the view.
 * 	conversionApi.writer.insert( viewPosition, viewElement );
 * } );
 * ```
 */ class DowncastDispatcher extends /* #__PURE__ */ EmitterMixin() {
    /**
	 * A template for an interface passed by the dispatcher to the event callbacks.
	 *
	 * @internal
	 */ _conversionApi;
    /**
	 * A map of already fired events for a given `ModelConsumable`.
	 */ _firedEventsMap;
    /**
	 * Creates a downcast dispatcher instance.
	 *
	 * @see module:engine/conversion/downcastdispatcher~DowncastConversionApi
	 *
	 * @param conversionApi Additional properties for an interface that will be passed to events fired
	 * by the downcast dispatcher.
	 */ constructor(conversionApi){
        super();
        this._conversionApi = {
            dispatcher: this,
            ...conversionApi
        };
        this._firedEventsMap = new WeakMap();
    }
    /**
	 * Converts changes buffered in the given {@link module:engine/model/differ~Differ model differ}
	 * and fires conversion events based on it.
	 *
	 * @fires insert
	 * @fires remove
	 * @fires attribute
	 * @fires addMarker
	 * @fires removeMarker
	 * @fires reduceChanges
	 * @param differ The differ object with buffered changes.
	 * @param markers Markers related to the model fragment to convert.
	 * @param writer The view writer that should be used to modify the view document.
	 */ convertChanges(differ, markers, writer) {
        const conversionApi = this._createConversionApi(writer, differ.getRefreshedItems());
        // Before the view is updated, remove markers which have changed.
        for (const change of differ.getMarkersToRemove()){
            this._convertMarkerRemove(change.name, change.range, conversionApi);
        }
        // Let features modify the change list (for example to allow reconversion).
        const changes = this._reduceChanges(differ.getChanges());
        // Convert changes that happened on model tree.
        for (const entry of changes){
            if (entry.type === 'insert') {
                this._convertInsert(Range._createFromPositionAndShift(entry.position, entry.length), conversionApi);
            } else if (entry.type === 'reinsert') {
                this._convertReinsert(Range._createFromPositionAndShift(entry.position, entry.length), conversionApi);
            } else if (entry.type === 'remove') {
                this._convertRemove(entry.position, entry.length, entry.name, conversionApi);
            } else {
                // Defaults to 'attribute' change.
                this._convertAttribute(entry.range, entry.attributeKey, entry.attributeOldValue, entry.attributeNewValue, conversionApi);
            }
        }
        // Remove mappings for all removed view elements.
        // Remove these mappings as soon as they are not needed (https://github.com/ckeditor/ckeditor5/issues/15411).
        conversionApi.mapper.flushDeferredBindings();
        for (const markerName of conversionApi.mapper.flushUnboundMarkerNames()){
            const markerRange = markers.get(markerName).getRange();
            this._convertMarkerRemove(markerName, markerRange, conversionApi);
            this._convertMarkerAdd(markerName, markerRange, conversionApi);
        }
        // After the view is updated, convert markers which have changed.
        for (const change of differ.getMarkersToAdd()){
            this._convertMarkerAdd(change.name, change.range, conversionApi);
        }
        // Verify if all insert consumables were consumed.
        conversionApi.consumable.verifyAllConsumed('insert');
    }
    /**
	 * Starts a conversion of a model range and the provided markers.
	 *
	 * @fires insert
	 * @fires attribute
	 * @fires addMarker
	 * @param range The inserted range.
	 * @param markers The map of markers that should be down-casted.
	 * @param writer The view writer that should be used to modify the view document.
	 * @param options Optional options object passed to `convertionApi.options`.
	 */ convert(range, markers, writer, options = {}) {
        const conversionApi = this._createConversionApi(writer, undefined, options);
        this._convertInsert(range, conversionApi);
        for (const [name, range] of markers){
            this._convertMarkerAdd(name, range, conversionApi);
        }
        // Verify if all insert consumables were consumed.
        conversionApi.consumable.verifyAllConsumed('insert');
    }
    /**
	 * Starts the model selection conversion.
	 *
	 * Fires events for a given {@link module:engine/model/selection~Selection selection} to start the selection conversion.
	 *
	 * @fires selection
	 * @fires addMarker
	 * @fires attribute
	 * @param selection The selection to convert.
	 * @param markers Markers connected with the converted model.
	 * @param writer View writer that should be used to modify the view document.
	 */ convertSelection(selection, markers, writer) {
        const conversionApi = this._createConversionApi(writer);
        // First perform a clean-up at the current position of the selection.
        this.fire('cleanSelection', {
            selection
        }, conversionApi);
        // Don't convert selection if it is in a model root that does not have a view root (for now this is only the graveyard root).
        const modelRoot = selection.getFirstPosition().root;
        if (!conversionApi.mapper.toViewElement(modelRoot)) {
            return;
        }
        // Now, perform actual selection conversion.
        const markersAtSelection = Array.from(markers.getMarkersAtPosition(selection.getFirstPosition()));
        this._addConsumablesForSelection(conversionApi.consumable, selection, markersAtSelection);
        this.fire('selection', {
            selection
        }, conversionApi);
        if (!selection.isCollapsed) {
            return;
        }
        for (const marker of markersAtSelection){
            // Do not fire event if the marker has been consumed.
            if (conversionApi.consumable.test(selection, 'addMarker:' + marker.name)) {
                const markerRange = marker.getRange();
                if (!shouldMarkerChangeBeConverted(selection.getFirstPosition(), marker, conversionApi.mapper)) {
                    continue;
                }
                const data = {
                    item: selection,
                    markerName: marker.name,
                    markerRange
                };
                this.fire(`addMarker:${marker.name}`, data, conversionApi);
            }
        }
        for (const key of selection.getAttributeKeys()){
            // Do not fire event if the attribute has been consumed.
            if (conversionApi.consumable.test(selection, 'attribute:' + key)) {
                const data = {
                    item: selection,
                    range: selection.getFirstRange(),
                    attributeKey: key,
                    attributeOldValue: null,
                    attributeNewValue: selection.getAttribute(key)
                };
                this.fire(`attribute:${key}:$text`, data, conversionApi);
            }
        }
    }
    /**
	 * Fires insertion conversion of a range of nodes.
	 *
	 * For each node in the range, {@link #event:insert `insert` event is fired}. For each attribute on each node,
	 * {@link #event:attribute `attribute` event is fired}.
	 *
	 * @fires insert
	 * @fires attribute
	 * @param range The inserted range.
	 * @param conversionApi The conversion API object.
	 * @param options.doNotAddConsumables Whether the ModelConsumable should not get populated
	 * for items in the provided range.
	 */ _convertInsert(range, conversionApi, options = {}) {
        if (!options.doNotAddConsumables) {
            // Collect a list of things that can be consumed, consisting of nodes and their attributes.
            this._addConsumablesForInsert(conversionApi.consumable, range);
        }
        // Fire a separate insert event for each node and text fragment contained in the range.
        for (const data of Array.from(range.getWalker({
            shallow: true
        })).map(walkerValueToEventData)){
            this._testAndFire('insert', data, conversionApi);
        }
    }
    /**
	 * Fires conversion of a single node removal. Fires {@link #event:remove remove event} with provided data.
	 *
	 * @param position Position from which node was removed.
	 * @param length Offset size of removed node.
	 * @param name Name of removed node.
	 * @param conversionApi The conversion API object.
	 */ _convertRemove(position, length, name, conversionApi) {
        this.fire(`remove:${name}`, {
            position,
            length
        }, conversionApi);
    }
    /**
	 * Starts a conversion of an attribute change on a given `range`.
	 *
	 * For each node in the given `range`, {@link #event:attribute attribute event} is fired with the passed data.
	 *
	 * @fires attribute
	 * @param range Changed range.
	 * @param key Key of the attribute that has changed.
	 * @param oldValue Attribute value before the change or `null` if the attribute has not been set before.
	 * @param newValue New attribute value or `null` if the attribute has been removed.
	 * @param conversionApi The conversion API object.
	 */ _convertAttribute(range, key, oldValue, newValue, conversionApi) {
        // Create a list with attributes to consume.
        this._addConsumablesForRange(conversionApi.consumable, range, `attribute:${key}`);
        // Create a separate attribute event for each node in the range.
        for (const value of range){
            const data = {
                item: value.item,
                range: Range._createFromPositionAndShift(value.previousPosition, value.length),
                attributeKey: key,
                attributeOldValue: oldValue,
                attributeNewValue: newValue
            };
            this._testAndFire(`attribute:${key}`, data, conversionApi);
        }
    }
    /**
	 * Fires re-insertion conversion (with a `reconversion` flag passed to `insert` events)
	 * of a range of elements (only elements on the range depth, without children).
	 *
	 * For each node in the range on its depth (without children), {@link #event:insert `insert` event} is fired.
	 * For each attribute on each node, {@link #event:attribute `attribute` event} is fired.
	 *
	 * @fires insert
	 * @fires attribute
	 * @param range The range to reinsert.
	 * @param conversionApi The conversion API object.
	 */ _convertReinsert(range, conversionApi) {
        // Convert the elements - without converting children.
        const walkerValues = Array.from(range.getWalker({
            shallow: true
        }));
        // Collect a list of things that can be consumed, consisting of nodes and their attributes.
        this._addConsumablesForInsert(conversionApi.consumable, walkerValues);
        // Fire a separate insert event for each node and text fragment contained shallowly in the range.
        for (const data of walkerValues.map(walkerValueToEventData)){
            this._testAndFire('insert', {
                ...data,
                reconversion: true
            }, conversionApi);
        }
    }
    /**
	 * Converts the added marker. Fires the {@link #event:addMarker `addMarker`} event for each item
	 * in the marker's range. If the range is collapsed, a single event is dispatched. See the event description for more details.
	 *
	 * @fires addMarker
	 * @param markerName Marker name.
	 * @param markerRange The marker range.
	 * @param conversionApi The conversion API object.
	 */ _convertMarkerAdd(markerName, markerRange, conversionApi) {
        // Do not convert if range is in graveyard.
        if (markerRange.root.rootName == '$graveyard') {
            return;
        }
        // In markers' case, event name == consumable name.
        const eventName = `addMarker:${markerName}`;
        //
        // First, fire an event for the whole marker.
        //
        conversionApi.consumable.add(markerRange, eventName);
        this.fire(eventName, {
            markerName,
            markerRange
        }, conversionApi);
        //
        // Do not fire events for each item inside the range if the range got consumed.
        // Also consume the whole marker consumable if it wasn't consumed.
        //
        if (!conversionApi.consumable.consume(markerRange, eventName)) {
            return;
        }
        //
        // Then, fire an event for each item inside the marker range.
        //
        this._addConsumablesForRange(conversionApi.consumable, markerRange, eventName);
        for (const item of markerRange.getItems()){
            // Do not fire event for already consumed items.
            if (!conversionApi.consumable.test(item, eventName)) {
                continue;
            }
            const data = {
                item,
                range: Range._createOn(item),
                markerName,
                markerRange
            };
            this.fire(eventName, data, conversionApi);
        }
    }
    /**
	 * Fires the conversion of the marker removal. Fires the {@link #event:removeMarker `removeMarker`} event with the provided data.
	 *
	 * @fires removeMarker
	 * @param markerName Marker name.
	 * @param markerRange The marker range.
	 * @param conversionApi The conversion API object.
	 */ _convertMarkerRemove(markerName, markerRange, conversionApi) {
        // Do not convert if range is in graveyard.
        if (markerRange.root.rootName == '$graveyard') {
            return;
        }
        this.fire(`removeMarker:${markerName}`, {
            markerName,
            markerRange
        }, conversionApi);
    }
    /**
	 * Fires the reduction of changes buffered in the {@link module:engine/model/differ~Differ `Differ`}.
	 *
	 * Features can replace selected {@link module:engine/model/differ~DiffItem `DiffItem`}s with `reinsert` entries to trigger
	 * reconversion. The {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToStructure
	 * `DowncastHelpers.elementToStructure()`} is using this event to trigger reconversion.
	 *
	 * @fires reduceChanges
	 */ _reduceChanges(changes) {
        const data = {
            changes
        };
        this.fire('reduceChanges', data);
        return data.changes;
    }
    /**
	 * Populates provided {@link module:engine/conversion/modelconsumable~ModelConsumable} with values to consume from a given range,
	 * assuming that the range has just been inserted to the model.
	 *
	 * @param consumable The consumable.
	 * @param walkerValues The walker values for the inserted range.
	 * @returns The values to consume.
	 */ _addConsumablesForInsert(consumable, walkerValues) {
        for (const value of walkerValues){
            const item = value.item;
            // Add consumable if it wasn't there yet.
            if (consumable.test(item, 'insert') === null) {
                consumable.add(item, 'insert');
                for (const key of item.getAttributeKeys()){
                    consumable.add(item, 'attribute:' + key);
                }
            }
        }
        return consumable;
    }
    /**
	 * Populates provided {@link module:engine/conversion/modelconsumable~ModelConsumable} with values to consume for a given range.
	 *
	 * @param consumable The consumable.
	 * @param range The affected range.
	 * @param type Consumable type.
	 * @returns The values to consume.
	 */ _addConsumablesForRange(consumable, range, type) {
        for (const item of range.getItems()){
            consumable.add(item, type);
        }
        return consumable;
    }
    /**
	 * Populates provided {@link module:engine/conversion/modelconsumable~ModelConsumable} with selection consumable values.
	 *
	 * @param consumable The consumable.
	 * @param selection The selection to create the consumable from.
	 * @param markers Markers that contain the selection.
	 * @returns The values to consume.
	 */ _addConsumablesForSelection(consumable, selection, markers) {
        consumable.add(selection, 'selection');
        for (const marker of markers){
            consumable.add(selection, 'addMarker:' + marker.name);
        }
        for (const key of selection.getAttributeKeys()){
            consumable.add(selection, 'attribute:' + key);
        }
        return consumable;
    }
    /**
	 * Tests whether given event wasn't already fired and if so, fires it.
	 *
	 * @fires insert
	 * @fires attribute
	 * @param type Event type.
	 * @param data Event data.
	 * @param conversionApi The conversion API object.
	 */ _testAndFire(type, data, conversionApi) {
        const eventName = getEventName(type, data);
        const itemKey = data.item.is('$textProxy') ? conversionApi.consumable._getSymbolForTextProxy(data.item) : data.item;
        const eventsFiredForConversion = this._firedEventsMap.get(conversionApi);
        const eventsFiredForItem = eventsFiredForConversion.get(itemKey);
        if (!eventsFiredForItem) {
            eventsFiredForConversion.set(itemKey, new Set([
                eventName
            ]));
        } else if (!eventsFiredForItem.has(eventName)) {
            eventsFiredForItem.add(eventName);
        } else {
            return;
        }
        this.fire(eventName, data, conversionApi);
    }
    /**
	 * Fires not already fired events for setting attributes on just inserted item.
	 *
	 * @param item The model item to convert attributes for.
	 * @param conversionApi The conversion API object.
	 */ _testAndFireAddAttributes(item, conversionApi) {
        const data = {
            item,
            range: Range._createOn(item)
        };
        for (const key of data.item.getAttributeKeys()){
            data.attributeKey = key;
            data.attributeOldValue = null;
            data.attributeNewValue = data.item.getAttribute(key);
            this._testAndFire(`attribute:${key}`, data, conversionApi);
        }
    }
    /**
	 * Builds an instance of the {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi} from a template and a given
	 * {@link module:engine/view/downcastwriter~DowncastWriter `DowncastWriter`} and options object.
	 *
	 * @param writer View writer that should be used to modify the view document.
	 * @param refreshedItems A set of model elements that should not reuse their
	 * previous view representations.
	 * @param options Optional options passed to `convertionApi.options`.
	 * @return The conversion API object.
	 */ _createConversionApi(writer, refreshedItems = new Set(), options = {}) {
        const conversionApi = {
            ...this._conversionApi,
            consumable: new ModelConsumable(),
            writer,
            options,
            convertItem: (item)=>this._convertInsert(Range._createOn(item), conversionApi),
            convertChildren: (element)=>this._convertInsert(Range._createIn(element), conversionApi, {
                    doNotAddConsumables: true
                }),
            convertAttributes: (item)=>this._testAndFireAddAttributes(item, conversionApi),
            canReuseView: (viewElement)=>!refreshedItems.has(conversionApi.mapper.toModelElement(viewElement))
        };
        this._firedEventsMap.set(conversionApi, new Map());
        return conversionApi;
    }
}
/**
 * Helper function, checks whether change of `marker` at `modelPosition` should be converted. Marker changes are not
 * converted if they happen inside an element with custom conversion method.
 */ function shouldMarkerChangeBeConverted(modelPosition, marker, mapper) {
    const range = marker.getRange();
    const ancestors = Array.from(modelPosition.getAncestors());
    ancestors.shift(); // Remove root element. It cannot be passed to `model.Range#containsItem`.
    ancestors.reverse();
    const hasCustomHandling = ancestors.some((element)=>{
        if (range.containsItem(element)) {
            const viewElement = mapper.toViewElement(element);
            return !!viewElement.getCustomProperty('addHighlight');
        }
    });
    return !hasCustomHandling;
}
function getEventName(type, data) {
    const name = data.item.is('element') ? data.item.name : '$text';
    return `${type}:${name}`;
}
function walkerValueToEventData(value) {
    const item = value.item;
    const itemRange = Range._createFromPositionAndShift(value.previousPosition, value.length);
    return {
        item,
        range: itemRange
    };
}

/**
 * Selection is a set of {@link module:engine/model/range~Range ranges}. It has a direction specified by its
 * {@link module:engine/model/selection~Selection#anchor anchor} and {@link module:engine/model/selection~Selection#focus focus}
 * (it can be {@link module:engine/model/selection~Selection#isBackward forward or backward}).
 * Additionally, selection may have its own attributes (think – whether text typed in in this selection
 * should have those attributes – e.g. whether you type a bolded text).
 */ class Selection extends /* #__PURE__ */ EmitterMixin(TypeCheckable) {
    /**
	 * Specifies whether the last added range was added as a backward or forward range.
	 */ _lastRangeBackward = false;
    /**
	 * List of attributes set on current selection.
	 */ _attrs = new Map();
    /** @internal */ _ranges = [];
    /**
	 * Creates a new selection instance based on the given {@link module:engine/model/selection~Selectable selectable}
	 * or creates an empty selection if no arguments were passed.
	 *
	 * ```ts
	 * // Creates empty selection without ranges.
	 * const selection = writer.createSelection();
	 *
	 * // Creates selection at the given range.
	 * const range = writer.createRange( start, end );
	 * const selection = writer.createSelection( range );
	 *
	 * // Creates selection at the given ranges
	 * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
	 * const selection = writer.createSelection( ranges );
	 *
	 * // Creates selection from the other selection.
	 * // Note: It doesn't copy selection attributes.
	 * const otherSelection = writer.createSelection();
	 * const selection = writer.createSelection( otherSelection );
	 *
	 * // Creates selection from the given document selection.
	 * // Note: It doesn't copy selection attributes.
	 * const documentSelection = model.document.selection;
	 * const selection = writer.createSelection( documentSelection );
	 *
	 * // Creates selection at the given position.
	 * const position = writer.createPositionFromPath( root, path );
	 * const selection = writer.createSelection( position );
	 *
	 * // Creates selection at the given offset in the given element.
	 * const paragraph = writer.createElement( 'paragraph' );
	 * const selection = writer.createSelection( paragraph, offset );
	 *
	 * // Creates a range inside an {@link module:engine/model/element~Element element} which starts before the
	 * // first child of that element and ends after the last child of that element.
	 * const selection = writer.createSelection( paragraph, 'in' );
	 *
	 * // Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends
	 * // just after the item.
	 * const selection = writer.createSelection( paragraph, 'on' );
	 * ```
	 *
	 * Selection's constructor allow passing additional options (`'backward'`) as the last argument.
	 *
	 * ```ts
	 * // Creates backward selection.
	 * const selection = writer.createSelection( range, { backward: true } );
	 * ```
	 *
	 * @internal
	 */ constructor(...args){
        super();
        if (args.length) {
            this.setTo(...args);
        }
    }
    /**
	 * Selection anchor. Anchor is the position from which the selection was started. If a user is making a selection
	 * by dragging the mouse, the anchor is where the user pressed the mouse button (the beginning of the selection).
	 *
	 * Anchor and {@link #focus} define the direction of the selection, which is important
	 * when expanding/shrinking selection. The focus moves, while the anchor should remain in the same place.
	 *
	 * Anchor is always set to the {@link module:engine/model/range~Range#start start} or
	 * {@link module:engine/model/range~Range#end end} position of the last of selection's ranges. Whether it is
	 * the `start` or `end` depends on the specified `options.backward`. See the {@link #setTo `setTo()`} method.
	 *
	 * May be set to `null` if there are no ranges in the selection.
	 *
	 * @see #focus
	 */ get anchor() {
        if (this._ranges.length > 0) {
            const range = this._ranges[this._ranges.length - 1];
            return this._lastRangeBackward ? range.end : range.start;
        }
        return null;
    }
    /**
	 * Selection focus. Focus is the position where the selection ends. If a user is making a selection
	 * by dragging the mouse, the focus is where the mouse cursor is.
	 *
	 * May be set to `null` if there are no ranges in the selection.
	 *
	 * @see #anchor
	 */ get focus() {
        if (this._ranges.length > 0) {
            const range = this._ranges[this._ranges.length - 1];
            return this._lastRangeBackward ? range.start : range.end;
        }
        return null;
    }
    /**
	 * Whether the selection is collapsed. Selection is collapsed when there is exactly one range in it
	 * and it is collapsed.
	 */ get isCollapsed() {
        const length = this._ranges.length;
        if (length === 1) {
            return this._ranges[0].isCollapsed;
        } else {
            return false;
        }
    }
    /**
	 * Returns the number of ranges in the selection.
	 */ get rangeCount() {
        return this._ranges.length;
    }
    /**
	 * Specifies whether the selection's {@link #focus} precedes the selection's {@link #anchor}.
	 */ get isBackward() {
        return !this.isCollapsed && this._lastRangeBackward;
    }
    /**
	 * Checks whether this selection is equal to the given selection. Selections are equal if they have the same directions,
	 * the same number of ranges and all ranges from one selection equal to ranges from the another selection.
	 *
	 * @param otherSelection Selection to compare with.
	 * @returns `true` if selections are equal, `false` otherwise.
	 */ isEqual(otherSelection) {
        if (this.rangeCount != otherSelection.rangeCount) {
            return false;
        } else if (this.rangeCount === 0) {
            return true;
        }
        if (!this.anchor.isEqual(otherSelection.anchor) || !this.focus.isEqual(otherSelection.focus)) {
            return false;
        }
        for (const thisRange of this._ranges){
            let found = false;
            for (const otherRange of otherSelection._ranges){
                if (thisRange.isEqual(otherRange)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return false;
            }
        }
        return true;
    }
    /**
	 * Returns an iterable object that iterates over copies of selection ranges.
	 */ *getRanges() {
        for (const range of this._ranges){
            yield new Range(range.start, range.end);
        }
    }
    /**
	 * Returns a copy of the first range in the selection.
	 * First range is the one which {@link module:engine/model/range~Range#start start} position
	 * {@link module:engine/model/position~Position#isBefore is before} start position of all other ranges
	 * (not to confuse with the first range added to the selection).
	 *
	 * Returns `null` if there are no ranges in selection.
	 */ getFirstRange() {
        let first = null;
        for (const range of this._ranges){
            if (!first || range.start.isBefore(first.start)) {
                first = range;
            }
        }
        return first ? new Range(first.start, first.end) : null;
    }
    /**
	 * Returns a copy of the last range in the selection.
	 * Last range is the one which {@link module:engine/model/range~Range#end end} position
	 * {@link module:engine/model/position~Position#isAfter is after} end position of all other ranges (not to confuse with the range most
	 * recently added to the selection).
	 *
	 * Returns `null` if there are no ranges in selection.
	 */ getLastRange() {
        let last = null;
        for (const range of this._ranges){
            if (!last || range.end.isAfter(last.end)) {
                last = range;
            }
        }
        return last ? new Range(last.start, last.end) : null;
    }
    /**
	 * Returns the first position in the selection.
	 * First position is the position that {@link module:engine/model/position~Position#isBefore is before}
	 * any other position in the selection.
	 *
	 * Returns `null` if there are no ranges in selection.
	 */ getFirstPosition() {
        const first = this.getFirstRange();
        return first ? first.start.clone() : null;
    }
    /**
	 * Returns the last position in the selection.
	 * Last position is the position that {@link module:engine/model/position~Position#isAfter is after}
	 * any other position in the selection.
	 *
	 * Returns `null` if there are no ranges in selection.
	 */ getLastPosition() {
        const lastRange = this.getLastRange();
        return lastRange ? lastRange.end.clone() : null;
    }
    /**
	 * Sets this selection's ranges and direction to the specified location based on the given
	 * {@link module:engine/model/selection~Selectable selectable}.
	 *
	 * ```ts
	 * // Removes all selection's ranges.
	 * selection.setTo( null );
	 *
	 * // Sets selection to the given range.
	 * const range = writer.createRange( start, end );
	 * selection.setTo( range );
	 *
	 * // Sets selection to given ranges.
	 * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
	 * selection.setTo( ranges );
	 *
	 * // Sets selection to other selection.
	 * // Note: It doesn't copy selection attributes.
	 * const otherSelection = writer.createSelection();
	 * selection.setTo( otherSelection );
	 *
	 * // Sets selection to the given document selection.
	 * // Note: It doesn't copy selection attributes.
	 * const documentSelection = new DocumentSelection( doc );
	 * selection.setTo( documentSelection );
	 *
	 * // Sets collapsed selection at the given position.
	 * const position = writer.createPositionFromPath( root, path );
	 * selection.setTo( position );
	 *
	 * // Sets collapsed selection at the position of the given node and an offset.
	 * selection.setTo( paragraph, offset );
	 * ```
	 *
	 * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
 	 * that element and ends after the last child of that element.
	 *
	 * ```ts
	 * selection.setTo( paragraph, 'in' );
	 * ```
	 *
	 * Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends just after the item.
	 *
	 * ```ts
	 * selection.setTo( paragraph, 'on' );
	 * ```
	 *
	 * `Selection#setTo()`' method allow passing additional options (`backward`) as the last argument.
	 *
	 * ```ts
	 * // Sets backward selection.
	 * const selection = writer.createSelection( range, { backward: true } );
	 * ```
	 */ setTo(...args) {
        let [selectable, placeOrOffset, options] = args;
        if (typeof placeOrOffset == 'object') {
            options = placeOrOffset;
            placeOrOffset = undefined;
        }
        if (selectable === null) {
            this._setRanges([]);
        } else if (selectable instanceof Selection) {
            this._setRanges(selectable.getRanges(), selectable.isBackward);
        } else if (selectable && typeof selectable.getRanges == 'function') {
            // We assume that the selectable is a DocumentSelection.
            // It can't be imported here, because it would lead to circular imports.
            this._setRanges(selectable.getRanges(), selectable.isBackward);
        } else if (selectable instanceof Range) {
            this._setRanges([
                selectable
            ], !!options && !!options.backward);
        } else if (selectable instanceof Position) {
            this._setRanges([
                new Range(selectable)
            ]);
        } else if (selectable instanceof Node$1) {
            const backward = !!options && !!options.backward;
            let range;
            if (placeOrOffset == 'in') {
                range = Range._createIn(selectable);
            } else if (placeOrOffset == 'on') {
                range = Range._createOn(selectable);
            } else if (placeOrOffset !== undefined) {
                range = new Range(Position._createAt(selectable, placeOrOffset));
            } else {
                /**
				 * selection.setTo requires the second parameter when the first parameter is a node.
				 *
				 * @error model-selection-setto-required-second-parameter
				 */ throw new CKEditorError('model-selection-setto-required-second-parameter', [
                    this,
                    selectable
                ]);
            }
            this._setRanges([
                range
            ], backward);
        } else if (isIterable(selectable)) {
            // We assume that the selectable is an iterable of ranges.
            this._setRanges(selectable, options && !!options.backward);
        } else {
            /**
			 * Cannot set the selection to the given place.
			 *
			 * Invalid parameters were specified when setting the selection. Common issues:
			 *
			 * * A {@link module:engine/model/textproxy~TextProxy} instance was passed instead of
			 * a real {@link module:engine/model/text~Text}.
			 * * View nodes were passed instead of model nodes.
			 * * `null`/`undefined` was passed.
			 *
			 * @error model-selection-setto-not-selectable
			 */ throw new CKEditorError('model-selection-setto-not-selectable', [
                this,
                selectable
            ]);
        }
    }
    /**
	 * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
	 * is treated like the last added range and is used to set {@link module:engine/model/selection~Selection#anchor} and
	 * {@link module:engine/model/selection~Selection#focus}. Accepts a flag describing in which direction the selection is made.
	 *
	 * @fires change:range
	 * @param newRanges Ranges to set.
	 * @param isLastBackward Flag describing if last added range was selected forward - from start to end (`false`)
	 * or backward - from end to start (`true`).
	 */ _setRanges(newRanges, isLastBackward = false) {
        const ranges = Array.from(newRanges);
        // Check whether there is any range in new ranges set that is different than all already added ranges.
        const anyNewRange = ranges.some((newRange)=>{
            if (!(newRange instanceof Range)) {
                /**
				 * Selection range set to an object that is not an instance of {@link module:engine/model/range~Range}.
				 *
				 * Only {@link module:engine/model/range~Range} instances can be used to set a selection.
				 * Common mistakes leading to this error are:
				 *
				 * * using DOM `Range` object,
				 * * incorrect CKEditor 5 installation with multiple `ckeditor5-engine` packages having different versions.
				 *
				 * @error model-selection-set-ranges-not-range
				 */ throw new CKEditorError('model-selection-set-ranges-not-range', [
                    this,
                    newRanges
                ]);
            }
            return this._ranges.every((oldRange)=>{
                return !oldRange.isEqual(newRange);
            });
        });
        // Don't do anything if nothing changed.
        if (ranges.length === this._ranges.length && !anyNewRange) {
            return;
        }
        this._replaceAllRanges(ranges);
        this._lastRangeBackward = !!isLastBackward;
        this.fire('change:range', {
            directChange: true
        });
    }
    /**
	 * Moves {@link module:engine/model/selection~Selection#focus} to the specified location.
	 *
	 * The location can be specified in the same form as
	 * {@link module:engine/model/writer~Writer#createPositionAt writer.createPositionAt()} parameters.
	 *
	 * @fires change:range
	 * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/model/item~Item model item}.
	 */ setFocus(itemOrPosition, offset) {
        if (this.anchor === null) {
            /**
			 * Cannot set selection focus if there are no ranges in selection.
			 *
			 * @error model-selection-setfocus-no-ranges
			 */ throw new CKEditorError('model-selection-setfocus-no-ranges', [
                this,
                itemOrPosition
            ]);
        }
        const newFocus = Position._createAt(itemOrPosition, offset);
        if (newFocus.compareWith(this.focus) == 'same') {
            return;
        }
        const anchor = this.anchor;
        if (this._ranges.length) {
            this._popRange();
        }
        if (newFocus.compareWith(anchor) == 'before') {
            this._pushRange(new Range(newFocus, anchor));
            this._lastRangeBackward = true;
        } else {
            this._pushRange(new Range(anchor, newFocus));
            this._lastRangeBackward = false;
        }
        this.fire('change:range', {
            directChange: true
        });
    }
    /**
	 * Gets an attribute value for given key or `undefined` if that attribute is not set on the selection.
	 *
	 * @param key Key of attribute to look for.
	 * @returns Attribute value or `undefined`.
	 */ getAttribute(key) {
        return this._attrs.get(key);
    }
    /**
	 * Returns iterable that iterates over this selection's attributes.
	 *
	 * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
	 * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
	 */ getAttributes() {
        return this._attrs.entries();
    }
    /**
	 * Returns iterable that iterates over this selection's attribute keys.
	 */ getAttributeKeys() {
        return this._attrs.keys();
    }
    /**
	 * Checks if the selection has an attribute for given key.
	 *
	 * @param key Key of attribute to check.
	 * @returns `true` if attribute with given key is set on selection, `false` otherwise.
	 */ hasAttribute(key) {
        return this._attrs.has(key);
    }
    /**
	 * Removes an attribute with given key from the selection.
	 *
	 * If given attribute was set on the selection, fires the {@link #event:change:range} event with
	 * removed attribute key.
	 *
	 * @fires change:attribute
	 * @param key Key of attribute to remove.
	 */ removeAttribute(key) {
        if (this.hasAttribute(key)) {
            this._attrs.delete(key);
            this.fire('change:attribute', {
                attributeKeys: [
                    key
                ],
                directChange: true
            });
        }
    }
    /**
	 * Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
	 *
	 * If the attribute value has changed, fires the {@link #event:change:range} event with
	 * the attribute key.
	 *
	 * @fires change:attribute
	 * @param key Key of attribute to set.
	 * @param value Attribute value.
	 */ setAttribute(key, value) {
        if (this.getAttribute(key) !== value) {
            this._attrs.set(key, value);
            this.fire('change:attribute', {
                attributeKeys: [
                    key
                ],
                directChange: true
            });
        }
    }
    /**
	 * Returns the selected element. {@link module:engine/model/element~Element Element} is considered as selected if there is only
	 * one range in the selection, and that range contains exactly one element.
	 * Returns `null` if there is no selected element.
	 */ getSelectedElement() {
        if (this.rangeCount !== 1) {
            return null;
        }
        return this.getFirstRange().getContainedElement();
    }
    /**
	 * Gets elements of type {@link module:engine/model/schema~Schema#isBlock "block"} touched by the selection.
	 *
	 * This method's result can be used for example to apply block styling to all blocks covered by this selection.
	 *
	 * **Note:** `getSelectedBlocks()` returns blocks that are nested in other non-block elements
	 * but will not return blocks nested in other blocks.
	 *
	 * In this case the function will return exactly all 3 paragraphs (note: `<blockQuote>` is not a block itself):
	 *
	 * ```xml
	 * <paragraph>[a</paragraph>
	 * <blockQuote>
	 * 	<paragraph>b</paragraph>
	 * </blockQuote>
	 * <paragraph>c]d</paragraph>
	 * ```
	 *
	 * In this case the paragraph will also be returned, despite the collapsed selection:
	 *
	 * ```xml
	 * <paragraph>[]a</paragraph>
	 * ```
	 *
	 * In such a scenario, however, only blocks A, B & E will be returned as blocks C & D are nested in block B:
	 *
	 * ```xml
	 * [<blockA></blockA>
	 * <blockB>
	 * 	<blockC></blockC>
	 * 	<blockD></blockD>
	 * </blockB>
	 * <blockE></blockE>]
	 * ```
	 *
	 * If the selection is inside a block all the inner blocks (A & B) are returned:
	 *
	 * ```xml
	 * <block>
	 * 	<blockA>[a</blockA>
	 * 	<blockB>b]</blockB>
	 * </block>
	 * ```
	 *
	 * **Special case**: Selection ignores first and/or last blocks if nothing (from user perspective) is selected in them.
	 *
	 * ```xml
	 * // Selection ends and the beginning of the last block.
	 * <paragraph>[a</paragraph>
	 * <paragraph>b</paragraph>
	 * <paragraph>]c</paragraph> // This block will not be returned
	 *
	 * // Selection begins at the end of the first block.
	 * <paragraph>a[</paragraph> // This block will not be returned
	 * <paragraph>b</paragraph>
	 * <paragraph>c]</paragraph>
	 *
	 * // Selection begings at the end of the first block and ends at the beginning of the last block.
	 * <paragraph>a[</paragraph> // This block will not be returned
	 * <paragraph>b</paragraph>
	 * <paragraph>]c</paragraph> // This block will not be returned
	 * ```
	 */ *getSelectedBlocks() {
        const visited = new WeakSet();
        for (const range of this.getRanges()){
            // Get start block of range in case of a collapsed range.
            const startBlock = getParentBlock$1(range.start, visited);
            if (isStartBlockSelected(startBlock, range)) {
                yield startBlock;
            }
            for (const value of range.getWalker()){
                const block = value.item;
                if (value.type == 'elementEnd' && isUnvisitedTopBlock(block, visited, range)) {
                    yield block;
                }
            }
            const endBlock = getParentBlock$1(range.end, visited);
            if (isEndBlockSelected(endBlock, range)) {
                yield endBlock;
            }
        }
    }
    /**
	 * Checks whether the selection contains the entire content of the given element. This means that selection must start
	 * at a position {@link module:engine/model/position~Position#isTouching touching} the element's start and ends at position
	 * touching the element's end.
	 *
	 * By default, this method will check whether the entire content of the selection's current root is selected.
	 * Useful to check if e.g. the user has just pressed <kbd>Ctrl</kbd> + <kbd>A</kbd>.
	 */ containsEntireContent(element = this.anchor.root) {
        const limitStartPosition = Position._createAt(element, 0);
        const limitEndPosition = Position._createAt(element, 'end');
        return limitStartPosition.isTouching(this.getFirstPosition()) && limitEndPosition.isTouching(this.getLastPosition());
    }
    /**
	 * Adds given range to internal {@link #_ranges ranges array}. Throws an error
	 * if given range is intersecting with any range that is already stored in this selection.
	 */ _pushRange(range) {
        this._checkRange(range);
        this._ranges.push(new Range(range.start, range.end));
    }
    /**
	 * Checks if given range intersects with ranges that are already in the selection. Throws an error if it does.
	 */ _checkRange(range) {
        for(let i = 0; i < this._ranges.length; i++){
            if (range.isIntersecting(this._ranges[i])) {
                /**
				 * Trying to add a range that intersects with another range in the selection.
				 *
				 * @error model-selection-range-intersects
				 * @param addedRange Range that was added to the selection.
				 * @param intersectingRange Range in the selection that intersects with `addedRange`.
				 */ throw new CKEditorError('model-selection-range-intersects', [
                    this,
                    range
                ], {
                    addedRange: range,
                    intersectingRange: this._ranges[i]
                });
            }
        }
    }
    /**
	 * Replaces all the ranges by the given ones.
	 * Uses {@link #_popRange _popRange} and {@link #_pushRange _pushRange} to ensure proper ranges removal and addition.
	 */ _replaceAllRanges(ranges) {
        this._removeAllRanges();
        for (const range of ranges){
            this._pushRange(range);
        }
    }
    /**
	 * Deletes ranges from internal range array. Uses {@link #_popRange _popRange} to
	 * ensure proper ranges removal.
	 */ _removeAllRanges() {
        while(this._ranges.length > 0){
            this._popRange();
        }
    }
    /**
	 * Removes most recently added range from the selection.
	 */ _popRange() {
        this._ranges.pop();
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Selection.prototype.is = function(type) {
    return type === 'selection' || type === 'model:selection';
};
/**
 * Checks whether the given element extends $block in the schema and has a parent (is not a root).
 * Marks it as already visited.
 */ function isUnvisitedBlock(element, visited) {
    if (visited.has(element)) {
        return false;
    }
    visited.add(element);
    return element.root.document.model.schema.isBlock(element) && !!element.parent;
}
/**
 * Checks if the given element is a $block was not previously visited and is a top block in a range.
 */ function isUnvisitedTopBlock(element, visited, range) {
    return isUnvisitedBlock(element, visited) && isTopBlockInRange(element, range);
}
/**
 * Finds the lowest element in position's ancestors which is a block.
 * It will search until first ancestor that is a limit element.
 * Marks all ancestors as already visited to not include any of them later on.
 */ function getParentBlock$1(position, visited) {
    const element = position.parent;
    const schema = element.root.document.model.schema;
    const ancestors = position.parent.getAncestors({
        parentFirst: true,
        includeSelf: true
    });
    let hasParentLimit = false;
    const block = ancestors.find((element)=>{
        // Stop searching after first parent node that is limit element.
        if (hasParentLimit) {
            return false;
        }
        hasParentLimit = schema.isLimit(element);
        return !hasParentLimit && isUnvisitedBlock(element, visited);
    });
    // Mark all ancestors of this position's parent, because find() might've stopped early and
    // the found block may be a child of another block.
    ancestors.forEach((element)=>visited.add(element));
    return block;
}
/**
 * Checks if the blocks is not nested in other block inside a range.
 */ function isTopBlockInRange(block, range) {
    const parentBlock = findAncestorBlock(block);
    if (!parentBlock) {
        return true;
    }
    // Add loose flag to check as parentRange can be equal to range.
    const isParentInRange = range.containsRange(Range._createOn(parentBlock), true);
    return !isParentInRange;
}
/**
 * If a selection starts at the end of a block, that block is not returned as from the user's perspective this block wasn't selected.
 * See [#11585](https://github.com/ckeditor/ckeditor5/issues/11585) for more details.
 *
 * ```xml
 * <paragraph>a[</paragraph> // This block will not be returned
 * <paragraph>b</paragraph>
 * <paragraph>c]</paragraph>
 * ```
 *
 * Collapsed selection is not affected by it:
 *
 * ```xml
 * <paragraph>a[]</paragraph> // This block will be returned
 * ```
 */ function isStartBlockSelected(startBlock, range) {
    if (!startBlock) {
        return false;
    }
    if (range.isCollapsed || startBlock.isEmpty) {
        return true;
    }
    if (range.start.isTouching(Position._createAt(startBlock, startBlock.maxOffset))) {
        return false;
    }
    return isTopBlockInRange(startBlock, range);
}
/**
 * If a selection ends at the beginning of a block, that block is not returned as from the user's perspective this block wasn't selected.
 * See [#984](https://github.com/ckeditor/ckeditor5-engine/issues/984) for more details.
 *
 * ```xml
 * <paragraph>[a</paragraph>
 * <paragraph>b</paragraph>
 * <paragraph>]c</paragraph> // this block will not be returned
 * ```
 *
 * Collapsed selection is not affected by it:
 *
 * ```xml
 * <paragraph>[]a</paragraph> // this block will be returned
 * ```
 */ function isEndBlockSelected(endBlock, range) {
    if (!endBlock) {
        return false;
    }
    if (range.isCollapsed || endBlock.isEmpty) {
        return true;
    }
    if (range.end.isTouching(Position._createAt(endBlock, 0))) {
        return false;
    }
    return isTopBlockInRange(endBlock, range);
}
/**
 * Returns first ancestor block of a node.
 */ function findAncestorBlock(node) {
    const schema = node.root.document.model.schema;
    let parent = node.parent;
    while(parent){
        if (schema.isBlock(parent)) {
            return parent;
        }
        parent = parent.parent;
    }
}

/**
 * `LiveRange` is a type of {@link module:engine/model/range~Range Range}
 * that updates itself as {@link module:engine/model/document~Document document}
 * is changed through operations. It may be used as a bookmark.
 *
 * **Note:** Be very careful when dealing with `LiveRange`. Each `LiveRange` instance bind events that might
 * have to be unbound. Use {@link module:engine/model/liverange~LiveRange#detach detach} whenever you don't need `LiveRange` anymore.
 */ class LiveRange extends /* #__PURE__ */ EmitterMixin(Range) {
    /**
	 * Creates a live range.
	 *
	 * @see module:engine/model/range~Range
	 */ constructor(start, end){
        super(start, end);
        bindWithDocument$1.call(this);
    }
    /**
	 * Unbinds all events previously bound by `LiveRange`. Use it whenever you don't need `LiveRange` instance
	 * anymore (i.e. when leaving scope in which it was declared or before re-assigning variable that was
	 * referring to it).
	 */ detach() {
        this.stopListening();
    }
    /**
	 * Creates a {@link module:engine/model/range~Range range instance} that is equal to this live range.
	 */ toRange() {
        return new Range(this.start, this.end);
    }
    /**
	 * Creates a `LiveRange` instance that is equal to the given range.
	 */ static fromRange(range) {
        return new LiveRange(range.start, range.end);
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
LiveRange.prototype.is = function(type) {
    return type === 'liveRange' || type === 'model:liveRange' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
    type == 'range' || type === 'model:range';
};
/**
 * Binds this `LiveRange` to the {@link module:engine/model/document~Document document}
 * that owns this range's {@link module:engine/model/range~Range#root root}.
 */ function bindWithDocument$1() {
    this.listenTo(this.root.document.model, 'applyOperation', (event, args)=>{
        const operation = args[0];
        if (!operation.isDocumentOperation) {
            return;
        }
        transform$2.call(this, operation);
    }, {
        priority: 'low'
    });
}
/**
 * Updates this range accordingly to the updates applied to the model. Bases on change events.
 */ function transform$2(operation) {
    // Transform the range by the operation. Join the result ranges if needed.
    const ranges = this.getTransformedByOperation(operation);
    const result = Range._createFromRanges(ranges);
    const boundariesChanged = !result.isEqual(this);
    const contentChanged = doesOperationChangeRangeContent(this, operation);
    let deletionPosition = null;
    if (boundariesChanged) {
        // If range boundaries have changed, fire `change:range` event.
        //
        if (result.root.rootName == '$graveyard') {
            // If the range was moved to the graveyard root, set `deletionPosition`.
            if (operation.type == 'remove') {
                deletionPosition = operation.sourcePosition;
            } else {
                // Merge operation.
                deletionPosition = operation.deletionPosition;
            }
        }
        const oldRange = this.toRange();
        this.start = result.start;
        this.end = result.end;
        this.fire('change:range', oldRange, {
            deletionPosition
        });
    } else if (contentChanged) {
        // If range boundaries have not changed, but there was change inside the range, fire `change:content` event.
        this.fire('change:content', this.toRange(), {
            deletionPosition
        });
    }
}
/**
 * Checks whether given operation changes something inside the range (even if it does not change boundaries).
 */ function doesOperationChangeRangeContent(range, operation) {
    switch(operation.type){
        case 'insert':
            return range.containsPosition(operation.position);
        case 'move':
        case 'remove':
        case 'reinsert':
        case 'merge':
            return range.containsPosition(operation.sourcePosition) || range.start.isEqual(operation.sourcePosition) || range.containsPosition(operation.targetPosition);
        case 'split':
            return range.containsPosition(operation.splitPosition) || range.containsPosition(operation.insertionPosition);
    }
    return false;
}

const storePrefix = 'selection:';
/**
 * `DocumentSelection` is a special selection which is used as the
 * {@link module:engine/model/document~Document#selection document's selection}.
 * There can be only one instance of `DocumentSelection` per document.
 *
 * Document selection can only be changed by using the {@link module:engine/model/writer~Writer} instance
 * inside the {@link module:engine/model/model~Model#change `change()`} block, as it provides a secure way to modify model.
 *
 * `DocumentSelection` is automatically updated upon changes in the {@link module:engine/model/document~Document document}
 * to always contain valid ranges. Its attributes are inherited from the text unless set explicitly.
 *
 * Differences between {@link module:engine/model/selection~Selection} and `DocumentSelection` are:
 * * there is always a range in `DocumentSelection` - even if no ranges were added there is a "default range"
 * present in the selection,
 * * ranges added to this selection updates automatically when the document changes,
 * * attributes of `DocumentSelection` are updated automatically according to selection ranges.
 *
 * Since `DocumentSelection` uses {@link module:engine/model/liverange~LiveRange live ranges}
 * and is updated when {@link module:engine/model/document~Document document}
 * changes, it cannot be set on {@link module:engine/model/node~Node nodes}
 * that are inside {@link module:engine/model/documentfragment~DocumentFragment document fragment}.
 * If you need to represent a selection in document fragment,
 * use {@link module:engine/model/selection~Selection Selection class} instead.
 */ class DocumentSelection extends /* #__PURE__ */ EmitterMixin(TypeCheckable) {
    /**
	 * Selection used internally by that class (`DocumentSelection` is a proxy to that selection).
	 */ _selection;
    /**
	 * Creates an empty live selection for given {@link module:engine/model/document~Document}.
	 *
	 * @param doc Document which owns this selection.
	 */ constructor(doc){
        super();
        this._selection = new LiveSelection(doc);
        this._selection.delegate('change:range').to(this);
        this._selection.delegate('change:attribute').to(this);
        this._selection.delegate('change:marker').to(this);
    }
    /**
	 * Describes whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
	 * collapsed.
	 */ get isCollapsed() {
        return this._selection.isCollapsed;
    }
    /**
	 * Selection anchor. Anchor may be described as a position where the most recent part of the selection starts.
	 * Together with {@link #focus} they define the direction of selection, which is important
	 * when expanding/shrinking selection. Anchor is always {@link module:engine/model/range~Range#start start} or
	 * {@link module:engine/model/range~Range#end end} position of the most recently added range.
	 *
	 * Is set to `null` if there are no ranges in selection.
	 *
	 * @see #focus
	 */ get anchor() {
        return this._selection.anchor;
    }
    /**
	 * Selection focus. Focus is a position where the selection ends.
	 *
	 * Is set to `null` if there are no ranges in selection.
	 *
	 * @see #anchor
	 */ get focus() {
        return this._selection.focus;
    }
    /**
	 * Number of ranges in selection.
	 */ get rangeCount() {
        return this._selection.rangeCount;
    }
    /**
	 * Describes whether `Documentselection` has own range(s) set, or if it is defaulted to
	 * {@link module:engine/model/document~Document#_getDefaultRange document's default range}.
	 */ get hasOwnRange() {
        return this._selection.hasOwnRange;
    }
    /**
	 * Specifies whether the {@link #focus}
	 * precedes {@link #anchor}.
	 *
	 * @readonly
	 * @type {Boolean}
	 */ get isBackward() {
        return this._selection.isBackward;
    }
    /**
	 * Describes whether the gravity is overridden (using {@link module:engine/model/writer~Writer#overrideSelectionGravity}) or not.
	 *
	 * Note that the gravity remains overridden as long as will not be restored the same number of times as it was overridden.
	 */ get isGravityOverridden() {
        return this._selection.isGravityOverridden;
    }
    /**
	 * A collection of selection {@link module:engine/model/markercollection~Marker markers}.
	 * Marker is a selection marker when selection range is inside the marker range.
	 *
	 * **Note**: Only markers from {@link ~DocumentSelection#observeMarkers observed markers groups} are collected.
	 */ get markers() {
        return this._selection.markers;
    }
    /**
	 * Used for the compatibility with the {@link module:engine/model/selection~Selection#isEqual} method.
	 *
	 * @internal
	 */ get _ranges() {
        return this._selection._ranges;
    }
    /**
	 * Returns an iterable that iterates over copies of selection ranges.
	 */ getRanges() {
        return this._selection.getRanges();
    }
    /**
	 * Returns the first position in the selection.
	 * First position is the position that {@link module:engine/model/position~Position#isBefore is before}
	 * any other position in the selection.
	 *
	 * Returns `null` if there are no ranges in selection.
	 */ getFirstPosition() {
        return this._selection.getFirstPosition();
    }
    /**
	 * Returns the last position in the selection.
	 * Last position is the position that {@link module:engine/model/position~Position#isAfter is after}
	 * any other position in the selection.
	 *
	 * Returns `null` if there are no ranges in selection.
	 */ getLastPosition() {
        return this._selection.getLastPosition();
    }
    /**
	 * Returns a copy of the first range in the selection.
	 * First range is the one which {@link module:engine/model/range~Range#start start} position
	 * {@link module:engine/model/position~Position#isBefore is before} start position of all other ranges
	 * (not to confuse with the first range added to the selection).
	 *
	 * Returns `null` if there are no ranges in selection.
	 */ getFirstRange() {
        return this._selection.getFirstRange();
    }
    /**
	 * Returns a copy of the last range in the selection.
	 * Last range is the one which {@link module:engine/model/range~Range#end end} position
	 * {@link module:engine/model/position~Position#isAfter is after} end position of all other ranges (not to confuse with the range most
	 * recently added to the selection).
	 *
	 * Returns `null` if there are no ranges in selection.
	 */ getLastRange() {
        return this._selection.getLastRange();
    }
    /**
	 * Gets elements of type {@link module:engine/model/schema~Schema#isBlock "block"} touched by the selection.
	 *
	 * This method's result can be used for example to apply block styling to all blocks covered by this selection.
	 *
	 * **Note:** `getSelectedBlocks()` returns blocks that are nested in other non-block elements
	 * but will not return blocks nested in other blocks.
	 *
	 * In this case the function will return exactly all 3 paragraphs (note: `<blockQuote>` is not a block itself):
	 *
	 * ```
	 * <paragraph>[a</paragraph>
	 * <blockQuote>
	 * 	<paragraph>b</paragraph>
	 * </blockQuote>
	 * <paragraph>c]d</paragraph>
	 * ```
	 *
	 * In this case the paragraph will also be returned, despite the collapsed selection:
	 *
	 * ```
	 * <paragraph>[]a</paragraph>
	 * ```
	 *
	 * In such a scenario, however, only blocks A, B & E will be returned as blocks C & D are nested in block B:
	 *
	 * ```
	 * [<blockA></blockA>
	 * <blockB>
	 * 	<blockC></blockC>
	 * 	<blockD></blockD>
	 * </blockB>
	 * <blockE></blockE>]
	 * ```
	 *
	 * If the selection is inside a block all the inner blocks (A & B) are returned:
	 *
	 * ```
	 * <block>
	 * 	<blockA>[a</blockA>
	 * 	<blockB>b]</blockB>
	 * </block>
	 * ```
	 *
	 * **Special case**: If a selection ends at the beginning of a block, that block is not returned as from user perspective
	 * this block wasn't selected. See [#984](https://github.com/ckeditor/ckeditor5-engine/issues/984) for more details.
	 *
	 * ```
	 * <paragraph>[a</paragraph>
	 * <paragraph>b</paragraph>
	 * <paragraph>]c</paragraph> // this block will not be returned
	 * ```
	 */ getSelectedBlocks() {
        return this._selection.getSelectedBlocks();
    }
    /**
	 * Returns the selected element. {@link module:engine/model/element~Element Element} is considered as selected if there is only
	 * one range in the selection, and that range contains exactly one element.
	 * Returns `null` if there is no selected element.
	 */ getSelectedElement() {
        return this._selection.getSelectedElement();
    }
    /**
	 * Checks whether the selection contains the entire content of the given element. This means that selection must start
	 * at a position {@link module:engine/model/position~Position#isTouching touching} the element's start and ends at position
	 * touching the element's end.
	 *
	 * By default, this method will check whether the entire content of the selection's current root is selected.
	 * Useful to check if e.g. the user has just pressed <kbd>Ctrl</kbd> + <kbd>A</kbd>.
	 */ containsEntireContent(element) {
        return this._selection.containsEntireContent(element);
    }
    /**
	 * Unbinds all events previously bound by document selection.
	 */ destroy() {
        this._selection.destroy();
    }
    /**
	 * Returns iterable that iterates over this selection's attribute keys.
	 */ getAttributeKeys() {
        return this._selection.getAttributeKeys();
    }
    /**
	 * Returns iterable that iterates over this selection's attributes.
	 *
	 * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
	 * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
	 */ getAttributes() {
        return this._selection.getAttributes();
    }
    /**
	 * Gets an attribute value for given key or `undefined` if that attribute is not set on the selection.
	 *
	 * @param key Key of attribute to look for.
	 * @returns Attribute value or `undefined`.
	 */ getAttribute(key) {
        return this._selection.getAttribute(key);
    }
    /**
	 * Checks if the selection has an attribute for given key.
	 *
	 * @param key Key of attribute to check.
	 * @returns `true` if attribute with given key is set on selection, `false` otherwise.
	 */ hasAttribute(key) {
        return this._selection.hasAttribute(key);
    }
    /**
	 * Refreshes selection attributes and markers according to the current position in the model.
	 */ refresh() {
        this._selection.updateMarkers();
        this._selection._updateAttributes(false);
    }
    /**
	 * Registers a marker group prefix or a marker name to be collected in the
	 * {@link ~DocumentSelection#markers selection markers collection}.
	 *
	 * See also {@link module:engine/model/markercollection~MarkerCollection#getMarkersGroup `MarkerCollection#getMarkersGroup()`}.
	 *
	 * @param prefixOrName The marker group prefix or marker name.
	 */ observeMarkers(prefixOrName) {
        this._selection.observeMarkers(prefixOrName);
    }
    /**
	 * Moves {@link module:engine/model/documentselection~DocumentSelection#focus} to the specified location.
	 * Should be used only within the {@link module:engine/model/writer~Writer#setSelectionFocus} method.
	 *
	 * The location can be specified in the same form as
	 * {@link module:engine/model/writer~Writer#createPositionAt writer.createPositionAt()} parameters.
	 *
	 * @see module:engine/model/writer~Writer#setSelectionFocus
	 * @internal
	 * @param offset Offset or one of the flags. Used only when
	 * first parameter is a {@link module:engine/model/item~Item model item}.
	 */ _setFocus(itemOrPosition, offset) {
        this._selection.setFocus(itemOrPosition, offset);
    }
    /**
	 * Sets this selection's ranges and direction to the specified location based on the given
	 * {@link module:engine/model/selection~Selectable selectable}.
	 * Should be used only within the {@link module:engine/model/writer~Writer#setSelection} method.
	 *
	 * @see module:engine/model/writer~Writer#setSelection
	 * @internal
	 */ _setTo(...args) {
        this._selection.setTo(...args);
    }
    /**
	 * Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
	 * Should be used only within the {@link module:engine/model/writer~Writer#setSelectionAttribute} method.
	 *
	 * @see module:engine/model/writer~Writer#setSelectionAttribute
	 * @internal
	 * @param key Key of the attribute to set.
	 * @param value Attribute value.
	 */ _setAttribute(key, value) {
        this._selection.setAttribute(key, value);
    }
    /**
	 * Removes an attribute with given key from the selection.
	 * If the given attribute was set on the selection, fires the {@link module:engine/model/selection~Selection#event:change:range}
	 * event with removed attribute key.
	 * Should be used only within the {@link module:engine/model/writer~Writer#removeSelectionAttribute} method.
	 *
	 * @see module:engine/model/writer~Writer#removeSelectionAttribute
	 * @internal
	 * @param key Key of the attribute to remove.
	 */ _removeAttribute(key) {
        this._selection.removeAttribute(key);
    }
    /**
	 * Returns an iterable that iterates through all selection attributes stored in current selection's parent.
	 *
	 * @internal
	 */ _getStoredAttributes() {
        return this._selection.getStoredAttributes();
    }
    /**
	 * Temporarily changes the gravity of the selection from the left to the right.
	 *
	 * The gravity defines from which direction the selection inherits its attributes. If it's the default left
	 * gravity, the selection (after being moved by the the user) inherits attributes from its left hand side.
	 * This method allows to temporarily override this behavior by forcing the gravity to the right.
	 *
	 * It returns an unique identifier which is required to restore the gravity. It guarantees the symmetry
	 * of the process.
	 *
	 * @see module:engine/model/writer~Writer#overrideSelectionGravity
	 * @internal
	 * @returns The unique id which allows restoring the gravity.
	 */ _overrideGravity() {
        return this._selection.overrideGravity();
    }
    /**
	 * Restores the {@link ~DocumentSelection#_overrideGravity overridden gravity}.
	 *
	 * Restoring the gravity is only possible using the unique identifier returned by
	 * {@link ~DocumentSelection#_overrideGravity}. Note that the gravity remains overridden as long as won't be restored
	 * the same number of times it was overridden.
	 *
	 * @see module:engine/model/writer~Writer#restoreSelectionGravity
	 * @internal
	 * @param uid The unique id returned by {@link #_overrideGravity}.
	 */ _restoreGravity(uid) {
        this._selection.restoreGravity(uid);
    }
    /**
	 * Generates and returns an attribute key for selection attributes store, basing on original attribute key.
	 *
	 * @internal
	 * @param key Attribute key to convert.
	 * @returns Converted attribute key, applicable for selection store.
	 */ static _getStoreAttributeKey(key) {
        return storePrefix + key;
    }
    /**
	 * Checks whether the given attribute key is an attribute stored on an element.
	 *
	 * @internal
	 */ static _isStoreAttributeKey(key) {
        return key.startsWith(storePrefix);
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
DocumentSelection.prototype.is = function(type) {
    return type === 'selection' || type == 'model:selection' || type == 'documentSelection' || type == 'model:documentSelection';
};
/**
 * `LiveSelection` is used internally by {@link module:engine/model/documentselection~DocumentSelection} and shouldn't be used directly.
 *
 * LiveSelection` is automatically updated upon changes in the {@link module:engine/model/document~Document document}
 * to always contain valid ranges. Its attributes are inherited from the text unless set explicitly.
 *
 * Differences between {@link module:engine/model/selection~Selection} and `LiveSelection` are:
 * * there is always a range in `LiveSelection` - even if no ranges were added there is a "default range"
 * present in the selection,
 * * ranges added to this selection updates automatically when the document changes,
 * * attributes of `LiveSelection` are updated automatically according to selection ranges.
 */ class LiveSelection extends Selection {
    /**
	 * List of selection markers.
	 * Marker is a selection marker when selection range is inside the marker range.
	 */ markers = new Collection({
        idProperty: 'name'
    });
    /**
	 * Document which owns this selection.
	 */ _model;
    /**
	 * Document which owns this selection.
	 */ _document;
    /**
	 * Keeps mapping of attribute name to priority with which the attribute got modified (added/changed/removed)
	 * last time. Possible values of priority are: `'low'` and `'normal'`.
	 *
	 * Priorities are used by internal `LiveSelection` mechanisms. All attributes set using `LiveSelection`
	 * attributes API are set with `'normal'` priority.
	 */ _attributePriority = new Map();
    /**
	 * Position to which the selection should be set if the last selection range was moved to the graveyard.
	 */ _selectionRestorePosition = null;
    /**
	 * Flag that informs whether the selection ranges have changed. It is changed on true when `LiveRange#change:range` event is fired.
	 */ _hasChangedRange = false;
    /**
	 * Each overriding gravity adds an UID to the set and each removal removes it.
	 * Gravity is overridden when there's at least one UID in the set.
	 * Gravity is restored when the set is empty.
	 * This is to prevent conflicts when gravity is overridden by more than one feature at the same time.
	 */ _overriddenGravityRegister = new Set();
    /**
	 * Prefixes of marker names that should affect `LiveSelection#markers` collection.
	 */ _observedMarkers = new Set();
    /**
	 * Creates an empty live selection for given {@link module:engine/model/document~Document}.
	 *
	 * @param doc Document which owns this selection.
	 */ constructor(doc){
        super();
        this._model = doc.model;
        this._document = doc;
        // Ensure selection is correct after each operation.
        this.listenTo(this._model, 'applyOperation', (evt, args)=>{
            const operation = args[0];
            if (!operation.isDocumentOperation || operation.type == 'marker' || operation.type == 'rename' || operation.type == 'noop') {
                return;
            }
            // Fix selection if the last range was removed from it and we have a position to which we can restore the selection.
            if (this._ranges.length == 0 && this._selectionRestorePosition) {
                this._fixGraveyardSelection(this._selectionRestorePosition);
            }
            // "Forget" the restore position even if it was not "used".
            this._selectionRestorePosition = null;
            if (this._hasChangedRange) {
                this._hasChangedRange = false;
                this.fire('change:range', {
                    directChange: false
                });
            }
        }, {
            priority: 'lowest'
        });
        // Ensure selection is correct and up to date after each range change.
        this.on('change:range', ()=>{
            this._validateSelectionRanges(this.getRanges());
        });
        // Update markers data stored by the selection after each marker change.
        // This handles only marker changes done through marker operations (not model tree changes).
        this.listenTo(this._model.markers, 'update', (evt, marker, oldRange, newRange)=>{
            this._updateMarker(marker, newRange);
        });
        // Ensure selection is up to date after each change block.
        this.listenTo(this._document, 'change', (evt, batch)=>{
            clearAttributesStoredInElement(this._model, batch);
        });
    }
    get isCollapsed() {
        const length = this._ranges.length;
        return length === 0 ? this._document._getDefaultRange().isCollapsed : super.isCollapsed;
    }
    get anchor() {
        return super.anchor || this._document._getDefaultRange().start;
    }
    get focus() {
        return super.focus || this._document._getDefaultRange().end;
    }
    get rangeCount() {
        return this._ranges.length ? this._ranges.length : 1;
    }
    /**
	 * Describes whether `LiveSelection` has own range(s) set, or if it is defaulted to
	 * {@link module:engine/model/document~Document#_getDefaultRange document's default range}.
	 */ get hasOwnRange() {
        return this._ranges.length > 0;
    }
    /**
	 * When set to `true` then selection attributes on node before the caret won't be taken
	 * into consideration while updating selection attributes.
	 */ get isGravityOverridden() {
        return !!this._overriddenGravityRegister.size;
    }
    /**
	 * Unbinds all events previously bound by live selection.
	 */ destroy() {
        for(let i = 0; i < this._ranges.length; i++){
            this._ranges[i].detach();
        }
        this.stopListening();
    }
    *getRanges() {
        if (this._ranges.length) {
            yield* super.getRanges();
        } else {
            yield this._document._getDefaultRange();
        }
    }
    getFirstRange() {
        return super.getFirstRange() || this._document._getDefaultRange();
    }
    getLastRange() {
        return super.getLastRange() || this._document._getDefaultRange();
    }
    setTo(...args) {
        super.setTo(...args);
        this._updateAttributes(true);
        this.updateMarkers();
    }
    setFocus(itemOrPosition, offset) {
        super.setFocus(itemOrPosition, offset);
        this._updateAttributes(true);
        this.updateMarkers();
    }
    setAttribute(key, value) {
        if (this._setAttribute(key, value)) {
            // Fire event with exact data.
            const attributeKeys = [
                key
            ];
            this.fire('change:attribute', {
                attributeKeys,
                directChange: true
            });
        }
    }
    removeAttribute(key) {
        if (this._removeAttribute(key)) {
            // Fire event with exact data.
            const attributeKeys = [
                key
            ];
            this.fire('change:attribute', {
                attributeKeys,
                directChange: true
            });
        }
    }
    overrideGravity() {
        const overrideUid = uid();
        // Remember that another overriding has been requested. It will need to be removed
        // before the gravity is to be restored.
        this._overriddenGravityRegister.add(overrideUid);
        if (this._overriddenGravityRegister.size === 1) {
            this._updateAttributes(true);
        }
        return overrideUid;
    }
    restoreGravity(uid) {
        if (!this._overriddenGravityRegister.has(uid)) {
            /**
			 * Restoring gravity for an unknown UID is not possible. Make sure you are using a correct
			 * UID obtained from the {@link module:engine/model/writer~Writer#overrideSelectionGravity} to restore.
			 *
			 * @error document-selection-gravity-wrong-restore
			 * @param uid The unique identifier returned by
			 * {@link module:engine/model/documentselection~DocumentSelection#_overrideGravity}.
			 */ throw new CKEditorError('document-selection-gravity-wrong-restore', this, {
                uid
            });
        }
        this._overriddenGravityRegister.delete(uid);
        // Restore gravity only when all overriding have been restored.
        if (!this.isGravityOverridden) {
            this._updateAttributes(true);
        }
    }
    observeMarkers(prefixOrName) {
        this._observedMarkers.add(prefixOrName);
        this.updateMarkers();
    }
    _replaceAllRanges(ranges) {
        this._validateSelectionRanges(ranges);
        super._replaceAllRanges(ranges);
    }
    _popRange() {
        this._ranges.pop().detach();
    }
    _pushRange(range) {
        const liveRange = this._prepareRange(range);
        // `undefined` is returned when given `range` is in graveyard root.
        if (liveRange) {
            this._ranges.push(liveRange);
        }
    }
    _validateSelectionRanges(ranges) {
        for (const range of ranges){
            if (!this._document._validateSelectionRange(range)) {
                /**
				 * Range from {@link module:engine/model/documentselection~DocumentSelection document selection}
				 * starts or ends at incorrect position.
				 *
				 * @error document-selection-wrong-position
				 * @param range
				 */ throw new CKEditorError('document-selection-wrong-position', this, {
                    range
                });
            }
        }
    }
    /**
	 * Prepares given range to be added to selection. Checks if it is correct,
	 * converts it to {@link module:engine/model/liverange~LiveRange LiveRange}
	 * and sets listeners listening to the range's change event.
	 */ _prepareRange(range) {
        this._checkRange(range);
        if (range.root == this._document.graveyard) {
            // @if CK_DEBUG // console.warn( 'Trying to add a Range that is in the graveyard root. Range rejected.' );
            return;
        }
        const liveRange = LiveRange.fromRange(range);
        // If selection range is moved to the graveyard remove it from the selection object.
        // Also, save some data that can be used to restore selection later, on `Model#applyOperation` event.
        liveRange.on('change:range', (evt, oldRange, data)=>{
            this._hasChangedRange = true;
            if (liveRange.root == this._document.graveyard) {
                this._selectionRestorePosition = data.deletionPosition;
                const index = this._ranges.indexOf(liveRange);
                this._ranges.splice(index, 1);
                liveRange.detach();
            }
        });
        return liveRange;
    }
    updateMarkers() {
        if (!this._observedMarkers.size) {
            return;
        }
        const markers = [];
        let changed = false;
        for (const marker of this._model.markers){
            const markerGroup = marker.name.split(':', 1)[0];
            if (!this._observedMarkers.has(markerGroup)) {
                continue;
            }
            const markerRange = marker.getRange();
            for (const selectionRange of this.getRanges()){
                if (markerRange.containsRange(selectionRange, !selectionRange.isCollapsed)) {
                    markers.push(marker);
                }
            }
        }
        const oldMarkers = Array.from(this.markers);
        for (const marker of markers){
            if (!this.markers.has(marker)) {
                this.markers.add(marker);
                changed = true;
            }
        }
        for (const marker of Array.from(this.markers)){
            if (!markers.includes(marker)) {
                this.markers.remove(marker);
                changed = true;
            }
        }
        if (changed) {
            this.fire('change:marker', {
                oldMarkers,
                directChange: false
            });
        }
    }
    _updateMarker(marker, markerRange) {
        const markerGroup = marker.name.split(':', 1)[0];
        if (!this._observedMarkers.has(markerGroup)) {
            return;
        }
        let changed = false;
        const oldMarkers = Array.from(this.markers);
        const hasMarker = this.markers.has(marker);
        if (!markerRange) {
            if (hasMarker) {
                this.markers.remove(marker);
                changed = true;
            }
        } else {
            let contained = false;
            for (const selectionRange of this.getRanges()){
                if (markerRange.containsRange(selectionRange, !selectionRange.isCollapsed)) {
                    contained = true;
                    break;
                }
            }
            if (contained && !hasMarker) {
                this.markers.add(marker);
                changed = true;
            } else if (!contained && hasMarker) {
                this.markers.remove(marker);
                changed = true;
            }
        }
        if (changed) {
            this.fire('change:marker', {
                oldMarkers,
                directChange: false
            });
        }
    }
    /**
	 * Updates this selection attributes according to its ranges and the {@link module:engine/model/document~Document model document}.
	 */ _updateAttributes(clearAll) {
        const newAttributes = toMap(this._getSurroundingAttributes());
        const oldAttributes = toMap(this.getAttributes());
        if (clearAll) {
            // If `clearAll` remove all attributes and reset priorities.
            this._attributePriority = new Map();
            this._attrs = new Map();
        } else {
            // If not, remove only attributes added with `low` priority.
            for (const [key, priority] of this._attributePriority){
                if (priority == 'low') {
                    this._attrs.delete(key);
                    this._attributePriority.delete(key);
                }
            }
        }
        this._setAttributesTo(newAttributes);
        // Let's evaluate which attributes really changed.
        const changed = [];
        // First, loop through all attributes that are set on selection right now.
        // Check which of them are different than old attributes.
        for (const [newKey, newValue] of this.getAttributes()){
            if (!oldAttributes.has(newKey) || oldAttributes.get(newKey) !== newValue) {
                changed.push(newKey);
            }
        }
        // Then, check which of old attributes got removed.
        for (const [oldKey] of oldAttributes){
            if (!this.hasAttribute(oldKey)) {
                changed.push(oldKey);
            }
        }
        // Fire event with exact data (fire only if anything changed).
        if (changed.length > 0) {
            this.fire('change:attribute', {
                attributeKeys: changed,
                directChange: false
            });
        }
    }
    /**
	 * Internal method for setting `LiveSelection` attribute. Supports attribute priorities (through `directChange`
	 * parameter).
	 */ _setAttribute(key, value, directChange = true) {
        const priority = directChange ? 'normal' : 'low';
        if (priority == 'low' && this._attributePriority.get(key) == 'normal') {
            // Priority too low.
            return false;
        }
        const oldValue = super.getAttribute(key);
        // Don't do anything if value has not changed.
        if (oldValue === value) {
            return false;
        }
        this._attrs.set(key, value);
        // Update priorities map.
        this._attributePriority.set(key, priority);
        return true;
    }
    /**
	 * Internal method for removing `LiveSelection` attribute. Supports attribute priorities (through `directChange`
	 * parameter).
	 *
	 * NOTE: Even if attribute is not present in the selection but is provided to this method, it's priority will
	 * be changed according to `directChange` parameter.
	 */ _removeAttribute(key, directChange = true) {
        const priority = directChange ? 'normal' : 'low';
        if (priority == 'low' && this._attributePriority.get(key) == 'normal') {
            // Priority too low.
            return false;
        }
        // Update priorities map.
        this._attributePriority.set(key, priority);
        // Don't do anything if value has not changed.
        if (!super.hasAttribute(key)) {
            return false;
        }
        this._attrs.delete(key);
        return true;
    }
    /**
	 * Internal method for setting multiple `LiveSelection` attributes. Supports attribute priorities (through
	 * `directChange` parameter).
	 */ _setAttributesTo(attrs) {
        const changed = new Set();
        for (const [oldKey, oldValue] of this.getAttributes()){
            // Do not remove attribute if attribute with same key and value is about to be set.
            if (attrs.get(oldKey) === oldValue) {
                continue;
            }
            // All rest attributes will be removed so changed attributes won't change .
            this._removeAttribute(oldKey, false);
        }
        for (const [key, value] of attrs){
            // Attribute may not be set because of attributes or because same key/value is already added.
            const gotAdded = this._setAttribute(key, value, false);
            if (gotAdded) {
                changed.add(key);
            }
        }
        return changed;
    }
    /**
	 * Returns an iterable that iterates through all selection attributes stored in current selection's parent.
	 */ *getStoredAttributes() {
        const selectionParent = this.getFirstPosition().parent;
        if (this.isCollapsed && selectionParent.isEmpty) {
            for (const key of selectionParent.getAttributeKeys()){
                if (key.startsWith(storePrefix)) {
                    const realKey = key.substr(storePrefix.length);
                    yield [
                        realKey,
                        selectionParent.getAttribute(key)
                    ];
                }
            }
        }
    }
    /**
	 * Checks model text nodes that are closest to the selection's first position and returns attributes of first
	 * found element. If there are no text nodes in selection's first position parent, it returns selection
	 * attributes stored in that parent.
	 */ _getSurroundingAttributes() {
        const position = this.getFirstPosition();
        const schema = this._model.schema;
        if (position.root.rootName == '$graveyard') {
            return null;
        }
        let attrs = null;
        if (!this.isCollapsed) {
            // 1. If selection is a range...
            const range = this.getFirstRange();
            // ...look for a first character node in that range and take attributes from it.
            for (const value of range){
                // If the item is an object, we don't want to get attributes from its children...
                if (value.item.is('element') && schema.isObject(value.item)) {
                    // ...but collect attributes from inline object.
                    attrs = getTextAttributes(value.item, schema);
                    break;
                }
                if (value.type == 'text') {
                    attrs = value.item.getAttributes();
                    break;
                }
            }
        } else {
            // 2. If the selection is a caret or the range does not contain a character node...
            const nodeBefore = position.textNode ? position.textNode : position.nodeBefore;
            const nodeAfter = position.textNode ? position.textNode : position.nodeAfter;
            // When gravity is overridden then don't take node before into consideration.
            if (!this.isGravityOverridden) {
                // ...look at the node before caret and take attributes from it if it is a character node.
                attrs = getTextAttributes(nodeBefore, schema);
            }
            // 3. If not, look at the node after caret...
            if (!attrs) {
                attrs = getTextAttributes(nodeAfter, schema);
            }
            // 4. If not, try to find the first character on the left, that is in the same node.
            // When gravity is overridden then don't take node before into consideration.
            if (!this.isGravityOverridden && !attrs) {
                let node = nodeBefore;
                while(node && !attrs){
                    node = node.previousSibling;
                    attrs = getTextAttributes(node, schema);
                }
            }
            // 5. If not found, try to find the first character on the right, that is in the same node.
            if (!attrs) {
                let node = nodeAfter;
                while(node && !attrs){
                    node = node.nextSibling;
                    attrs = getTextAttributes(node, schema);
                }
            }
            // 6. If not found, selection should retrieve attributes from parent.
            if (!attrs) {
                attrs = this.getStoredAttributes();
            }
        }
        return attrs;
    }
    /**
	 * Fixes the selection after all its ranges got removed.
	 * @param deletionPosition Position where the deletion happened.
	 */ _fixGraveyardSelection(deletionPosition) {
        // Find a range that is a correct selection range and is closest to the position where the deletion happened.
        const selectionRange = this._model.schema.getNearestSelectionRange(deletionPosition);
        // If nearest valid selection range has been found - add it in the place of old range.
        if (selectionRange) {
            // Check the range, convert it to live range, bind events, etc.
            this._pushRange(selectionRange);
        }
    // If nearest valid selection range cannot be found don't add any range. Selection will be set to the default range.
    }
}
/**
 * Helper function for {@link module:engine/model/liveselection~LiveSelection#_updateAttributes}.
 *
 * It checks if the passed model item is a text node (or text proxy) and, if so, returns it's attributes.
 * If not, it checks if item is an inline object and does the same. Otherwise it returns `null`.
 */ function getTextAttributes(node, schema) {
    if (!node) {
        return null;
    }
    if (node instanceof TextProxy || node instanceof Text) {
        return node.getAttributes();
    }
    if (!schema.isInline(node)) {
        return null;
    }
    // Stop on inline elements (such as `<softBreak>`) that are not objects (such as `<imageInline>` or `<mathml>`).
    if (!schema.isObject(node)) {
        return [];
    }
    const attributes = [];
    // Collect all attributes that can be applied to the text node.
    for (const [key, value] of node.getAttributes()){
        if (schema.checkAttribute('$text', key) && schema.getAttributeProperties(key).copyFromObject !== false) {
            attributes.push([
                key,
                value
            ]);
        }
    }
    return attributes;
}
/**
 * Removes selection attributes from element which is not empty anymore.
 */ function clearAttributesStoredInElement(model, batch) {
    const differ = model.document.differ;
    for (const entry of differ.getChanges()){
        if (entry.type != 'insert') {
            continue;
        }
        const changeParent = entry.position.parent;
        const isNoLongerEmpty = entry.length === changeParent.maxOffset;
        if (isNoLongerEmpty) {
            model.enqueueChange(batch, (writer)=>{
                const storedAttributes = Array.from(changeParent.getAttributeKeys()).filter((key)=>key.startsWith(storePrefix));
                for (const key of storedAttributes){
                    writer.removeAttribute(key, changeParent);
                }
            });
        }
    }
}

/**
 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */ /**
 * @module engine/conversion/conversionhelpers
 */ /**
 * Base class for conversion helpers.
 */ class ConversionHelpers {
    _dispatchers;
    /**
	 * Creates a conversion helpers instance.
	 */ constructor(dispatchers){
        this._dispatchers = dispatchers;
    }
    /**
	 * Registers a conversion helper.
	 *
	 * **Note**: See full usage example in the `{@link module:engine/conversion/conversion~Conversion#for conversion.for()}`
	 * method description.
	 *
	 * @param conversionHelper The function to be called on event.
	 */ add(conversionHelper) {
        for (const dispatcher of this._dispatchers){
            conversionHelper(dispatcher);
        }
        return this;
    }
}

/**
 * Downcast conversion helper functions.
 *
 * Learn more about {@glink framework/deep-dive/conversion/downcast downcast helpers}.
 *
 * @extends module:engine/conversion/conversionhelpers~ConversionHelpers
 */ class DowncastHelpers extends ConversionHelpers {
    /**
	 * Model element to view element conversion helper.
	 *
	 * This conversion results in creating a view element. For example, model `<paragraph>Foo</paragraph>` becomes `<p>Foo</p>` in the view.
	 *
	 * ```ts
	 * editor.conversion.for( 'downcast' ).elementToElement( {
	 * 	model: 'paragraph',
	 * 	view: 'p'
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).elementToElement( {
	 * 	model: 'paragraph',
	 * 	view: 'div',
	 * 	converterPriority: 'high'
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).elementToElement( {
	 * 	model: 'fancyParagraph',
	 * 	view: {
	 * 		name: 'p',
	 * 		classes: 'fancy'
	 * 	}
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).elementToElement( {
	 * 	model: 'heading',
	 * 	view: ( modelElement, conversionApi ) => {
	 * 		const { writer } = conversionApi;
	 *
	 * 		return writer.createContainerElement( 'h' + modelElement.getAttribute( 'level' ) );
	 * 	}
	 * } );
	 * ```
	 *
	 * The element-to-element conversion supports the reconversion mechanism. It can be enabled by using either the `attributes` or
	 * the `children` props on a model description. You will find a couple examples below.
	 *
	 * In order to reconvert an element if any of its direct children have been added or removed, use the `children` property on a `model`
	 * description. For example, this model:
	 *
	 * ```xml
	 * <box>
	 * 	<paragraph>Some text.</paragraph>
	 * </box>
	 * ```
	 *
	 * will be converted into this structure in the view:
	 *
	 * ```html
	 * <div class="box" data-type="single">
	 * 	<p>Some text.</p>
	 * </div>
	 * ```
	 *
	 * But if more items were inserted in the model:
	 *
	 * ```xml
	 * <box>
	 * 	<paragraph>Some text.</paragraph>
	 * 	<paragraph>Other item.</paragraph>
	 * </box>
	 * ```
	 *
	 * it will be converted into this structure in the view (note the element `data-type` change):
	 *
	 * ```html
	 * <div class="box" data-type="multiple">
	 * 	<p>Some text.</p>
	 * 	<p>Other item.</p>
	 * </div>
	 * ```
	 *
	 * Such a converter would look like this (note that the `paragraph` elements are converted separately):
	 *
	 * ```ts
	 * editor.conversion.for( 'downcast' ).elementToElement( {
	 * 	model: {
	 * 		name: 'box',
	 * 		children: true
	 * 	},
	 * 	view: ( modelElement, conversionApi ) => {
	 * 		const { writer } = conversionApi;
	 *
	 * 		return writer.createContainerElement( 'div', {
	 * 			class: 'box',
	 * 			'data-type': modelElement.childCount == 1 ? 'single' : 'multiple'
	 * 		} );
	 * 	}
	 * } );
	 * ```
	 *
	 * In order to reconvert element if any of its attributes have been updated, use the `attributes` property on a `model`
	 * description. For example, this model:
	 *
	 * ```xml
	 * <heading level="2">Some text.</heading>
	 * ```
	 *
	 * will be converted into this structure in the view:
	 *
	 * ```html
	 * <h2>Some text.</h2>
	 * ```
	 *
	 * But if the `heading` element's `level` attribute has been updated to `3` for example, then
	 * it will be converted into this structure in the view:
	 *
	 * ```html
	 * <h3>Some text.</h3>
	 * ```
	 *
	 * Such a converter would look as follows:
	 *
	 * ```ts
	 * editor.conversion.for( 'downcast' ).elementToElement( {
	 * 	model: {
	 * 		name: 'heading',
	 * 		attributes: 'level'
	 * 	},
	 * 	view: ( modelElement, conversionApi ) => {
	 * 		const { writer } = conversionApi;
	 *
	 * 		return writer.createContainerElement( 'h' + modelElement.getAttribute( 'level' ) );
	 * 	}
	 * } );
	 * ```
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * You can read more about the element-to-element conversion in the
	 * {@glink framework/deep-dive/conversion/downcast downcast conversion} guide.
	 *
	 * @param config Conversion configuration.
	 * @param config.model The description or a name of the model element to convert.
	 * @param config.model.attributes The list of attribute names that should be consumed while creating
	 * the view element. Note that the view will be reconverted if any of the listed attributes changes.
 	 * @param config.model.children Specifies whether the view element requires reconversion if the list
	 * of the model child nodes changed.
	 * @param config.view A view element definition or a function that takes the model element and
	 * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API}
	 * as parameters and returns a view container element.
	 */ elementToElement(config) {
        return this.add(downcastElementToElement(config));
    }
    /**
	 * The model element to view structure (several elements) conversion helper.
	 *
	 * This conversion results in creating a view structure with one or more slots defined for the child nodes.
	 * For example, a model `<table>` may become this structure in the view:
	 *
	 * ```html
	 * <figure class="table">
	 * 	<table>
	 * 		<tbody>${ slot for table rows }</tbody>
	 * 	</table>
	 * </figure>
	 * ```
	 *
	 * The children of the model's `<table>` element will be inserted into the `<tbody>` element.
	 * If the `elementToElement()` helper was used, the children would be inserted into the `<figure>`.
	 *
	 * Imagine a table feature where for this model structure:
	 *
	 * ```xml
	 * <table headingRows="1">
	 * 	<tableRow> ... table cells 1 ... </tableRow>
	 * 	<tableRow> ... table cells 2 ... </tableRow>
	 * 	<tableRow> ... table cells 3 ... </tableRow>
	 * 	<caption>Caption text</caption>
	 * </table>
	 * ```
	 *
	 * we want to generate this view structure:
	 *
	 * ```html
	 * <figure class="table">
	 * 	<table>
	 * 		<thead>
	 * 			<tr> ... table cells 1 ... </tr>
	 * 		</thead>
	 * 		<tbody>
	 * 			<tr> ... table cells 2 ... </tr>
	 * 			<tr> ... table cells 3 ... </tr>
	 * 		</tbody>
	 * 	</table>
	 * 	<figcaption>Caption text</figcaption>
	 * </figure>
	 * ```
	 *
	 * The converter has to take the `headingRows` attribute into consideration when allocating the `<tableRow>` elements
	 * into the `<tbody>` and `<thead>` elements. Hence, we need two slots and need to define proper filter callbacks for them.
	 *
	 * Additionally, all elements other than `<tableRow>` should be placed outside the `<table>` tag.
	 * In the example above, this will handle the table caption.
	 *
	 * Such a converter would look like this:
	 *
	 * ```ts
	 * editor.conversion.for( 'downcast' ).elementToStructure( {
	 * 	model: {
	 * 		name: 'table',
	 * 		attributes: [ 'headingRows' ]
	 * 	},
	 * 	view: ( modelElement, conversionApi ) => {
	 * 		const { writer } = conversionApi;
	 *
	 * 		const figureElement = writer.createContainerElement( 'figure', { class: 'table' } );
	 * 		const tableElement = writer.createContainerElement( 'table' );
	 *
	 * 		writer.insert( writer.createPositionAt( figureElement, 0 ), tableElement );
	 *
	 * 		const headingRows = modelElement.getAttribute( 'headingRows' ) || 0;
	 *
	 * 		if ( headingRows > 0 ) {
	 * 			const tableHead = writer.createContainerElement( 'thead' );
	 *
	 * 			const headSlot = writer.createSlot( node => node.is( 'element', 'tableRow' ) && node.index < headingRows );
	 *
	 * 			writer.insert( writer.createPositionAt( tableElement, 'end' ), tableHead );
	 * 			writer.insert( writer.createPositionAt( tableHead, 0 ), headSlot );
	 * 		}
	 *
	 * 		if ( headingRows < tableUtils.getRows( table ) ) {
	 * 			const tableBody = writer.createContainerElement( 'tbody' );
	 *
	 * 			const bodySlot = writer.createSlot( node => node.is( 'element', 'tableRow' ) && node.index >= headingRows );
	 *
	 * 			writer.insert( writer.createPositionAt( tableElement, 'end' ), tableBody );
	 * 			writer.insert( writer.createPositionAt( tableBody, 0 ), bodySlot );
	 * 		}
	 *
	 * 		const restSlot = writer.createSlot( node => !node.is( 'element', 'tableRow' ) );
	 *
	 * 		writer.insert( writer.createPositionAt( figureElement, 'end' ), restSlot );
	 *
	 * 		return figureElement;
	 * 	}
	 * } );
	 * ```
	 *
	 * Note: The children of a model element that's being converted must be allocated in the same order in the view
	 * in which they are placed in the model.
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
 	 * @param config.model The description or a name of the model element to convert.
	 * @param config.model.name The name of the model element to convert.
 	 * @param config.model.attributes The list of attribute names that should be consumed while creating
	 * the view structure. Note that the view will be reconverted if any of the listed attributes will change.
	 * @param config.view A function that takes the model element and
	 * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API} as parameters
	 * and returns a view container element with slots for model child nodes to be converted into.
	 */ elementToStructure(config) {
        return this.add(downcastElementToStructure(config));
    }
    /**
	 * Model attribute to view element conversion helper.
	 *
	 * This conversion results in wrapping view nodes with a view attribute element. For example, a model text node with
	 * `"Foo"` as data and the `bold` attribute becomes `<strong>Foo</strong>` in the view.
	 *
	 * ```ts
	 * editor.conversion.for( 'downcast' ).attributeToElement( {
	 * 	model: 'bold',
	 * 	view: 'strong'
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).attributeToElement( {
	 * 	model: 'bold',
	 * 	view: 'b',
	 * 	converterPriority: 'high'
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).attributeToElement( {
	 * 	model: 'invert',
	 * 	view: {
	 * 		name: 'span',
	 * 		classes: [ 'font-light', 'bg-dark' ]
	 * 	}
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).attributeToElement( {
	 * 	model: {
	 * 		key: 'fontSize',
	 * 		values: [ 'big', 'small' ]
	 * 	},
	 * 	view: {
	 * 		big: {
	 * 			name: 'span',
	 * 			styles: {
	 * 				'font-size': '1.2em'
	 * 			}
	 * 		},
	 * 		small: {
	 * 			name: 'span',
	 * 			styles: {
	 * 				'font-size': '0.8em'
	 * 			}
	 * 		}
	 * 	}
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).attributeToElement( {
	 * 	model: 'bold',
	 * 	view: ( modelAttributeValue, conversionApi ) => {
	 * 		const { writer } = conversionApi;
	 *
	 * 		return writer.createAttributeElement( 'span', {
	 * 			style: 'font-weight:' + modelAttributeValue
	 * 		} );
	 * 	}
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).attributeToElement( {
	 * 	model: {
	 * 		key: 'color',
	 * 		name: '$text'
	 * 	},
	 * 	view: ( modelAttributeValue, conversionApi ) => {
	 * 		const { writer } = conversionApi;
	 *
	 * 		return writer.createAttributeElement( 'span', {
	 * 			style: 'color:' + modelAttributeValue
	 * 		} );
	 * 	}
	 * } );
	 * ```
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.model The key of the attribute to convert from or a `{ key, values }` object. `values` is an array
	 * of `String`s with possible values if the model attribute is an enumerable.
	 * @param config.view A view element definition or a function
	 * that takes the model attribute value and
	 * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API} as parameters and returns a view
	 * attribute element. If `config.model.values` is given, `config.view` should be an object assigning values from `config.model.values`
	 * to view element definitions or functions.
	 * @param config.converterPriority Converter priority.
	 */ attributeToElement(config) {
        return this.add(downcastAttributeToElement(config));
    }
    /**
	 * Model attribute to view attribute conversion helper.
	 *
	 * This conversion results in adding an attribute to a view node, basing on an attribute from a model node. For example,
	 * `<imageInline src='foo.jpg'></imageInline>` is converted to `<img src='foo.jpg'></img>`.
	 *
	 * ```ts
	 * editor.conversion.for( 'downcast' ).attributeToAttribute( {
	 * 	model: 'source',
	 * 	view: 'src'
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).attributeToAttribute( {
	 * 	model: 'source',
	 * 	view: 'href',
	 * 	converterPriority: 'high'
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).attributeToAttribute( {
	 * 	model: {
	 * 		name: 'imageInline',
	 * 		key: 'source'
	 * 	},
	 * 	view: 'src'
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).attributeToAttribute( {
	 * 	model: {
	 * 		name: 'styled',
	 * 		values: [ 'dark', 'light' ]
	 * 	},
	 * 	view: {
	 * 		dark: {
	 * 			key: 'class',
	 * 			value: [ 'styled', 'styled-dark' ]
	 * 		},
	 * 		light: {
	 * 			key: 'class',
	 * 			value: [ 'styled', 'styled-light' ]
	 * 		}
	 * 	}
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).attributeToAttribute( {
	 * 	model: 'styled',
	 * 	view: modelAttributeValue => ( {
	 * 		key: 'class',
	 * 		value: 'styled-' + modelAttributeValue
	 * 	} )
	 * } );
	 * ```
	 *
	 * **Note**: Downcasting to a style property requires providing `value` as an object:
	 *
	 * ```ts
	 * editor.conversion.for( 'downcast' ).attributeToAttribute( {
	 * 	model: 'lineHeight',
	 * 	view: modelAttributeValue => ( {
	 * 		key: 'style',
	 * 		value: {
	 * 			'line-height': modelAttributeValue,
	 * 			'border-bottom': '1px dotted #ba2'
	 * 		}
	 * 	} )
	 * } );
	 * ```
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.model The key of the attribute to convert from or a `{ key, values, [ name ] }` object describing
	 * the attribute key, possible values and, optionally, an element name to convert from.
	 * @param config.view A view attribute key, or a `{ key, value }` object or a function that takes the model attribute value and
	 * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API}
	 * as parameters and returns a `{ key, value }` object. If the `key` is `'class'`, the `value` can be a `String` or an
	 * array of `String`s. If the `key` is `'style'`, the `value` is an object with key-value pairs. In other cases, `value` is a `String`.
	 * If `config.model.values` is set, `config.view` should be an object assigning values from `config.model.values` to
	 * `{ key, value }` objects or a functions.
	 * @param config.converterPriority Converter priority.
	 */ attributeToAttribute(config) {
        return this.add(downcastAttributeToAttribute(config));
    }
    /**
	 * Model marker to view element conversion helper.
	 *
	 * **Note**: This method should be used mainly for editing the downcast and it is recommended
	 * to use the {@link #markerToData `#markerToData()`} helper instead.
	 *
	 * This helper may produce invalid HTML code (e.g. a span between table cells).
	 * It should only be used when you are sure that the produced HTML will be semantically correct.
	 *
	 * This conversion results in creating a view element on the boundaries of the converted marker. If the converted marker
	 * is collapsed, only one element is created. For example, a model marker set like this: `<paragraph>F[oo b]ar</paragraph>`
	 * becomes `<p>F<span data-marker="search"></span>oo b<span data-marker="search"></span>ar</p>` in the view.
	 *
	 * ```ts
	 * editor.conversion.for( 'editingDowncast' ).markerToElement( {
	 * 	model: 'search',
	 * 	view: 'marker-search'
	 * } );
	 *
	 * editor.conversion.for( 'editingDowncast' ).markerToElement( {
	 * 	model: 'search',
	 * 	view: 'search-result',
	 * 	converterPriority: 'high'
	 * } );
	 *
	 * editor.conversion.for( 'editingDowncast' ).markerToElement( {
	 * 	model: 'search',
	 * 	view: {
	 * 		name: 'span',
	 * 		attributes: {
	 * 			'data-marker': 'search'
	 * 		}
	 * 	}
	 * } );
	 *
	 * editor.conversion.for( 'editingDowncast' ).markerToElement( {
	 * 	model: 'search',
	 * 	view: ( markerData, conversionApi ) => {
	 * 		const { writer } = conversionApi;
	 *
	 * 		return writer.createUIElement( 'span', {
	 * 			'data-marker': 'search',
	 * 			'data-start': markerData.isOpening
	 * 		} );
	 * 	}
	 * } );
	 * ```
	 *
	 * If a function is passed as the `config.view` parameter, it will be used to generate both boundary elements. The function
	 * receives the `data` object and {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API}
	 * as a parameters and should return an instance of the
	 * {@link module:engine/view/uielement~UIElement view UI element}. The `data` object and
	 * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi `conversionApi`} are passed from
	 * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker}. Additionally,
	 * the `data.isOpening` parameter is passed, which is set to `true` for the marker start boundary element, and `false` for
	 * the marker end boundary element.
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.model The name of the model marker (or model marker group) to convert.
	 * @param config.view A view element definition or a function that takes the model marker data and
	 * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API} as a parameters
	 * and returns a view UI element.
	 * @param config.converterPriority Converter priority.
	 */ markerToElement(config) {
        return this.add(downcastMarkerToElement(config));
    }
    /**
	 * Model marker to highlight conversion helper.
	 *
	 * This conversion results in creating a highlight on view nodes. For this kind of conversion,
	 * the {@link module:engine/conversion/downcasthelpers~HighlightDescriptor} should be provided.
	 *
	 * For text nodes, a `<span>` {@link module:engine/view/attributeelement~AttributeElement} is created and it wraps all text nodes
	 * in the converted marker range. For example, a model marker set like this: `<paragraph>F[oo b]ar</paragraph>` becomes
	 * `<p>F<span class="comment">oo b</span>ar</p>` in the view.
	 *
	 * {@link module:engine/view/containerelement~ContainerElement} may provide a custom way of handling highlight. Most often,
	 * the element itself is given classes and attributes described in the highlight descriptor (instead of being wrapped in `<span>`).
	 * For example, a model marker set like this:
	 * `[<imageInline src="foo.jpg"></imageInline>]` becomes `<img src="foo.jpg" class="comment"></img>` in the view.
	 *
	 * For container elements, the conversion is two-step. While the converter processes the highlight descriptor and passes it
	 * to a container element, it is the container element instance itself that applies values from the highlight descriptor.
	 * So, in a sense, the converter takes care of stating what should be applied on what, while the element decides how to apply that.
	 *
	 * ```ts
	 * editor.conversion.for( 'downcast' ).markerToHighlight( { model: 'comment', view: { classes: 'comment' } } );
	 *
	 * editor.conversion.for( 'downcast' ).markerToHighlight( {
	 * 	model: 'comment',
	 * 	view: { classes: 'comment' },
	 * 	converterPriority: 'high'
	 * } );
	 *
	 * editor.conversion.for( 'downcast' ).markerToHighlight( {
	 * 	model: 'comment',
	 * 	view: ( data, conversionApi ) => {
	 * 		// Assuming that the marker name is in a form of comment:commentType:commentId.
	 * 		const [ , commentType, commentId ] = data.markerName.split( ':' );
	 *
	 * 		return {
	 * 			classes: [ 'comment', 'comment-' + commentType ],
	 * 			attributes: { 'data-comment-id': commentId }
	 * 		};
	 * 	}
	 * } );
	 * ```
	 *
	 * If a function is passed as the `config.view` parameter, it will be used to generate the highlight descriptor. The function
	 * receives the `data` object and {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API}
	 * as the parameters and should return a
	 * {@link module:engine/conversion/downcasthelpers~HighlightDescriptor highlight descriptor}.
	 * The `data` object properties are passed from {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker}.
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.model The name of the model marker (or model marker group) to convert.
	 * @param config.view A highlight descriptor that will be used for highlighting or a function that takes the model marker data and
	 * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API} as a parameters
	 * and returns a highlight descriptor.
	 * @param config.converterPriority Converter priority.
	 */ markerToHighlight(config) {
        return this.add(downcastMarkerToHighlight(config));
    }
    /**
	 * Model marker converter for data downcast.
	 *
	 * This conversion creates a representation for model marker boundaries in the view:
	 *
	 * * If the marker boundary is before or after a model element, a view attribute is set on a corresponding view element.
	 * * In other cases, a view element with the specified tag name is inserted at the corresponding view position.
	 *
	 * Typically, the marker names use the `group:uniqueId:otherData` convention. For example: `comment:e34zfk9k2n459df53sjl34:zx32c`.
	 * The default configuration for this conversion is that the first part is the `group` part and the rest of
	 * the marker name becomes the `name` part.
	 *
	 * Tag and attribute names and values are generated from the marker name:
	 *
	 * * The templates for attributes are `data-[group]-start-before="[name]"`, `data-[group]-start-after="[name]"`,
	 * `data-[group]-end-before="[name]"` and `data-[group]-end-after="[name]"`.
	 * * The templates for view elements are `<[group]-start name="[name]">` and `<[group]-end name="[name]">`.
	 *
	 * Attributes mark whether the given marker's start or end boundary is before or after the given element.
	 * The `data-[group]-start-before` and `data-[group]-end-after` attributes are favored.
	 * The other two are used when the former two cannot be used.
	 *
	 * The conversion configuration can take a function that will generate different group and name parts.
	 * If such a function is set as the `config.view` parameter, it is passed a marker name and it is expected to return an object with two
	 * properties: `group` and `name`. If the function returns a falsy value, the conversion will not take place.
	 *
	 * Basic usage:
	 *
	 * ```ts
	 * // Using the default conversion.
	 * // In this case, all markers with names starting with 'comment:' will be converted.
	 * // The `group` parameter will be set to `comment`.
	 * // The `name` parameter will be the rest of the marker name (without the `:`).
	 * editor.conversion.for( 'dataDowncast' ).markerToData( {
	 * 	model: 'comment'
	 * } );
	 * ```
	 *
	 * An example of a view that may be generated by this conversion (assuming a marker with the name `comment:commentId:uid` marked
	 * by `[]`):
	 *
	 * ```
	 * // Model:
	 * <paragraph>Foo[bar</paragraph>
	 * <imageBlock src="abc.jpg"></imageBlock>]
	 *
	 * // View:
	 * <p>Foo<comment-start name="commentId:uid"></comment-start>bar</p>
	 * <figure data-comment-end-after="commentId:uid" class="image"><img src="abc.jpg" /></figure>
	 * ```
	 *
	 * In the example above, the comment starts before "bar" and ends after the image.
	 *
	 * If the `name` part is empty, the following view may be generated:
	 *
	 * ```html
	 * <p>Foo <myMarker-start></myMarker-start>bar</p>
	 * <figure data-myMarker-end-after="" class="image"><img src="abc.jpg" /></figure>
	 * ```
	 *
	 * **Note:** A situation where some markers have the `name` part and some do not, is incorrect and should be avoided.
	 *
	 * Examples where `data-group-start-after` and `data-group-end-before` are used:
	 *
	 * ```
	 * // Model:
	 * <blockQuote>[]<paragraph>Foo</paragraph></blockQuote>
	 *
	 * // View:
	 * <blockquote><p data-group-end-before="name" data-group-start-before="name">Foo</p></blockquote>
	 * ```
	 *
	 * Similarly, when a marker is collapsed after the last element:
	 *
	 * ```
	 * // Model:
	 * <blockQuote><paragraph>Foo</paragraph>[]</blockQuote>
	 *
	 * // View:
	 * <blockquote><p data-group-end-after="name" data-group-start-after="name">Foo</p></blockquote>
	 * ```
	 *
	 * When there are multiple markers from the same group stored in the same attribute of the same element, their
	 * name parts are put together in the attribute value, for example: `data-group-start-before="name1,name2,name3"`.
	 *
	 * Other examples of usage:
	 *
	 * ```ts
	 * // Using a custom function which is the same as the default conversion:
	 * editor.conversion.for( 'dataDowncast' ).markerToData( {
	 * 	model: 'comment',
	 * 	view: markerName => ( {
	 * 		group: 'comment',
	 * 		name: markerName.substr( 8 ) // Removes 'comment:' part.
	 * 	} )
	 * } );
	 *
	 * // Using the converter priority:
	 * editor.conversion.for( 'dataDowncast' ).markerToData( {
	 * 	model: 'comment',
	 * 	view: markerName => ( {
	 * 		group: 'comment',
	 * 		name: markerName.substr( 8 ) // Removes 'comment:' part.
	 * 	} ),
	 * 	converterPriority: 'high'
	 * } );
	 * ```
	 *
	 * This kind of conversion is useful for saving data into the database, so it should be used in the data conversion pipeline.
	 *
	 * See the {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} API guide to learn how to
	 * add a converter to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.model The name of the model marker (or the model marker group) to convert.
	 * @param config.view A function that takes the model marker name and
	 * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API} as the parameters
	 * and returns an object with the `group` and `name` properties.
	 * @param config.converterPriority Converter priority.
	 */ markerToData(config) {
        return this.add(downcastMarkerToData(config));
    }
}
/**
 * Function factory that creates a default downcast converter for text insertion changes.
 *
 * The converter automatically consumes the corresponding value from the consumables list and stops the event (see
 * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}).
 *
 * ```ts
 * modelDispatcher.on( 'insert:$text', insertText() );
 * ```
 *
 * @returns Insert text event converter.
 */ function insertText() {
    return (evt, data, conversionApi)=>{
        if (!conversionApi.consumable.consume(data.item, evt.name)) {
            return;
        }
        const viewWriter = conversionApi.writer;
        const viewPosition = conversionApi.mapper.toViewPosition(data.range.start);
        const viewText = viewWriter.createText(data.item.data);
        viewWriter.insert(viewPosition, viewText);
    };
}
/**
 * Function factory that creates a default downcast converter for triggering attributes and children conversion.
 *
 * @returns The converter.
 */ function insertAttributesAndChildren() {
    return (evt, data, conversionApi)=>{
        conversionApi.convertAttributes(data.item);
        // Start converting children of the current item.
        // In case of reconversion children were already re-inserted or converted separately.
        if (!data.reconversion && data.item.is('element') && !data.item.isEmpty) {
            conversionApi.convertChildren(data.item);
        }
    };
}
/**
 * Function factory that creates a default downcast converter for node remove changes.
 *
 * ```ts
 * modelDispatcher.on( 'remove', remove() );
 * ```
 *
 * @returns Remove event converter.
 */ function remove() {
    return (evt, data, conversionApi)=>{
        // Find the view range start position by mapping the model position at which the remove happened.
        const viewStart = conversionApi.mapper.toViewPosition(data.position);
        const modelEnd = data.position.getShiftedBy(data.length);
        const viewEnd = conversionApi.mapper.toViewPosition(modelEnd, {
            isPhantom: true
        });
        const viewRange = conversionApi.writer.createRange(viewStart, viewEnd);
        // Trim the range to remove in case some UI elements are on the view range boundaries.
        const removed = conversionApi.writer.remove(viewRange.getTrimmed());
        // After the range is removed, unbind all view elements from the model.
        // Range inside view document fragment is used to unbind deeply.
        for (const child of conversionApi.writer.createRangeIn(removed).getItems()){
            conversionApi.mapper.unbindViewElement(child, {
                defer: true
            });
        }
    };
}
/**
 * Creates a `<span>` {@link module:engine/view/attributeelement~AttributeElement view attribute element} from the information
 * provided by the {@link module:engine/conversion/downcasthelpers~HighlightDescriptor highlight descriptor} object. If the priority
 * is not provided in the descriptor, the default priority will be used.
 */ function createViewElementFromHighlightDescriptor(writer, descriptor) {
    const viewElement = writer.createAttributeElement('span', descriptor.attributes);
    if (descriptor.classes) {
        viewElement._addClass(descriptor.classes);
    }
    if (typeof descriptor.priority === 'number') {
        viewElement._priority = descriptor.priority;
    }
    viewElement._id = descriptor.id;
    return viewElement;
}
/**
 * Function factory that creates a converter which converts a non-collapsed {@link module:engine/model/selection~Selection model selection}
 * to a {@link module:engine/view/documentselection~DocumentSelection view selection}. The converter consumes appropriate
 * value from the `consumable` object and maps model positions from the selection to view positions.
 *
 * ```ts
 * modelDispatcher.on( 'selection', convertRangeSelection() );
 * ```
 *
 * @returns Selection converter.
 */ function convertRangeSelection() {
    return (evt, data, conversionApi)=>{
        const selection = data.selection;
        if (selection.isCollapsed) {
            return;
        }
        if (!conversionApi.consumable.consume(selection, 'selection')) {
            return;
        }
        const viewRanges = [];
        for (const range of selection.getRanges()){
            viewRanges.push(conversionApi.mapper.toViewRange(range));
        }
        conversionApi.writer.setSelection(viewRanges, {
            backward: selection.isBackward
        });
    };
}
/**
 * Function factory that creates a converter which converts a collapsed {@link module:engine/model/selection~Selection model selection} to
 * a {@link module:engine/view/documentselection~DocumentSelection view selection}. The converter consumes appropriate
 * value from the `consumable` object, maps the model selection position to the view position and breaks
 * {@link module:engine/view/attributeelement~AttributeElement attribute elements} at the selection position.
 *
 * ```ts
 * modelDispatcher.on( 'selection', convertCollapsedSelection() );
 * ```
 *
 * An example of the view state before and after converting the collapsed selection:
 *
 * ```
 *    <p><strong>f^oo<strong>bar</p>
 * -> <p><strong>f</strong>^<strong>oo</strong>bar</p>
 * ```
 *
 * By breaking attribute elements like `<strong>`, the selection is in a correct element. Then, when the selection attribute is
 * converted, broken attributes might be merged again, or the position where the selection is may be wrapped
 * with different, appropriate attribute elements.
 *
 * See also {@link module:engine/conversion/downcasthelpers~cleanSelection} which does a clean-up
 * by merging attributes.
 *
 * @returns Selection converter.
 */ function convertCollapsedSelection() {
    return (evt, data, conversionApi)=>{
        const selection = data.selection;
        if (!selection.isCollapsed) {
            return;
        }
        if (!conversionApi.consumable.consume(selection, 'selection')) {
            return;
        }
        const viewWriter = conversionApi.writer;
        const modelPosition = selection.getFirstPosition();
        const viewPosition = conversionApi.mapper.toViewPosition(modelPosition);
        const brokenPosition = viewWriter.breakAttributes(viewPosition);
        viewWriter.setSelection(brokenPosition);
    };
}
/**
 * Function factory that creates a converter which cleans artifacts after the previous
 * {@link module:engine/model/selection~Selection model selection} conversion. It removes all empty
 * {@link module:engine/view/attributeelement~AttributeElement view attribute elements} and merges sibling attributes at all start and end
 * positions of all ranges.
 *
 * ```
 *    <p><strong>^</strong></p>
 * -> <p>^</p>
 *
 *    <p><strong>foo</strong>^<strong>bar</strong>bar</p>
 * -> <p><strong>foo^bar<strong>bar</p>
 *
 *    <p><strong>foo</strong><em>^</em><strong>bar</strong>bar</p>
 * -> <p><strong>foo^bar<strong>bar</p>
 * ```
 *
 * This listener should be assigned before any converter for the new selection:
 *
 * ```ts
 * modelDispatcher.on( 'cleanSelection', cleanSelection() );
 * ```
 *
 * See {@link module:engine/conversion/downcasthelpers~convertCollapsedSelection}
 * which does the opposite by breaking attributes in the selection position.
 *
 * @returns Selection converter.
 */ function cleanSelection() {
    return (evt, data, conversionApi)=>{
        const viewWriter = conversionApi.writer;
        const viewSelection = viewWriter.document.selection;
        for (const range of viewSelection.getRanges()){
            // Not collapsed selection should not have artifacts.
            if (range.isCollapsed) {
                // Position might be in the node removed by the view writer.
                if (range.end.parent.isAttached()) {
                    conversionApi.writer.mergeAttributes(range.start);
                }
            }
        }
        viewWriter.setSelection(null);
    };
}
/**
 * Function factory that creates a converter which converts the set/change/remove attribute changes from the model to the view.
 * It can also be used to convert selection attributes. In that case, an empty attribute element will be created and the
 * selection will be put inside it.
 *
 * Attributes from the model are converted to a view element that will be wrapping these view nodes that are bound to
 * model elements having the given attribute. This is useful for attributes like `bold` that may be set on text nodes in the model
 * but are represented as an element in the view:
 *
 * ```
 * [paragraph]              MODEL ====> VIEW        <p>
 * 	|- a {bold: true}                             |- <b>
 * 	|- b {bold: true}                             |   |- ab
 * 	|- c                                          |- c
 * 	```
 *
 * Passed `Function` will be provided with the attribute value and then all the parameters of the
 * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute` event}.
 * It is expected that the function returns an {@link module:engine/view/element~Element}.
 * The result of the function will be the wrapping element.
 * When the provided `Function` does not return any element, no conversion will take place.
 *
 * The converter automatically consumes the corresponding value from the consumables list and stops the event (see
 * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}).
 *
 * ```ts
 * modelDispatcher.on( 'attribute:bold', wrap( ( modelAttributeValue, { writer } ) => {
 * 	return writer.createAttributeElement( 'strong' );
 * } );
 * ```
 *
 * @internal
 * @param elementCreator Function returning a view element that will be used for wrapping.
 * @returns Set/change attribute converter.
 */ function wrap(elementCreator) {
    return (evt, data, conversionApi)=>{
        if (!conversionApi.consumable.test(data.item, evt.name)) {
            return;
        }
        // Recreate current wrapping node. It will be used to unwrap view range if the attribute value has changed
        // or the attribute was removed.
        const oldViewElement = elementCreator(data.attributeOldValue, conversionApi, data);
        // Create node to wrap with.
        const newViewElement = elementCreator(data.attributeNewValue, conversionApi, data);
        if (!oldViewElement && !newViewElement) {
            return;
        }
        conversionApi.consumable.consume(data.item, evt.name);
        const viewWriter = conversionApi.writer;
        const viewSelection = viewWriter.document.selection;
        if (data.item instanceof Selection || data.item instanceof DocumentSelection) {
            // Selection attribute conversion.
            viewWriter.wrap(viewSelection.getFirstRange(), newViewElement);
        } else {
            // Node attribute conversion.
            let viewRange = conversionApi.mapper.toViewRange(data.range);
            // First, unwrap the range from current wrapper.
            if (data.attributeOldValue !== null && oldViewElement) {
                viewRange = viewWriter.unwrap(viewRange, oldViewElement);
            }
            if (data.attributeNewValue !== null && newViewElement) {
                viewWriter.wrap(viewRange, newViewElement);
            }
        }
    };
}
/**
 * Function factory that creates a converter which converts node insertion changes from the model to the view.
 * The function passed will be provided with all the parameters of the dispatcher's
 * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert `insert` event}.
 * It is expected that the function returns an {@link module:engine/view/element~Element}.
 * The result of the function will be inserted into the view.
 *
 * The converter automatically consumes the corresponding value from the consumables list and binds the model and view elements.
 *
 * ```ts
 * downcastDispatcher.on(
 * 	'insert:myElem',
 * 	insertElement( ( modelItem, { writer } ) => {
 * 		const text = writer.createText( 'myText' );
 * 		const myElem = writer.createElement( 'myElem', { myAttr: 'my-' + modelItem.getAttribute( 'myAttr' ) }, text );
 *
 * 		// Do something fancy with `myElem` using `modelItem` or other parameters.
 *
 * 		return myElem;
 * 	}
 * ) );
 * ```
 *
 * @internal
 * @param  elementCreator Function returning a view element, which will be inserted.
 * @param consumer Function defining element consumption process.
 * By default this function just consume passed item insertion.
 * @returns Insert element event converter.
 */ function insertElement(elementCreator, consumer = defaultConsumer) {
    return (evt, data, conversionApi)=>{
        if (!consumer(data.item, conversionApi.consumable, {
            preflight: true
        })) {
            return;
        }
        const viewElement = elementCreator(data.item, conversionApi, data);
        if (!viewElement) {
            return;
        }
        // Consume an element insertion and all present attributes that are specified as a reconversion triggers.
        consumer(data.item, conversionApi.consumable);
        const viewPosition = conversionApi.mapper.toViewPosition(data.range.start);
        conversionApi.mapper.bindElements(data.item, viewElement);
        conversionApi.writer.insert(viewPosition, viewElement);
        // Convert attributes before converting children.
        conversionApi.convertAttributes(data.item);
        // Convert children or reinsert previous view elements.
        reinsertOrConvertNodes(viewElement, data.item.getChildren(), conversionApi, {
            reconversion: data.reconversion
        });
    };
}
/**
 * Function factory that creates a converter which converts a single model node insertion to a view structure.
 *
 * It is expected that the passed element creator function returns an {@link module:engine/view/element~Element} with attached slots
 * created with `writer.createSlot()` to indicate where child nodes should be converted.
 *
 * @see module:engine/conversion/downcasthelpers~DowncastHelpers#elementToStructure
 *
 * @internal
 * @param elementCreator Function returning a view structure, which will be inserted.
 * @param consumer A callback that is expected to consume all the consumables
 * that were used by the element creator.
 * @returns Insert element event converter.
*/ function insertStructure(elementCreator, consumer) {
    return (evt, data, conversionApi)=>{
        if (!consumer(data.item, conversionApi.consumable, {
            preflight: true
        })) {
            return;
        }
        const slotsMap = new Map();
        conversionApi.writer._registerSlotFactory(createSlotFactory(data.item, slotsMap, conversionApi));
        // View creation.
        const viewElement = elementCreator(data.item, conversionApi, data);
        conversionApi.writer._clearSlotFactory();
        if (!viewElement) {
            return;
        }
        // Check if all children are covered by slots and there is no child that landed in multiple slots.
        validateSlotsChildren(data.item, slotsMap, conversionApi);
        // Consume an element insertion and all present attributes that are specified as a reconversion triggers.
        consumer(data.item, conversionApi.consumable);
        const viewPosition = conversionApi.mapper.toViewPosition(data.range.start);
        conversionApi.mapper.bindElements(data.item, viewElement);
        conversionApi.writer.insert(viewPosition, viewElement);
        // Convert attributes before converting children.
        conversionApi.convertAttributes(data.item);
        // Fill view slots with previous view elements or create new ones.
        fillSlots(viewElement, slotsMap, conversionApi, {
            reconversion: data.reconversion
        });
    };
}
/**
 * Function factory that creates a converter which converts marker adding change to the
 * {@link module:engine/view/uielement~UIElement view UI element}.
 *
 * The view UI element that will be added to the view depends on the passed parameter. See {@link ~insertElement}.
 * In case of a non-collapsed range, the UI element will not wrap nodes but separate elements will be placed at the beginning
 * and at the end of the range.
 *
 * This converter binds created UI elements with the marker name using {@link module:engine/conversion/mapper~Mapper#bindElementToMarker}.
 *
 * @internal
 * @param elementCreator A view UI element or a function returning the view element that will be inserted.
 * @returns Insert element event converter.
 */ function insertUIElement(elementCreator) {
    return (evt, data, conversionApi)=>{
        // Create two view elements. One will be inserted at the beginning of marker, one at the end.
        // If marker is collapsed, only "opening" element will be inserted.
        data.isOpening = true;
        const viewStartElement = elementCreator(data, conversionApi);
        data.isOpening = false;
        const viewEndElement = elementCreator(data, conversionApi);
        if (!viewStartElement || !viewEndElement) {
            return;
        }
        const markerRange = data.markerRange;
        // Marker that is collapsed has consumable build differently that non-collapsed one.
        // For more information see `addMarker` event description.
        // If marker's range is collapsed - check if it can be consumed.
        if (markerRange.isCollapsed && !conversionApi.consumable.consume(markerRange, evt.name)) {
            return;
        }
        // If marker's range is not collapsed - consume all items inside.
        for (const value of markerRange){
            if (!conversionApi.consumable.consume(value.item, evt.name)) {
                return;
            }
        }
        const mapper = conversionApi.mapper;
        const viewWriter = conversionApi.writer;
        // Add "opening" element.
        viewWriter.insert(mapper.toViewPosition(markerRange.start), viewStartElement);
        conversionApi.mapper.bindElementToMarker(viewStartElement, data.markerName);
        // Add "closing" element only if range is not collapsed.
        if (!markerRange.isCollapsed) {
            viewWriter.insert(mapper.toViewPosition(markerRange.end), viewEndElement);
            conversionApi.mapper.bindElementToMarker(viewEndElement, data.markerName);
        }
        evt.stop();
    };
}
/**
 * Function factory that returns a default downcast converter for removing a {@link module:engine/view/uielement~UIElement UI element}
 * based on marker remove change.
 *
 * This converter unbinds elements from the marker name.
 *
 * @returns Removed UI element converter.
 */ function removeUIElement() {
    return (evt, data, conversionApi)=>{
        const elements = conversionApi.mapper.markerNameToElements(data.markerName);
        if (!elements) {
            return;
        }
        for (const element of elements){
            conversionApi.mapper.unbindElementFromMarkerName(element, data.markerName);
            conversionApi.writer.clear(conversionApi.writer.createRangeOn(element), element);
        }
        conversionApi.writer.clearClonedElementsGroup(data.markerName);
        evt.stop();
    };
}
/**
 * Function factory that creates a default converter for model markers.
 *
 * See {@link DowncastHelpers#markerToData} for more information what type of view is generated.
 *
 * This converter binds created UI elements and affected view elements with the marker name
 * using {@link module:engine/conversion/mapper~Mapper#bindElementToMarker}.
 *
 * @returns Add marker converter.
 */ function insertMarkerData(viewCreator) {
    return (evt, data, conversionApi)=>{
        const viewMarkerData = viewCreator(data.markerName, conversionApi);
        if (!viewMarkerData) {
            return;
        }
        const markerRange = data.markerRange;
        if (!conversionApi.consumable.consume(markerRange, evt.name)) {
            return;
        }
        // Adding closing data first to keep the proper order in the view.
        handleMarkerBoundary(markerRange, false, conversionApi, data, viewMarkerData);
        handleMarkerBoundary(markerRange, true, conversionApi, data, viewMarkerData);
        evt.stop();
    };
}
/**
 * Helper function for `insertMarkerData()` that marks a marker boundary at the beginning or end of given `range`.
 */ function handleMarkerBoundary(range, isStart, conversionApi, data, viewMarkerData) {
    const modelPosition = isStart ? range.start : range.end;
    const elementAfter = modelPosition.nodeAfter && modelPosition.nodeAfter.is('element') ? modelPosition.nodeAfter : null;
    const elementBefore = modelPosition.nodeBefore && modelPosition.nodeBefore.is('element') ? modelPosition.nodeBefore : null;
    if (elementAfter || elementBefore) {
        let modelElement;
        let isBefore;
        // If possible, we want to add `data-group-start-before` and `data-group-end-after` attributes.
        if (isStart && elementAfter || !isStart && !elementBefore) {
            // [<elementAfter>...</elementAfter> -> <elementAfter data-group-start-before="...">...</elementAfter>
            // <parent>]<elementAfter> -> <parent><elementAfter data-group-end-before="...">
            modelElement = elementAfter;
            isBefore = true;
        } else {
            // <elementBefore>...</elementBefore>] -> <elementBefore data-group-end-after="...">...</elementBefore>
            // </elementBefore>[</parent> -> </elementBefore data-group-start-after="..."></parent>
            modelElement = elementBefore;
            isBefore = false;
        }
        const viewElement = conversionApi.mapper.toViewElement(modelElement);
        // In rare circumstances, the model element may be not mapped to any view element and that would cause an error.
        // One of those situations is a soft break inside code block.
        if (viewElement) {
            insertMarkerAsAttribute(viewElement, isStart, isBefore, conversionApi, data, viewMarkerData);
            return;
        }
    }
    const viewPosition = conversionApi.mapper.toViewPosition(modelPosition);
    insertMarkerAsElement(viewPosition, isStart, conversionApi, data, viewMarkerData);
}
/**
 * Helper function for `insertMarkerData()` that marks a marker boundary in the view as an attribute on a view element.
 */ function insertMarkerAsAttribute(viewElement, isStart, isBefore, conversionApi, data, viewMarkerData) {
    const attributeName = `data-${viewMarkerData.group}-${isStart ? 'start' : 'end'}-${isBefore ? 'before' : 'after'}`;
    const markerNames = viewElement.hasAttribute(attributeName) ? viewElement.getAttribute(attributeName).split(',') : [];
    // Adding marker name at the beginning to have the same order in the attribute as there is with marker elements.
    markerNames.unshift(viewMarkerData.name);
    conversionApi.writer.setAttribute(attributeName, markerNames.join(','), viewElement);
    conversionApi.mapper.bindElementToMarker(viewElement, data.markerName);
}
/**
 * Helper function for `insertMarkerData()` that marks a marker boundary in the view as a separate view ui element.
 */ function insertMarkerAsElement(position, isStart, conversionApi, data, viewMarkerData) {
    const viewElementName = `${viewMarkerData.group}-${isStart ? 'start' : 'end'}`;
    const attrs = viewMarkerData.name ? {
        'name': viewMarkerData.name
    } : null;
    const viewElement = conversionApi.writer.createUIElement(viewElementName, attrs);
    conversionApi.writer.insert(position, viewElement);
    conversionApi.mapper.bindElementToMarker(viewElement, data.markerName);
}
/**
 * Function factory that creates a converter for removing a model marker data added by the {@link #insertMarkerData} converter.
 *
 * @returns Remove marker converter.
 */ function removeMarkerData(viewCreator) {
    return (evt, data, conversionApi)=>{
        const viewData = viewCreator(data.markerName, conversionApi);
        if (!viewData) {
            return;
        }
        const elements = conversionApi.mapper.markerNameToElements(data.markerName);
        if (!elements) {
            return;
        }
        for (const element of elements){
            conversionApi.mapper.unbindElementFromMarkerName(element, data.markerName);
            if (element.is('containerElement')) {
                removeMarkerFromAttribute(`data-${viewData.group}-start-before`, element);
                removeMarkerFromAttribute(`data-${viewData.group}-start-after`, element);
                removeMarkerFromAttribute(`data-${viewData.group}-end-before`, element);
                removeMarkerFromAttribute(`data-${viewData.group}-end-after`, element);
            } else {
                conversionApi.writer.clear(conversionApi.writer.createRangeOn(element), element);
            }
        }
        conversionApi.writer.clearClonedElementsGroup(data.markerName);
        evt.stop();
        function removeMarkerFromAttribute(attributeName, element) {
            if (element.hasAttribute(attributeName)) {
                const markerNames = new Set(element.getAttribute(attributeName).split(','));
                markerNames.delete(viewData.name);
                if (markerNames.size == 0) {
                    conversionApi.writer.removeAttribute(attributeName, element);
                } else {
                    conversionApi.writer.setAttribute(attributeName, Array.from(markerNames).join(','), element);
                }
            }
        }
    };
}
/**
 * Function factory that creates a converter which converts the set/change/remove attribute changes from the model to the view.
 *
 * Attributes from the model are converted to the view element attributes in the view. You may provide a custom function to generate
 * a key-value attribute pair to add/change/remove. If not provided, model attributes will be converted to view element
 * attributes on a one-to-one basis.
 *
 * *Note:** The provided attribute creator should always return the same `key` for a given attribute from the model.
 *
 * The converter automatically consumes the corresponding value from the consumables list and stops the event (see
 * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}).
 *
 * ```ts
 * modelDispatcher.on( 'attribute:customAttr:myElem', changeAttribute( ( value, data ) => {
 * 	// Change attribute key from `customAttr` to `class` in the view.
 * 	const key = 'class';
 * 	let value = data.attributeNewValue;
 *
 * 	// Force attribute value to 'empty' if the model element is empty.
 * 	if ( data.item.childCount === 0 ) {
 * 		value = 'empty';
 * 	}
 *
 * 	// Return the key-value pair.
 * 	return { key, value };
 * } ) );
 * ```
 *
 * @param attributeCreator Function returning an object with two properties: `key` and `value`, which
 * represent the attribute key and attribute value to be set on a {@link module:engine/view/element~Element view element}.
 * The function is passed the model attribute value as the first parameter and additional data about the change as the second parameter.
 * @returns Set/change attribute converter.
 */ function changeAttribute(attributeCreator) {
    return (evt, data, conversionApi)=>{
        if (!conversionApi.consumable.test(data.item, evt.name)) {
            return;
        }
        const oldAttribute = attributeCreator(data.attributeOldValue, conversionApi, data);
        const newAttribute = attributeCreator(data.attributeNewValue, conversionApi, data);
        if (!oldAttribute && !newAttribute) {
            return;
        }
        conversionApi.consumable.consume(data.item, evt.name);
        const viewElement = conversionApi.mapper.toViewElement(data.item);
        const viewWriter = conversionApi.writer;
        // If model item cannot be mapped to a view element, it means item is not an `Element` instance but a `TextProxy` node.
        // Only elements can have attributes in a view so do not proceed for anything else (#1587).
        if (!viewElement) {
            /**
			 * This error occurs when a {@link module:engine/model/textproxy~TextProxy text node's} attribute is to be downcasted
			 * by an {@link module:engine/conversion/conversion~Conversion#attributeToAttribute `Attribute to Attribute converter`}.
			 * In most cases it is caused by converters misconfiguration when only "generic" converter is defined:
			 *
			 * ```ts
			 * editor.conversion.for( 'downcast' ).attributeToAttribute( {
			 * 	model: 'attribute-name',
			 * 	view: 'attribute-name'
			 * } ) );
			 * ```
			 *
			 * and given attribute is used on text node, for example:
			 *
			 * ```ts
			 * model.change( writer => {
			 * 	writer.insertText( 'Foo', { 'attribute-name': 'bar' }, parent, 0 );
			 * } );
			 * ```
			 *
			 * In such cases, to convert the same attribute for both {@link module:engine/model/element~Element}
			 * and {@link module:engine/model/textproxy~TextProxy `Text`} nodes, text specific
			 * {@link module:engine/conversion/conversion~Conversion#attributeToElement `Attribute to Element converter`}
			 * with higher {@link module:utils/priorities~PriorityString priority} must also be defined:
			 *
			 * ```ts
			 * editor.conversion.for( 'downcast' ).attributeToElement( {
			 * 	model: {
			 * 		key: 'attribute-name',
			 * 		name: '$text'
			 * 	},
			 * 	view: ( value, { writer } ) => {
			 * 		return writer.createAttributeElement( 'span', { 'attribute-name': value } );
			 * 	},
			 * 	converterPriority: 'high'
			 * } ) );
			 * ```
			 *
			 * @error conversion-attribute-to-attribute-on-text
			 */ throw new CKEditorError('conversion-attribute-to-attribute-on-text', conversionApi.dispatcher, data);
        }
        // First remove the old attribute if there was one.
        if (data.attributeOldValue !== null && oldAttribute) {
            if (oldAttribute.key == 'class') {
                const classes = typeof oldAttribute.value == 'string' ? oldAttribute.value.split(/\s+/) : oldAttribute.value;
                for (const className of classes){
                    viewWriter.removeClass(className, viewElement);
                }
            } else if (oldAttribute.key == 'style') {
                if (typeof oldAttribute.value == 'string') {
                    const styles = new StylesMap(viewWriter.document.stylesProcessor);
                    styles.setTo(oldAttribute.value);
                    for (const [key] of styles.getStylesEntries()){
                        viewWriter.removeStyle(key, viewElement);
                    }
                } else {
                    const keys = Object.keys(oldAttribute.value);
                    for (const key of keys){
                        viewWriter.removeStyle(key, viewElement);
                    }
                }
            } else {
                viewWriter.removeAttribute(oldAttribute.key, viewElement);
            }
        }
        // Then set the new attribute.
        if (data.attributeNewValue !== null && newAttribute) {
            if (newAttribute.key == 'class') {
                const classes = typeof newAttribute.value == 'string' ? newAttribute.value.split(/\s+/) : newAttribute.value;
                for (const className of classes){
                    viewWriter.addClass(className, viewElement);
                }
            } else if (newAttribute.key == 'style') {
                if (typeof newAttribute.value == 'string') {
                    const styles = new StylesMap(viewWriter.document.stylesProcessor);
                    styles.setTo(newAttribute.value);
                    for (const [key, value] of styles.getStylesEntries()){
                        viewWriter.setStyle(key, value, viewElement);
                    }
                } else {
                    const keys = Object.keys(newAttribute.value);
                    for (const key of keys){
                        viewWriter.setStyle(key, newAttribute.value[key], viewElement);
                    }
                }
            } else {
                viewWriter.setAttribute(newAttribute.key, newAttribute.value, viewElement);
            }
        }
    };
}
/**
 * Function factory that creates a converter which converts the text inside marker's range. The converter wraps the text with
 * {@link module:engine/view/attributeelement~AttributeElement} created from the provided descriptor.
 * See {link module:engine/conversion/downcasthelpers~createViewElementFromHighlightDescriptor}.
 *
 * It can also be used to convert the selection that is inside a marker. In that case, an empty attribute element will be
 * created and the selection will be put inside it.
 *
 * If the highlight descriptor does not provide the `priority` property, `10` will be used.
 *
 * If the highlight descriptor does not provide the `id` property, the name of the marker will be used.
 *
 * This converter binds the created {@link module:engine/view/attributeelement~AttributeElement attribute elemens} with the marker name
 * using the {@link module:engine/conversion/mapper~Mapper#bindElementToMarker} method.
 */ function highlightText(highlightDescriptor) {
    return (evt, data, conversionApi)=>{
        if (!data.item) {
            return;
        }
        if (!(data.item instanceof Selection || data.item instanceof DocumentSelection) && !data.item.is('$textProxy')) {
            return;
        }
        const descriptor = prepareDescriptor(highlightDescriptor, data, conversionApi);
        if (!descriptor) {
            return;
        }
        if (!conversionApi.consumable.consume(data.item, evt.name)) {
            return;
        }
        const viewWriter = conversionApi.writer;
        const viewElement = createViewElementFromHighlightDescriptor(viewWriter, descriptor);
        const viewSelection = viewWriter.document.selection;
        if (data.item instanceof Selection || data.item instanceof DocumentSelection) {
            viewWriter.wrap(viewSelection.getFirstRange(), viewElement);
        } else {
            const viewRange = conversionApi.mapper.toViewRange(data.range);
            const rangeAfterWrap = viewWriter.wrap(viewRange, viewElement);
            for (const element of rangeAfterWrap.getItems()){
                if (element.is('attributeElement') && element.isSimilar(viewElement)) {
                    conversionApi.mapper.bindElementToMarker(element, data.markerName);
                    break;
                }
            }
        }
    };
}
/**
 * Converter function factory. It creates a function which applies the marker's highlight to an element inside the marker's range.
 *
 * The converter checks if an element has the `addHighlight` function stored as a
 * {@link module:engine/view/element~Element#_setCustomProperty custom property} and, if so, uses it to apply the highlight.
 * In such case the converter will consume all element's children, assuming that they were handled by the element itself.
 *
 * When the `addHighlight` custom property is not present, the element is not converted in any special way.
 * This means that converters will proceed to convert the element's child nodes.
 *
 * If the highlight descriptor does not provide the `priority` property, `10` will be used.
 *
 * If the highlight descriptor does not provide the `id` property, the name of the marker will be used.
 *
 * This converter binds altered {@link module:engine/view/containerelement~ContainerElement container elements} with the marker name using
 * the {@link module:engine/conversion/mapper~Mapper#bindElementToMarker} method.
 */ function highlightElement(highlightDescriptor) {
    return (evt, data, conversionApi)=>{
        if (!data.item) {
            return;
        }
        if (!(data.item instanceof Element)) {
            return;
        }
        const descriptor = prepareDescriptor(highlightDescriptor, data, conversionApi);
        if (!descriptor) {
            return;
        }
        if (!conversionApi.consumable.test(data.item, evt.name)) {
            return;
        }
        const viewElement = conversionApi.mapper.toViewElement(data.item);
        if (viewElement && viewElement.getCustomProperty('addHighlight')) {
            // Consume element itself.
            conversionApi.consumable.consume(data.item, evt.name);
            // Consume all children nodes.
            for (const value of Range._createIn(data.item)){
                conversionApi.consumable.consume(value.item, evt.name);
            }
            const addHighlightCallback = viewElement.getCustomProperty('addHighlight');
            addHighlightCallback(viewElement, descriptor, conversionApi.writer);
            conversionApi.mapper.bindElementToMarker(viewElement, data.markerName);
        }
    };
}
/**
 * Function factory that creates a converter which converts the removing model marker to the view.
 *
 * Both text nodes and elements are handled by this converter but they are handled a bit differently.
 *
 * Text nodes are unwrapped using the {@link module:engine/view/attributeelement~AttributeElement attribute element} created from the
 * provided highlight descriptor. See {link module:engine/conversion/downcasthelpers~HighlightDescriptor}.
 *
 * For elements, the converter checks if an element has the `removeHighlight` function stored as a
 * {@link module:engine/view/element~Element#_setCustomProperty custom property}. If so, it uses it to remove the highlight.
 * In such case, the children of that element will not be converted.
 *
 * When `removeHighlight` is not present, the element is not converted in any special way.
 * The converter will proceed to convert the element's child nodes instead.
 *
 * If the highlight descriptor does not provide the `priority` property, `10` will be used.
 *
 * If the highlight descriptor does not provide the `id` property, the name of the marker will be used.
 *
 * This converter unbinds elements from the marker name.
 */ function removeHighlight(highlightDescriptor) {
    return (evt, data, conversionApi)=>{
        // This conversion makes sense only for non-collapsed range.
        if (data.markerRange.isCollapsed) {
            return;
        }
        const descriptor = prepareDescriptor(highlightDescriptor, data, conversionApi);
        if (!descriptor) {
            return;
        }
        // View element that will be used to unwrap `AttributeElement`s.
        const viewHighlightElement = createViewElementFromHighlightDescriptor(conversionApi.writer, descriptor);
        // Get all elements bound with given marker name.
        const elements = conversionApi.mapper.markerNameToElements(data.markerName);
        if (!elements) {
            return;
        }
        for (const element of elements){
            conversionApi.mapper.unbindElementFromMarkerName(element, data.markerName);
            if (element.is('attributeElement')) {
                conversionApi.writer.unwrap(conversionApi.writer.createRangeOn(element), viewHighlightElement);
            } else {
                // if element.is( 'containerElement' ).
                const removeHighlightCallback = element.getCustomProperty('removeHighlight');
                removeHighlightCallback(element, descriptor.id, conversionApi.writer);
            }
        }
        conversionApi.writer.clearClonedElementsGroup(data.markerName);
        evt.stop();
    };
}
/**
 * Model element to view element conversion helper.
 *
 * See {@link ~DowncastHelpers#elementToElement `.elementToElement()` downcast helper} for examples and config params description.
 *
 * @param config Conversion configuration.
 * @param config.model The description or a name of the model element to convert.
 * @param config.model.attributes List of attributes triggering element reconversion.
 * @param config.model.children Should reconvert element if the list of model child nodes changed.
 * @returns Conversion helper.
 */ function downcastElementToElement(config) {
    const model = normalizeModelElementConfig(config.model);
    const view = normalizeToElementConfig(config.view, 'container');
    // Trigger reconversion on children list change if element is a subject to any reconversion.
    // This is required to be able to trigger Differ#refreshItem() on a direct child of the reconverted element.
    if (model.attributes.length) {
        model.children = true;
    }
    return (dispatcher)=>{
        dispatcher.on(`insert:${model.name}`, insertElement(view, createConsumer(model)), {
            priority: config.converterPriority || 'normal'
        });
        if (model.children || model.attributes.length) {
            dispatcher.on('reduceChanges', createChangeReducer(model), {
                priority: 'low'
            });
        }
    };
}
/**
 * Model element to view structure conversion helper.
 *
 * See {@link ~DowncastHelpers#elementToStructure `.elementToStructure()` downcast helper} for examples and config params description.
 *
 * @param config Conversion configuration.
 * @returns Conversion helper.
 */ function downcastElementToStructure(config) {
    const model = normalizeModelElementConfig(config.model);
    const view = normalizeToElementConfig(config.view, 'container');
    // Trigger reconversion on children list change because it always needs to use slots to put children in proper places.
    // This is required to be able to trigger Differ#refreshItem() on a direct child of the reconverted element.
    model.children = true;
    return (dispatcher)=>{
        if (dispatcher._conversionApi.schema.checkChild(model.name, '$text')) {
            /**
			 * This error occurs when a {@link module:engine/model/element~Element model element} is downcasted
			 * via {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToStructure} helper but the element was
			 * allowed to host `$text` by the {@link module:engine/model/schema~Schema model schema}.
			 *
			 * For instance, this may be the result of `myElement` allowing the content of
			 * {@glink framework/deep-dive/schema#generic-items `$block`} in its schema definition:
			 *
			 * ```ts
			 * // Element definition in schema.
			 * schema.register( 'myElement', {
			 * 	allowContentOf: '$block',
			 *
			 * 	// ...
			 * } );
			 *
			 * // ...
			 *
			 * // Conversion of myElement with the use of elementToStructure().
			 * editor.conversion.for( 'downcast' ).elementToStructure( {
			 * 	model: 'myElement',
			 * 	view: ( modelElement, { writer } ) => {
			 * 		// ...
			 * 	}
			 * } );
			 * ```
			 *
			 * In such case, {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToElement `elementToElement()`} helper
			 * can be used instead to get around this problem:
			 *
			 * ```ts
			 * editor.conversion.for( 'downcast' ).elementToElement( {
			 * 	model: 'myElement',
			 * 	view: ( modelElement, { writer } ) => {
			 * 		// ...
			 * 	}
			 * } );
			 * ```
			 *
			 * @error conversion-element-to-structure-disallowed-text
			 * @param {String} elementName The name of the element the structure is to be created for.
			 */ throw new CKEditorError('conversion-element-to-structure-disallowed-text', dispatcher, {
                elementName: model.name
            });
        }
        dispatcher.on(`insert:${model.name}`, insertStructure(view, createConsumer(model)), {
            priority: config.converterPriority || 'normal'
        });
        dispatcher.on('reduceChanges', createChangeReducer(model), {
            priority: 'low'
        });
    };
}
/**
 * Model attribute to view element conversion helper.
 *
 * See {@link ~DowncastHelpers#attributeToElement `.attributeToElement()` downcast helper} for examples.
 *
 * @param config Conversion configuration.
 * @param config.model The key of the attribute to convert from or a `{ key, values }` object. `values` is an array
 * of `String`s with possible values if the model attribute is an enumerable.
 * @param config.view A view element definition or a function that takes the model attribute value and
 * {@link module:engine/view/downcastwriter~DowncastWriter view downcast writer} as parameters and returns a view attribute element.
 * If `config.model.values` is given, `config.view` should be an object assigning values from `config.model.values` to view element
 * definitions or functions.
 * @param config.converterPriority Converter priority.
 * @returns Conversion helper.
 */ function downcastAttributeToElement(config) {
    config = cloneDeep(config);
    let model = config.model;
    if (typeof model == 'string') {
        model = {
            key: model
        };
    }
    let eventName = `attribute:${model.key}`;
    if (model.name) {
        eventName += ':' + model.name;
    }
    if (model.values) {
        for (const modelValue of model.values){
            config.view[modelValue] = normalizeToElementConfig(config.view[modelValue], 'attribute');
        }
    } else {
        config.view = normalizeToElementConfig(config.view, 'attribute');
    }
    const elementCreator = getFromAttributeCreator(config);
    return (dispatcher)=>{
        dispatcher.on(eventName, wrap(elementCreator), {
            priority: config.converterPriority || 'normal'
        });
    };
}
/**
 * Model attribute to view attribute conversion helper.
 *
 * See {@link ~DowncastHelpers#attributeToAttribute `.attributeToAttribute()` downcast helper} for examples.
 *
 * @param config Conversion configuration.
 * @param config.model The key of the attribute to convert from or a `{ key, values, [ name ] }` object describing
 * the attribute key, possible values and, optionally, an element name to convert from.
 * @param config.view A view attribute key, or a `{ key, value }` object or a function that takes the model attribute value and returns
 * a `{ key, value }` object.
 * If `key` is `'class'`, `value` can be a `String` or an array of `String`s. If `key` is `'style'`, `value` is an object with
 * key-value pairs. In other cases, `value` is a `String`.
 * If `config.model.values` is set, `config.view` should be an object assigning values from `config.model.values` to
 * `{ key, value }` objects or a functions.
 * @param config.converterPriority Converter priority.
 * @returns Conversion helper.
 */ function downcastAttributeToAttribute(config) {
    config = cloneDeep(config);
    let model = config.model;
    if (typeof model == 'string') {
        model = {
            key: model
        };
    }
    let eventName = `attribute:${model.key}`;
    if (model.name) {
        eventName += ':' + model.name;
    }
    if (model.values) {
        for (const modelValue of model.values){
            config.view[modelValue] = normalizeToAttributeConfig(config.view[modelValue]);
        }
    } else {
        config.view = normalizeToAttributeConfig(config.view);
    }
    const elementCreator = getFromAttributeCreator(config);
    return (dispatcher)=>{
        dispatcher.on(eventName, changeAttribute(elementCreator), {
            priority: config.converterPriority || 'normal'
        });
    };
}
/**
 * Model marker to view element conversion helper.
 *
 * See {@link ~DowncastHelpers#markerToElement `.markerToElement()` downcast helper} for examples.
 *
 * @param config Conversion configuration.
 * @param config.model The name of the model marker (or model marker group) to convert.
 * @param config.view A view element definition or a function that takes the model marker data as a parameter and returns a view UI element.
 * @param config.converterPriority Converter priority.
 * @returns Conversion helper.
 */ function downcastMarkerToElement(config) {
    const view = normalizeToElementConfig(config.view, 'ui');
    return (dispatcher)=>{
        dispatcher.on(`addMarker:${config.model}`, insertUIElement(view), {
            priority: config.converterPriority || 'normal'
        });
        dispatcher.on(`removeMarker:${config.model}`, removeUIElement(), {
            priority: config.converterPriority || 'normal'
        });
    };
}
/**
 * Model marker to view data conversion helper.
 *
 * See {@link ~DowncastHelpers#markerToData `markerToData()` downcast helper} to learn more.
 *
 * @returns Conversion helper.
 */ function downcastMarkerToData(config) {
    config = cloneDeep(config);
    const group = config.model;
    let view = config.view;
    // Default conversion.
    if (!view) {
        view = (markerName)=>({
                group,
                name: markerName.substr(config.model.length + 1)
            });
    }
    return (dispatcher)=>{
        dispatcher.on(`addMarker:${group}`, insertMarkerData(view), {
            priority: config.converterPriority || 'normal'
        });
        dispatcher.on(`removeMarker:${group}`, removeMarkerData(view), {
            priority: config.converterPriority || 'normal'
        });
    };
}
/**
 * Model marker to highlight conversion helper.
 *
 * See {@link ~DowncastHelpers#markerToElement `.markerToElement()` downcast helper} for examples.
 *
 * @param config Conversion configuration.
 * @param config.model The name of the model marker (or model marker group) to convert.
 * @param config.view A highlight descriptor that will be used for highlighting or a function that takes
 * the model marker data as a parameter and returns a highlight descriptor.
 * @param config.converterPriority Converter priority.
 * @returns Conversion helper.
 */ function downcastMarkerToHighlight(config) {
    return (dispatcher)=>{
        dispatcher.on(`addMarker:${config.model}`, highlightText(config.view), {
            priority: config.converterPriority || 'normal'
        });
        dispatcher.on(`addMarker:${config.model}`, highlightElement(config.view), {
            priority: config.converterPriority || 'normal'
        });
        dispatcher.on(`removeMarker:${config.model}`, removeHighlight(config.view), {
            priority: config.converterPriority || 'normal'
        });
    };
}
/**
 * Takes `config.model`, and converts it to an object with normalized structure.
 *
 * @param model Model configuration or element name.
 */ function normalizeModelElementConfig(model) {
    if (typeof model == 'string') {
        model = {
            name: model
        };
    }
    return {
        name: model.name,
        attributes: model.attributes ? toArray(model.attributes) : [],
        children: !!model.children
    };
}
/**
 * Takes `config.view`, and if it is an {@link module:engine/view/elementdefinition~ElementDefinition}, converts it
 * to a function (because lower level converters accept only element creator functions).
 *
 * @param view View configuration.
 * @param viewElementType View element type to create.
 * @returns Element creator function to use in lower level converters.
 */ function normalizeToElementConfig(view, viewElementType) {
    if (typeof view == 'function') {
        // If `view` is already a function, don't do anything.
        return view;
    }
    return (modelData, conversionApi)=>createViewElementFromDefinition(view, conversionApi, viewElementType);
}
/**
 * Creates a view element instance from the provided {@link module:engine/view/elementdefinition~ElementDefinition} and class.
 */ function createViewElementFromDefinition(viewElementDefinition, conversionApi, viewElementType) {
    if (typeof viewElementDefinition == 'string') {
        // If `viewElementDefinition` is given as a `String`, normalize it to an object with `name` property.
        viewElementDefinition = {
            name: viewElementDefinition
        };
    }
    let element;
    const viewWriter = conversionApi.writer;
    const attributes = Object.assign({}, viewElementDefinition.attributes);
    if (viewElementType == 'container') {
        element = viewWriter.createContainerElement(viewElementDefinition.name, attributes);
    } else if (viewElementType == 'attribute') {
        const options = {
            priority: viewElementDefinition.priority || AttributeElement.DEFAULT_PRIORITY
        };
        element = viewWriter.createAttributeElement(viewElementDefinition.name, attributes, options);
    } else {
        // 'ui'.
        element = viewWriter.createUIElement(viewElementDefinition.name, attributes);
    }
    if (viewElementDefinition.styles) {
        const keys = Object.keys(viewElementDefinition.styles);
        for (const key of keys){
            viewWriter.setStyle(key, viewElementDefinition.styles[key], element);
        }
    }
    if (viewElementDefinition.classes) {
        const classes = viewElementDefinition.classes;
        if (typeof classes == 'string') {
            viewWriter.addClass(classes, element);
        } else {
            for (const className of classes){
                viewWriter.addClass(className, element);
            }
        }
    }
    return element;
}
function getFromAttributeCreator(config) {
    if (config.model.values) {
        return (modelAttributeValue, conversionApi, data)=>{
            const view = config.view[modelAttributeValue];
            if (view) {
                return view(modelAttributeValue, conversionApi, data);
            }
            return null;
        };
    } else {
        return config.view;
    }
}
/**
 * Takes the configuration, adds default parameters if they do not exist and normalizes other parameters to be used in downcast converters
 * for generating a view attribute.
 *
 * @param view View configuration.
 */ function normalizeToAttributeConfig(view) {
    if (typeof view == 'string') {
        return (modelAttributeValue)=>({
                key: view,
                value: modelAttributeValue
            });
    } else if (typeof view == 'object') {
        // { key, value, ... }
        if (view.value) {
            return ()=>view;
        } else {
            return (modelAttributeValue)=>({
                    key: view.key,
                    value: modelAttributeValue
                });
        }
    } else {
        // function.
        return view;
    }
}
/**
 * Helper function for `highlight`. Prepares the actual descriptor object using value passed to the converter.
 */ function prepareDescriptor(highlightDescriptor, data, conversionApi) {
    // If passed descriptor is a creator function, call it. If not, just use passed value.
    const descriptor = typeof highlightDescriptor == 'function' ? highlightDescriptor(data, conversionApi) : highlightDescriptor;
    if (!descriptor) {
        return null;
    }
    // Apply default descriptor priority.
    if (!descriptor.priority) {
        descriptor.priority = 10;
    }
    // Default descriptor id is marker name.
    if (!descriptor.id) {
        descriptor.id = data.markerName;
    }
    return descriptor;
}
/**
 * Creates a function that checks a single differ diff item whether it should trigger reconversion.
 *
 * @param model A normalized `config.model` converter configuration.
 * @param model.name The name of element.
 * @param model.attributes The list of attribute names that should trigger reconversion.
 * @param model.children Whether the child list change should trigger reconversion.
 */ function createChangeReducerCallback(model) {
    return (node, change)=>{
        if (!node.is('element', model.name)) {
            return false;
        }
        if (change.type == 'attribute') {
            if (model.attributes.includes(change.attributeKey)) {
                return true;
            }
        } else {
            /* istanbul ignore else: This is always true because otherwise it would not register a reducer callback. -- @preserve */ if (model.children) {
                return true;
            }
        }
        return false;
    };
}
/**
 * Creates a `reduceChanges` event handler for reconversion.
 *
 * @param model A normalized `config.model` converter configuration.
 * @param model.name The name of element.
 * @param model.attributes The list of attribute names that should trigger reconversion.
 * @param model.children Whether the child list change should trigger reconversion.
 */ function createChangeReducer(model) {
    const shouldReplace = createChangeReducerCallback(model);
    return (evt, data)=>{
        const reducedChanges = [];
        if (!data.reconvertedElements) {
            data.reconvertedElements = new Set();
        }
        for (const change of data.changes){
            // For attribute use node affected by the change.
            // For insert or remove use parent element because we need to check if it's added/removed child.
            const node = change.type == 'attribute' ? change.range.start.nodeAfter : change.position.parent;
            if (!node || !shouldReplace(node, change)) {
                reducedChanges.push(change);
                continue;
            }
            // If it's already marked for reconversion, so skip this change, otherwise add the diff items.
            if (!data.reconvertedElements.has(node)) {
                data.reconvertedElements.add(node);
                const position = Position._createBefore(node);
                let changeIndex = reducedChanges.length;
                // We need to insert remove+reinsert before any other change on and inside the re-converted element.
                // This is important because otherwise we would remove element that had already been modified by the previous change.
                // Note that there could be some element removed before the re-converted element, so we must not break this behavior.
                for(let i = reducedChanges.length - 1; i >= 0; i--){
                    const change = reducedChanges[i];
                    const changePosition = change.type == 'attribute' ? change.range.start : change.position;
                    const positionRelation = changePosition.compareWith(position);
                    if (positionRelation == 'before' || change.type == 'remove' && positionRelation == 'same') {
                        break;
                    }
                    changeIndex = i;
                }
                reducedChanges.splice(changeIndex, 0, {
                    type: 'remove',
                    name: node.name,
                    position,
                    length: 1
                }, {
                    type: 'reinsert',
                    name: node.name,
                    position,
                    length: 1
                });
            }
        }
        data.changes = reducedChanges;
    };
}
/**
 * Creates a function that checks if an element and its watched attributes can be consumed and consumes them.
 *
 * @param model A normalized `config.model` converter configuration.
 * @param model.name The name of element.
 * @param model.attributes The list of attribute names that should trigger reconversion.
 * @param model.children Whether the child list change should trigger reconversion.
 */ function createConsumer(model) {
    return (node, consumable, options = {})=>{
        const events = [
            'insert'
        ];
        // Collect all set attributes that are triggering conversion.
        for (const attributeName of model.attributes){
            if (node.hasAttribute(attributeName)) {
                events.push(`attribute:${attributeName}`);
            }
        }
        if (!events.every((event)=>consumable.test(node, event))) {
            return false;
        }
        if (!options.preflight) {
            events.forEach((event)=>consumable.consume(node, event));
        }
        return true;
    };
}
/**
 * Creates a function that create view slots.
 *
 * @returns Function exposed by writer as createSlot().
 */ function createSlotFactory(element, slotsMap, conversionApi) {
    return (writer, modeOrFilter)=>{
        const slot = writer.createContainerElement('$slot');
        let children = null;
        if (modeOrFilter === 'children') {
            children = Array.from(element.getChildren());
        } else if (typeof modeOrFilter == 'function') {
            children = Array.from(element.getChildren()).filter((element)=>modeOrFilter(element));
        } else {
            /**
			 * Unknown slot mode was provided to `writer.createSlot()` in downcast converter.
			 *
			 * @error conversion-slot-mode-unknown
			 */ throw new CKEditorError('conversion-slot-mode-unknown', conversionApi.dispatcher, {
                modeOrFilter
            });
        }
        slotsMap.set(slot, children);
        return slot;
    };
}
/**
 * Checks if all children are covered by slots and there is no child that landed in multiple slots.
 */ function validateSlotsChildren(element, slotsMap, conversionApi) {
    const childrenInSlots = Array.from(slotsMap.values()).flat();
    const uniqueChildrenInSlots = new Set(childrenInSlots);
    if (uniqueChildrenInSlots.size != childrenInSlots.length) {
        /**
		 * Filters provided to `writer.createSlot()` overlap (at least two filters accept the same child element).
		 *
		 * @error conversion-slot-filter-overlap
		 * @param {module:engine/model/element~Element} element The element of which children would not be properly
		 * allocated to multiple slots.
		 */ throw new CKEditorError('conversion-slot-filter-overlap', conversionApi.dispatcher, {
            element
        });
    }
    if (uniqueChildrenInSlots.size != element.childCount) {
        /**
		 * Filters provided to `writer.createSlot()` are incomplete and exclude at least one children element (one of
		 * the children elements would not be assigned to any of the slots).
		 *
		 * @error conversion-slot-filter-incomplete
		 * @param {module:engine/model/element~Element} element The element of which children would not be properly
		 * allocated to multiple slots.
		 */ throw new CKEditorError('conversion-slot-filter-incomplete', conversionApi.dispatcher, {
            element
        });
    }
}
/**
 * Fill slots with appropriate view elements.
 */ function fillSlots(viewElement, slotsMap, conversionApi, options) {
    // Set temporary position mapping to redirect child view elements into a proper slots.
    conversionApi.mapper.on('modelToViewPosition', toViewPositionMapping, {
        priority: 'highest'
    });
    let currentSlot = null;
    let currentSlotNodes = null;
    // Fill slots with nested view nodes.
    for ([currentSlot, currentSlotNodes] of slotsMap){
        reinsertOrConvertNodes(viewElement, currentSlotNodes, conversionApi, options);
        conversionApi.writer.move(conversionApi.writer.createRangeIn(currentSlot), conversionApi.writer.createPositionBefore(currentSlot));
        conversionApi.writer.remove(currentSlot);
    }
    conversionApi.mapper.off('modelToViewPosition', toViewPositionMapping);
    function toViewPositionMapping(evt, data) {
        const element = data.modelPosition.nodeAfter;
        // Find the proper offset within the slot.
        const index = currentSlotNodes.indexOf(element);
        if (index < 0) {
            return;
        }
        data.viewPosition = data.mapper.findPositionIn(currentSlot, index);
    }
}
/**
 * Inserts view representation of `nodes` into the `viewElement` either by bringing back just removed view nodes
 * or by triggering conversion for them.
 */ function reinsertOrConvertNodes(viewElement, modelNodes, conversionApi, options) {
    // Fill with nested view nodes.
    for (const modelChildNode of modelNodes){
        // Try reinserting the view node for the specified model node...
        if (!reinsertNode(viewElement.root, modelChildNode, conversionApi, options)) {
            // ...or else convert the model element to the view.
            conversionApi.convertItem(modelChildNode);
        }
    }
}
/**
 * Checks if the view for the given model element could be reused and reinserts it to the view.
 *
 * @returns `false` if view element can't be reused.
 */ function reinsertNode(viewRoot, modelNode, conversionApi, options) {
    const { writer, mapper } = conversionApi;
    // Don't reinsert if this is not a reconversion...
    if (!options.reconversion) {
        return false;
    }
    const viewChildNode = mapper.toViewElement(modelNode);
    // ...or there is no view to reinsert or it was already inserted to the view structure...
    if (!viewChildNode || viewChildNode.root == viewRoot) {
        return false;
    }
    // ...or it was strictly marked as not to be reused.
    if (!conversionApi.canReuseView(viewChildNode)) {
        return false;
    }
    // Otherwise reinsert the view node.
    writer.move(writer.createRangeOn(viewChildNode), mapper.toViewPosition(Position._createBefore(modelNode)));
    return true;
}
/**
 * The default consumer for insert events.
 *
 * @param item Model item.
 * @param consumable The model consumable.
 * @param options.preflight Whether should consume or just check if can be consumed.
 */ function defaultConsumer(item, consumable, { preflight } = {}) {
    if (preflight) {
        return consumable.test(item, 'insert');
    } else {
        return consumable.consume(item, 'insert');
    }
}

/**
 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */ /**
 * @module engine/model/utils/autoparagraphing
 */ /**
 * Fixes all empty roots.
 *
 * @internal
 * @param writer The model writer.
 * @returns `true` if any change has been applied, `false` otherwise.
 */ function autoParagraphEmptyRoots(writer) {
    const { schema, document } = writer.model;
    for (const root of document.getRoots()){
        if (root.isEmpty && !schema.checkChild(root, '$text')) {
            // If paragraph element is allowed in the root, create paragraph element.
            if (schema.checkChild(root, 'paragraph')) {
                writer.insertElement('paragraph', root);
                // Other roots will get fixed in the next post-fixer round. Those will be triggered
                // in the same batch no matter if this method was triggered by the post-fixing or not
                // (the above insertElement call will trigger the post-fixers).
                return true;
            }
        }
    }
    return false;
}
/**
 * Checks if the given node wrapped with a paragraph would be accepted by the schema in the given position.
 *
 * @internal
 * @param position The position at which to check.
 * @param nodeOrType The child node or child type to check.
 * @param schema A schema instance used for element validation.
 */ function isParagraphable(position, nodeOrType, schema) {
    const context = schema.createContext(position);
    // When paragraph is allowed in this context...
    if (!schema.checkChild(context, 'paragraph')) {
        return false;
    }
    // And a node would be allowed in this paragraph...
    if (!schema.checkChild(context.push('paragraph'), nodeOrType)) {
        return false;
    }
    return true;
}
/**
 * Inserts a new paragraph at the given position and returns a position inside that paragraph.
 *
 * @internal
 * @param position The position where a paragraph should be inserted.
 * @param writer The model writer.
 * @returns  Position inside the created paragraph.
 */ function wrapInParagraph(position, writer) {
    const paragraph = writer.createElement('paragraph');
    writer.insert(paragraph, position);
    return writer.createPositionAt(paragraph, 0);
}

/**
 * Contains the {@link module:engine/view/view view} to {@link module:engine/model/model model} converters for
 * {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher}.
 *
 * @module engine/conversion/upcasthelpers
 */ /**
 * Upcast conversion helper functions.
 *
 * Learn more about {@glink framework/deep-dive/conversion/upcast upcast helpers}.
 *
 * @extends module:engine/conversion/conversionhelpers~ConversionHelpers
 */ class UpcastHelpers extends ConversionHelpers {
    /**
	 * View element to model element conversion helper.
	 *
	 * This conversion results in creating a model element. For example,
	 * view `<p>Foo</p>` becomes `<paragraph>Foo</paragraph>` in the model.
	 *
	 * Keep in mind that the element will be inserted only if it is allowed
	 * by {@link module:engine/model/schema~Schema schema} configuration.
	 *
	 * ```ts
	 * editor.conversion.for( 'upcast' ).elementToElement( {
	 * 	view: 'p',
	 * 	model: 'paragraph'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToElement( {
	 * 	view: 'p',
	 * 	model: 'paragraph',
	 * 	converterPriority: 'high'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToElement( {
	 * 	view: {
	 * 		name: 'p',
	 * 		classes: 'fancy'
	 * 	},
	 * 	model: 'fancyParagraph'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToElement( {
	 * 	view: {
	 * 		name: 'p',
	 * 		classes: 'heading'
	 * 	},
	 * 	model: ( viewElement, conversionApi ) => {
	 * 		const modelWriter = conversionApi.writer;
	 *
	 * 		return modelWriter.createElement( 'heading', { level: viewElement.getAttribute( 'data-level' ) } );
	 * 	}
	 * } );
	 * ```
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.view Pattern matching all view elements which should be converted. If not set, the converter
	 * will fire for every view element.
	 * @param config.model Name of the model element, a model element instance or a function that takes a view element
	 * and {@link module:engine/conversion/upcastdispatcher~UpcastConversionApi upcast conversion API}
	 * and returns a model element. The model element will be inserted in the model.
	 * @param config.converterPriority Converter priority.
	 */ elementToElement(config) {
        return this.add(upcastElementToElement(config));
    }
    /**
	 * View element to model attribute conversion helper.
	 *
	 * This conversion results in setting an attribute on a model node. For example, view `<strong>Foo</strong>` becomes
	 * `Foo` {@link module:engine/model/text~Text model text node} with `bold` attribute set to `true`.
	 *
	 * This helper is meant to set a model attribute on all the elements that are inside the converted element:
	 *
	 * ```
	 * <strong>Foo</strong>   -->   <strong><p>Foo</p></strong>   -->   <paragraph><$text bold="true">Foo</$text></paragraph>
	 * ```
	 *
	 * Above is a sample of HTML code, that goes through autoparagraphing (first step) and then is converted (second step).
	 * Even though `<strong>` is over `<p>` element, `bold="true"` was added to the text. See
	 * {@link module:engine/conversion/upcasthelpers~UpcastHelpers#attributeToAttribute} for comparison.
	 *
	 * Keep in mind that the attribute will be set only if it is allowed by {@link module:engine/model/schema~Schema schema} configuration.
	 *
	 * ```ts
	 * editor.conversion.for( 'upcast' ).elementToAttribute( {
	 * 	view: 'strong',
	 * 	model: 'bold'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToAttribute( {
	 * 	view: 'strong',
	 * 	model: 'bold',
	 * 	converterPriority: 'high'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToAttribute( {
	 * 	view: {
	 * 		name: 'span',
	 * 		classes: 'bold'
	 * 	},
	 * 	model: 'bold'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToAttribute( {
	 * 	view: {
	 * 		name: 'span',
	 * 		classes: [ 'styled', 'styled-dark' ]
	 * 	},
	 * 	model: {
	 * 		key: 'styled',
	 * 		value: 'dark'
	 * 	}
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToAttribute( {
	 * 	view: {
	 * 		name: 'span',
	 * 		styles: {
	 * 			'font-size': /[\s\S]+/
	 * 		}
	 * 	},
	 * 	model: {
	 * 		key: 'fontSize',
	 * 		value: ( viewElement, conversionApi ) => {
	 * 			const fontSize = viewElement.getStyle( 'font-size' );
	 * 			const value = fontSize.substr( 0, fontSize.length - 2 );
	 *
	 * 			if ( value <= 10 ) {
	 * 				return 'small';
	 * 			} else if ( value > 12 ) {
	 * 				return 'big';
	 * 			}
	 *
	 * 			return null;
	 * 		}
	 * 	}
	 * } );
	 * ```
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.view Pattern matching all view elements which should be converted.
	 * @param config.model Model attribute key or an object with `key` and `value` properties, describing
	 * the model attribute. `value` property may be set as a function that takes a view element and
	 * {@link module:engine/conversion/upcastdispatcher~UpcastConversionApi upcast conversion API} and returns the value.
	 * If `String` is given, the model attribute value will be set to `true`.
	 * @param config.converterPriority Converter priority. Defaults to `low`.
	 */ elementToAttribute(config) {
        return this.add(upcastElementToAttribute(config));
    }
    /**
	 * View attribute to model attribute conversion helper.
	 *
	 * This conversion results in setting an attribute on a model node. For example, view `<img src="foo.jpg"></img>` becomes
	 * `<imageBlock source="foo.jpg"></imageBlock>` in the model.
	 *
	 * This helper is meant to convert view attributes from view elements which got converted to the model, so the view attribute
	 * is set only on the corresponding model node:
	 *
	 * ```
	 * <div class="dark"><div>foo</div></div>    -->    <div dark="true"><div>foo</div></div>
	 * ```
	 *
	 * Above, `class="dark"` attribute is added only to the `<div>` elements that has it. This is in contrast to
	 * {@link module:engine/conversion/upcasthelpers~UpcastHelpers#elementToAttribute} which sets attributes for
	 * all the children in the model:
	 *
	 * ```
	 * <strong>Foo</strong>   -->   <strong><p>Foo</p></strong>   -->   <paragraph><$text bold="true">Foo</$text></paragraph>
	 * ```
	 *
	 * Above is a sample of HTML code, that goes through autoparagraphing (first step) and then is converted (second step).
	 * Even though `<strong>` is over `<p>` element, `bold="true"` was added to the text.
	 *
	 * Keep in mind that the attribute will be set only if it is allowed by {@link module:engine/model/schema~Schema schema} configuration.
	 *
	 * ```ts
	 * editor.conversion.for( 'upcast' ).attributeToAttribute( {
	 * 	view: 'src',
	 * 	model: 'source'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).attributeToAttribute( {
	 * 	view: { key: 'src' },
	 * 	model: 'source'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).attributeToAttribute( {
	 * 	view: { key: 'src' },
	 * 	model: 'source',
	 * 	converterPriority: 'normal'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).attributeToAttribute( {
	 * 	view: {
	 * 		key: 'data-style',
	 * 		value: /[\s\S]+/
	 * 	},
	 * 	model: 'styled'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).attributeToAttribute( {
	 * 	view: {
	 * 		name: 'img',
	 * 		key: 'class',
	 * 		value: 'styled-dark'
	 * 	},
	 * 	model: {
	 * 		key: 'styled',
	 * 		value: 'dark'
	 * 	}
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).attributeToAttribute( {
	 * 	view: {
	 * 		key: 'class',
	 * 		value: /styled-[\S]+/
	 * 	},
	 * 	model: {
	 * 		key: 'styled'
	 * 		value: ( viewElement, conversionApi ) => {
	 * 			const regexp = /styled-([\S]+)/;
	 * 			const match = viewElement.getAttribute( 'class' ).match( regexp );
	 *
	 * 			return match[ 1 ];
	 * 		}
	 * 	}
	 * } );
	 * ```
	 *
	 * Converting styles works a bit differently as it requires `view.styles` to be an object and by default
	 * a model attribute will be set to `true` by such a converter. You can set the model attribute to any value by providing the `value`
	 * callback that returns the desired value.
	 *
	 * ```ts
	 * // Default conversion of font-weight style will result in setting bold attribute to true.
	 * editor.conversion.for( 'upcast' ).attributeToAttribute( {
	 * 	view: {
	 * 		styles: {
	 * 			'font-weight': 'bold'
	 * 		}
	 * 	},
	 * 	model: 'bold'
	 * } );
	 *
	 * // This converter will pass any style value to the `lineHeight` model attribute.
	 * editor.conversion.for( 'upcast' ).attributeToAttribute( {
	 * 	view: {
	 * 		styles: {
	 * 			'line-height': /[\s\S]+/
	 * 		}
	 * 	},
	 * 	model: {
	 * 		key: 'lineHeight',
	 * 		value: ( viewElement, conversionApi ) => viewElement.getStyle( 'line-height' )
	 * 	}
	 * } );
	 * ```
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.view Specifies which view attribute will be converted. If a `String` is passed,
	 * attributes with given key will be converted. If an `Object` is passed, it must have a required `key` property,
	 * specifying view attribute key, and may have an optional `value` property, specifying view attribute value and optional `name`
	 * property specifying a view element name from/on which the attribute should be converted. `value` can be given as a `String`,
	 * a `RegExp` or a function callback, that takes view attribute value as the only parameter and returns `Boolean`.
	 * @param config.model Model attribute key or an object with `key` and `value` properties, describing
	 * the model attribute. `value` property may be set as a function that takes a view element and
	 * {@link module:engine/conversion/upcastdispatcher~UpcastConversionApi upcast conversion API} and returns the value.
	 * If `String` is given, the model attribute value will be same as view attribute value.
	 * @param config.converterPriority Converter priority. Defaults to `low`.
	 */ attributeToAttribute(config) {
        return this.add(upcastAttributeToAttribute(config));
    }
    /**
	 * View element to model marker conversion helper.
	 *
	 * This conversion results in creating a model marker. For example, if the marker was stored in a view as an element:
	 * `<p>Fo<span data-marker="comment" data-comment-id="7"></span>o</p><p>B<span data-marker="comment" data-comment-id="7"></span>ar</p>`,
	 * after the conversion is done, the marker will be available in
	 * {@link module:engine/model/model~Model#markers model document markers}.
	 *
	 * **Note**: When this helper is used in the data upcast in combination with
	 * {@link module:engine/conversion/downcasthelpers~DowncastHelpers#markerToData `#markerToData()`} in the data downcast,
	 * then invalid HTML code (e.g. a span between table cells) may be produced by the latter converter.
	 *
	 * In most of the cases, the {@link #dataToMarker} should be used instead.
	 *
	 * ```ts
	 * editor.conversion.for( 'upcast' ).elementToMarker( {
	 * 	view: 'marker-search',
	 * 	model: 'search'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToMarker( {
	 * 	view: 'marker-search',
	 * 	model: 'search',
	 * 	converterPriority: 'high'
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToMarker( {
	 * 	view: 'marker-search',
	 * 	model: ( viewElement, conversionApi ) => 'comment:' + viewElement.getAttribute( 'data-comment-id' )
	 * } );
	 *
	 * editor.conversion.for( 'upcast' ).elementToMarker( {
	 * 	view: {
	 * 		name: 'span',
	 * 		attributes: {
	 * 			'data-marker': 'search'
	 * 		}
	 * 	},
	 * 	model: 'search'
	 * } );
	 * ```
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.view Pattern matching all view elements which should be converted.
	 * @param config.model Name of the model marker, or a function that takes a view element and returns
	 * a model marker name.
	 * @param config.converterPriority Converter priority.
	 */ elementToMarker(config) {
        return this.add(upcastElementToMarker(config));
    }
    /**
	 * View-to-model marker conversion helper.
	 *
	 * Converts view data created by {@link module:engine/conversion/downcasthelpers~DowncastHelpers#markerToData `#markerToData()`}
	 * back to a model marker.
	 *
	 * This converter looks for specific view elements and view attributes that mark marker boundaries. See
	 * {@link module:engine/conversion/downcasthelpers~DowncastHelpers#markerToData `#markerToData()`} to learn what view data
	 * is expected by this converter.
	 *
	 * The `config.view` property is equal to the marker group name to convert.
	 *
	 * By default, this converter creates markers with the `group:name` name convention (to match the default `markerToData` conversion).
	 *
	 * The conversion configuration can take a function that will generate a marker name.
	 * If such function is set as the `config.model` parameter, it is passed the `name` part from the view element or attribute and it is
	 * expected to return a string with the marker name.
	 *
	 * Basic usage:
	 *
	 * ```ts
	 * // Using the default conversion.
	 * // In this case, all markers from the `comment` group will be converted.
	 * // The conversion will look for `<comment-start>` and `<comment-end>` tags and
	 * // `data-comment-start-before`, `data-comment-start-after`,
	 * // `data-comment-end-before` and `data-comment-end-after` attributes.
	 * editor.conversion.for( 'upcast' ).dataToMarker( {
	 * 	view: 'comment'
	 * } );
	 * ```
	 *
	 * An example of a model that may be generated by this conversion:
	 *
	 * ```
	 * // View:
	 * <p>Foo<comment-start name="commentId:uid"></comment-start>bar</p>
	 * <figure data-comment-end-after="commentId:uid" class="image"><img src="abc.jpg" /></figure>
	 *
	 * // Model:
	 * <paragraph>Foo[bar</paragraph>
	 * <imageBlock src="abc.jpg"></imageBlock>]
	 * ```
	 *
	 * Where `[]` are boundaries of a marker that will receive the `comment:commentId:uid` name.
	 *
	 * Other examples of usage:
	 *
	 * ```ts
	 * // Using a custom function which is the same as the default conversion:
	 * editor.conversion.for( 'upcast' ).dataToMarker( {
	 * 	view: 'comment',
	 * 	model: ( name, conversionApi ) => 'comment:' + name,
	 * } );
	 *
	 * // Using the converter priority:
	 * editor.conversion.for( 'upcast' ).dataToMarker( {
	 * 	view: 'comment',
	 * 	model: ( name, conversionApi ) => 'comment:' + name,
	 * 	converterPriority: 'high'
	 * } );
	 * ```
	 *
	 * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
	 * to the conversion process.
	 *
	 * @param config Conversion configuration.
	 * @param config.view The marker group name to convert.
	 * @param config.model A function that takes the `name` part from the view element or attribute and
	 * {@link module:engine/conversion/upcastdispatcher~UpcastConversionApi upcast conversion API} and returns the marker name.
	 * @param config.converterPriority Converter priority.
	 */ dataToMarker(config) {
        return this.add(upcastDataToMarker(config));
    }
}
/**
 * Function factory, creates a converter that converts {@link module:engine/view/documentfragment~DocumentFragment view document fragment}
 * or all children of {@link module:engine/view/element~Element} into
 * {@link module:engine/model/documentfragment~DocumentFragment model document fragment}.
 * This is the "entry-point" converter for upcast (view to model conversion). This converter starts the conversion of all children
 * of passed view document fragment. Those children {@link module:engine/view/node~Node view nodes} are then handled by other converters.
 *
 * This also a "default", last resort converter for all view elements that has not been converted by other converters.
 * When a view element is being converted to the model but it does not have converter specified, that view element
 * will be converted to {@link module:engine/model/documentfragment~DocumentFragment model document fragment} and returned.
 *
 * @returns Universal converter for view {@link module:engine/view/documentfragment~DocumentFragment fragments} and
 * {@link module:engine/view/element~Element elements} that returns
 * {@link module:engine/model/documentfragment~DocumentFragment model fragment} with children of converted view item.
 */ function convertToModelFragment$1() {
    return (evt, data, conversionApi)=>{
        // Second argument in `consumable.consume` is discarded for ViewDocumentFragment but is needed for ViewElement.
        if (!data.modelRange && conversionApi.consumable.consume(data.viewItem, {
            name: true
        })) {
            const { modelRange, modelCursor } = conversionApi.convertChildren(data.viewItem, data.modelCursor);
            data.modelRange = modelRange;
            data.modelCursor = modelCursor;
        }
    };
}
/**
 * Function factory, creates a converter that converts {@link module:engine/view/text~Text} to {@link module:engine/model/text~Text}.
 *
 * @returns {@link module:engine/view/text~Text View text} converter.
 */ function convertText() {
    return (evt, data, { schema, consumable, writer })=>{
        let position = data.modelCursor;
        // When node is already converted then do nothing.
        if (!consumable.test(data.viewItem)) {
            return;
        }
        if (!schema.checkChild(position, '$text')) {
            if (!isParagraphable(position, '$text', schema)) {
                return;
            }
            // Do not auto-paragraph whitespaces.
            if (data.viewItem.data.trim().length == 0) {
                return;
            }
            // Wrap `$text` in paragraph and include any marker that is directly before `$text`. See #13053.
            const nodeBefore = position.nodeBefore;
            position = wrapInParagraph(position, writer);
            if (nodeBefore && nodeBefore.is('element', '$marker')) {
                // Move `$marker` to the paragraph.
                writer.move(writer.createRangeOn(nodeBefore), position);
                position = writer.createPositionAfter(nodeBefore);
            }
        }
        consumable.consume(data.viewItem);
        const text = writer.createText(data.viewItem.data);
        writer.insert(text, position);
        data.modelRange = writer.createRange(position, position.getShiftedBy(text.offsetSize));
        data.modelCursor = data.modelRange.end;
    };
}
/**
 * Function factory, creates a callback function which converts a {@link module:engine/view/selection~Selection
 * view selection} taken from the {@link module:engine/view/document~Document#event:selectionChange} event
 * and sets in on the {@link module:engine/model/document~Document#selection model}.
 *
 * **Note**: because there is no view selection change dispatcher nor any other advanced view selection to model
 * conversion mechanism, the callback should be set directly on view document.
 *
 * ```ts
 * view.document.on( 'selectionChange', convertSelectionChange( modelDocument, mapper ) );
 * ```
 *
 * @param model Data model.
 * @param mapper Conversion mapper.
 * @returns {@link module:engine/view/document~Document#event:selectionChange} callback function.
 */ function convertSelectionChange(model, mapper) {
    return (evt, data)=>{
        const viewSelection = data.newSelection;
        const ranges = [];
        for (const viewRange of viewSelection.getRanges()){
            ranges.push(mapper.toModelRange(viewRange));
        }
        const modelSelection = model.createSelection(ranges, {
            backward: viewSelection.isBackward
        });
        if (!modelSelection.isEqual(model.document.selection)) {
            model.change((writer)=>{
                writer.setSelection(modelSelection);
            });
        }
    };
}
/**
 * View element to model element conversion helper.
 *
 * See {@link ~UpcastHelpers#elementToElement `.elementToElement()` upcast helper} for examples.
 *
 * @param config Conversion configuration.
 * @param config.view Pattern matching all view elements which should be converted. If not
 * set, the converter will fire for every view element.
 * @param config.model Name of the model element, a model element
 * instance or a function that takes a view element and returns a model element. The model element will be inserted in the model.
 * @param config.converterPriority Converter priority.
 * @returns Conversion helper.
 */ function upcastElementToElement(config) {
    config = cloneDeep(config);
    const converter = prepareToElementConverter(config);
    const elementName = getViewElementNameFromConfig(config.view);
    const eventName = elementName ? `element:${elementName}` : 'element';
    return (dispatcher)=>{
        dispatcher.on(eventName, converter, {
            priority: config.converterPriority || 'normal'
        });
    };
}
/**
 * View element to model attribute conversion helper.
 *
 * See {@link ~UpcastHelpers#elementToAttribute `.elementToAttribute()` upcast helper} for examples.
 *
 * @param config Conversion configuration.
 * @param config.view Pattern matching all view elements which should be converted.
 * @param config.model Model attribute key or an object with `key` and `value` properties, describing
 * the model attribute. `value` property may be set as a function that takes a view element and returns the value.
 * If `String` is given, the model attribute value will be set to `true`.
 * @param config.converterPriority Converter priority. Defaults to `low`.
 * @returns Conversion helper.
 */ function upcastElementToAttribute(config) {
    config = cloneDeep(config);
    normalizeModelAttributeConfig(config);
    const converter = prepareToAttributeConverter(config, false);
    const elementName = getViewElementNameFromConfig(config.view);
    const eventName = elementName ? `element:${elementName}` : 'element';
    return (dispatcher)=>{
        dispatcher.on(eventName, converter, {
            priority: config.converterPriority || 'low'
        });
    };
}
/**
 * View attribute to model attribute conversion helper.
 *
 * See {@link ~UpcastHelpers#attributeToAttribute `.attributeToAttribute()` upcast helper} for examples.
 *
 * @param config Conversion configuration.
 * @param config.view Specifies which view attribute will be converted. If a `String` is passed,
 * attributes with given key will be converted. If an `Object` is passed, it must have a required `key` property,
 * specifying view attribute key, and may have an optional `value` property, specifying view attribute value and optional `name`
 * property specifying a view element name from/on which the attribute should be converted. `value` can be given as a `String`,
 * a `RegExp` or a function callback, that takes view attribute value as the only parameter and returns `Boolean`.
 * @param config.model Model attribute key or an object with `key` and `value` properties, describing
 * the model attribute. `value` property may be set as a function that takes a view element and returns the value.
 * If `String` is given, the model attribute value will be same as view attribute value.
 * @param config.converterPriority Converter priority. Defaults to `low`.
 * @returns Conversion helper.
 */ function upcastAttributeToAttribute(config) {
    config = cloneDeep(config);
    let viewKey = null;
    if (typeof config.view == 'string' || config.view.key) {
        viewKey = normalizeViewAttributeKeyValueConfig(config);
    }
    normalizeModelAttributeConfig(config, viewKey);
    const converter = prepareToAttributeConverter(config, true);
    return (dispatcher)=>{
        dispatcher.on('element', converter, {
            priority: config.converterPriority || 'low'
        });
    };
}
/**
 * View element to model marker conversion helper.
 *
 * See {@link ~UpcastHelpers#elementToMarker `.elementToMarker()` upcast helper} for examples.
 *
 * @param config Conversion configuration.
 * @param config.view Pattern matching all view elements which should be converted.
 * @param config.model Name of the model marker, or a function that takes a view element and returns
 * a model marker name.
 * @param config.converterPriority Converter priority.
 * @returns Conversion helper.
 */ function upcastElementToMarker(config) {
    const model = normalizeElementToMarkerModelConfig(config.model);
    return upcastElementToElement({
        ...config,
        model
    });
}
/**
 * View data to model marker conversion helper.
 *
 * See {@link ~UpcastHelpers#dataToMarker} to learn more.
 *
 * @returns Conversion helper.
 */ function upcastDataToMarker(config) {
    config = cloneDeep(config);
    // Default conversion.
    if (!config.model) {
        config.model = (name)=>{
            return name ? config.view + ':' + name : config.view;
        };
    }
    const normalizedConfig = {
        view: config.view,
        model: config.model
    };
    const converterStart = prepareToElementConverter(normalizeDataToMarkerConfig(normalizedConfig, 'start'));
    const converterEnd = prepareToElementConverter(normalizeDataToMarkerConfig(normalizedConfig, 'end'));
    return (dispatcher)=>{
        dispatcher.on(`element:${config.view}-start`, converterStart, {
            priority: config.converterPriority || 'normal'
        });
        dispatcher.on(`element:${config.view}-end`, converterEnd, {
            priority: config.converterPriority || 'normal'
        });
        // Below is a hack that is needed to properly handle `converterPriority` for both elements and attributes.
        // Attribute conversion needs to be performed *after* element conversion.
        // This converter handles both element conversion and attribute conversion, which means that if a single
        // `config.converterPriority` is used, it will lead to problems. For example, if the `'high'` priority is used,
        // the attribute conversion will be performed before a lot of element upcast converters.
        // On the other hand, we want to support `config.converterPriority` and converter overwriting.
        //
        // To make it work, we need to do some extra processing for priority for attribute converter.
        // Priority `'low'` value should be the base value and then we will change it depending on `config.converterPriority` value.
        //
        // This hack probably would not be needed if attributes are upcasted separately.
        //
        const basePriority = priorities.low;
        const maxPriority = priorities.highest;
        const priorityFactor = priorities.get(config.converterPriority) / maxPriority; // Number in range [ -1, 1 ].
        dispatcher.on('element', upcastAttributeToMarker(normalizedConfig), {
            priority: basePriority + priorityFactor
        });
    };
}
/**
 * Function factory, returns a callback function which converts view attributes to a model marker.
 *
 * The converter looks for elements with `data-group-start-before`, `data-group-start-after`, `data-group-end-before`
 * and `data-group-end-after` attributes and inserts `$marker` model elements before/after those elements.
 * `group` part is specified in `config.view`.
 *
 * @returns Marker converter.
 */ function upcastAttributeToMarker(config) {
    return (evt, data, conversionApi)=>{
        const attrName = `data-${config.view}`;
        // Check if any attribute for the given view item can be consumed before changing the conversion data
        // and consuming view items with these attributes.
        if (!conversionApi.consumable.test(data.viewItem, {
            attributes: attrName + '-end-after'
        }) && !conversionApi.consumable.test(data.viewItem, {
            attributes: attrName + '-start-after'
        }) && !conversionApi.consumable.test(data.viewItem, {
            attributes: attrName + '-end-before'
        }) && !conversionApi.consumable.test(data.viewItem, {
            attributes: attrName + '-start-before'
        })) {
            return;
        }
        // This converter wants to add a model element, marking a marker, before/after an element (or maybe even group of elements).
        // To do that, we can use `data.modelRange` which is set on an element (or a group of elements) that has been upcasted.
        // But, if the processed view element has not been upcasted yet (it does not have been converted), we need to
        // fire conversion for its children first, then we will have `data.modelRange` available.
        if (!data.modelRange) {
            Object.assign(data, conversionApi.convertChildren(data.viewItem, data.modelCursor));
        }
        if (conversionApi.consumable.consume(data.viewItem, {
            attributes: attrName + '-end-after'
        })) {
            addMarkerElements(data.modelRange.end, data.viewItem.getAttribute(attrName + '-end-after').split(','));
        }
        if (conversionApi.consumable.consume(data.viewItem, {
            attributes: attrName + '-start-after'
        })) {
            addMarkerElements(data.modelRange.end, data.viewItem.getAttribute(attrName + '-start-after').split(','));
        }
        if (conversionApi.consumable.consume(data.viewItem, {
            attributes: attrName + '-end-before'
        })) {
            addMarkerElements(data.modelRange.start, data.viewItem.getAttribute(attrName + '-end-before').split(','));
        }
        if (conversionApi.consumable.consume(data.viewItem, {
            attributes: attrName + '-start-before'
        })) {
            addMarkerElements(data.modelRange.start, data.viewItem.getAttribute(attrName + '-start-before').split(','));
        }
        function addMarkerElements(position, markerViewNames) {
            for (const markerViewName of markerViewNames){
                const markerName = config.model(markerViewName, conversionApi);
                const element = conversionApi.writer.createElement('$marker', {
                    'data-name': markerName
                });
                conversionApi.writer.insert(element, position);
                if (data.modelCursor.isEqual(position)) {
                    data.modelCursor = data.modelCursor.getShiftedBy(1);
                } else {
                    data.modelCursor = data.modelCursor._getTransformedByInsertion(position, 1);
                }
                data.modelRange = data.modelRange._getTransformedByInsertion(position, 1)[0];
            }
        }
    };
}
/**
 * Helper function for from-view-element conversion. Checks if `config.view` directly specifies converted view element's name
 * and if so, returns it.
 *
 * @param config Conversion view config.
 * @returns View element name or `null` if name is not directly set.
 */ function getViewElementNameFromConfig(viewConfig) {
    if (typeof viewConfig == 'string') {
        return viewConfig;
    }
    if (typeof viewConfig == 'object' && typeof viewConfig.name == 'string') {
        return viewConfig.name;
    }
    return null;
}
/**
 * Helper for to-model-element conversion. Takes a config object and returns a proper converter function.
 *
 * @param config Conversion configuration.
 * @returns View to model converter.
 */ function prepareToElementConverter(config) {
    const matcher = new Matcher(config.view);
    return (evt, data, conversionApi)=>{
        const matcherResult = matcher.match(data.viewItem);
        if (!matcherResult) {
            return;
        }
        const match = matcherResult.match;
        // Force consuming element's name.
        match.name = true;
        if (!conversionApi.consumable.test(data.viewItem, match)) {
            return;
        }
        const modelElement = getModelElement(config.model, data.viewItem, conversionApi);
        if (!modelElement) {
            return;
        }
        if (!conversionApi.safeInsert(modelElement, data.modelCursor)) {
            return;
        }
        conversionApi.consumable.consume(data.viewItem, match);
        conversionApi.convertChildren(data.viewItem, modelElement);
        conversionApi.updateConversionResult(modelElement, data);
    };
}
/**
 * Helper function for upcasting-to-element converter. Takes the model configuration, the converted view element
 * and a writer instance and returns a model element instance to be inserted in the model.
 *
 * @param model Model conversion configuration.
 * @param input The converted view node.
 * @param conversionApi The upcast conversion API.
 */ function getModelElement(model, input, conversionApi) {
    if (model instanceof Function) {
        return model(input, conversionApi);
    } else {
        return conversionApi.writer.createElement(model);
    }
}
/**
 * Helper function view-attribute-to-model-attribute helper. Normalizes `config.view` which was set as `String` or
 * as an `Object` with `key`, `value` and `name` properties. Normalized `config.view` has is compatible with
 * {@link module:engine/view/matcher~MatcherPattern}.
 *
 * @param config Conversion config.
 * @returns Key of the converted view attribute.
 */ function normalizeViewAttributeKeyValueConfig(config) {
    if (typeof config.view == 'string') {
        config.view = {
            key: config.view
        };
    }
    const key = config.view.key;
    const value = typeof config.view.value == 'undefined' ? /[\s\S]*/ : config.view.value;
    let normalized;
    if (key == 'class' || key == 'style') {
        const keyName = key == 'class' ? 'classes' : 'styles';
        normalized = {
            [keyName]: value
        };
    } else {
        normalized = {
            attributes: {
                [key]: value
            }
        };
    }
    if (config.view.name) {
        normalized.name = config.view.name;
    }
    config.view = normalized;
    return key;
}
/**
 * Helper function that normalizes `config.model` in from-model-attribute conversion. `config.model` can be set
 * as a `String`, an `Object` with only `key` property or an `Object` with `key` and `value` properties. Normalized
 * `config.model` is an `Object` with `key` and `value` properties.
 *
 * @param config Conversion config.
 * @param viewAttributeKeyToCopy Key of the converted view attribute. If it is set, model attribute value
 * will be equal to view attribute value.
 */ function normalizeModelAttributeConfig(config, viewAttributeKeyToCopy = null) {
    const defaultModelValue = viewAttributeKeyToCopy === null ? true : (viewElement)=>viewElement.getAttribute(viewAttributeKeyToCopy);
    const key = typeof config.model != 'object' ? config.model : config.model.key;
    const value = typeof config.model != 'object' || typeof config.model.value == 'undefined' ? defaultModelValue : config.model.value;
    config.model = {
        key,
        value
    };
}
/**
 * Helper for to-model-attribute conversion. Takes the model attribute name and conversion configuration and returns
 * a proper converter function.
 *
 * @param config Conversion configuration. It is possible to provide multiple configurations in an array.
 * @param shallow If set to `true` the attribute will be set only on top-level nodes. Otherwise, it will be set
 * on all elements in the range.
 */ function prepareToAttributeConverter(config, shallow) {
    const matcher = new Matcher(config.view);
    return (evt, data, conversionApi)=>{
        // Converting an attribute of an element that has not been converted to anything does not make sense
        // because there will be nowhere to set that attribute on. At this stage, the element should've already
        // been converted (https://github.com/ckeditor/ckeditor5/issues/11000).
        if (!data.modelRange && shallow) {
            return;
        }
        const match = matcher.match(data.viewItem);
        // If there is no match, this callback should not do anything.
        if (!match) {
            return;
        }
        if (onlyViewNameIsDefined(config.view, data.viewItem)) {
            match.match.name = true;
        } else {
            // Do not test `name` consumable because it could get consumed already while upcasting some other attribute
            // on the same element (for example <span class="big" style="color: red">foo</span>).
            delete match.match.name;
        }
        // Try to consume appropriate values from consumable values list.
        if (!conversionApi.consumable.test(data.viewItem, match.match)) {
            return;
        }
        const modelKey = config.model.key;
        const modelValue = typeof config.model.value == 'function' ? config.model.value(data.viewItem, conversionApi) : config.model.value;
        // Do not convert if attribute building function returned falsy value.
        if (modelValue === null) {
            return;
        }
        // Since we are converting to attribute we need a range on which we will set the attribute.
        // If the range is not created yet, let's create it by converting children of the current node first.
        if (!data.modelRange) {
            // Convert children and set conversion result as a current data.
            Object.assign(data, conversionApi.convertChildren(data.viewItem, data.modelCursor));
        }
        // Set attribute on current `output`. `Schema` is checked inside this helper function.
        const attributeWasSet = setAttributeOn(data.modelRange, {
            key: modelKey,
            value: modelValue
        }, shallow, conversionApi);
        // It may happen that a converter will try to set an attribute that is not allowed in the given context.
        // In such a situation we cannot consume the attribute. See: https://github.com/ckeditor/ckeditor5/pull/9249#issuecomment-815658459.
        if (attributeWasSet) {
            // Verify if the element itself wasn't consumed yet. It could be consumed already while upcasting some other attribute
            // on the same element (for example <span class="big" style="color: red">foo</span>).
            // We need to consume it so other features (especially GHS) won't try to convert it.
            // Note that it's not tested by the other element-to-attribute converters whether an element was consumed before
            // (in case of converters that the element itself is just a context and not the primary information to convert).
            if (conversionApi.consumable.test(data.viewItem, {
                name: true
            })) {
                match.match.name = true;
            }
            conversionApi.consumable.consume(data.viewItem, match.match);
        }
    };
}
/**
 * Helper function that checks if element name should be consumed in attribute converters.
 *
 * @param viewConfig Conversion view config.
 */ function onlyViewNameIsDefined(viewConfig, viewItem) {
    // https://github.com/ckeditor/ckeditor5-engine/issues/1786
    const configToTest = typeof viewConfig == 'function' ? viewConfig(viewItem) : viewConfig;
    if (typeof configToTest == 'object' && !getViewElementNameFromConfig(configToTest)) {
        return false;
    }
    return !configToTest.classes && !configToTest.attributes && !configToTest.styles;
}
/**
 * Helper function for to-model-attribute converter. Sets model attribute on given range. Checks {@link module:engine/model/schema~Schema}
 * to ensure proper model structure.
 *
 * If any node on the given range has already defined an attribute with the same name, its value will not be updated.
 *
 * @param modelRange Model range on which attribute should be set.
 * @param modelAttribute Model attribute to set.
 * @param conversionApi Conversion API.
 * @param shallow If set to `true` the attribute will be set only on top-level nodes. Otherwise, it will be set
 * on all elements in the range.
 * @returns `true` if attribute was set on at least one node from given `modelRange`.
 */ function setAttributeOn(modelRange, modelAttribute, shallow, conversionApi) {
    let result = false;
    // Set attribute on each item in range according to Schema.
    for (const node of Array.from(modelRange.getItems({
        shallow
    }))){
        // Skip if not allowed.
        if (!conversionApi.schema.checkAttribute(node, modelAttribute.key)) {
            continue;
        }
        // Mark the node as consumed even if the attribute will not be updated because it's in a valid context (schema)
        // and would be converted if the attribute wouldn't be present. See #8921.
        result = true;
        // Do not override the attribute if it's already present.
        if (node.hasAttribute(modelAttribute.key)) {
            continue;
        }
        conversionApi.writer.setAttribute(modelAttribute.key, modelAttribute.value, node);
    }
    return result;
}
/**
 * Helper function for upcasting-to-marker conversion. Takes the config in a format requested by `upcastElementToMarker()`
 * function and converts it to a format that is supported by `upcastElementToElement()` function.
 */ function normalizeElementToMarkerModelConfig(model) {
    return (viewElement, conversionApi)=>{
        const markerName = typeof model == 'string' ? model : model(viewElement, conversionApi);
        return conversionApi.writer.createElement('$marker', {
            'data-name': markerName
        });
    };
}
/**
 * Helper function for upcasting-to-marker conversion. Takes the config in a format requested by `upcastDataToMarker()`
 * function and converts it to a format that is supported by `upcastElementToElement()` function.
 */ function normalizeDataToMarkerConfig(config, type) {
    const elementCreatorFunction = (viewElement, conversionApi)=>{
        const viewName = viewElement.getAttribute('name');
        const markerName = config.model(viewName, conversionApi);
        return conversionApi.writer.createElement('$marker', {
            'data-name': markerName
        });
    };
    return {
        // Upcast <markerGroup-start> and <markerGroup-end> elements.
        view: `${config.view}-${type}`,
        model: elementCreatorFunction
    };
}

/**
 * Injects selection post-fixer to the model.
 *
 * The role of the selection post-fixer is to ensure that the selection is in a correct place
 * after a {@link module:engine/model/model~Model#change `change()`} block was executed.
 *
 * The correct position means that:
 *
 * * All collapsed selection ranges are in a place where the {@link module:engine/model/schema~Schema}
 * allows a `$text`.
 * * None of the selection's non-collapsed ranges crosses a {@link module:engine/model/schema~Schema#isLimit limit element}
 * boundary (a range must be rooted within one limit element).
 * * Only {@link module:engine/model/schema~Schema#isSelectable selectable elements} can be selected from the outside
 * (e.g. `[<paragraph>foo</paragraph>]` is invalid). This rule applies independently to both selection ends, so this
 * selection is correct: `<paragraph>f[oo</paragraph><imageBlock></imageBlock>]`.
 *
 * If the position is not correct, the post-fixer will automatically correct it.
 *
 * ## Fixing a non-collapsed selection
 *
 * See as an example a selection that starts in a P1 element and ends inside the text of a TD element
 * (`[` and `]` are range boundaries and `(l)` denotes an element defined as `isLimit=true`):
 *
 * ```
 * root
 *  |- element P1
 *  |   |- "foo"                                      root
 *  |- element TABLE (l)                   P1         TABLE             P2
 *  |   |- element TR (l)                 f o[o     TR      TR         b a r
 *  |   |   |- element TD (l)                       TD      TD
 *  |   |       |- "aaa"                          a]a a    b b b
 *  |   |- element TR (l)
 *  |   |   |- element TD (l)                           ||
 *  |   |       |- "bbb"                                ||
 *  |- element P2                                       VV
 *  |   |- "bar"
 *                                                    root
 *                                         P1         TABLE]            P2
 *                                        f o[o     TR      TR         b a r
 *                                                  TD      TD
 *                                                a a a    b b b
 * ```
 *
 * In the example above, the TABLE, TR and TD are defined as `isLimit=true` in the schema. The range which is not contained within
 * a single limit element must be expanded to select the outermost limit element. The range end is inside the text node of the TD element.
 * As the TD element is a child of the TR and TABLE elements, where both are defined as `isLimit=true` in the schema, the range must be
 * expanded to select the whole TABLE element.
 *
 * **Note** If the selection contains multiple ranges, the method returns a minimal set of ranges that are not intersecting after expanding
 * them to select `isLimit=true` elements.
 */ function injectSelectionPostFixer(model) {
    model.document.registerPostFixer((writer)=>selectionPostFixer(writer, model));
}
/**
 * The selection post-fixer.
 */ function selectionPostFixer(writer, model) {
    const selection = model.document.selection;
    const schema = model.schema;
    const ranges = [];
    let wasFixed = false;
    for (const modelRange of selection.getRanges()){
        // Go through all ranges in selection and try fixing each of them.
        // Those ranges might overlap but will be corrected later.
        const correctedRange = tryFixingRange(modelRange, schema);
        // "Selection fixing" algorithms sometimes get lost. In consequence, it may happen
        // that a new range is returned but, in fact, it has the same positions as the original
        // range anyway. If this range is not discarded, a new selection will be set and that,
        // for instance, would destroy the selection attributes. Let's make sure that the post-fixer
        // actually worked first before setting a new selection.
        //
        // https://github.com/ckeditor/ckeditor5/issues/6693
        if (correctedRange && !correctedRange.isEqual(modelRange)) {
            ranges.push(correctedRange);
            wasFixed = true;
        } else {
            ranges.push(modelRange);
        }
    }
    // If any of ranges were corrected update the selection.
    if (wasFixed) {
        writer.setSelection(mergeIntersectingRanges(ranges), {
            backward: selection.isBackward
        });
    }
    return false;
}
/**
 * Tries fixing a range if it's incorrect.
 *
 * **Note:** This helper is used by the selection post-fixer and to fix the `beforeinput` target ranges.
 *
 * @returns Returns fixed range or null if range is valid.
 */ function tryFixingRange(range, schema) {
    if (range.isCollapsed) {
        return tryFixingCollapsedRange(range, schema);
    }
    return tryFixingNonCollapsedRage(range, schema);
}
/**
 * Tries to fix collapsed ranges.
 *
 * * Fixes situation when a range is in a place where $text is not allowed
 *
 * @param range Collapsed range to fix.
 * @returns Returns fixed range or null if range is valid.
 */ function tryFixingCollapsedRange(range, schema) {
    const originalPosition = range.start;
    const nearestSelectionRange = schema.getNearestSelectionRange(originalPosition);
    // This might be null, i.e. when the editor data is empty or the selection is inside a limit element
    // that doesn't allow text inside.
    // In the first case, there is no need to fix the selection range.
    // In the second, let's go up to the outer selectable element
    if (!nearestSelectionRange) {
        const ancestorObject = originalPosition.getAncestors().reverse().find((item)=>schema.isObject(item));
        if (ancestorObject) {
            return Range._createOn(ancestorObject);
        }
        return null;
    }
    if (!nearestSelectionRange.isCollapsed) {
        return nearestSelectionRange;
    }
    const fixedPosition = nearestSelectionRange.start;
    // Fixed position is the same as original - no need to return corrected range.
    if (originalPosition.isEqual(fixedPosition)) {
        return null;
    }
    return new Range(fixedPosition);
}
/**
 * Tries to fix an expanded range.
 *
 * @param range Expanded range to fix.
 * @returns Returns fixed range or null if range is valid.
 */ function tryFixingNonCollapsedRage(range, schema) {
    const { start, end } = range;
    const isTextAllowedOnStart = schema.checkChild(start, '$text');
    const isTextAllowedOnEnd = schema.checkChild(end, '$text');
    const startLimitElement = schema.getLimitElement(start);
    const endLimitElement = schema.getLimitElement(end);
    // Ranges which both end are inside the same limit element (or root) might needs only minor fix.
    if (startLimitElement === endLimitElement) {
        // Range is valid when both position allows to place a text:
        // - <block>f[oobarba]z</block>
        // This would be "fixed" by a next check but as it will be the same it's better to return null so the selection stays the same.
        if (isTextAllowedOnStart && isTextAllowedOnEnd) {
            return null;
        }
        // Range that is on non-limit element (or is partially) must be fixed so it is placed inside the block around $text:
        // - [<block>foo</block>]    ->    <block>[foo]</block>
        // - [<block>foo]</block>    ->    <block>[foo]</block>
        // - <block>f[oo</block>]    ->    <block>f[oo]</block>
        // - [<block>foo</block><selectable></selectable>]    ->    <block>[foo</block><selectable></selectable>]
        if (checkSelectionOnNonLimitElements(start, end, schema)) {
            const isStartBeforeSelectable = start.nodeAfter && schema.isSelectable(start.nodeAfter);
            const fixedStart = isStartBeforeSelectable ? null : schema.getNearestSelectionRange(start, 'forward');
            const isEndAfterSelectable = end.nodeBefore && schema.isSelectable(end.nodeBefore);
            const fixedEnd = isEndAfterSelectable ? null : schema.getNearestSelectionRange(end, 'backward');
            // The schema.getNearestSelectionRange might return null - if that happens use original position.
            const rangeStart = fixedStart ? fixedStart.start : start;
            const rangeEnd = fixedEnd ? fixedEnd.end : end;
            return new Range(rangeStart, rangeEnd);
        }
    }
    const isStartInLimit = startLimitElement && !startLimitElement.is('rootElement');
    const isEndInLimit = endLimitElement && !endLimitElement.is('rootElement');
    // At this point we eliminated valid positions on text nodes so if one of range positions is placed inside a limit element
    // then the range crossed limit element boundaries and needs to be fixed.
    if (isStartInLimit || isEndInLimit) {
        const bothInSameParent = start.nodeAfter && end.nodeBefore && start.nodeAfter.parent === end.nodeBefore.parent;
        const expandStart = isStartInLimit && (!bothInSameParent || !isSelectable(start.nodeAfter, schema));
        const expandEnd = isEndInLimit && (!bothInSameParent || !isSelectable(end.nodeBefore, schema));
        // Although we've already found limit element on start/end positions we must find the outer-most limit element.
        // as limit elements might be nested directly inside (ie table > tableRow > tableCell).
        let fixedStart = start;
        let fixedEnd = end;
        if (expandStart) {
            fixedStart = Position._createBefore(findOutermostLimitAncestor(startLimitElement, schema));
        }
        if (expandEnd) {
            fixedEnd = Position._createAfter(findOutermostLimitAncestor(endLimitElement, schema));
        }
        return new Range(fixedStart, fixedEnd);
    }
    // Range was not fixed at this point so it is valid - ie it was placed around limit element already.
    return null;
}
/**
 * Finds the outer-most ancestor.
 */ function findOutermostLimitAncestor(startingNode, schema) {
    let isLimitNode = startingNode;
    let parent = isLimitNode;
    // Find outer most isLimit block as such blocks might be nested (ie. in tables).
    while(schema.isLimit(parent) && parent.parent){
        isLimitNode = parent;
        parent = parent.parent;
    }
    return isLimitNode;
}
/**
 * Checks whether any of range boundaries is placed around non-limit elements.
 */ function checkSelectionOnNonLimitElements(start, end, schema) {
    const startIsOnBlock = start.nodeAfter && !schema.isLimit(start.nodeAfter) || schema.checkChild(start, '$text');
    const endIsOnBlock = end.nodeBefore && !schema.isLimit(end.nodeBefore) || schema.checkChild(end, '$text');
    // We should fix such selection when one of those nodes needs fixing.
    return startIsOnBlock || endIsOnBlock;
}
/**
 * Returns a minimal non-intersecting array of ranges without duplicates.
 *
 * @param ranges Ranges to merge.
 * @returns Array of unique and non-intersecting ranges.
 */ function mergeIntersectingRanges(ranges) {
    const rangesToMerge = [
        ...ranges
    ];
    const rangeIndexesToRemove = new Set();
    let currentRangeIndex = 1;
    while(currentRangeIndex < rangesToMerge.length){
        const currentRange = rangesToMerge[currentRangeIndex];
        const previousRanges = rangesToMerge.slice(0, currentRangeIndex);
        for (const [previousRangeIndex, previousRange] of previousRanges.entries()){
            if (rangeIndexesToRemove.has(previousRangeIndex)) {
                continue;
            }
            if (currentRange.isEqual(previousRange)) {
                rangeIndexesToRemove.add(previousRangeIndex);
            } else if (currentRange.isIntersecting(previousRange)) {
                rangeIndexesToRemove.add(previousRangeIndex);
                rangeIndexesToRemove.add(currentRangeIndex);
                const mergedRange = currentRange.getJoined(previousRange);
                rangesToMerge.push(mergedRange);
            }
        }
        currentRangeIndex++;
    }
    const nonIntersectingRanges = rangesToMerge.filter((_, index)=>!rangeIndexesToRemove.has(index));
    return nonIntersectingRanges;
}
/**
 * Checks if node exists and if it's a selectable.
 */ function isSelectable(node, schema) {
    return node && schema.isSelectable(node);
}

// @if CK_DEBUG_ENGINE // const { dumpTrees, initDocumentDumping } = require( '../dev-utils/utils' );
/**
 * A controller for the editing pipeline. The editing pipeline controls the {@link ~EditingController#model model} rendering,
 * including selection handling. It also creates the {@link ~EditingController#view view} which builds a
 * browser-independent virtualization over the DOM elements. The editing controller also attaches default converters.
 */ class EditingController extends /* #__PURE__ */ ObservableMixin() {
    /**
	 * Editor model.
	 */ model;
    /**
	 * Editing view controller.
	 */ view;
    /**
	 * A mapper that describes the model-view binding.
	 */ mapper;
    /**
	 * Downcast dispatcher that converts changes from the model to the {@link #view editing view}.
	 */ downcastDispatcher;
    /**
	 * Creates an editing controller instance.
	 *
	 * @param model Editing model.
	 * @param stylesProcessor The styles processor instance.
	 */ constructor(model, stylesProcessor){
        super();
        this.model = model;
        this.view = new View(stylesProcessor);
        this.mapper = new Mapper();
        this.downcastDispatcher = new DowncastDispatcher({
            mapper: this.mapper,
            schema: model.schema
        });
        const doc = this.model.document;
        const selection = doc.selection;
        const markers = this.model.markers;
        // When plugins listen on model changes (on selection change, post fixers, etc.) and change the view as a result of
        // the model's change, they might trigger view rendering before the conversion is completed (e.g. before the selection
        // is converted). We disable rendering for the length of the outermost model change() block to prevent that.
        //
        // See https://github.com/ckeditor/ckeditor5-engine/issues/1528
        this.listenTo(this.model, '_beforeChanges', ()=>{
            this.view._disableRendering(true);
        }, {
            priority: 'highest'
        });
        this.listenTo(this.model, '_afterChanges', ()=>{
            this.view._disableRendering(false);
        }, {
            priority: 'lowest'
        });
        // Whenever model document is changed, convert those changes to the view (using model.Document#differ).
        // Do it on 'low' priority, so changes are converted after other listeners did their job.
        // Also convert model selection.
        this.listenTo(doc, 'change', ()=>{
            this.view.change((writer)=>{
                this.downcastDispatcher.convertChanges(doc.differ, markers, writer);
                this.downcastDispatcher.convertSelection(selection, markers, writer);
            });
        }, {
            priority: 'low'
        });
        // Convert selection from the view to the model when it changes in the view.
        this.listenTo(this.view.document, 'selectionChange', convertSelectionChange(this.model, this.mapper));
        // Fix `beforeinput` target ranges so that they map to the valid model ranges.
        this.listenTo(this.view.document, 'beforeinput', fixTargetRanges(this.mapper, this.model.schema, this.view), {
            priority: 'high'
        });
        // Attach default model converters.
        this.downcastDispatcher.on('insert:$text', insertText(), {
            priority: 'lowest'
        });
        this.downcastDispatcher.on('insert', insertAttributesAndChildren(), {
            priority: 'lowest'
        });
        this.downcastDispatcher.on('remove', remove(), {
            priority: 'low'
        });
        // Attach default model selection converters.
        this.downcastDispatcher.on('cleanSelection', cleanSelection());
        this.downcastDispatcher.on('selection', convertRangeSelection(), {
            priority: 'low'
        });
        this.downcastDispatcher.on('selection', convertCollapsedSelection(), {
            priority: 'low'
        });
        // Binds {@link module:engine/view/document~Document#roots view roots collection} to
        // {@link module:engine/model/document~Document#roots model roots collection} so creating
        // model root automatically creates corresponding view root.
        this.view.document.roots.bindTo(this.model.document.roots).using((root)=>{
            // $graveyard is a special root that has no reflection in the view.
            if (root.rootName == '$graveyard') {
                return null;
            }
            const viewRoot = new RootEditableElement(this.view.document, root.name);
            viewRoot.rootName = root.rootName;
            this.mapper.bindElements(root, viewRoot);
            return viewRoot;
        });
    // @if CK_DEBUG_ENGINE // initDocumentDumping( this.model.document );
    // @if CK_DEBUG_ENGINE // initDocumentDumping( this.view.document );
    // @if CK_DEBUG_ENGINE // dumpTrees( this.model.document, this.model.document.version );
    // @if CK_DEBUG_ENGINE // dumpTrees( this.view.document, this.model.document.version );
    // @if CK_DEBUG_ENGINE // this.model.document.on( 'change', () => {
    // @if CK_DEBUG_ENGINE //	dumpTrees( this.view.document, this.model.document.version );
    // @if CK_DEBUG_ENGINE // }, { priority: 'lowest' } );
    }
    /**
	 * Removes all event listeners attached to the `EditingController`. Destroys all objects created
	 * by `EditingController` that need to be destroyed.
	 */ destroy() {
        this.view.destroy();
        this.stopListening();
    }
    /**
	 * Calling this method will refresh the marker by triggering the downcast conversion for it.
	 *
	 * Reconverting the marker is useful when you want to change its {@link module:engine/view/element~Element view element}
	 * without changing any marker data. For instance:
	 *
	 * ```ts
	 * let isCommentActive = false;
	 *
	 * model.conversion.markerToHighlight( {
	 * 	model: 'comment',
	 * 	view: data => {
	 * 		const classes = [ 'comment-marker' ];
	 *
	 * 		if ( isCommentActive ) {
	 * 			classes.push( 'comment-marker--active' );
	 * 		}
	 *
	 * 		return { classes };
	 * 	}
	 * } );
	 *
	 * // ...
	 *
	 * // Change the property that indicates if marker is displayed as active or not.
	 * isCommentActive = true;
	 *
	 * // Reconverting will downcast and synchronize the marker with the new isCommentActive state value.
	 * editor.editing.reconvertMarker( 'comment' );
	 * ```
	 *
	 * **Note**: If you want to reconvert a model item, use {@link #reconvertItem} instead.
	 *
	 * @param markerOrName Name of a marker to update, or a marker instance.
	 */ reconvertMarker(markerOrName) {
        const markerName = typeof markerOrName == 'string' ? markerOrName : markerOrName.name;
        const currentMarker = this.model.markers.get(markerName);
        if (!currentMarker) {
            /**
			 * The marker with the provided name does not exist and cannot be reconverted.
			 *
			 * @error editingcontroller-reconvertmarker-marker-not-exist
			 * @param {String} markerName The name of the reconverted marker.
			 */ throw new CKEditorError('editingcontroller-reconvertmarker-marker-not-exist', this, {
                markerName
            });
        }
        this.model.change(()=>{
            this.model.markers._refresh(currentMarker);
        });
    }
    /**
	 * Calling this method will downcast a model item on demand (by requesting a refresh in the {@link module:engine/model/differ~Differ}).
	 *
	 * You can use it if you want the view representation of a specific item updated as a response to external modifications. For instance,
	 * when the view structure depends not only on the associated model data but also on some external state.
	 *
	 * **Note**: If you want to reconvert a model marker, use {@link #reconvertMarker} instead.
	 *
	 * @param item Item to refresh.
	 */ reconvertItem(item) {
        this.model.change(()=>{
            this.model.document.differ._refreshItem(item);
        });
    }
}
/**
 * Checks whether the target ranges provided by the `beforeInput` event can be properly mapped to model ranges and fixes them if needed.
 *
 * This is using the same logic as the selection post-fixer.
 */ function fixTargetRanges(mapper, schema, view) {
    return (evt, data)=>{
        // The Renderer is disabled while composing on non-android browsers, so we can't be sure that target ranges
        // could be properly mapped to view and model because the DOM and view tree drifted apart.
        if (view.document.isComposing && !env.isAndroid) {
            return;
        }
        for(let i = 0; i < data.targetRanges.length; i++){
            const viewRange = data.targetRanges[i];
            const modelRange = mapper.toModelRange(viewRange);
            const correctedRange = tryFixingRange(modelRange, schema);
            if (!correctedRange || correctedRange.isEqual(modelRange)) {
                continue;
            }
            data.targetRanges[i] = mapper.toViewRange(correctedRange);
        }
    };
}

/**
 * Class used for handling consumption of view {@link module:engine/view/element~Element elements},
 * {@link module:engine/view/text~Text text nodes} and {@link module:engine/view/documentfragment~DocumentFragment document fragments}.
 * Element's name and its parts (attributes, classes and styles) can be consumed separately. Consuming an element's name
 * does not consume its attributes, classes and styles.
 * To add items for consumption use {@link module:engine/conversion/viewconsumable~ViewConsumable#add add method}.
 * To test items use {@link module:engine/conversion/viewconsumable~ViewConsumable#test test method}.
 * To consume items use {@link module:engine/conversion/viewconsumable~ViewConsumable#consume consume method}.
 * To revert already consumed items use {@link module:engine/conversion/viewconsumable~ViewConsumable#revert revert method}.
 *
 * ```ts
 * viewConsumable.add( element, { name: true } ); // Adds element's name as ready to be consumed.
 * viewConsumable.add( textNode ); // Adds text node for consumption.
 * viewConsumable.add( docFragment ); // Adds document fragment for consumption.
 * viewConsumable.test( element, { name: true }  ); // Tests if element's name can be consumed.
 * viewConsumable.test( textNode ); // Tests if text node can be consumed.
 * viewConsumable.test( docFragment ); // Tests if document fragment can be consumed.
 * viewConsumable.consume( element, { name: true }  ); // Consume element's name.
 * viewConsumable.consume( textNode ); // Consume text node.
 * viewConsumable.consume( docFragment ); // Consume document fragment.
 * viewConsumable.revert( element, { name: true }  ); // Revert already consumed element's name.
 * viewConsumable.revert( textNode ); // Revert already consumed text node.
 * viewConsumable.revert( docFragment ); // Revert already consumed document fragment.
 * ```
 */ class ViewConsumable {
    /**
	 * Map of consumable elements. If {@link module:engine/view/element~Element element} is used as a key,
	 * {@link module:engine/conversion/viewconsumable~ViewElementConsumables ViewElementConsumables} instance is stored as value.
	 * For {@link module:engine/view/text~Text text nodes} and
	 * {@link module:engine/view/documentfragment~DocumentFragment document fragments} boolean value is stored as value.
	 */ _consumables = new Map();
    add(element, consumables) {
        let elementConsumables;
        // For text nodes and document fragments just mark them as consumable.
        if (element.is('$text') || element.is('documentFragment')) {
            this._consumables.set(element, true);
            return;
        }
        // For elements create new ViewElementConsumables or update already existing one.
        if (!this._consumables.has(element)) {
            elementConsumables = new ViewElementConsumables(element);
            this._consumables.set(element, elementConsumables);
        } else {
            elementConsumables = this._consumables.get(element);
        }
        elementConsumables.add(consumables);
    }
    /**
	 * Tests if {@link module:engine/view/element~Element view element}, {@link module:engine/view/text~Text text node} or
	 * {@link module:engine/view/documentfragment~DocumentFragment document fragment} can be consumed.
	 * It returns `true` when all items included in method's call can be consumed. Returns `false` when
	 * first already consumed item is found and `null` when first non-consumable item is found.
	 *
	 * ```ts
	 * viewConsumable.test( p, { name: true } ); // Tests element's name.
	 * viewConsumable.test( p, { attributes: 'name' } ); // Tests attribute.
	 * viewConsumable.test( p, { classes: 'foobar' } ); // Tests class.
	 * viewConsumable.test( p, { styles: 'color' } ); // Tests style.
	 * viewConsumable.test( p, { attributes: 'name', styles: 'color' } ); // Tests attribute and style.
	 * viewConsumable.test( p, { classes: [ 'baz', 'bar' ] } ); // Multiple consumables can be tested.
	 * viewConsumable.test( textNode ); // Tests text node.
	 * viewConsumable.test( docFragment ); // Tests document fragment.
	 * ```
	 *
	 * Testing classes and styles as attribute will test if all added classes/styles can be consumed.
	 *
	 * ```ts
	 * viewConsumable.test( p, { attributes: 'class' } ); // Tests if all added classes can be consumed.
	 * viewConsumable.test( p, { attributes: 'style' } ); // Tests if all added styles can be consumed.
	 * ```
	 *
	 * @param consumables Used only if first parameter is {@link module:engine/view/element~Element view element} instance.
	 * @param consumables.name If set to true element's name will be included.
	 * @param consumables.attributes Attribute name or array of attribute names.
	 * @param consumables.classes Class name or array of class names.
	 * @param consumables.styles Style name or array of style names.
	 * @returns Returns `true` when all items included in method's call can be consumed. Returns `false`
	 * when first already consumed item is found and `null` when first non-consumable item is found.
	 */ test(element, consumables) {
        const elementConsumables = this._consumables.get(element);
        if (elementConsumables === undefined) {
            return null;
        }
        // For text nodes and document fragments return stored boolean value.
        if (element.is('$text') || element.is('documentFragment')) {
            return elementConsumables;
        }
        // For elements test consumables object.
        return elementConsumables.test(consumables);
    }
    /**
	 * Consumes {@link module:engine/view/element~Element view element}, {@link module:engine/view/text~Text text node} or
	 * {@link module:engine/view/documentfragment~DocumentFragment document fragment}.
	 * It returns `true` when all items included in method's call can be consumed, otherwise returns `false`.
	 *
	 * ```ts
	 * viewConsumable.consume( p, { name: true } ); // Consumes element's name.
	 * viewConsumable.consume( p, { attributes: 'name' } ); // Consumes element's attribute.
	 * viewConsumable.consume( p, { classes: 'foobar' } ); // Consumes element's class.
	 * viewConsumable.consume( p, { styles: 'color' } ); // Consumes element's style.
	 * viewConsumable.consume( p, { attributes: 'name', styles: 'color' } ); // Consumes attribute and style.
	 * viewConsumable.consume( p, { classes: [ 'baz', 'bar' ] } ); // Multiple consumables can be consumed.
	 * viewConsumable.consume( textNode ); // Consumes text node.
	 * viewConsumable.consume( docFragment ); // Consumes document fragment.
	 * ```
	 *
	 * Consuming classes and styles as attribute will test if all added classes/styles can be consumed.
	 *
	 * ```ts
	 * viewConsumable.consume( p, { attributes: 'class' } ); // Consume only if all added classes can be consumed.
	 * viewConsumable.consume( p, { attributes: 'style' } ); // Consume only if all added styles can be consumed.
	 * ```
	 *
	 * @param consumables Used only if first parameter is {@link module:engine/view/element~Element view element} instance.
	 * @param consumables.name If set to true element's name will be included.
	 * @param consumables.attributes Attribute name or array of attribute names.
	 * @param consumables.classes Class name or array of class names.
	 * @param consumables.styles Style name or array of style names.
	 * @returns Returns `true` when all items included in method's call can be consumed,
	 * otherwise returns `false`.
	 */ consume(element, consumables) {
        if (this.test(element, consumables)) {
            if (element.is('$text') || element.is('documentFragment')) {
                // For text nodes and document fragments set value to false.
                this._consumables.set(element, false);
            } else {
                // For elements - consume consumables object.
                this._consumables.get(element).consume(consumables);
            }
            return true;
        }
        return false;
    }
    /**
	 * Reverts {@link module:engine/view/element~Element view element}, {@link module:engine/view/text~Text text node} or
	 * {@link module:engine/view/documentfragment~DocumentFragment document fragment} so they can be consumed once again.
	 * Method does not revert items that were never previously added for consumption, even if they are included in
	 * method's call.
	 *
	 * ```ts
	 * viewConsumable.revert( p, { name: true } ); // Reverts element's name.
	 * viewConsumable.revert( p, { attributes: 'name' } ); // Reverts element's attribute.
	 * viewConsumable.revert( p, { classes: 'foobar' } ); // Reverts element's class.
	 * viewConsumable.revert( p, { styles: 'color' } ); // Reverts element's style.
	 * viewConsumable.revert( p, { attributes: 'name', styles: 'color' } ); // Reverts attribute and style.
	 * viewConsumable.revert( p, { classes: [ 'baz', 'bar' ] } ); // Multiple names can be reverted.
	 * viewConsumable.revert( textNode ); // Reverts text node.
	 * viewConsumable.revert( docFragment ); // Reverts document fragment.
	 * ```
	 *
	 * Reverting classes and styles as attribute will revert all classes/styles that were previously added for
	 * consumption.
	 *
	 * ```ts
	 * viewConsumable.revert( p, { attributes: 'class' } ); // Reverts all classes added for consumption.
	 * viewConsumable.revert( p, { attributes: 'style' } ); // Reverts all styles added for consumption.
	 * ```
	 *
	 * @param consumables Used only if first parameter is {@link module:engine/view/element~Element view element} instance.
	 * @param consumables.name If set to true element's name will be included.
	 * @param consumables.attributes Attribute name or array of attribute names.
	 * @param consumables.classes Class name or array of class names.
	 * @param consumables.styles Style name or array of style names.
	 */ revert(element, consumables) {
        const elementConsumables = this._consumables.get(element);
        if (elementConsumables !== undefined) {
            if (element.is('$text') || element.is('documentFragment')) {
                // For text nodes and document fragments - set consumable to true.
                this._consumables.set(element, true);
            } else {
                // For elements - revert items from consumables object.
                elementConsumables.revert(consumables);
            }
        }
    }
    /**
	 * Creates consumable object from {@link module:engine/view/element~Element view element}. Consumable object will include
	 * element's name and all its attributes, classes and styles.
	 */ static consumablesFromElement(element) {
        const consumables = {
            element,
            name: true,
            attributes: [],
            classes: [],
            styles: []
        };
        const attributes = element.getAttributeKeys();
        for (const attribute of attributes){
            // Skip classes and styles - will be added separately.
            if (attribute == 'style' || attribute == 'class') {
                continue;
            }
            consumables.attributes.push(attribute);
        }
        const classes = element.getClassNames();
        for (const className of classes){
            consumables.classes.push(className);
        }
        const styles = element.getStyleNames();
        for (const style of styles){
            consumables.styles.push(style);
        }
        return consumables;
    }
    /**
	 * Creates {@link module:engine/conversion/viewconsumable~ViewConsumable ViewConsumable} instance from
	 * {@link module:engine/view/node~Node node} or {@link module:engine/view/documentfragment~DocumentFragment document fragment}.
	 * Instance will contain all elements, child nodes, attributes, styles and classes added for consumption.
	 *
	 * @param from View node or document fragment from which `ViewConsumable` will be created.
	 * @param instance If provided, given `ViewConsumable` instance will be used
	 * to add all consumables. It will be returned instead of a new instance.
	 */ static createFrom(from, instance) {
        if (!instance) {
            instance = new ViewConsumable();
        }
        if (from.is('$text')) {
            instance.add(from);
            return instance;
        }
        // Add `from` itself, if it is an element.
        if (from.is('element')) {
            instance.add(from, ViewConsumable.consumablesFromElement(from));
        }
        if (from.is('documentFragment')) {
            instance.add(from);
        }
        for (const child of from.getChildren()){
            instance = ViewConsumable.createFrom(child, instance);
        }
        return instance;
    }
}
const CONSUMABLE_TYPES = [
    'attributes',
    'classes',
    'styles'
];
/**
 * This is a private helper-class for {@link module:engine/conversion/viewconsumable~ViewConsumable}.
 * It represents and manipulates consumable parts of a single {@link module:engine/view/element~Element}.
 */ class ViewElementConsumables {
    element;
    /**
	 * Flag indicating if name of the element can be consumed.
	 */ _canConsumeName;
    /**
	 * Contains maps of element's consumables: attributes, classes and styles.
	 */ _consumables;
    /**
	 * Creates ViewElementConsumables instance.
	 *
	 * @param from View node or document fragment from which `ViewElementConsumables` is being created.
	 */ constructor(from){
        this.element = from;
        this._canConsumeName = null;
        this._consumables = {
            attributes: new Map(),
            styles: new Map(),
            classes: new Map()
        };
    }
    /**
	 * Adds consumable parts of the {@link module:engine/view/element~Element view element}.
	 * Element's name itself can be marked to be consumed (when element's name is consumed its attributes, classes and
	 * styles still could be consumed):
	 *
	 * ```ts
	 * consumables.add( { name: true } );
	 * ```
	 *
	 * Attributes classes and styles:
	 *
	 * ```ts
	 * consumables.add( { attributes: 'title', classes: 'foo', styles: 'color' } );
	 * consumables.add( { attributes: [ 'title', 'name' ], classes: [ 'foo', 'bar' ] );
	 * ```
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `viewconsumable-invalid-attribute` when `class` or `style`
	 * attribute is provided - it should be handled separately by providing `style` and `class` in consumables object.
	 *
	 * @param consumables Object describing which parts of the element can be consumed.
	 * @param consumables.name If set to `true` element's name will be added as consumable.
	 * @param consumables.attributes Attribute name or array of attribute names to add as consumable.
	 * @param consumables.classes Class name or array of class names to add as consumable.
	 * @param consumables.styles Style name or array of style names to add as consumable.
	 */ add(consumables) {
        if (consumables.name) {
            this._canConsumeName = true;
        }
        for (const type of CONSUMABLE_TYPES){
            if (type in consumables) {
                this._add(type, consumables[type]);
            }
        }
    }
    /**
	 * Tests if parts of the {@link module:engine/view/node~Node view node} can be consumed.
	 *
	 * Element's name can be tested:
	 *
	 * ```ts
	 * consumables.test( { name: true } );
	 * ```
	 *
	 * Attributes classes and styles:
	 *
	 * ```ts
	 * consumables.test( { attributes: 'title', classes: 'foo', styles: 'color' } );
	 * consumables.test( { attributes: [ 'title', 'name' ], classes: [ 'foo', 'bar' ] );
	 * ```
	 *
	 * @param consumables Object describing which parts of the element should be tested.
	 * @param consumables.name If set to `true` element's name will be tested.
	 * @param consumables.attributes Attribute name or array of attribute names to test.
	 * @param consumables.classes Class name or array of class names to test.
	 * @param consumables.styles Style name or array of style names to test.
	 * @returns `true` when all tested items can be consumed, `null` when even one of the items
	 * was never marked for consumption and `false` when even one of the items was already consumed.
	 */ test(consumables) {
        // Check if name can be consumed.
        if (consumables.name && !this._canConsumeName) {
            return this._canConsumeName;
        }
        for (const type of CONSUMABLE_TYPES){
            if (type in consumables) {
                const value = this._test(type, consumables[type]);
                if (value !== true) {
                    return value;
                }
            }
        }
        // Return true only if all can be consumed.
        return true;
    }
    /**
	 * Consumes parts of {@link module:engine/view/element~Element view element}. This function does not check if consumable item
	 * is already consumed - it consumes all consumable items provided.
	 * Element's name can be consumed:
	 *
	 * ```ts
	 * consumables.consume( { name: true } );
	 * ```
	 *
	 * Attributes classes and styles:
	 *
	 * ```ts
	 * consumables.consume( { attributes: 'title', classes: 'foo', styles: 'color' } );
	 * consumables.consume( { attributes: [ 'title', 'name' ], classes: [ 'foo', 'bar' ] );
	 * ```
	 *
	 * @param consumables Object describing which parts of the element should be consumed.
	 * @param consumables.name If set to `true` element's name will be consumed.
	 * @param consumables.attributes Attribute name or array of attribute names to consume.
	 * @param consumables.classes Class name or array of class names to consume.
	 * @param consumables.styles Style name or array of style names to consume.
	 */ consume(consumables) {
        if (consumables.name) {
            this._canConsumeName = false;
        }
        for (const type of CONSUMABLE_TYPES){
            if (type in consumables) {
                this._consume(type, consumables[type]);
            }
        }
    }
    /**
	 * Revert already consumed parts of {@link module:engine/view/element~Element view Element}, so they can be consumed once again.
	 * Element's name can be reverted:
	 *
	 * ```ts
	 * consumables.revert( { name: true } );
	 * ```
	 *
	 * Attributes classes and styles:
	 *
	 * ```ts
	 * consumables.revert( { attributes: 'title', classes: 'foo', styles: 'color' } );
	 * consumables.revert( { attributes: [ 'title', 'name' ], classes: [ 'foo', 'bar' ] );
	 * ```
	 *
	 * @param consumables Object describing which parts of the element should be reverted.
	 * @param consumables.name If set to `true` element's name will be reverted.
	 * @param consumables.attributes Attribute name or array of attribute names to revert.
	 * @param consumables.classes Class name or array of class names to revert.
	 * @param consumables.styles Style name or array of style names to revert.
	 */ revert(consumables) {
        if (consumables.name) {
            this._canConsumeName = true;
        }
        for (const type of CONSUMABLE_TYPES){
            if (type in consumables) {
                this._revert(type, consumables[type]);
            }
        }
    }
    /**
	 * Helper method that adds consumables of a given type: attribute, class or style.
	 *
	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `viewconsumable-invalid-attribute` when `class` or `style`
	 * type is provided - it should be handled separately by providing actual style/class type.
	 *
	 * @param type Type of the consumable item: `attributes`, `classes` or `styles`.
	 * @param item Consumable item or array of items.
	 */ _add(type, item) {
        const items = toArray(item);
        const consumables = this._consumables[type];
        for (const name of items){
            if (type === 'attributes' && (name === 'class' || name === 'style')) {
                /**
				 * Class and style attributes should be handled separately in
				 * {@link module:engine/conversion/viewconsumable~ViewConsumable#add `ViewConsumable#add()`}.
				 *
				 * What you have done is trying to use:
				 *
				 * ```ts
				 * consumables.add( { attributes: [ 'class', 'style' ] } );
				 * ```
				 *
				 * While each class and style should be registered separately:
				 *
				 * ```ts
				 * consumables.add( { classes: 'some-class', styles: 'font-weight' } );
				 * ```
				 *
				 * @error viewconsumable-invalid-attribute
				 */ throw new CKEditorError('viewconsumable-invalid-attribute', this);
            }
            consumables.set(name, true);
            if (type === 'styles') {
                for (const alsoName of this.element.document.stylesProcessor.getRelatedStyles(name)){
                    consumables.set(alsoName, true);
                }
            }
        }
    }
    /**
	 * Helper method that tests consumables of a given type: attribute, class or style.
	 *
	 * @param type Type of the consumable item: `attributes`, `classes` or `styles`.
	 * @param item Consumable item or array of items.
	 * @returns Returns `true` if all items can be consumed, `null` when one of the items cannot be
	 * consumed and `false` when one of the items is already consumed.
	 */ _test(type, item) {
        const items = toArray(item);
        const consumables = this._consumables[type];
        for (const name of items){
            if (type === 'attributes' && (name === 'class' || name === 'style')) {
                const consumableName = name == 'class' ? 'classes' : 'styles';
                // Check all classes/styles if class/style attribute is tested.
                const value = this._test(consumableName, [
                    ...this._consumables[consumableName].keys()
                ]);
                if (value !== true) {
                    return value;
                }
            } else {
                const value = consumables.get(name);
                // Return null if attribute is not found.
                if (value === undefined) {
                    return null;
                }
                if (!value) {
                    return false;
                }
            }
        }
        return true;
    }
    /**
	 * Helper method that consumes items of a given type: attribute, class or style.
	 *
	 * @param type Type of the consumable item: `attributes`, `classes` or `styles`.
	 * @param item Consumable item or array of items.
	 */ _consume(type, item) {
        const items = toArray(item);
        const consumables = this._consumables[type];
        for (const name of items){
            if (type === 'attributes' && (name === 'class' || name === 'style')) {
                const consumableName = name == 'class' ? 'classes' : 'styles';
                // If class or style is provided for consumption - consume them all.
                this._consume(consumableName, [
                    ...this._consumables[consumableName].keys()
                ]);
            } else {
                consumables.set(name, false);
                if (type == 'styles') {
                    for (const toConsume of this.element.document.stylesProcessor.getRelatedStyles(name)){
                        consumables.set(toConsume, false);
                    }
                }
            }
        }
    }
    /**
	 * Helper method that reverts items of a given type: attribute, class or style.
	 *
	 * @param type Type of the consumable item: `attributes`, `classes` or , `styles`.
	 * @param item Consumable item or array of items.
	 */ _revert(type, item) {
        const items = toArray(item);
        const consumables = this._consumables[type];
        for (const name of items){
            if (type === 'attributes' && (name === 'class' || name === 'style')) {
                const consumableName = name == 'class' ? 'classes' : 'styles';
                // If class or style is provided for reverting - revert them all.
                this._revert(consumableName, [
                    ...this._consumables[consumableName].keys()
                ]);
            } else {
                const value = consumables.get(name);
                if (value === false) {
                    consumables.set(name, true);
                }
            }
        }
    }
}

/**
 * The model's schema. It defines the allowed and disallowed structures of nodes as well as nodes' attributes.
 * The schema is usually defined by the features and based on them, the editing framework and features
 * make decisions on how to change and process the model.
 *
 * The instance of schema is available in {@link module:engine/model/model~Model#schema `editor.model.schema`}.
 *
 * Read more about the schema in:
 *
 * * The {@glink framework/architecture/editing-engine#schema schema section} of the
 * {@glink framework/architecture/editing-engine Introduction to the Editing engine architecture} guide.
 * * The {@glink framework/deep-dive/schema Schema deep-dive} guide.
 */ class Schema extends /* #__PURE__ */ ObservableMixin() {
    _sourceDefinitions = {};
    /**
	 * A dictionary containing attribute properties.
	 */ _attributeProperties = {};
    _compiledDefinitions;
    /**
	 * Creates a schema instance.
	 */ constructor(){
        super();
        this.decorate('checkChild');
        this.decorate('checkAttribute');
        this.on('checkAttribute', (evt, args)=>{
            args[0] = new SchemaContext(args[0]);
        }, {
            priority: 'highest'
        });
        this.on('checkChild', (evt, args)=>{
            args[0] = new SchemaContext(args[0]);
            args[1] = this.getDefinition(args[1]);
        }, {
            priority: 'highest'
        });
    }
    /**
	 * Registers a schema item. Can only be called once for every item name.
	 *
	 * ```ts
	 * schema.register( 'paragraph', {
	 * 	inheritAllFrom: '$block'
	 * } );
	 * ```
	 */ register(itemName, definition) {
        if (this._sourceDefinitions[itemName]) {
            /**
			 * A single item cannot be registered twice in the schema.
			 *
			 * This situation may happen when:
			 *
			 * * Two or more plugins called {@link module:engine/model/schema~Schema#register `register()`} with the same name.
			 * This will usually mean that there is a collision between plugins which try to use the same element in the model.
			 * Unfortunately, the only way to solve this is by modifying one of these plugins to use a unique model element name.
			 * * A single plugin was loaded twice. This happens when it is installed by npm/yarn in two versions
			 * and usually means one or more of the following issues:
			 *     * a version mismatch (two of your dependencies require two different versions of this plugin),
			 *     * incorrect imports (this plugin is somehow imported twice in a way which confuses webpack),
			 *     * mess in `node_modules/` (`rm -rf node_modules/` may help).
			 *
			 * **Note:** Check the logged `itemName` to better understand which plugin was duplicated/conflicting.
			 *
			 * @param itemName The name of the model element that is being registered twice.
			 * @error schema-cannot-register-item-twice
			 */ throw new CKEditorError('schema-cannot-register-item-twice', this, {
                itemName
            });
        }
        this._sourceDefinitions[itemName] = [
            Object.assign({}, definition)
        ];
        this._clearCache();
    }
    /**
	 * Extends a {@link #register registered} item's definition.
	 *
	 * Extending properties such as `allowIn` will add more items to the existing properties,
	 * while redefining properties such as `isBlock` will override the previously defined ones.
	 *
	 * ```ts
	 * schema.register( 'foo', {
	 * 	allowIn: '$root',
	 * 	isBlock: true;
	 * } );
	 * schema.extend( 'foo', {
	 * 	allowIn: 'blockQuote',
	 * 	isBlock: false
	 * } );
	 *
	 * schema.getDefinition( 'foo' );
	 * //	{
	 * //		allowIn: [ '$root', 'blockQuote' ],
	 * // 		isBlock: false
	 * //	}
	 * ```
	 */ extend(itemName, definition) {
        if (!this._sourceDefinitions[itemName]) {
            /**
			 * Cannot extend an item which was not registered yet.
			 *
			 * This error happens when a plugin tries to extend the schema definition of an item which was not
			 * {@link module:engine/model/schema~Schema#register registered} yet.
			 *
			 * @param itemName The name of the model element which is being extended.
			 * @error schema-cannot-extend-missing-item
			 */ throw new CKEditorError('schema-cannot-extend-missing-item', this, {
                itemName
            });
        }
        this._sourceDefinitions[itemName].push(Object.assign({}, definition));
        this._clearCache();
    }
    /**
	 * Returns data of all registered items.
	 *
	 * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
	 * checking a list of all block elements, etc).
	 * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
	 * in other cases.
	 */ getDefinitions() {
        if (!this._compiledDefinitions) {
            this._compile();
        }
        return this._compiledDefinitions;
    }
    /**
	 * Returns a definition of the given item or `undefined` if an item is not registered.
	 *
	 * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
	 * checking a list of all block elements, etc).
	 * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
	 * in other cases.
	 */ getDefinition(item) {
        let itemName;
        if (typeof item == 'string') {
            itemName = item;
        } else if ('is' in item && (item.is('$text') || item.is('$textProxy'))) {
            itemName = '$text';
        } else {
            itemName = item.name;
        }
        return this.getDefinitions()[itemName];
    }
    /**
	 * Returns `true` if the given item is registered in the schema.
	 *
	 * ```ts
	 * schema.isRegistered( 'paragraph' ); // -> true
	 * schema.isRegistered( editor.model.document.getRoot() ); // -> true
	 * schema.isRegistered( 'foo' ); // -> false
	 * ```
	 */ isRegistered(item) {
        return !!this.getDefinition(item);
    }
    /**
	 * Returns `true` if the given item is defined to be
	 * a block by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isBlock` property.
	 *
	 * ```ts
	 * schema.isBlock( 'paragraph' ); // -> true
	 * schema.isBlock( '$root' ); // -> false
	 *
	 * const paragraphElement = writer.createElement( 'paragraph' );
	 * schema.isBlock( paragraphElement ); // -> true
	 * ```
	 *
	 * See the {@glink framework/deep-dive/schema#block-elements Block elements} section of
	 * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
	 */ isBlock(item) {
        const def = this.getDefinition(item);
        return !!(def && def.isBlock);
    }
    /**
	 * Returns `true` if the given item should be treated as a limit element.
	 *
	 * It considers an item to be a limit element if its
	 * {@link module:engine/model/schema~SchemaItemDefinition}'s
	 * {@link module:engine/model/schema~SchemaItemDefinition#isLimit `isLimit`} or
	 * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
	 * was set to `true`.
	 *
	 * ```ts
	 * schema.isLimit( 'paragraph' ); // -> false
	 * schema.isLimit( '$root' ); // -> true
	 * schema.isLimit( editor.model.document.getRoot() ); // -> true
	 * schema.isLimit( 'imageBlock' ); // -> true
	 * ```
	 *
	 * See the {@glink framework/deep-dive/schema#limit-elements Limit elements} section of
	 * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
	 */ isLimit(item) {
        const def = this.getDefinition(item);
        if (!def) {
            return false;
        }
        return !!(def.isLimit || def.isObject);
    }
    /**
	 * Returns `true` if the given item should be treated as an object element.
	 *
	 * It considers an item to be an object element if its
	 * {@link module:engine/model/schema~SchemaItemDefinition}'s
	 * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
	 * was set to `true`.
	 *
	 * ```ts
	 * schema.isObject( 'paragraph' ); // -> false
	 * schema.isObject( 'imageBlock' ); // -> true
	 *
	 * const imageElement = writer.createElement( 'imageBlock' );
	 * schema.isObject( imageElement ); // -> true
	 * ```
	 *
	 * See the {@glink framework/deep-dive/schema#object-elements Object elements} section of
	 * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
	 */ isObject(item) {
        const def = this.getDefinition(item);
        if (!def) {
            return false;
        }
        // Note: Check out the implementation of #isLimit(), #isSelectable(), and #isContent()
        // to understand why these three constitute an object.
        return !!(def.isObject || def.isLimit && def.isSelectable && def.isContent);
    }
    /**
	 * Returns `true` if the given item is defined to be
	 * an inline element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isInline` property.
	 *
	 * ```ts
	 * schema.isInline( 'paragraph' ); // -> false
	 * schema.isInline( 'softBreak' ); // -> true
	 *
	 * const text = writer.createText( 'foo' );
	 * schema.isInline( text ); // -> true
	 * ```
	 *
	 * See the {@glink framework/deep-dive/schema#inline-elements Inline elements} section of
	 * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
	 */ isInline(item) {
        const def = this.getDefinition(item);
        return !!(def && def.isInline);
    }
    /**
	 * Returns `true` if the given item is defined to be
	 * a selectable element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isSelectable` property.
	 *
	 * ```ts
	 * schema.isSelectable( 'paragraph' ); // -> false
	 * schema.isSelectable( 'heading1' ); // -> false
	 * schema.isSelectable( 'imageBlock' ); // -> true
	 * schema.isSelectable( 'tableCell' ); // -> true
	 *
	 * const text = writer.createText( 'foo' );
	 * schema.isSelectable( text ); // -> false
	 * ```
	 *
	 * See the {@glink framework/deep-dive/schema#selectable-elements Selectable elements section} of
	 * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
	 */ isSelectable(item) {
        const def = this.getDefinition(item);
        if (!def) {
            return false;
        }
        return !!(def.isSelectable || def.isObject);
    }
    /**
	 * Returns `true` if the given item is defined to be
	 * a content by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isContent` property.
	 *
	 * ```ts
	 * schema.isContent( 'paragraph' ); // -> false
	 * schema.isContent( 'heading1' ); // -> false
	 * schema.isContent( 'imageBlock' ); // -> true
	 * schema.isContent( 'horizontalLine' ); // -> true
	 *
	 * const text = writer.createText( 'foo' );
	 * schema.isContent( text ); // -> true
	 * ```
	 *
	 * See the {@glink framework/deep-dive/schema#content-elements Content elements section} of
	 * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
	 */ isContent(item) {
        const def = this.getDefinition(item);
        if (!def) {
            return false;
        }
        return !!(def.isContent || def.isObject);
    }
    /**
	 * Checks whether the given node (`child`) can be a child of the given context.
	 *
	 * ```ts
	 * schema.checkChild( model.document.getRoot(), paragraph ); // -> false
	 *
	 * schema.register( 'paragraph', {
	 * 	allowIn: '$root'
	 * } );
	 * schema.checkChild( model.document.getRoot(), paragraph ); // -> true
	 * ```
	 *
	 * Note: When verifying whether the given node can be a child of the given context, the
	 * schema also verifies the entire context &ndash; from its root to its last element. Therefore, it is possible
	 * for `checkChild()` to return `false` even though the context's last element can contain the checked child.
	 * It happens if one of the context's elements does not allow its child.
	 *
	 * @fires checkChild
	 * @param context The context in which the child will be checked.
	 * @param def The child to check.
	 */ checkChild(context, def) {
        // Note: context and child are already normalized here to a SchemaContext and SchemaCompiledItemDefinition.
        if (!def) {
            return false;
        }
        return this._checkContextMatch(def, context);
    }
    /**
	 * Checks whether the given attribute can be applied in the given context (on the last
	 * item of the context).
	 *
	 * ```ts
	 * schema.checkAttribute( textNode, 'bold' ); // -> false
	 *
	 * schema.extend( '$text', {
	 * 	allowAttributes: 'bold'
	 * } );
	 * schema.checkAttribute( textNode, 'bold' ); // -> true
	 * ```
	 *
	 * @fires checkAttribute
	 * @param context The context in which the attribute will be checked.
	 */ checkAttribute(context, attributeName) {
        const def = this.getDefinition(context.last);
        if (!def) {
            return false;
        }
        return def.allowAttributes.includes(attributeName);
    }
    /**
	 * Checks whether the given element (`elementToMerge`) can be merged with the specified base element (`positionOrBaseElement`).
	 *
	 * In other words &ndash; whether `elementToMerge`'s children {@link #checkChild are allowed} in the `positionOrBaseElement`.
	 *
	 * This check ensures that elements merged with {@link module:engine/model/writer~Writer#merge `Writer#merge()`}
	 * will be valid.
	 *
	 * Instead of elements, you can pass the instance of the {@link module:engine/model/position~Position} class as the
	 * `positionOrBaseElement`. It means that the elements before and after the position will be checked whether they can be merged.
	 *
	 * @param positionOrBaseElement The position or base element to which the `elementToMerge` will be merged.
	 * @param elementToMerge The element to merge. Required if `positionOrBaseElement` is an element.
	 */ checkMerge(positionOrBaseElement, elementToMerge) {
        if (positionOrBaseElement instanceof Position) {
            const nodeBefore = positionOrBaseElement.nodeBefore;
            const nodeAfter = positionOrBaseElement.nodeAfter;
            if (!(nodeBefore instanceof Element)) {
                /**
				 * The node before the merge position must be an element.
				 *
				 * @error schema-check-merge-no-element-before
				 */ throw new CKEditorError('schema-check-merge-no-element-before', this);
            }
            if (!(nodeAfter instanceof Element)) {
                /**
				 * The node after the merge position must be an element.
				 *
				 * @error schema-check-merge-no-element-after
				 */ throw new CKEditorError('schema-check-merge-no-element-after', this);
            }
            return this.checkMerge(nodeBefore, nodeAfter);
        }
        for (const child of elementToMerge.getChildren()){
            if (!this.checkChild(positionOrBaseElement, child)) {
                return false;
            }
        }
        return true;
    }
    /**
	 * Allows registering a callback to the {@link #checkChild} method calls.
	 *
	 * Callbacks allow you to implement rules which are not otherwise possible to achieve
	 * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
	 * For example, by using this method you can disallow elements in specific contexts.
	 *
	 * This method is a shorthand for using the {@link #event:checkChild} event. For even better control,
	 * you can use that event instead.
	 *
	 * Example:
	 *
	 * ```ts
	 * // Disallow heading1 directly inside a blockQuote.
	 * schema.addChildCheck( ( context, childDefinition ) => {
	 * 	if ( context.endsWith( 'blockQuote' ) && childDefinition.name == 'heading1' ) {
	 * 		return false;
	 * 	}
	 * } );
	 * ```
	 *
	 * Which translates to:
	 *
	 * ```ts
	 * schema.on( 'checkChild', ( evt, args ) => {
	 * 	const context = args[ 0 ];
	 * 	const childDefinition = args[ 1 ];
	 *
	 * 	if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
	 * 		// Prevent next listeners from being called.
	 * 		evt.stop();
	 * 		// Set the checkChild()'s return value.
	 * 		evt.return = false;
	 * 	}
	 * }, { priority: 'high' } );
	 * ```
	 *
	 * @param callback The callback to be called. It is called with two parameters:
	 * {@link module:engine/model/schema~SchemaContext} (context) instance and
	 * {@link module:engine/model/schema~SchemaCompiledItemDefinition} (child-to-check definition).
	 * The callback may return `true/false` to override `checkChild()`'s return value. If it does not return
	 * a boolean value, the default algorithm (or other callbacks) will define `checkChild()`'s return value.
	 */ addChildCheck(callback) {
        this.on('checkChild', (evt, [ctx, childDef])=>{
            // checkChild() was called with a non-registered child.
            // In 99% cases such check should return false, so not to overcomplicate all callbacks
            // don't even execute them.
            if (!childDef) {
                return;
            }
            const retValue = callback(ctx, childDef);
            if (typeof retValue == 'boolean') {
                evt.stop();
                evt.return = retValue;
            }
        }, {
            priority: 'high'
        });
    }
    /**
	 * Allows registering a callback to the {@link #checkAttribute} method calls.
	 *
	 * Callbacks allow you to implement rules which are not otherwise possible to achieve
	 * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
	 * For example, by using this method you can disallow attribute if node to which it is applied
	 * is contained within some other element (e.g. you want to disallow `bold` on `$text` within `heading1`).
	 *
	 * This method is a shorthand for using the {@link #event:checkAttribute} event. For even better control,
	 * you can use that event instead.
	 *
	 * Example:
	 *
	 * ```ts
	 * // Disallow bold on $text inside heading1.
	 * schema.addAttributeCheck( ( context, attributeName ) => {
	 * 	if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
	 * 		return false;
	 * 	}
	 * } );
	 * ```
	 *
	 * Which translates to:
	 *
	 * ```ts
	 * schema.on( 'checkAttribute', ( evt, args ) => {
	 * 	const context = args[ 0 ];
	 * 	const attributeName = args[ 1 ];
	 *
	 * 	if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
	 * 		// Prevent next listeners from being called.
	 * 		evt.stop();
	 * 		// Set the checkAttribute()'s return value.
	 * 		evt.return = false;
	 * 	}
	 * }, { priority: 'high' } );
	 * ```
	 *
	 * @param callback The callback to be called. It is called with two parameters:
	 * {@link module:engine/model/schema~SchemaContext} (context) instance and attribute name.
	 * The callback may return `true/false` to override `checkAttribute()`'s return value. If it does not return
	 * a boolean value, the default algorithm (or other callbacks) will define `checkAttribute()`'s return value.
	 */ addAttributeCheck(callback) {
        this.on('checkAttribute', (evt, [ctx, attributeName])=>{
            const retValue = callback(ctx, attributeName);
            if (typeof retValue == 'boolean') {
                evt.stop();
                evt.return = retValue;
            }
        }, {
            priority: 'high'
        });
    }
    /**
	 * This method allows assigning additional metadata to the model attributes. For example,
	 * {@link module:engine/model/schema~AttributeProperties `AttributeProperties#isFormatting` property} is
	 * used to mark formatting attributes (like `bold` or `italic`).
	 *
	 * ```ts
	 * // Mark bold as a formatting attribute.
	 * schema.setAttributeProperties( 'bold', {
	 * 	isFormatting: true
	 * } );
	 *
	 * // Override code not to be considered a formatting markup.
	 * schema.setAttributeProperties( 'code', {
	 * 	isFormatting: false
	 * } );
	 * ```
	 *
	 * Properties are not limited to members defined in the
	 * {@link module:engine/model/schema~AttributeProperties `AttributeProperties` type} and you can also use custom properties:
	 *
	 * ```ts
	 * schema.setAttributeProperties( 'blockQuote', {
	 * 	customProperty: 'value'
	 * } );
	 * ```
	 *
	 * Subsequent calls with the same attribute will extend its custom properties:
	 *
	 * ```ts
	 * schema.setAttributeProperties( 'blockQuote', {
	 * 	one: 1
	 * } );
	 *
	 * schema.setAttributeProperties( 'blockQuote', {
	 * 	two: 2
	 * } );
	 *
	 * console.log( schema.getAttributeProperties( 'blockQuote' ) );
	 * // Logs: { one: 1, two: 2 }
	 * ```
	 *
	 * @param attributeName A name of the attribute to receive the properties.
	 * @param properties A dictionary of properties.
	 */ setAttributeProperties(attributeName, properties) {
        this._attributeProperties[attributeName] = Object.assign(this.getAttributeProperties(attributeName), properties);
    }
    /**
	 * Returns properties associated with a given model attribute. See {@link #setAttributeProperties `setAttributeProperties()`}.
	 *
	 * @param attributeName A name of the attribute.
	 */ getAttributeProperties(attributeName) {
        return this._attributeProperties[attributeName] || {};
    }
    /**
	 * Returns the lowest {@link module:engine/model/schema~Schema#isLimit limit element} containing the entire
	 * selection/range/position or the root otherwise.
	 *
	 * @param selectionOrRangeOrPosition The selection/range/position to check.
	 * @returns The lowest limit element containing the entire `selectionOrRangeOrPosition`.
	 */ getLimitElement(selectionOrRangeOrPosition) {
        let element;
        if (selectionOrRangeOrPosition instanceof Position) {
            element = selectionOrRangeOrPosition.parent;
        } else {
            const ranges = selectionOrRangeOrPosition instanceof Range ? [
                selectionOrRangeOrPosition
            ] : Array.from(selectionOrRangeOrPosition.getRanges());
            // Find the common ancestor for all selection's ranges.
            element = ranges.reduce((element, range)=>{
                const rangeCommonAncestor = range.getCommonAncestor();
                if (!element) {
                    return rangeCommonAncestor;
                }
                return element.getCommonAncestor(rangeCommonAncestor, {
                    includeSelf: true
                });
            }, null);
        }
        while(!this.isLimit(element)){
            if (element.parent) {
                element = element.parent;
            } else {
                break;
            }
        }
        return element;
    }
    /**
	 * Checks whether the attribute is allowed in selection:
	 *
	 * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
	 * * if the selection is collapsed, then checks if on the selection position there's a text with the
	 * specified attribute allowed.
	 *
	 * @param selection Selection which will be checked.
	 * @param attribute The name of the attribute to check.
	 */ checkAttributeInSelection(selection, attribute) {
        if (selection.isCollapsed) {
            const firstPosition = selection.getFirstPosition();
            const context = [
                ...firstPosition.getAncestors(),
                new Text('', selection.getAttributes())
            ];
            // Check whether schema allows for a text with the attribute in the selection.
            return this.checkAttribute(context, attribute);
        } else {
            const ranges = selection.getRanges();
            // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
            for (const range of ranges){
                for (const value of range){
                    if (this.checkAttribute(value.item, attribute)) {
                        // If we found a node that is allowed to have the attribute, return true.
                        return true;
                    }
                }
            }
        }
        // If we haven't found such node, return false.
        return false;
    }
    /**
	 * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
	 *
	 * @param ranges Ranges to be validated.
	 * @param attribute The name of the attribute to check.
	 * @returns Ranges in which the attribute is allowed.
	 */ *getValidRanges(ranges, attribute) {
        ranges = convertToMinimalFlatRanges(ranges);
        for (const range of ranges){
            yield* this._getValidRangesForRange(range, attribute);
        }
    }
    /**
	 * Basing on given `position`, finds and returns a {@link module:engine/model/range~Range range} which is
	 * nearest to that `position` and is a correct range for selection.
	 *
	 * The correct selection range might be collapsed when it is located in a position where the text node can be placed.
	 * Non-collapsed range is returned when selection can be placed around element marked as an "object" in
	 * the {@link module:engine/model/schema~Schema schema}.
	 *
	 * Direction of searching for the nearest correct selection range can be specified as:
	 *
	 * * `both` - searching will be performed in both ways,
	 * * `forward` - searching will be performed only forward,
	 * * `backward` - searching will be performed only backward.
	 *
	 * When valid selection range cannot be found, `null` is returned.
	 *
	 * @param position Reference position where new selection range should be looked for.
	 * @param direction Search direction.
	 * @returns Nearest selection range or `null` if one cannot be found.
	 */ getNearestSelectionRange(position, direction = 'both') {
        if (position.root.rootName == '$graveyard') {
            // No valid selection range in the graveyard.
            // This is important when getting the document selection default range.
            return null;
        }
        // Return collapsed range if provided position is valid.
        if (this.checkChild(position, '$text')) {
            return new Range(position);
        }
        let backwardWalker, forwardWalker;
        // Never leave a limit element.
        const limitElement = position.getAncestors().reverse().find((item)=>this.isLimit(item)) || position.root;
        if (direction == 'both' || direction == 'backward') {
            backwardWalker = new TreeWalker({
                boundaries: Range._createIn(limitElement),
                startPosition: position,
                direction: 'backward'
            });
        }
        if (direction == 'both' || direction == 'forward') {
            forwardWalker = new TreeWalker({
                boundaries: Range._createIn(limitElement),
                startPosition: position
            });
        }
        for (const data of combineWalkers(backwardWalker, forwardWalker)){
            const type = data.walker == backwardWalker ? 'elementEnd' : 'elementStart';
            const value = data.value;
            if (value.type == type && this.isObject(value.item)) {
                return Range._createOn(value.item);
            }
            if (this.checkChild(value.nextPosition, '$text')) {
                return new Range(value.nextPosition);
            }
        }
        return null;
    }
    /**
	 * Tries to find position ancestors that allow to insert a given node.
	 * It starts searching from the given position and goes node by node to the top of the model tree
	 * as long as a {@link module:engine/model/schema~Schema#isLimit limit element}, an
	 * {@link module:engine/model/schema~Schema#isObject object element} or a topmost ancestor is not reached.
	 *
	 * @param position The position that the search will start from.
	 * @param node The node for which an allowed parent should be found or its name.
	 * @returns Allowed parent or null if nothing was found.
	 */ findAllowedParent(position, node) {
        let parent = position.parent;
        while(parent){
            if (this.checkChild(parent, node)) {
                return parent;
            }
            // Do not split limit elements.
            if (this.isLimit(parent)) {
                return null;
            }
            parent = parent.parent;
        }
        return null;
    }
    /**
	 * Sets attributes allowed by the schema on a given node.
	 *
	 * @param node A node to set attributes on.
	 * @param attributes Attributes keys and values.
	 * @param writer An instance of the model writer.
	 */ setAllowedAttributes(node, attributes, writer) {
        const model = writer.model;
        for (const [attributeName, attributeValue] of Object.entries(attributes)){
            if (model.schema.checkAttribute(node, attributeName)) {
                writer.setAttribute(attributeName, attributeValue, node);
            }
        }
    }
    /**
	 * Removes attributes disallowed by the schema.
	 *
	 * @param nodes Nodes that will be filtered.
	 */ removeDisallowedAttributes(nodes, writer) {
        for (const node of nodes){
            // When node is a `Text` it has no children, so just filter it out.
            if (node.is('$text')) {
                removeDisallowedAttributeFromNode(this, node, writer);
            } else {
                const rangeInNode = Range._createIn(node);
                const positionsInRange = rangeInNode.getPositions();
                for (const position of positionsInRange){
                    const item = position.nodeBefore || position.parent;
                    removeDisallowedAttributeFromNode(this, item, writer);
                }
            }
        }
    }
    /**
	 * Gets attributes of a node that have a given property.
	 *
	 * @param node Node to get attributes from.
	 * @param propertyName Name of the property that attribute must have to return it.
	 * @param propertyValue Desired value of the property that we want to check.
	 * When `undefined` attributes will be returned if they have set a given property no matter what the value is. If specified it will
	 * return attributes which given property's value is equal to this parameter.
	 * @returns Object with attributes' names as key and attributes' values as value.
	 */ getAttributesWithProperty(node, propertyName, propertyValue) {
        const attributes = {};
        for (const [attributeName, attributeValue] of node.getAttributes()){
            const attributeProperties = this.getAttributeProperties(attributeName);
            if (attributeProperties[propertyName] === undefined) {
                continue;
            }
            if (propertyValue === undefined || propertyValue === attributeProperties[propertyName]) {
                attributes[attributeName] = attributeValue;
            }
        }
        return attributes;
    }
    /**
	 * Creates an instance of the schema context.
	 */ createContext(context) {
        return new SchemaContext(context);
    }
    _clearCache() {
        this._compiledDefinitions = null;
    }
    _compile() {
        const definitions = {};
        const sourceRules = this._sourceDefinitions;
        const itemNames = Object.keys(sourceRules);
        for (const itemName of itemNames){
            definitions[itemName] = compileBaseItemRule(sourceRules[itemName], itemName);
        }
        const items = Object.values(definitions);
        // Sometimes features add rules (allows, disallows) for items that has not been registered yet. We allow that, to make it easier
        // to put the schema together. However, sometimes these items are never registered. To prevent operating
        // removeUnregisteredEntries( definitions, items );
        // 1. Propagate `childItem.allowIn` to `parentItem.allowChildren` and vice versa, so that these properties are completely mirrored
        // for all children and parents. Do the same for `disallowIn` and `disallowChildren`.
        for (const item of items){
            propagateAllowIn(definitions, item);
            propagateAllowChildren(definitions, item);
            propagateDisallowIn(definitions, item);
            propagateDisallowChildren(definitions, item);
        }
        // 2. Remove from `allowIn` and `allowChildren` these items which where disallowed by `disallowIn` and `disallowChildren`.
        // Do the same for attributes. Now we have a clear situation where which item/attribute is allowed. Inheritance is in next steps.
        for (const item of items){
            resolveDisallows(definitions, item);
        }
        // 3. Compile `item.allowContentOf` property. For each entry in `allowContentOf`, we want to take `allowChildren` and rewrite
        // them into `item.allowChildren`. `item.disallowChildren` is used to filter out some entries. This way "own rules" have higher
        // priority than "inherited rules". Mirroring from step 1. is maintained.
        for (const item of items){
            compileAllowContentOf(definitions, item);
        }
        // 4. Compile `item.allowWhere` property. For each entry in `allowWhere`, we want to take `allowIn` and rewrite them into
        // `item.allowIn`. `item.disallowIn` is used to filter out some entries. This way "own rules" have higher priority than
        // "inherited rules". Mirroring from step 1. is maintained.
        for (const item of items){
            compileAllowWhere(definitions, item);
        }
        // 5. Compile `item.allowAttributesOf`. For each entry in `allowAttributesOf`, we want to take `allowAttributes` and rewrite them
        // into `item.allowAttributes`. `item.disallowAttributes` is used to filter out some entries. This way "own rules" have higher
        // priority than "inherited rules".
        for (const item of items){
            compileAllowAttributesOf(definitions, item);
        }
        // 6. Compile `item.inheritTypesFrom` property. For each entry in `inheritTypesFrom`, we want to take `is*` properties and
        // set them on `item` (if they are not set yet).
        for (const item of items){
            compileInheritPropertiesFrom(definitions, item);
        }
        // Compile final definitions. Unnecessary properties are removed and some additional cleaning is applied.
        this._compiledDefinitions = compileDefinitions(definitions);
    }
    _checkContextMatch(def, context, contextItemIndex = context.length - 1) {
        const contextItem = context.getItem(contextItemIndex);
        if (def.allowIn.includes(contextItem.name)) {
            if (contextItemIndex == 0) {
                return true;
            } else {
                const parentRule = this.getDefinition(contextItem);
                return this._checkContextMatch(parentRule, context, contextItemIndex - 1);
            }
        } else {
            return false;
        }
    }
    /**
	 * Takes a flat range and an attribute name. Traverses the range recursively and deeply to find and return all ranges
	 * inside the given range on which the attribute can be applied.
	 *
	 * This is a helper function for {@link ~Schema#getValidRanges}.
	 *
	 * @param range The range to process.
	 * @param attribute The name of the attribute to check.
	 * @returns Ranges in which the attribute is allowed.
	 */ *_getValidRangesForRange(range, attribute) {
        let start = range.start;
        let end = range.start;
        for (const item of range.getItems({
            shallow: true
        })){
            if (item.is('element')) {
                yield* this._getValidRangesForRange(Range._createIn(item), attribute);
            }
            if (!this.checkAttribute(item, attribute)) {
                if (!start.isEqual(end)) {
                    yield new Range(start, end);
                }
                start = Position._createAfter(item);
            }
            end = Position._createAfter(item);
        }
        if (!start.isEqual(end)) {
            yield new Range(start, end);
        }
    }
    /**
	 * Returns a model range which is optimal (in terms of UX) for inserting a widget block.
	 *
	 * For instance, if a selection is in the middle of a paragraph, the collapsed range before this paragraph
	 * will be returned so that it is not split. If the selection is at the end of a paragraph,
	 * the collapsed range after this paragraph will be returned.
	 *
	 * Note: If the selection is placed in an empty block, the range in that block will be returned. If that range
	 * is then passed to {@link module:engine/model/model~Model#insertContent}, the block will be fully replaced
	 * by the inserted widget block.
	 *
	 * @internal
	 * @param selection The selection based on which the insertion position should be calculated.
	 * @param place The place where to look for optimal insertion range.
	 * The `auto` value will determine itself the best position for insertion.
	 * The `before` value will try to find a position before selection.
	 * The `after` value will try to find a position after selection.
	 * @returns The optimal range.
	 */ findOptimalInsertionRange(selection, place) {
        const selectedElement = selection.getSelectedElement();
        if (selectedElement && this.isObject(selectedElement) && !this.isInline(selectedElement)) {
            if (place == 'before' || place == 'after') {
                return new Range(Position._createAt(selectedElement, place));
            }
            return Range._createOn(selectedElement);
        }
        const firstBlock = first(selection.getSelectedBlocks());
        // There are no block elements within ancestors (in the current limit element).
        if (!firstBlock) {
            return new Range(selection.focus);
        }
        // If inserting into an empty block – return position in that block. It will get
        // replaced with the image by insertContent(). #42.
        if (firstBlock.isEmpty) {
            return new Range(Position._createAt(firstBlock, 0));
        }
        const positionAfter = Position._createAfter(firstBlock);
        // If selection is at the end of the block - return position after the block.
        if (selection.focus.isTouching(positionAfter)) {
            return new Range(positionAfter);
        }
        // Otherwise, return position before the block.
        return new Range(Position._createBefore(firstBlock));
    }
}
/**
 * A schema context &ndash; a list of ancestors of a given position in the document.
 *
 * Considering such position:
 *
 * ```xml
 * <$root>
 * 	<blockQuote>
 * 		<paragraph>
 * 			^
 * 		</paragraph>
 * 	</blockQuote>
 * </$root>
 * ```
 *
 * The context of this position is its {@link module:engine/model/position~Position#getAncestors lists of ancestors}:
 *
 *		[ rootElement, blockQuoteElement, paragraphElement ]
 *
 * Contexts are used in the {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`} and
 * {@link module:engine/model/schema~Schema#event:checkAttribute `Schema#checkAttribute`} events as a definition
 * of a place in the document where the check occurs. The context instances are created based on the first arguments
 * of the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and
 * {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods so when
 * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
 */ class SchemaContext {
    _items;
    /**
	 * Creates an instance of the context.
	 */ constructor(context){
        if (context instanceof SchemaContext) {
            return context;
        }
        let items;
        if (typeof context == 'string') {
            items = [
                context
            ];
        } else if (!Array.isArray(context)) {
            // `context` is item or position.
            // Position#getAncestors() doesn't accept any parameters but it works just fine here.
            items = context.getAncestors({
                includeSelf: true
            });
        } else {
            items = context;
        }
        this._items = items.map(mapContextItem);
    }
    /**
	 * The number of items.
	 */ get length() {
        return this._items.length;
    }
    /**
	 * The last item (the lowest node).
	 */ get last() {
        return this._items[this._items.length - 1];
    }
    /**
	 * Iterable interface.
	 *
	 * Iterates over all context items.
	 */ [Symbol.iterator]() {
        return this._items[Symbol.iterator]();
    }
    /**
	 * Returns a new schema context instance with an additional item.
	 *
	 * Item can be added as:
	 *
	 * ```ts
	 * const context = new SchemaContext( [ '$root' ] );
	 *
	 * // An element.
	 * const fooElement = writer.createElement( 'fooElement' );
	 * const newContext = context.push( fooElement ); // [ '$root', 'fooElement' ]
	 *
	 * // A text node.
	 * const text = writer.createText( 'foobar' );
	 * const newContext = context.push( text ); // [ '$root', '$text' ]
	 *
	 * // A string (element name).
	 * const newContext = context.push( 'barElement' ); // [ '$root', 'barElement' ]
	 * ```
	 *
	 * **Note** {@link module:engine/model/node~Node} that is already in the model tree will be added as the only item
	 * (without ancestors).
	 *
	 * @param item An item that will be added to the current context.
	 * @returns A new schema context instance with an additional item.
	 */ push(item) {
        const ctx = new SchemaContext([
            item
        ]);
        ctx._items = [
            ...this._items,
            ...ctx._items
        ];
        return ctx;
    }
    /**
	 * Gets an item on the given index.
	 */ getItem(index) {
        return this._items[index];
    }
    /**
	 * Returns the names of items.
	 */ *getNames() {
        yield* this._items.map((item)=>item.name);
    }
    /**
	 * Checks whether the context ends with the given nodes.
	 *
	 * ```ts
	 * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
	 *
	 * ctx.endsWith( '$text' ); // -> true
	 * ctx.endsWith( 'paragraph $text' ); // -> true
	 * ctx.endsWith( '$root' ); // -> false
	 * ctx.endsWith( 'paragraph' ); // -> false
	 * ```
	 */ endsWith(query) {
        return Array.from(this.getNames()).join(' ').endsWith(query);
    }
    /**
	 * Checks whether the context starts with the given nodes.
	 *
	 * ```ts
	 * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
	 *
	 * ctx.endsWith( '$root' ); // -> true
	 * ctx.endsWith( '$root paragraph' ); // -> true
	 * ctx.endsWith( '$text' ); // -> false
	 * ctx.endsWith( 'paragraph' ); // -> false
	 * ```
	 */ startsWith(query) {
        return Array.from(this.getNames()).join(' ').startsWith(query);
    }
}
function compileBaseItemRule(sourceItemRules, itemName) {
    const itemRule = {
        name: itemName,
        allowIn: new Set(),
        allowChildren: new Set(),
        disallowIn: new Set(),
        disallowChildren: new Set(),
        allowContentOf: new Set(),
        allowWhere: new Set(),
        allowAttributes: new Set(),
        disallowAttributes: new Set(),
        allowAttributesOf: new Set(),
        inheritTypesFrom: new Set()
    };
    copyTypes(sourceItemRules, itemRule);
    copyProperty(sourceItemRules, itemRule, 'allowIn');
    copyProperty(sourceItemRules, itemRule, 'allowChildren');
    copyProperty(sourceItemRules, itemRule, 'disallowIn');
    copyProperty(sourceItemRules, itemRule, 'disallowChildren');
    copyProperty(sourceItemRules, itemRule, 'allowContentOf');
    copyProperty(sourceItemRules, itemRule, 'allowWhere');
    copyProperty(sourceItemRules, itemRule, 'allowAttributes');
    copyProperty(sourceItemRules, itemRule, 'disallowAttributes');
    copyProperty(sourceItemRules, itemRule, 'allowAttributesOf');
    copyProperty(sourceItemRules, itemRule, 'inheritTypesFrom');
    resolveInheritAll(sourceItemRules, itemRule);
    return itemRule;
}
function propagateAllowIn(definitions, item) {
    for (const parentName of item.allowIn){
        const parentItem = definitions[parentName];
        if (parentItem) {
            parentItem.allowChildren.add(item.name);
        } else {
            item.allowIn.delete(parentName);
        }
    }
}
function propagateAllowChildren(definitions, item) {
    for (const childName of item.allowChildren){
        const childItem = definitions[childName];
        if (childItem) {
            childItem.allowIn.add(item.name);
        } else {
            item.allowChildren.delete(childName);
        }
    }
}
function propagateDisallowIn(definitions, item) {
    for (const parentName of item.disallowIn){
        const parentItem = definitions[parentName];
        if (parentItem) {
            parentItem.disallowChildren.add(item.name);
        } else {
            item.disallowIn.delete(parentName);
        }
    }
}
function propagateDisallowChildren(definitions, item) {
    for (const childName of item.disallowChildren){
        const childItem = definitions[childName];
        if (childItem) {
            childItem.disallowIn.add(item.name);
        } else {
            item.disallowChildren.delete(childName);
        }
    }
}
function resolveDisallows(definitions, item) {
    for (const childName of item.disallowChildren){
        item.allowChildren.delete(childName);
    }
    for (const parentName of item.disallowIn){
        item.allowIn.delete(parentName);
    }
    for (const attributeName of item.disallowAttributes){
        item.allowAttributes.delete(attributeName);
    }
}
function compileAllowContentOf(definitions, item) {
    for (const allowContentOfItemName of item.allowContentOf){
        const baseItem = definitions[allowContentOfItemName];
        if (!baseItem) {
            continue;
        }
        // Copy `disallowChildren` to propagate this "knowledge" down the inheritance chain. The inheritance may involve multiple items and
        // if this is not propagated, then items down the chain may start to allow for items that were disallowed by previous base items.
        //
        // The scenarios were it is important involves multiple inherits both on parent items side and on the child items side.
        baseItem.disallowChildren.forEach((childName)=>{
            // Own item's rules takes precedence before inherited.
            // If the item directly allows for given child, ignore that base item disallowed that child.
            if (item.allowChildren.has(childName)) {
                return;
            }
            item.disallowChildren.add(childName);
            definitions[childName].disallowIn.add(item.name);
        });
        // Copy `allowChildren` from the base item to allow for the same items.
        baseItem.allowChildren.forEach((childName)=>{
            // Own item's rules takes precedence before inherited.
            // Also, `item.disallowChildren` might get some new items during inheritance process.
            if (item.disallowChildren.has(childName)) {
                return;
            }
            item.allowChildren.add(childName);
            definitions[childName].allowIn.add(item.name);
        });
    }
}
function compileAllowWhere(definitions, item) {
    for (const allowWhereItemName of item.allowWhere){
        const baseItem = definitions[allowWhereItemName];
        if (!baseItem) {
            continue;
        }
        // Copy `disallowIn` to propagate this "knowledge" down the inheritance chain. The inheritance may involve multiple items and
        // if this is not propagated, then items down the chain may start to be allowed in items in which they were disallowed previously.
        //
        // The scenarios were it is important involves multiple inherits both on parent items side and on the child items side.
        baseItem.disallowIn.forEach((parentName)=>{
            // Own item's rules takes precedence before inherited.
            // If the item is directly allowed in given parent, ignore that base item was disallowed in it.
            if (item.allowIn.has(parentName)) {
                return;
            }
            item.disallowIn.add(parentName);
            definitions[parentName].disallowChildren.add(item.name);
        });
        // Copy `allowIn` from the base item to allow item in same parents.
        baseItem.allowIn.forEach((parentName)=>{
            // Own item's rules takes precedence before inherited.
            // Also, `item.disallowIn` might get some new items during inheritance process.
            if (item.disallowIn.has(parentName)) {
                return;
            }
            item.allowIn.add(parentName);
            definitions[parentName].allowChildren.add(item.name);
        });
    }
}
function compileDefinitions(definitions) {
    const finalDefinitions = {};
    for (const item of Object.values(definitions)){
        finalDefinitions[item.name] = {
            name: item.name,
            // `is*` properties may not be set - convert `undefined` to `false`.
            isBlock: !!item.isBlock,
            isContent: !!item.isContent,
            isInline: !!item.isInline,
            isLimit: !!item.isLimit,
            isObject: !!item.isObject,
            isSelectable: !!item.isSelectable,
            // Filter out non-existing items.
            allowIn: Array.from(item.allowIn).filter((name)=>!!definitions[name]),
            allowChildren: Array.from(item.allowChildren).filter((name)=>!!definitions[name]),
            allowAttributes: Array.from(item.allowAttributes)
        };
    }
    return finalDefinitions;
}
function compileAllowAttributesOf(definitions, item) {
    for (const allowAttributeOfItemName of item.allowAttributesOf){
        const baseItem = definitions[allowAttributeOfItemName];
        if (!baseItem) {
            return;
        }
        baseItem.allowAttributes.forEach((attributeName)=>{
            if (item.disallowAttributes.has(attributeName)) {
                return;
            }
            item.allowAttributes.add(attributeName);
        });
    }
}
function compileInheritPropertiesFrom(definitions, item) {
    for (const inheritPropertiesOfItemName of item.inheritTypesFrom){
        const inheritFrom = definitions[inheritPropertiesOfItemName];
        if (inheritFrom) {
            const typeNames = Object.keys(inheritFrom).filter((name)=>name.startsWith('is'));
            for (const name of typeNames){
                if (!(name in item)) {
                    item[name] = inheritFrom[name];
                }
            }
        }
    }
}
function copyTypes(sourceItemRules, itemRule) {
    for (const sourceItemRule of sourceItemRules){
        const typeNames = Object.keys(sourceItemRule).filter((name)=>name.startsWith('is'));
        for (const name of typeNames){
            itemRule[name] = !!sourceItemRule[name];
        }
    }
}
function copyProperty(sourceItemRules, itemRule, propertyName) {
    for (const sourceItemRule of sourceItemRules){
        let value = sourceItemRule[propertyName];
        // `value` can be a string, an array or undefined.
        // Convert a string to an array with one item, then handle an array. Skip undefined this way.
        if (typeof value == 'string') {
            value = [
                value
            ];
        }
        if (Array.isArray(value)) {
            value.forEach((singleValue)=>itemRule[propertyName].add(singleValue));
        }
    }
}
function resolveInheritAll(sourceItemRules, itemRule) {
    for (const sourceItemRule of sourceItemRules){
        const inheritFrom = sourceItemRule.inheritAllFrom;
        if (inheritFrom) {
            itemRule.allowContentOf.add(inheritFrom);
            itemRule.allowWhere.add(inheritFrom);
            itemRule.allowAttributesOf.add(inheritFrom);
            itemRule.inheritTypesFrom.add(inheritFrom);
        }
    }
}
function mapContextItem(ctxItem) {
    if (typeof ctxItem == 'string' || ctxItem.is('documentFragment')) {
        return {
            name: typeof ctxItem == 'string' ? ctxItem : '$documentFragment',
            *getAttributeKeys () {},
            getAttribute () {}
        };
    } else {
        return {
            // '$text' means text nodes and text proxies.
            name: ctxItem.is('element') ? ctxItem.name : '$text',
            *getAttributeKeys () {
                yield* ctxItem.getAttributeKeys();
            },
            getAttribute (key) {
                return ctxItem.getAttribute(key);
            }
        };
    }
}
/**
 * Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
 * is provided it will return data only from that walker.
 *
 * @param backward Walker iterating in backward direction.
 * @param forward Walker iterating in forward direction.
 * @returns Object returned at each iteration contains `value` and `walker` (informing which walker returned
 * given value) fields.
 */ function* combineWalkers(backward, forward) {
    let done = false;
    while(!done){
        done = true;
        if (backward) {
            const step = backward.next();
            if (!step.done) {
                done = false;
                yield {
                    walker: backward,
                    value: step.value
                };
            }
        }
        if (forward) {
            const step = forward.next();
            if (!step.done) {
                done = false;
                yield {
                    walker: forward,
                    value: step.value
                };
            }
        }
    }
}
/**
 * Takes an array of non-intersecting ranges. For each of them gets minimal flat ranges covering that range and returns
 * all those minimal flat ranges.
 *
 * @param ranges Ranges to process.
 * @returns Minimal flat ranges of given `ranges`.
 */ function* convertToMinimalFlatRanges(ranges) {
    for (const range of ranges){
        yield* range.getMinimalFlatRanges();
    }
}
function removeDisallowedAttributeFromNode(schema, node, writer) {
    for (const attribute of node.getAttributeKeys()){
        if (!schema.checkAttribute(node, attribute)) {
            writer.removeAttribute(attribute, node);
        }
    }
}

/**
 * Upcast dispatcher is a central point of the view-to-model conversion, which is a process of
 * converting a given {@link module:engine/view/documentfragment~DocumentFragment view document fragment} or
 * {@link module:engine/view/element~Element view element} into a correct model structure.
 *
 * During the conversion process, the dispatcher fires events for all {@link module:engine/view/node~Node view nodes}
 * from the converted view document fragment.
 * Special callbacks called "converters" should listen to these events in order to convert the view nodes.
 *
 * The second parameter of the callback is the `data` object with the following properties:
 *
 * * `data.viewItem` contains a {@link module:engine/view/node~Node view node} or a
 * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}
 * that is converted at the moment and might be handled by the callback.
 * * `data.modelRange` is used to point to the result
 * of the current conversion (e.g. the element that is being inserted)
 * and is always a {@link module:engine/model/range~Range} when the conversion succeeds.
 * * `data.modelCursor` is a {@link module:engine/model/position~Position position} on which the converter should insert
 * the newly created items.
 *
 * The third parameter of the callback is an instance of {@link module:engine/conversion/upcastdispatcher~UpcastConversionApi}
 * which provides additional tools for converters.
 *
 * You can read more about conversion in the {@glink framework/deep-dive/conversion/upcast Upcast conversion} guide.
 *
 * Examples of event-based converters:
 *
 * ```ts
 * // A converter for links (<a>).
 * editor.data.upcastDispatcher.on( 'element:a', ( evt, data, conversionApi ) => {
 * 	if ( conversionApi.consumable.consume( data.viewItem, { name: true, attributes: [ 'href' ] } ) ) {
 * 		// The <a> element is inline and is represented by an attribute in the model.
 * 		// This is why you need to convert only children.
 * 		const { modelRange } = conversionApi.convertChildren( data.viewItem, data.modelCursor );
 *
 * 		for ( let item of modelRange.getItems() ) {
 * 			if ( conversionApi.schema.checkAttribute( item, 'linkHref' ) ) {
 * 				conversionApi.writer.setAttribute( 'linkHref', data.viewItem.getAttribute( 'href' ), item );
 * 			}
 * 		}
 * 	}
 * } );
 *
 * // Convert <p> element's font-size style.
 * // Note: You should use a low-priority observer in order to ensure that
 * // it is executed after the element-to-element converter.
 * editor.data.upcastDispatcher.on( 'element:p', ( evt, data, conversionApi ) => {
 * 	const { consumable, schema, writer } = conversionApi;
 *
 * 	if ( !consumable.consume( data.viewItem, { style: 'font-size' } ) ) {
 * 		return;
 * 	}
 *
 * 	const fontSize = data.viewItem.getStyle( 'font-size' );
 *
 * 	// Do not go for the model element after data.modelCursor because it might happen
 * 	// that a single view element was converted to multiple model elements. Get all of them.
 * 	for ( const item of data.modelRange.getItems( { shallow: true } ) ) {
 * 		if ( schema.checkAttribute( item, 'fontSize' ) ) {
 * 			writer.setAttribute( 'fontSize', fontSize, item );
 * 		}
 * 	}
 * }, { priority: 'low' } );
 *
 * // Convert all elements which have no custom converter into a paragraph (autoparagraphing).
 * editor.data.upcastDispatcher.on( 'element', ( evt, data, conversionApi ) => {
 * 	// Check if an element can be converted.
 * 	if ( !conversionApi.consumable.test( data.viewItem, { name: data.viewItem.name } ) ) {
 * 		// When an element is already consumed by higher priority converters, do nothing.
 * 		return;
 * 	}
 *
 * 	const paragraph = conversionApi.writer.createElement( 'paragraph' );
 *
 * 	// Try to safely insert a paragraph at the model cursor - it will find an allowed parent for the current element.
 * 	if ( !conversionApi.safeInsert( paragraph, data.modelCursor ) ) {
 * 		// When an element was not inserted, it means that you cannot insert a paragraph at this position.
 * 		return;
 * 	}
 *
 * 	// Consume the inserted element.
 * 	conversionApi.consumable.consume( data.viewItem, { name: data.viewItem.name } ) );
 *
 * 	// Convert the children to a paragraph.
 * 	const { modelRange } = conversionApi.convertChildren( data.viewItem,  paragraph ) );
 *
 * 	// Update `modelRange` and `modelCursor` in the `data` as a conversion result.
 * 	conversionApi.updateConversionResult( paragraph, data );
 * }, { priority: 'low' } );
 * ```
 *
 * @fires viewCleanup
 * @fires element
 * @fires text
 * @fires documentFragment
 */ class UpcastDispatcher extends /* #__PURE__ */ EmitterMixin() {
    /**
	 * An interface passed by the dispatcher to the event callbacks.
	 */ conversionApi;
    /**
	 * The list of elements that were created during splitting.
	 *
	 * After the conversion process, the list is cleared.
	 */ _splitParts = new Map();
    /**
	 * The list of cursor parent elements that were created during splitting.
	 *
	 * After the conversion process the list is cleared.
	 */ _cursorParents = new Map();
    /**
	 * The position in the temporary structure where the converted content is inserted. The structure reflects the context of
	 * the target position where the content will be inserted. This property is built based on the context parameter of the
	 * convert method.
	 */ _modelCursor = null;
    /**
	 * The list of elements that were created during the splitting but should not get removed on conversion end even if they are empty.
	 *
	 * The list is cleared after the conversion process.
	 */ _emptyElementsToKeep = new Set();
    /**
	 * Creates an upcast dispatcher that operates using the passed API.
	 *
	 * @see module:engine/conversion/upcastdispatcher~UpcastConversionApi
	 * @param conversionApi Additional properties for an interface that will be passed to events fired
	 * by the upcast dispatcher.
	 */ constructor(conversionApi){
        super();
        this.conversionApi = {
            ...conversionApi,
            consumable: null,
            writer: null,
            store: null,
            convertItem: (viewItem, modelCursor)=>this._convertItem(viewItem, modelCursor),
            convertChildren: (viewElement, positionOrElement)=>this._convertChildren(viewElement, positionOrElement),
            safeInsert: (modelNode, position)=>this._safeInsert(modelNode, position),
            updateConversionResult: (modelElement, data)=>this._updateConversionResult(modelElement, data),
            // Advanced API - use only if custom position handling is needed.
            splitToAllowedParent: (modelNode, modelCursor)=>this._splitToAllowedParent(modelNode, modelCursor),
            getSplitParts: (modelElement)=>this._getSplitParts(modelElement),
            keepEmptyElement: (modelElement)=>this._keepEmptyElement(modelElement)
        };
    }
    /**
	 * Starts the conversion process. The entry point for the conversion.
	 *
	 * @fires element
	 * @fires text
	 * @fires documentFragment
	 * @param viewElement The part of the view to be converted.
	 * @param writer An instance of the model writer.
	 * @param context Elements will be converted according to this context.
	 * @returns Model data that is the result of the conversion process
	 * wrapped in `DocumentFragment`. Converted marker elements will be set as the document fragment's
	 * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
	 */ convert(viewElement, writer, context = [
        '$root'
    ]) {
        this.fire('viewCleanup', viewElement);
        // Create context tree and set position in the top element.
        // Items will be converted according to this position.
        this._modelCursor = createContextTree(context, writer);
        // Store writer in conversion as a conversion API
        // to be sure that conversion process will use the same batch.
        this.conversionApi.writer = writer;
        // Create consumable values list for conversion process.
        this.conversionApi.consumable = ViewConsumable.createFrom(viewElement);
        // Custom data stored by converter for conversion process.
        this.conversionApi.store = {};
        // Do the conversion.
        const { modelRange } = this._convertItem(viewElement, this._modelCursor);
        // Conversion result is always a document fragment so let's create it.
        const documentFragment = writer.createDocumentFragment();
        // When there is a conversion result.
        if (modelRange) {
            // Remove all empty elements that were created while splitting.
            this._removeEmptyElements();
            // Move all items that were converted in context tree to the document fragment.
            for (const item of Array.from(this._modelCursor.parent.getChildren())){
                writer.append(item, documentFragment);
            }
            // Extract temporary markers elements from model and set as static markers collection.
            documentFragment.markers = extractMarkersFromModelFragment(documentFragment, writer);
        }
        // Clear context position.
        this._modelCursor = null;
        // Clear split elements & parents lists.
        this._splitParts.clear();
        this._cursorParents.clear();
        this._emptyElementsToKeep.clear();
        // Clear conversion API.
        this.conversionApi.writer = null;
        this.conversionApi.store = null;
        // Return fragment as conversion result.
        return documentFragment;
    }
    /**
	 * @see module:engine/conversion/upcastdispatcher~UpcastConversionApi#convertItem
	 */ _convertItem(viewItem, modelCursor) {
        const data = {
            viewItem,
            modelCursor,
            modelRange: null
        };
        if (viewItem.is('element')) {
            this.fire(`element:${viewItem.name}`, data, this.conversionApi);
        } else if (viewItem.is('$text')) {
            this.fire('text', data, this.conversionApi);
        } else {
            this.fire('documentFragment', data, this.conversionApi);
        }
        // Handle incorrect conversion result.
        if (data.modelRange && !(data.modelRange instanceof Range)) {
            /**
			 * Incorrect conversion result was dropped.
			 *
			 * {@link module:engine/model/range~Range Model range} should be a conversion result.
			 *
			 * @error view-conversion-dispatcher-incorrect-result
			 */ throw new CKEditorError('view-conversion-dispatcher-incorrect-result', this);
        }
        return {
            modelRange: data.modelRange,
            modelCursor: data.modelCursor
        };
    }
    /**
	 * @see module:engine/conversion/upcastdispatcher~UpcastConversionApi#convertChildren
	 */ _convertChildren(viewItem, elementOrModelCursor) {
        let nextModelCursor = elementOrModelCursor.is('position') ? elementOrModelCursor : Position._createAt(elementOrModelCursor, 0);
        const modelRange = new Range(nextModelCursor);
        for (const viewChild of Array.from(viewItem.getChildren())){
            const result = this._convertItem(viewChild, nextModelCursor);
            if (result.modelRange instanceof Range) {
                modelRange.end = result.modelRange.end;
                nextModelCursor = result.modelCursor;
            }
        }
        return {
            modelRange,
            modelCursor: nextModelCursor
        };
    }
    /**
	 * @see module:engine/conversion/upcastdispatcher~UpcastConversionApi#safeInsert
	 */ _safeInsert(modelNode, position) {
        // Find allowed parent for element that we are going to insert.
        // If current parent does not allow to insert element but one of the ancestors does
        // then split nodes to allowed parent.
        const splitResult = this._splitToAllowedParent(modelNode, position);
        // When there is no split result it means that we can't insert element to model tree, so let's skip it.
        if (!splitResult) {
            return false;
        }
        // Insert element on allowed position.
        this.conversionApi.writer.insert(modelNode, splitResult.position);
        return true;
    }
    /**
	 * @see module:engine/conversion/upcastdispatcher~UpcastConversionApi#updateConversionResult
	 */ _updateConversionResult(modelElement, data) {
        const parts = this._getSplitParts(modelElement);
        const writer = this.conversionApi.writer;
        // Set conversion result range - only if not set already.
        if (!data.modelRange) {
            data.modelRange = writer.createRange(writer.createPositionBefore(modelElement), writer.createPositionAfter(parts[parts.length - 1]));
        }
        const savedCursorParent = this._cursorParents.get(modelElement);
        // Now we need to check where the `modelCursor` should be.
        if (savedCursorParent) {
            // If we split parent to insert our element then we want to continue conversion in the new part of the split parent.
            //
            // before: <allowed><notAllowed>foo[]</notAllowed></allowed>
            // after:  <allowed><notAllowed>foo</notAllowed> <converted></converted> <notAllowed>[]</notAllowed></allowed>
            data.modelCursor = writer.createPositionAt(savedCursorParent, 0);
        } else {
            // Otherwise just continue after inserted element.
            data.modelCursor = data.modelRange.end;
        }
    }
    /**
	 * @see module:engine/conversion/upcastdispatcher~UpcastConversionApi#splitToAllowedParent
	 */ _splitToAllowedParent(node, modelCursor) {
        const { schema, writer } = this.conversionApi;
        // Try to find allowed parent.
        let allowedParent = schema.findAllowedParent(modelCursor, node);
        if (allowedParent) {
            // When current position parent allows to insert node then return this position.
            if (allowedParent === modelCursor.parent) {
                return {
                    position: modelCursor
                };
            }
            // When allowed parent is in context tree (it's outside the converted tree).
            if (this._modelCursor.parent.getAncestors().includes(allowedParent)) {
                allowedParent = null;
            }
        }
        if (!allowedParent) {
            // Check if the node wrapped with a paragraph would be accepted by the schema.
            if (!isParagraphable(modelCursor, node, schema)) {
                return null;
            }
            return {
                position: wrapInParagraph(modelCursor, writer)
            };
        }
        // Split element to allowed parent.
        const splitResult = this.conversionApi.writer.split(modelCursor, allowedParent);
        // Using the range returned by `model.Writer#split`, we will pair original elements with their split parts.
        //
        // The range returned from the writer spans "over the split" or, precisely saying, from the end of the original element (the one
        // that got split) to the beginning of the other part of that element:
        //
        // <limit><a><b><c>X[]Y</c></b><a></limit> ->
        // <limit><a><b><c>X[</c></b></a><a><b><c>]Y</c></b></a>
        //
        // After the split there cannot be any full node between the positions in `splitRange`. The positions are touching.
        // Also, because of how splitting works, it is easy to notice, that "closing tags" are in the reverse order than "opening tags".
        // Also, since we split all those elements, each of them has to have the other part.
        //
        // With those observations in mind, we will pair the original elements with their split parts by saving "closing tags" and matching
        // them with "opening tags" in the reverse order. For that we can use a stack.
        const stack = [];
        for (const treeWalkerValue of splitResult.range.getWalker()){
            if (treeWalkerValue.type == 'elementEnd') {
                stack.push(treeWalkerValue.item);
            } else {
                // There should not be any text nodes after the element is split, so the only other value is `elementStart`.
                const originalPart = stack.pop();
                const splitPart = treeWalkerValue.item;
                this._registerSplitPair(originalPart, splitPart);
            }
        }
        const cursorParent = splitResult.range.end.parent;
        this._cursorParents.set(node, cursorParent);
        return {
            position: splitResult.position,
            cursorParent
        };
    }
    /**
	 * Registers that a `splitPart` element is a split part of the `originalPart` element.
	 *
	 * The data set by this method is used by {@link #_getSplitParts} and {@link #_removeEmptyElements}.
	 */ _registerSplitPair(originalPart, splitPart) {
        if (!this._splitParts.has(originalPart)) {
            this._splitParts.set(originalPart, [
                originalPart
            ]);
        }
        const list = this._splitParts.get(originalPart);
        this._splitParts.set(splitPart, list);
        list.push(splitPart);
    }
    /**
	 * @see module:engine/conversion/upcastdispatcher~UpcastConversionApi#getSplitParts
	 */ _getSplitParts(element) {
        let parts;
        if (!this._splitParts.has(element)) {
            parts = [
                element
            ];
        } else {
            parts = this._splitParts.get(element);
        }
        return parts;
    }
    /**
	 * Mark an element that were created during the splitting to not get removed on conversion end even if it is empty.
	 */ _keepEmptyElement(element) {
        this._emptyElementsToKeep.add(element);
    }
    /**
	 * Checks if there are any empty elements created while splitting and removes them.
	 *
	 * This method works recursively to re-check empty elements again after at least one element was removed in the initial call,
	 * as some elements might have become empty after other empty elements were removed from them.
	 */ _removeEmptyElements() {
        let anyRemoved = false;
        for (const element of this._splitParts.keys()){
            if (element.isEmpty && !this._emptyElementsToKeep.has(element)) {
                this.conversionApi.writer.remove(element);
                this._splitParts.delete(element);
                anyRemoved = true;
            }
        }
        if (anyRemoved) {
            this._removeEmptyElements();
        }
    }
}
/**
 * Traverses given model item and searches elements which marks marker range. Found element is removed from
 * DocumentFragment but path of this element is stored in a Map which is then returned.
 *
 * @param modelItem Fragment of model.
 * @returns List of static markers.
 */ function extractMarkersFromModelFragment(modelItem, writer) {
    const markerElements = new Set();
    const markers = new Map();
    // Create ModelTreeWalker.
    const range = Range._createIn(modelItem).getItems();
    // Walk through DocumentFragment and collect marker elements.
    for (const item of range){
        // Check if current element is a marker.
        if (item.is('element', '$marker')) {
            markerElements.add(item);
        }
    }
    // Walk through collected marker elements store its path and remove its from the DocumentFragment.
    for (const markerElement of markerElements){
        const markerName = markerElement.getAttribute('data-name');
        const currentPosition = writer.createPositionBefore(markerElement);
        // When marker of given name is not stored it means that we have found the beginning of the range.
        if (!markers.has(markerName)) {
            markers.set(markerName, new Range(currentPosition.clone()));
        // Otherwise is means that we have found end of the marker range.
        } else {
            markers.get(markerName).end = currentPosition.clone();
        }
        // Remove marker element from DocumentFragment.
        writer.remove(markerElement);
    }
    return markers;
}
/**
 * Creates model fragment according to given context and returns position in the bottom (the deepest) element.
 */ function createContextTree(contextDefinition, writer) {
    let position;
    for (const item of new SchemaContext(contextDefinition)){
        const attributes = {};
        for (const key of item.getAttributeKeys()){
            attributes[key] = item.getAttribute(key);
        }
        const current = writer.createElement(item.name, attributes);
        if (position) {
            writer.insert(current, position);
        }
        position = Position._createAt(current, 0);
    }
    return position;
}

/**
 * Basic HTML writer. It uses the native `innerHTML` property for basic conversion
 * from a document fragment to an HTML string.
 */ class BasicHtmlWriter {
    /**
	 * Returns an HTML string created from the document fragment.
	 */ getHtml(fragment) {
        const doc = global.document.implementation.createHTMLDocument('');
        const container = doc.createElement('div');
        container.appendChild(fragment);
        return container.innerHTML;
    }
}

/**
 * The HTML data processor class.
 * This data processor implementation uses HTML as input and output data.
 */ class HtmlDataProcessor {
    /**
	 * A DOM parser instance used to parse an HTML string to an HTML document.
	 */ domParser;
    /**
	 * A DOM converter used to convert DOM elements to view elements.
	 */ domConverter;
    /**
	 * A basic HTML writer instance used to convert DOM elements to an HTML string.
	 */ htmlWriter;
    skipComments = true;
    /**
	 * Creates a new instance of the HTML data processor class.
	 *
	 * @param document The view document instance.
	 */ constructor(document){
        this.domParser = new DOMParser();
        this.domConverter = new DomConverter(document, {
            renderingMode: 'data'
        });
        this.htmlWriter = new BasicHtmlWriter();
    }
    /**
	 * Converts a provided {@link module:engine/view/documentfragment~DocumentFragment document fragment}
	 * to data format &ndash; in this case to an HTML string.
	 *
	 * @returns HTML string.
	 */ toData(viewFragment) {
        // Convert view DocumentFragment to DOM DocumentFragment.
        const domFragment = this.domConverter.viewToDom(viewFragment);
        // Convert DOM DocumentFragment to HTML output.
        return this.htmlWriter.getHtml(domFragment);
    }
    /**
	 * Converts the provided HTML string to a view tree.
	 *
	 * @param data An HTML string.
	 * @returns A converted view element.
	 */ toView(data) {
        // Convert input HTML data to DOM DocumentFragment.
        const domFragment = this._toDom(data);
        // Convert DOM DocumentFragment to view DocumentFragment.
        return this.domConverter.domToView(domFragment, {
            skipComments: this.skipComments
        });
    }
    /**
	 * Registers a {@link module:engine/view/matcher~MatcherPattern} for view elements whose content should be treated as raw data
	 * and not processed during the conversion from the DOM to the view elements.
	 *
	 * The raw data can be later accessed by a
	 * {@link module:engine/view/element~Element#getCustomProperty custom property of a view element} called `"$rawContent"`.
	 *
	 * @param pattern Pattern matching all view elements whose content should be treated as raw data.
	 */ registerRawContentMatcher(pattern) {
        this.domConverter.registerRawContentMatcher(pattern);
    }
    /**
	 * If the processor is set to use marked fillers, it will insert `&nbsp;` fillers wrapped in `<span>` elements
	 * (`<span data-cke-filler="true">&nbsp;</span>`) instead of regular `&nbsp;` characters.
	 *
	 * This mode allows for a more precise handling of the block fillers (so they do not leak into the editor content) but
	 * bloats the editor data with additional markup.
	 *
	 * This mode may be required by some features and will be turned on by them automatically.
	 *
	 * @param type Whether to use the default or the marked `&nbsp;` block fillers.
	 */ useFillerType(type) {
        this.domConverter.blockFillerMode = type == 'marked' ? 'markedNbsp' : 'nbsp';
    }
    /**
	 * Converts an HTML string to its DOM representation. Returns a document fragment containing nodes parsed from
	 * the provided data.
	 */ _toDom(data) {
        // Wrap data with a <body> tag so leading non-layout nodes (like <script>, <style>, HTML comment)
        // will be preserved in the body collection.
        // Do it only for data that is not a full HTML document.
        if (!data.match(/<(?:html|body|head|meta)(?:\s[^>]*)?>/i)) {
            data = `<body>${data}</body>`;
        }
        const document = this.domParser.parseFromString(data, 'text/html');
        const fragment = document.createDocumentFragment();
        const bodyChildNodes = document.body.childNodes;
        while(bodyChildNodes.length > 0){
            fragment.appendChild(bodyChildNodes[0]);
        }
        return fragment;
    }
}

/**
 * Controller for the data pipeline. The data pipeline controls how data is retrieved from the document
 * and set inside it. Hence, the controller features two methods which allow to {@link ~DataController#get get}
 * and {@link ~DataController#set set} data of the {@link ~DataController#model model}
 * using the given:
 *
 * * {@link module:engine/dataprocessor/dataprocessor~DataProcessor data processor},
 * * downcast converters,
 * * upcast converters.
 *
 * An instance of the data controller is always available in the {@link module:core/editor/editor~Editor#data `editor.data`}
 * property:
 *
 * ```ts
 * editor.data.get( { rootName: 'customRoot' } ); // -> '<p>Hello!</p>'
 * ```
 */ class DataController extends /* #__PURE__ */ EmitterMixin() {
    /**
	 * Data model.
	 */ model;
    /**
	 * Mapper used for the conversion. It has no permanent bindings, because these are created while getting data and
	 * are cleared directly after the data are converted. However, the mapper is defined as a class property, because
	 * it needs to be passed to the `DowncastDispatcher` as a conversion API.
	 */ mapper;
    /**
	 * Downcast dispatcher used by the {@link #get get method}. Downcast converters should be attached to it.
	 */ downcastDispatcher;
    /**
	 * Upcast dispatcher used by the {@link #set set method}. Upcast converters should be attached to it.
	 */ upcastDispatcher;
    /**
	 * The view document used by the data controller.
	 */ viewDocument;
    /**
	 * Styles processor used during the conversion.
	 */ stylesProcessor;
    /**
	 * Data processor used specifically for HTML conversion.
	 */ htmlProcessor;
    /**
	 * Data processor used during the conversion.
	 * Same instance as {@link #htmlProcessor} by default. Can be replaced at run time to handle different format, e.g. XML or Markdown.
	 */ processor;
    /**
	 * The view downcast writer just for data conversion purposes, i.e. to modify
	 * the {@link #viewDocument}.
	 */ _viewWriter;
    /**
	 * Creates a data controller instance.
	 *
	 * @param model Data model.
	 * @param stylesProcessor The styles processor instance.
	 */ constructor(model, stylesProcessor){
        super();
        this.model = model;
        this.mapper = new Mapper();
        this.downcastDispatcher = new DowncastDispatcher({
            mapper: this.mapper,
            schema: model.schema
        });
        this.downcastDispatcher.on('insert:$text', insertText(), {
            priority: 'lowest'
        });
        this.downcastDispatcher.on('insert', insertAttributesAndChildren(), {
            priority: 'lowest'
        });
        this.upcastDispatcher = new UpcastDispatcher({
            schema: model.schema
        });
        this.viewDocument = new Document$1(stylesProcessor);
        this.stylesProcessor = stylesProcessor;
        this.htmlProcessor = new HtmlDataProcessor(this.viewDocument);
        this.processor = this.htmlProcessor;
        this._viewWriter = new DowncastWriter(this.viewDocument);
        // Define default converters for text and elements.
        //
        // Note that if there is no default converter for the element it will be skipped, for instance `<b>foo</b>` will be
        // converted to nothing. We therefore add `convertToModelFragment` as a last converter so it converts children of that
        // element to the document fragment so `<b>foo</b>` will still be converted to `foo` even if there is no converter for `<b>`.
        this.upcastDispatcher.on('text', convertText(), {
            priority: 'lowest'
        });
        this.upcastDispatcher.on('element', convertToModelFragment$1(), {
            priority: 'lowest'
        });
        this.upcastDispatcher.on('documentFragment', convertToModelFragment$1(), {
            priority: 'lowest'
        });
        ObservableMixin().prototype.decorate.call(this, 'init');
        ObservableMixin().prototype.decorate.call(this, 'set');
        ObservableMixin().prototype.decorate.call(this, 'get');
        ObservableMixin().prototype.decorate.call(this, 'toView');
        ObservableMixin().prototype.decorate.call(this, 'toModel');
        // Fire the `ready` event when the initialization has completed. Such low-level listener offers the possibility
        // to plug into the initialization pipeline without interrupting the initialization flow.
        this.on('init', ()=>{
            this.fire('ready');
        }, {
            priority: 'lowest'
        });
        // Fix empty roots after DataController is 'ready' (note that the init method could be decorated and stopped).
        // We need to handle this event because initial data could be empty and the post-fixer would not get triggered.
        this.on('ready', ()=>{
            this.model.enqueueChange({
                isUndoable: false
            }, autoParagraphEmptyRoots);
        }, {
            priority: 'lowest'
        });
    }
    /**
	 * Returns the model's data converted by downcast dispatchers attached to {@link #downcastDispatcher} and
	 * formatted by the {@link #processor data processor}.
	 *
	 * A warning is logged when you try to retrieve data for a detached root, as most probably this is a mistake. A detached root should
	 * be treated like it is removed, and you should not save its data. Note, that the detached root data is always an empty string.
	 *
	 * @fires get
	 * @param options Additional configuration for the retrieved data. `DataController` provides two optional
	 * properties: `rootName` and `trim`. Other properties of this object are specified by various editor features.
	 * @param options.rootName Root name. Default 'main'.
	 * @param options.trim Whether returned data should be trimmed. This option is set to `empty` by default,
	 * which means whenever editor content is considered empty, an empty string will be returned. To turn off trimming completely
	 * use `'none'`. In such cases the exact content will be returned (for example a `<p>&nbsp;</p>` for an empty editor).
	 * @returns Output data.
	 */ get(options = {}) {
        const { rootName = 'main', trim = 'empty' } = options;
        if (!this._checkIfRootsExists([
            rootName
        ])) {
            /**
			 * Cannot get data from a non-existing root. This error is thrown when
			 * {@link module:engine/controller/datacontroller~DataController#get `DataController#get()` method}
			 * is called with a non-existent root name. For example, if there is an editor instance with only `main` root,
			 * calling {@link module:engine/controller/datacontroller~DataController#get} like:
			 *
			 * ```ts
			 * data.get( { rootName: 'root2' } );
			 * ```
			 *
			 * will throw this error.
			 *
			 * @error datacontroller-get-non-existent-root
			 */ throw new CKEditorError('datacontroller-get-non-existent-root', this);
        }
        const root = this.model.document.getRoot(rootName);
        if (!root.isAttached()) {
            /**
			 * Retrieving document data for a detached root.
			 *
			 * This usually indicates an error as a detached root should be considered "removed" and should not be included in the
			 * document data.
			 *
			 * @error datacontroller-get-detached-root
			 */ logWarning('datacontroller-get-detached-root', this);
        }
        if (trim === 'empty' && !this.model.hasContent(root, {
            ignoreWhitespaces: true
        })) {
            return '';
        }
        return this.stringify(root, options);
    }
    /**
	 * Returns the content of the given {@link module:engine/model/element~Element model's element} or
	 * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast converters
	 * attached to the {@link #downcastDispatcher} and formatted by the {@link #processor data processor}.
	 *
	 * @param modelElementOrFragment The element whose content will be stringified.
	 * @param options Additional configuration passed to the conversion process.
	 * @returns Output data.
	 */ stringify(modelElementOrFragment, options = {}) {
        // Model -> view.
        const viewDocumentFragment = this.toView(modelElementOrFragment, options);
        // View -> data.
        return this.processor.toData(viewDocumentFragment);
    }
    /**
	 * Returns the content of the given {@link module:engine/model/element~Element model element} or
	 * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast
	 * converters attached to {@link #downcastDispatcher} into a
	 * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}.
	 *
	 * @fires toView
	 * @param modelElementOrFragment Element or document fragment whose content will be converted.
	 * @param options Additional configuration that will be available through the
	 * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi#options} during the conversion process.
	 * @returns Output view DocumentFragment.
	 */ toView(modelElementOrFragment, options = {}) {
        const viewDocument = this.viewDocument;
        const viewWriter = this._viewWriter;
        // Clear bindings so the call to this method returns correct results.
        this.mapper.clearBindings();
        // First, convert elements.
        const modelRange = Range._createIn(modelElementOrFragment);
        const viewDocumentFragment = new DocumentFragment$1(viewDocument);
        this.mapper.bindElements(modelElementOrFragment, viewDocumentFragment);
        // Prepare list of markers.
        // For document fragment, simply take the markers assigned to this document fragment.
        // For model root, all markers in that root will be taken.
        // For model element, we need to check which markers are intersecting with this element and relatively modify the markers' ranges.
        // Collapsed markers at element boundary, although considered as not intersecting with the element, will also be returned.
        const markers = modelElementOrFragment.is('documentFragment') ? modelElementOrFragment.markers : _getMarkersRelativeToElement(modelElementOrFragment);
        this.downcastDispatcher.convert(modelRange, markers, viewWriter, options);
        return viewDocumentFragment;
    }
    /**
	 * Sets the initial input data parsed by the {@link #processor data processor} and
	 * converted by the {@link #upcastDispatcher view-to-model converters}.
	 * Initial data can be only set to a document whose {@link module:engine/model/document~Document#version} is equal 0.
	 *
	 * **Note** This method is {@link module:utils/observablemixin~Observable#decorate decorated} which is
	 * used by e.g. collaborative editing plugin that syncs remote data on init.
	 *
	 * When data is passed as a string, it is initialized on the default `main` root:
	 *
	 * ```ts
	 * dataController.init( '<p>Foo</p>' ); // Initializes data on the `main` root only, as no other is specified.
	 * ```
	 *
	 * To initialize data on a different root or multiple roots at once, an object containing `rootName` - `data` pairs should be passed:
	 *
	 * ```ts
	 * dataController.init( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Initializes data on both the `main` and `title` roots.
	 * ```
	 *
	 * @fires init
	 * @param data Input data as a string or an object containing the `rootName` - `data`
	 * pairs to initialize data on multiple roots at once.
	 * @returns Promise that is resolved after the data is set on the editor.
	 */ init(data) {
        if (this.model.document.version) {
            /**
			 * Cannot set initial data to a non-empty {@link module:engine/model/document~Document}.
			 * Initial data should be set once, during the {@link module:core/editor/editor~Editor} initialization,
			 * when the {@link module:engine/model/document~Document#version} is equal 0.
			 *
			 * @error datacontroller-init-document-not-empty
			 */ throw new CKEditorError('datacontroller-init-document-not-empty', this);
        }
        let initialData = {};
        if (typeof data === 'string') {
            initialData.main = data; // Default root is 'main'. To initiate data on a different root, object should be passed.
        } else {
            initialData = data;
        }
        if (!this._checkIfRootsExists(Object.keys(initialData))) {
            /**
			 * Cannot init data on a non-existent root. This error is thrown when
			 * {@link module:engine/controller/datacontroller~DataController#init DataController#init() method}
			 * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
			 * calling {@link module:engine/controller/datacontroller~DataController#init} like:
			 *
			 * ```ts
			 * data.init( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
			 * ```
			 *
			 * will throw this error.
			 *
			 * @error datacontroller-init-non-existent-root
			 */ throw new CKEditorError('datacontroller-init-non-existent-root', this);
        }
        this.model.enqueueChange({
            isUndoable: false
        }, (writer)=>{
            for (const rootName of Object.keys(initialData)){
                const modelRoot = this.model.document.getRoot(rootName);
                writer.insert(this.parse(initialData[rootName], modelRoot), modelRoot, 0);
            }
        });
        return Promise.resolve();
    }
    /**
	 * Sets the input data parsed by the {@link #processor data processor} and
	 * converted by the {@link #upcastDispatcher view-to-model converters}.
	 * This method can be used any time to replace existing editor data with the new one without clearing the
	 * {@link module:engine/model/document~Document#history document history}.
	 *
	 * This method also creates a batch with all the changes applied. If all you need is to parse data, use
	 * the {@link #parse} method.
	 *
	 * When data is passed as a string it is set on the default `main` root:
	 *
	 * ```ts
	 * dataController.set( '<p>Foo</p>' ); // Sets data on the `main` root, as no other is specified.
	 * ```
	 *
	 * To set data on a different root or multiple roots at once, an object containing `rootName` - `data` pairs should be passed:
	 *
	 * ```ts
	 * dataController.set( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Sets data on the `main` and `title` roots as specified.
	 * ```
	 *
	 * To set the data with a preserved undo stack and add the change to the undo stack, set `{ isUndoable: true }` as a `batchType` option.
	 *
	 * ```ts
	 * dataController.set( '<p>Foo</p>', { batchType: { isUndoable: true } } );
	 * ```
	 *
	 * @fires set
	 * @param data Input data as a string or an object containing the `rootName` - `data`
	 * pairs to set data on multiple roots at once.
	 * @param options Options for setting data.
	 * @param options.batchType The batch type that will be used to create a batch for the changes applied by this method.
	 * By default, the batch will be set as {@link module:engine/model/batch~Batch#isUndoable not undoable} and the undo stack will be
	 * cleared after the new data is applied (all undo steps will be removed). If the batch type `isUndoable` flag is be set to `true`,
	 * the undo stack will be preserved instead and not cleared when new data is applied.
	 */ set(data, options = {}) {
        let newData = {};
        if (typeof data === 'string') {
            newData.main = data; // The default root is 'main'. To set data on a different root, an object should be passed.
        } else {
            newData = data;
        }
        if (!this._checkIfRootsExists(Object.keys(newData))) {
            /**
			 * Cannot set data on a non-existent root. This error is thrown when the
			 * {@link module:engine/controller/datacontroller~DataController#set DataController#set() method}
			 * is called with non-existent root name. For example, if there is an editor instance with only the default `main` root,
			 * calling {@link module:engine/controller/datacontroller~DataController#set} like:
			 *
			 * ```ts
			 * data.set( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
			 * ```
			 *
			 * will throw this error.
			 *
			 * @error datacontroller-set-non-existent-root
			 */ throw new CKEditorError('datacontroller-set-non-existent-root', this);
        }
        this.model.enqueueChange(options.batchType || {}, (writer)=>{
            writer.setSelection(null);
            writer.removeSelectionAttribute(this.model.document.selection.getAttributeKeys());
            for (const rootName of Object.keys(newData)){
                // Save to model.
                const modelRoot = this.model.document.getRoot(rootName);
                writer.remove(writer.createRangeIn(modelRoot));
                writer.insert(this.parse(newData[rootName], modelRoot), modelRoot, 0);
            }
        });
    }
    /**
	 * Returns the data parsed by the {@link #processor data processor} and then converted by upcast converters
	 * attached to the {@link #upcastDispatcher}.
	 *
	 * @see #set
	 * @param data Data to parse.
	 * @param context Base context in which the view will be converted to the model.
	 * See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
	 * @returns Parsed data.
	 */ parse(data, context = '$root') {
        // data -> view
        const viewDocumentFragment = this.processor.toView(data);
        // view -> model
        return this.toModel(viewDocumentFragment, context);
    }
    /**
	 * Returns the result of the given {@link module:engine/view/element~Element view element} or
	 * {@link module:engine/view/documentfragment~DocumentFragment view document fragment} converted by the
	 * {@link #upcastDispatcher view-to-model converters}, wrapped by {@link module:engine/model/documentfragment~DocumentFragment}.
	 *
	 * When marker elements were converted during the conversion process, it will be set as a document fragment's
	 * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
	 *
	 * @fires toModel
	 * @param viewElementOrFragment The element or document fragment whose content will be converted.
	 * @param context Base context in which the view will be converted to the model.
	 * See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
	 * @returns Output document fragment.
	 */ toModel(viewElementOrFragment, context = '$root') {
        return this.model.change((writer)=>{
            return this.upcastDispatcher.convert(viewElementOrFragment, writer, context);
        });
    }
    /**
	 * Adds the style processor normalization rules.
	 *
	 * You can implement your own rules as well as use one of the available processor rules:
	 *
	 * * background: {@link module:engine/view/styles/background~addBackgroundRules}
	 * * border: {@link module:engine/view/styles/border~addBorderRules}
	 * * margin: {@link module:engine/view/styles/margin~addMarginRules}
	 * * padding: {@link module:engine/view/styles/padding~addPaddingRules}
	 */ addStyleProcessorRules(callback) {
        callback(this.stylesProcessor);
    }
    /**
	 * Registers a {@link module:engine/view/matcher~MatcherPattern} on an {@link #htmlProcessor htmlProcessor}
	 * and a {@link #processor processor} for view elements whose content should be treated as raw data
	 * and not processed during the conversion from DOM to view elements.
	 *
	 * The raw data can be later accessed by the {@link module:engine/view/element~Element#getCustomProperty view element custom property}
	 * `"$rawContent"`.
	 *
	 * @param pattern Pattern matching all view elements whose content should be treated as a raw data.
	 */ registerRawContentMatcher(pattern) {
        // No need to register the pattern if both the `htmlProcessor` and `processor` are the same instances.
        if (this.processor && this.processor !== this.htmlProcessor) {
            this.processor.registerRawContentMatcher(pattern);
        }
        this.htmlProcessor.registerRawContentMatcher(pattern);
    }
    /**
	 * Removes all event listeners set by the DataController.
	 */ destroy() {
        this.stopListening();
    }
    /**
	 * Checks whether all provided root names are actually existing editor roots.
	 *
	 * @param rootNames Root names to check.
	 * @returns Whether all provided root names are existing editor roots.
	 */ _checkIfRootsExists(rootNames) {
        for (const rootName of rootNames){
            if (!this.model.document.getRoot(rootName)) {
                return false;
            }
        }
        return true;
    }
}
/**
 * Helper function for downcast conversion.
 *
 * Takes a document element (element that is added to a model document) and checks which markers are inside it. If the marker is collapsed
 * at element boundary, it is considered as contained inside the element and marker range is returned. Otherwise, if the marker is
 * intersecting with the element, the intersection is returned.
 */ function _getMarkersRelativeToElement(element) {
    const result = [];
    const doc = element.root.document;
    if (!doc) {
        return new Map();
    }
    const elementRange = Range._createIn(element);
    for (const marker of doc.model.markers){
        const markerRange = marker.getRange();
        const isMarkerCollapsed = markerRange.isCollapsed;
        const isMarkerAtElementBoundary = markerRange.start.isEqual(elementRange.start) || markerRange.end.isEqual(elementRange.end);
        if (isMarkerCollapsed && isMarkerAtElementBoundary) {
            result.push([
                marker.name,
                markerRange
            ]);
        } else {
            const updatedMarkerRange = elementRange.getIntersection(markerRange);
            if (updatedMarkerRange) {
                result.push([
                    marker.name,
                    updatedMarkerRange
                ]);
            }
        }
    }
    // Sort the markers in a stable fashion to ensure that the order in which they are
    // added to the model's marker collection does not affect how they are
    // downcast. One particular use case that we are targeting here, is one where
    // two markers are adjacent but not overlapping, such as an insertion/deletion
    // suggestion pair representing the replacement of a range of text. In this
    // case, putting the markers in DOM order causes the first marker's end to be
    // serialized right after the second marker's start, while putting the markers
    // in reverse DOM order causes it to be right before the second marker's
    // start. So, we sort these in a way that ensures non-intersecting ranges are in
    // reverse DOM order, and intersecting ranges are in something approximating
    // reverse DOM order (since reverse DOM order doesn't have a precise meaning
    // when working with intersecting ranges).
    result.sort(([n1, r1], [n2, r2])=>{
        if (r1.end.compareWith(r2.start) !== 'after') {
            // m1.end <= m2.start -- m1 is entirely <= m2
            return 1;
        } else if (r1.start.compareWith(r2.end) !== 'before') {
            // m1.start >= m2.end -- m1 is entirely >= m2
            return -1;
        } else {
            // they overlap, so use their start positions as the primary sort key and
            // end positions as the secondary sort key
            switch(r1.start.compareWith(r2.start)){
                case 'before':
                    return 1;
                case 'after':
                    return -1;
                default:
                    switch(r1.end.compareWith(r2.end)){
                        case 'before':
                            return 1;
                        case 'after':
                            return -1;
                        default:
                            return n2.localeCompare(n1);
                    }
            }
        }
    });
    return new Map(result);
}

/**
 * A utility class that helps add converters to upcast and downcast dispatchers.
 *
 * We recommend reading the {@glink framework/deep-dive/conversion/intro editor conversion} guide first to
 * understand the core concepts of the conversion mechanisms.
 *
 * An instance of the conversion manager is available in the
 * {@link module:core/editor/editor~Editor#conversion `editor.conversion`} property
 * and by default has the following groups of dispatchers (i.e. directions of conversion):
 *
 * * `downcast` (editing and data downcasts)
 * * `editingDowncast`
 * * `dataDowncast`
 * * `upcast`
 *
 * # One-way converters
 *
 * To add a converter to a specific group, use the {@link module:engine/conversion/conversion~Conversion#for `for()`}
 * method:
 *
 * ```ts
 * // Add a converter to editing downcast and data downcast.
 * editor.conversion.for( 'downcast' ).elementToElement( config ) );
 *
 * // Add a converter to the data pipepline only:
 * editor.conversion.for( 'dataDowncast' ).elementToElement( dataConversionConfig ) );
 *
 * // And a slightly different one for the editing pipeline:
 * editor.conversion.for( 'editingDowncast' ).elementToElement( editingConversionConfig ) );
 * ```
 *
 * See {@link module:engine/conversion/conversion~Conversion#for `for()`} method documentation to learn more about
 * available conversion helpers and how to use your custom ones.
 *
 * # Two-way converters
 *
 * Besides using one-way converters via the `for()` method, you can also use other methods available in this
 * class to add two-way converters (upcast and downcast):
 *
 * * {@link module:engine/conversion/conversion~Conversion#elementToElement `elementToElement()`} &ndash;
 * Model element to view element and vice versa.
 * * {@link module:engine/conversion/conversion~Conversion#attributeToElement `attributeToElement()`} &ndash;
 * Model attribute to view element and vice versa.
 * * {@link module:engine/conversion/conversion~Conversion#attributeToAttribute `attributeToAttribute()`} &ndash;
 * Model attribute to view attribute and vice versa.
 */ class Conversion {
    /**
	 * Maps dispatchers group name to ConversionHelpers instances.
	 */ _helpers = new Map();
    _downcast;
    _upcast;
    /**
	 * Creates a new conversion instance.
	 */ constructor(downcastDispatchers, upcastDispatchers){
        // Define default 'downcast' & 'upcast' dispatchers groups. Those groups are always available as two-way converters needs them.
        this._downcast = toArray(downcastDispatchers);
        this._createConversionHelpers({
            name: 'downcast',
            dispatchers: this._downcast,
            isDowncast: true
        });
        this._upcast = toArray(upcastDispatchers);
        this._createConversionHelpers({
            name: 'upcast',
            dispatchers: this._upcast,
            isDowncast: false
        });
    }
    /**
	 * Define an alias for registered dispatcher.
	 *
	 * ```ts
	 * const conversion = new Conversion(
	 * 	[ dataDowncastDispatcher, editingDowncastDispatcher ],
	 * 	upcastDispatcher
	 * );
	 *
	 * conversion.addAlias( 'dataDowncast', dataDowncastDispatcher );
	 * ```
	 *
	 * @param alias An alias of a dispatcher.
	 * @param dispatcher Dispatcher which should have an alias.
	 */ addAlias(alias, dispatcher) {
        const isDowncast = this._downcast.includes(dispatcher);
        const isUpcast = this._upcast.includes(dispatcher);
        if (!isUpcast && !isDowncast) {
            /**
			 * Trying to register an alias for a dispatcher that nas not been registered.
			 *
			 * @error conversion-add-alias-dispatcher-not-registered
			 */ throw new CKEditorError('conversion-add-alias-dispatcher-not-registered', this);
        }
        this._createConversionHelpers({
            name: alias,
            dispatchers: [
                dispatcher
            ],
            isDowncast
        });
    }
    /**
	 * Provides a chainable API to assign converters to a conversion dispatchers group.
	 *
	 * If the given group name has not been registered, the
	 * {@link module:utils/ckeditorerror~CKEditorError `conversion-for-unknown-group` error} is thrown.
	 *
	 * You can use conversion helpers available directly in the `for()` chain or your custom ones via
	 * the {@link module:engine/conversion/conversionhelpers~ConversionHelpers#add `add()`} method.
	 *
	 * # Using built-in conversion helpers
	 *
	 * The `for()` chain comes with a set of conversion helpers which you can use like this:
	 *
	 * ```ts
	 * editor.conversion.for( 'downcast' )
	 * 	.elementToElement( config1 )        // Adds an element-to-element downcast converter.
	 * 	.attributeToElement( config2 );     // Adds an attribute-to-element downcast converter.
	 *
	 * editor.conversion.for( 'upcast' )
	 * 	.elementToAttribute( config3 );     // Adds an element-to-attribute upcast converter.
	 * ```
	 *
	 * Refer to the documentation of built-in conversion helpers to learn about their configuration options.
	 *
	 * * downcast (model-to-view) conversion helpers:
	 *
	 *	* {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToElement `elementToElement()`},
	 *	* {@link module:engine/conversion/downcasthelpers~DowncastHelpers#attributeToElement `attributeToElement()`},
	 *	* {@link module:engine/conversion/downcasthelpers~DowncastHelpers#attributeToAttribute `attributeToAttribute()`}.
	 *	* {@link module:engine/conversion/downcasthelpers~DowncastHelpers#markerToElement `markerToElement()`}.
	 *	* {@link module:engine/conversion/downcasthelpers~DowncastHelpers#markerToHighlight `markerToHighlight()`}.
	 *
	 * * upcast (view-to-model) conversion helpers:
	 *
	 *	* {@link module:engine/conversion/upcasthelpers~UpcastHelpers#elementToElement `elementToElement()`},
	 *	* {@link module:engine/conversion/upcasthelpers~UpcastHelpers#elementToAttribute `elementToAttribute()`},
	 *	* {@link module:engine/conversion/upcasthelpers~UpcastHelpers#attributeToAttribute `attributeToAttribute()`}.
	 *	* {@link module:engine/conversion/upcasthelpers~UpcastHelpers#elementToMarker `elementToMarker()`}.
	 *
	 * # Using custom conversion helpers
	 *
	 * If you need to implement an atypical converter, you can do so by calling:
	 *
	 * ```ts
	 * editor.conversion.for( direction ).add( customHelper );
	 * ```
	 *
	 * The `.add()` method takes exactly one parameter, which is a function. This function should accept one parameter that
	 * is a dispatcher instance. The function should add an actual converter to the passed dispatcher instance.
	 *
	 * Example:
	 *
	 * ```ts
	 * editor.conversion.for( 'upcast' ).add( dispatcher => {
	 * 	dispatcher.on( 'element:a',  ( evt, data, conversionApi ) => {
	 * 		// Do something with a view <a> element.
	 * 	} );
	 * } );
	 * ```
	 *
	 * Refer to the documentation of {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher}
	 * and {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher} to learn how to write
	 * custom converters.
	 *
	 * @param groupName The name of dispatchers group to add the converters to.
	 */ for(groupName) {
        if (!this._helpers.has(groupName)) {
            /**
			 * Trying to add a converter to an unknown dispatchers group.
			 *
			 * @error conversion-for-unknown-group
			 */ throw new CKEditorError('conversion-for-unknown-group', this);
        }
        return this._helpers.get(groupName);
    }
    /**
	 * Sets up converters between the model and the view that convert a model element to a view element (and vice versa).
	 * For example, the model `<paragraph>Foo</paragraph>` is turned into `<p>Foo</p>` in the view.
	 *
	 * ```ts
	 * // A simple conversion from the `paragraph` model element to the `<p>` view element (and vice versa).
	 * editor.conversion.elementToElement( { model: 'paragraph', view: 'p' } );
	 *
	 * // Override other converters by specifying a converter definition with a higher priority.
	 * editor.conversion.elementToElement( { model: 'paragraph', view: 'div', converterPriority: 'high' } );
	 *
	 * // View specified as an object instead of a string.
	 * editor.conversion.elementToElement( {
	 * 	model: 'fancyParagraph',
	 * 	view: {
	 * 		name: 'p',
	 * 		classes: 'fancy'
	 * 	}
	 * } );
	 *
	 * // Use `upcastAlso` to define other view elements that should also be converted to a `paragraph` element.
	 * editor.conversion.elementToElement( {
	 * 	model: 'paragraph',
	 * 	view: 'p',
	 * 	upcastAlso: [
	 * 		'div',
	 * 		{
	 * 			// Any element with the `display: block` style.
	 * 			styles: {
	 * 				display: 'block'
	 * 			}
	 * 		}
	 * 	]
	 * } );
	 *
	 * // `upcastAlso` set as callback enables a conversion of a wide range of different view elements.
	 * editor.conversion.elementToElement( {
	 * 	model: 'heading',
	 * 	view: 'h2',
	 * 	// Convert "heading-like" paragraphs to headings.
	 * 	upcastAlso: viewElement => {
	 * 		const fontSize = viewElement.getStyle( 'font-size' );
	 *
	 * 		if ( !fontSize ) {
	 * 			return null;
	 * 		}
	 *
	 * 		const match = fontSize.match( /(\d+)\s*px/ );
	 *
	 * 		if ( !match ) {
	 * 			return null;
	 * 		}
	 *
	 * 		const size = Number( match[ 1 ] );
	 *
	 * 		if ( size > 26 ) {
	 * 			// Returned value can be an object with the matched properties.
	 * 			// These properties will be "consumed" during the conversion.
	 * 			// See `engine.view.Matcher~MatcherPattern` and `engine.view.Matcher#match` for more details.
	 *
	 * 			return { name: true, styles: [ 'font-size' ] };
	 * 		}
	 *
	 * 		return null;
	 * 	}
	 * } );
	 * ```
	 *
	 * `definition.model` is a `String` with a model element name to convert from or to.
	 *
	 * @param definition The converter definition.
	 */ elementToElement(definition) {
        // Set up downcast converter.
        this.for('downcast').elementToElement(definition);
        // Set up upcast converter.
        for (const { model, view } of _getAllUpcastDefinitions(definition)){
            this.for('upcast').elementToElement({
                model,
                view,
                converterPriority: definition.converterPriority
            });
        }
    }
    /**
	 * Sets up converters between the model and the view that convert a model attribute to a view element (and vice versa).
	 * For example, a model text node with `"Foo"` as data and the `bold` attribute will be turned to `<strong>Foo</strong>` in the view.
	 *
	 * ```ts
	 * // A simple conversion from the `bold=true` attribute to the `<strong>` view element (and vice versa).
	 * editor.conversion.attributeToElement( { model: 'bold', view: 'strong' } );
	 *
	 * // Override other converters by specifying a converter definition with a higher priority.
	 * editor.conversion.attributeToElement( { model: 'bold', view: 'b', converterPriority: 'high' } );
	 *
	 * // View specified as an object instead of a string.
	 * editor.conversion.attributeToElement( {
	 * 	model: 'bold',
	 * 	view: {
	 * 		name: 'span',
	 * 		classes: 'bold'
	 * 	}
	 * } );
	 *
	 * // Use `config.model.name` to define the conversion only from a given node type, `$text` in this case.
	 * // The same attribute on different elements may then be handled by a different converter.
	 * editor.conversion.attributeToElement( {
	 * 	model: {
	 * 		key: 'textDecoration',
	 * 		values: [ 'underline', 'lineThrough' ],
	 * 		name: '$text'
	 * 	},
	 * 	view: {
	 * 		underline: {
	 * 			name: 'span',
	 * 			styles: {
	 * 				'text-decoration': 'underline'
	 * 			}
	 * 		},
	 * 		lineThrough: {
	 * 			name: 'span',
	 * 			styles: {
	 * 				'text-decoration': 'line-through'
	 * 			}
	 * 		}
	 * 	}
	 * } );
	 *
	 * // Use `upcastAlso` to define other view elements that should also be converted to the `bold` attribute.
	 * editor.conversion.attributeToElement( {
	 * 	model: 'bold',
	 * 	view: 'strong',
	 * 	upcastAlso: [
	 * 		'b',
	 * 		{
	 * 			name: 'span',
	 * 			classes: 'bold'
	 * 		},
	 * 		{
	 * 			name: 'span',
	 * 			styles: {
	 * 				'font-weight': 'bold'
	 * 			}
	 * 		},
	 * 		viewElement => {
	 * 			const fontWeight = viewElement.getStyle( 'font-weight' );
	 *
	 * 			if ( viewElement.is( 'element', 'span' ) && fontWeight && /\d+/.test() && Number( fontWeight ) > 500 ) {
	 * 				// Returned value can be an object with the matched properties.
	 * 				// These properties will be "consumed" during the conversion.
	 * 				// See `engine.view.Matcher~MatcherPattern` and `engine.view.Matcher#match` for more details.
	 *
	 * 				return {
	 * 					name: true,
	 * 					styles: [ 'font-weight' ]
	 * 				};
	 * 			}
	 * 		}
	 * 	]
	 * } );
	 *
	 * // Conversion from and to a model attribute key whose value is an enum (`fontSize=big|small`).
	 * // `upcastAlso` set as callback enables a conversion of a wide range of different view elements.
	 * editor.conversion.attributeToElement( {
	 * 	model: {
	 * 		key: 'fontSize',
	 * 		values: [ 'big', 'small' ]
	 * 	},
	 * 	view: {
	 * 		big: {
	 * 			name: 'span',
	 * 			styles: {
	 * 				'font-size': '1.2em'
	 * 			}
	 * 		},
	 * 		small: {
	 * 			name: 'span',
	 * 			styles: {
	 * 				'font-size': '0.8em'
	 * 			}
	 * 		}
	 * 	},
	 * 	upcastAlso: {
	 * 		big: viewElement => {
	 * 			const fontSize = viewElement.getStyle( 'font-size' );
	 *
	 * 			if ( !fontSize ) {
	 * 				return null;
	 * 			}
	 *
	 * 			const match = fontSize.match( /(\d+)\s*px/ );
	 *
	 * 			if ( !match ) {
	 * 				return null;
	 * 			}
	 *
	 * 			const size = Number( match[ 1 ] );
	 *
	 * 			if ( viewElement.is( 'element', 'span' ) && size > 10 ) {
	 * 				// Returned value can be an object with the matched properties.
	 * 				// These properties will be "consumed" during the conversion.
	 * 				// See `engine.view.Matcher~MatcherPattern` and `engine.view.Matcher#match` for more details.
	 *
	 * 				return { name: true, styles: [ 'font-size' ] };
	 * 			}
	 *
	 * 			return null;
	 * 		},
	 * 		small: viewElement => {
	 * 			const fontSize = viewElement.getStyle( 'font-size' );
	 *
	 * 			if ( !fontSize ) {
	 * 				return null;
	 * 			}
	 *
	 * 			const match = fontSize.match( /(\d+)\s*px/ );
	 *
	 * 			if ( !match ) {
	 * 				return null;
	 * 			}
	 *
	 * 			const size = Number( match[ 1 ] );
	 *
	 * 			if ( viewElement.is( 'element', 'span' ) && size < 10 ) {
	 * 				// Returned value can be an object with the matched properties.
	 * 				// These properties will be "consumed" during the conversion.
	 * 				// See `engine.view.Matcher~MatcherPattern` and `engine.view.Matcher#match` for more details.
	 *
	 * 				return { name: true, styles: [ 'font-size' ] };
	 * 			}
	 *
	 * 			return null;
	 * 		}
	 * 	}
	 * } );
	 * ```
	 *
	 * The `definition.model` parameter specifies which model attribute should be converted from or to. It can be a `{ key, value }` object
	 * describing the attribute key and value to convert or a `String` specifying just the attribute key (in such a case
	 * `value` is set to `true`).
	 *
	 * @param definition The converter definition.
	 */ attributeToElement(definition) {
        // Set up downcast converter.
        this.for('downcast').attributeToElement(definition);
        // Set up upcast converter.
        for (const { model, view } of _getAllUpcastDefinitions(definition)){
            this.for('upcast').elementToAttribute({
                view,
                model,
                converterPriority: definition.converterPriority
            });
        }
    }
    /**
	 * Sets up converters between the model and the view that convert a model attribute to a view attribute (and vice versa). For example,
	 * `<imageBlock src='foo.jpg'></imageBlock>` is converted to `<img src='foo.jpg'></img>` (the same attribute key and value).
	 * This type of converters is intended to be used with {@link module:engine/model/element~Element model element} nodes.
	 * To convert the text attributes,
	 * the {@link module:engine/conversion/conversion~Conversion#attributeToElement `attributeToElement converter`}should be set up.
	 *
	 * ```ts
	 * // A simple conversion from the `source` model attribute to the `src` view attribute (and vice versa).
	 * editor.conversion.attributeToAttribute( { model: 'source', view: 'src' } );
	 *
	 * // Attribute values are strictly specified.
	 * editor.conversion.attributeToAttribute( {
	 * 	model: {
	 * 		name: 'imageInline',
	 * 		key: 'aside',
	 * 		values: [ 'aside' ]
	 * 	},
	 * 	view: {
	 * 		aside: {
	 * 			name: 'img',
	 * 			key: 'class',
	 * 			value: [ 'aside', 'half-size' ]
	 * 		}
	 * 	}
	 * } );
	 *
	 * // Set the style attribute.
	 * editor.conversion.attributeToAttribute( {
	 * 	model: {
	 * 		name: 'imageInline',
	 * 		key: 'aside',
	 * 		values: [ 'aside' ]
	 * 	},
	 * 	view: {
	 * 		aside: {
	 * 			name: 'img',
	 * 			key: 'style',
	 * 			value: {
	 * 				float: 'right',
	 * 				width: '50%',
	 * 				margin: '5px'
	 * 			}
	 * 		}
	 * 	}
	 * } );
	 *
	 * // Conversion from and to a model attribute key whose value is an enum (`align=right|center`).
	 * // Use `upcastAlso` to define other view elements that should also be converted to the `align=right` attribute.
	 * editor.conversion.attributeToAttribute( {
	 * 	model: {
	 * 		key: 'align',
	 * 		values: [ 'right', 'center' ]
	 * 	},
	 * 	view: {
	 * 		right: {
	 * 			key: 'class',
	 * 			value: 'align-right'
	 * 		},
	 * 		center: {
	 * 			key: 'class',
	 * 			value: 'align-center'
	 * 		}
	 * 	},
	 * 	upcastAlso: {
	 * 		right: {
	 * 			styles: {
	 * 				'text-align': 'right'
	 * 			}
	 * 		},
	 * 		center: {
	 * 			styles: {
	 * 				'text-align': 'center'
	 * 			}
	 * 		}
	 * 	}
	 * } );
	 * ```
	 *
	 * The `definition.model` parameter specifies which model attribute should be converted from and to.
	 * It can be a `{ key, [ values ], [ name ] }` object or a `String`, which will be treated like `{ key: definition.model }`.
	 * The `key` property is the model attribute key to convert from and to.
	 * The `values` are the possible model attribute values. If the `values` parameter is not set, the model attribute value
	 * will be the same as the view attribute value.
	 * If `name` is set, the conversion will be set up only for model elements with the given name.
	 *
	 * The `definition.view` parameter specifies which view attribute should be converted from and to.
	 * It can be a `{ key, value, [ name ] }` object or a `String`, which will be treated like `{ key: definition.view }`.
	 * The `key` property is the view attribute key to convert from and to.
	 * The `value` is the view attribute value to convert from and to. If `definition.value` is not set, the view attribute value will be
	 * the same as the model attribute value.
	 * If `key` is `'class'`, `value` can be a `String` or an array of `String`s.
	 * If `key` is `'style'`, `value` is an object with key-value pairs.
	 * In other cases, `value` is a `String`.
	 * If `name` is set, the conversion will be set up only for model elements with the given name.
	 * If `definition.model.values` is set, `definition.view` is an object that assigns values from `definition.model.values`
	 * to `{ key, value, [ name ] }` objects.
	 *
	 * `definition.upcastAlso` specifies which other matching view elements should also be upcast to the given model configuration.
	 * If `definition.model.values` is set, `definition.upcastAlso` should be an object assigning values from `definition.model.values`
	 * to {@link module:engine/view/matcher~MatcherPattern}s or arrays of {@link module:engine/view/matcher~MatcherPattern}s.
	 *
	 * **Note:** `definition.model` and `definition.view` form should be mirrored, so the same types of parameters should
	 * be given in both parameters.
	 *
	 * @param definition The converter definition.
	 * @param definition.model The model attribute to convert from and to.
	 * @param definition.view The view attribute to convert from and to.
	 * @param definition.upcastAlso Any view element matching `definition.upcastAlso` will also be converted to the given model attribute.
	 * `definition.upcastAlso` is used only if `config.model.values` is specified.
	 */ attributeToAttribute(definition) {
        // Set up downcast converter.
        this.for('downcast').attributeToAttribute(definition);
        // Set up upcast converter.
        for (const { model, view } of _getAllUpcastDefinitions(definition)){
            this.for('upcast').attributeToAttribute({
                view,
                model
            });
        }
    }
    /**
	 * Creates and caches conversion helpers for given dispatchers group.
	 *
	 * @param options.name Group name.
	 */ _createConversionHelpers({ name, dispatchers, isDowncast }) {
        if (this._helpers.has(name)) {
            /**
			 * Trying to register a group name that has already been registered.
			 *
			 * @error conversion-group-exists
			 */ throw new CKEditorError('conversion-group-exists', this);
        }
        const helpers = isDowncast ? new DowncastHelpers(dispatchers) : new UpcastHelpers(dispatchers);
        this._helpers.set(name, helpers);
    }
}
/**
 * Helper function that creates a joint array out of an item passed in `definition.view` and items passed in
 * `definition.upcastAlso`.
 */ function* _getAllUpcastDefinitions(definition) {
    if (definition.model.values) {
        for (const value of definition.model.values){
            const model = {
                key: definition.model.key,
                value
            };
            const view = definition.view[value];
            const upcastAlso = definition.upcastAlso ? definition.upcastAlso[value] : undefined;
            yield* _getUpcastDefinition(model, view, upcastAlso);
        }
    } else {
        yield* _getUpcastDefinition(definition.model, definition.view, definition.upcastAlso);
    }
}
function* _getUpcastDefinition(model, view, upcastAlso) {
    yield {
        model,
        view
    };
    if (upcastAlso) {
        for (const upcastAlsoItem of toArray(upcastAlso)){
            yield {
                model,
                view: upcastAlsoItem
            };
        }
    }
}

/**
 * The XML data processor class.
 * This data processor implementation uses XML as input and output data.
 * This class is needed because unlike HTML, XML allows to use any tag with any value.
 * For example, `<link>Text</link>` is a valid XML but invalid HTML.
 */ class XmlDataProcessor {
    /**
	 * A list of namespaces allowed to use in the XML input.
	 *
	 * For example, registering namespaces [ 'attribute', 'container' ] allows to use `<attirbute:tagName></attribute:tagName>`
	 * and `<container:tagName></container:tagName>` input. It is mainly for debugging.
	 */ namespaces;
    /**
	 * DOM parser instance used to parse an XML string to an XML document.
	 */ domParser;
    /**
	 * DOM converter used to convert DOM elements to view elements.
	 */ domConverter;
    /**
	 * A basic HTML writer instance used to convert DOM elements to an XML string.
	 * There is no need to use a dedicated XML writer because the basic HTML writer works well in this case.
	 */ htmlWriter;
    skipComments = true;
    /**
	 * Creates a new instance of the XML data processor class.
	 *
	 * @param document The view document instance.
	 * @param options Configuration options.
	 * @param options.namespaces A list of namespaces allowed to use in the XML input.
	 */ constructor(document, options = {}){
        this.namespaces = options.namespaces || [];
        this.domParser = new DOMParser();
        this.domConverter = new DomConverter(document, {
            renderingMode: 'data'
        });
        this.htmlWriter = new BasicHtmlWriter();
    }
    /**
	 * Converts the provided {@link module:engine/view/documentfragment~DocumentFragment document fragment}
	 * to data format &ndash; in this case an XML string.
	 *
	 * @returns An XML string.
	 */ toData(viewFragment) {
        // Convert view DocumentFragment to DOM DocumentFragment.
        const domFragment = this.domConverter.viewToDom(viewFragment);
        // Convert DOM DocumentFragment to XML output.
        // There is no need to use dedicated for XML serializing method because BasicHtmlWriter works well in this case.
        return this.htmlWriter.getHtml(domFragment);
    }
    /**
	 * Converts the provided XML string to a view tree.
	 *
	 * @param data An XML string.
	 * @returns A converted view element.
	 */ toView(data) {
        // Convert input XML data to DOM DocumentFragment.
        const domFragment = this._toDom(data);
        // Convert DOM DocumentFragment to view DocumentFragment.
        return this.domConverter.domToView(domFragment, {
            keepOriginalCase: true,
            skipComments: this.skipComments
        });
    }
    /**
	 * Registers a {@link module:engine/view/matcher~MatcherPattern} for view elements whose content should be treated as raw data
	 * and not processed during the conversion from XML to view elements.
	 *
	 * The raw data can be later accessed by a
	 * {@link module:engine/view/element~Element#getCustomProperty custom property of a view element} called `"$rawContent"`.
	 *
	 * @param pattern Pattern matching all view elements whose content should be treated as raw data.
	 */ registerRawContentMatcher(pattern) {
        this.domConverter.registerRawContentMatcher(pattern);
    }
    /**
	 * If the processor is set to use marked fillers, it will insert `&nbsp;` fillers wrapped in `<span>` elements
	 * (`<span data-cke-filler="true">&nbsp;</span>`) instead of regular `&nbsp;` characters.
	 *
	 * This mode allows for a more precise handling of block fillers (so they do not leak into editor content) but
	 * bloats the editor data with additional markup.
	 *
	 * This mode may be required by some features and will be turned on by them automatically.
	 *
	 * @param type Whether to use the default or the marked `&nbsp;` block fillers.
	 */ useFillerType(type) {
        this.domConverter.blockFillerMode = type == 'marked' ? 'markedNbsp' : 'nbsp';
    }
    /**
	 * Converts an XML string to its DOM representation. Returns a document fragment containing nodes parsed from
	 * the provided data.
	 */ _toDom(data) {
        // Stringify namespaces.
        const namespaces = this.namespaces.map((nsp)=>`xmlns:${nsp}="nsp"`).join(' ');
        // Wrap data into root element with optional namespace definitions.
        data = `<xml ${namespaces}>${data}</xml>`;
        const parsedDocument = this.domParser.parseFromString(data, 'text/xml');
        // Parse validation.
        const parserError = parsedDocument.querySelector('parsererror');
        if (parserError) {
            throw new Error('Parse error - ' + parserError.textContent);
        }
        const fragment = parsedDocument.createDocumentFragment();
        const nodes = parsedDocument.documentElement.childNodes;
        while(nodes.length > 0){
            fragment.appendChild(nodes[0]);
        }
        return fragment;
    }
}

/**
 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */ /* eslint-disable @typescript-eslint/no-unused-vars */ /**
 * @module engine/model/operation/operation
 */ /**
 * Abstract base operation class.
 */ class Operation {
    /**
	 * {@link module:engine/model/document~Document#version} on which operation can be applied. If you try to
	 * {@link module:engine/model/model~Model#applyOperation apply} operation with different base version than the
	 * {@link module:engine/model/document~Document#version document version} the
	 * {@link module:utils/ckeditorerror~CKEditorError model-document-applyOperation-wrong-version} error is thrown.
	 */ baseVersion;
    /**
	 * Defines whether operation is executed on attached or detached {@link module:engine/model/item~Item items}.
	 */ isDocumentOperation;
    /**
	 * {@link module:engine/model/batch~Batch Batch} to which the operation is added or `null` if the operation is not
	 * added to any batch yet.
	 */ batch;
    /**
	 * Base operation constructor.
	 *
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation
	 * can be applied or `null` if the operation operates on detached (non-document) tree.
	 */ constructor(baseVersion){
        this.baseVersion = baseVersion;
        this.isDocumentOperation = this.baseVersion !== null;
        this.batch = null;
    }
    /**
	 * Checks whether the operation's parameters are correct and the operation can be correctly executed. Throws
	 * an error if operation is not valid.
	 *
	 * @internal
	 */ _validate() {}
    /**
	 * Custom toJSON method to solve child-parent circular dependencies.
	 *
	 * @returns Clone of this object with the operation property replaced with string.
	 */ toJSON() {
        // This method creates only a shallow copy, all nested objects should be defined separately.
        // See https://github.com/ckeditor/ckeditor5-engine/issues/1477.
        const json = Object.assign({}, this);
        json.__className = this.constructor.className;
        // Remove reference to the parent `Batch` to avoid circular dependencies.
        delete json.batch;
        // Only document operations are shared with other clients so it is not necessary to keep this information.
        delete json.isDocumentOperation;
        return json;
    }
    /**
	 * Name of the operation class used for serialization.
	 */ static get className() {
        return 'Operation';
    }
    /**
	 * Creates `Operation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param doc Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        return new this(json.baseVersion);
    }
}

/**
 * Inserts given nodes at given position.
 *
 * @internal
 * @param position Position at which nodes should be inserted.
 * @param normalizedNodes Nodes to insert.
 * @returns Range spanning over inserted elements.
 */ function _insert(position, nodes) {
    const normalizedNodes = _normalizeNodes(nodes);
    // We have to count offset before inserting nodes because they can get merged and we would get wrong offsets.
    const offset = normalizedNodes.reduce((sum, node)=>sum + node.offsetSize, 0);
    const parent = position.parent;
    // Insertion might be in a text node, we should split it if that's the case.
    _splitNodeAtPosition(position);
    const index = position.index;
    // Insert nodes at given index. After splitting we have a proper index and insertion is between nodes,
    // using basic `Element` API.
    parent._insertChild(index, normalizedNodes);
    // Merge text nodes, if possible. Merging is needed only at points where inserted nodes "touch" "old" nodes.
    _mergeNodesAtIndex(parent, index + normalizedNodes.length);
    _mergeNodesAtIndex(parent, index);
    return new Range(position, position.getShiftedBy(offset));
}
/**
 * Removed nodes in given range. Only {@link module:engine/model/range~Range#isFlat flat} ranges are accepted.
 *
 * @internal
 * @param range Range containing nodes to remove.
 */ function _remove(range) {
    if (!range.isFlat) {
        /**
		 * Trying to remove a range which starts and ends in different element.
		 *
		 * @error operation-utils-remove-range-not-flat
		 */ throw new CKEditorError('operation-utils-remove-range-not-flat', this);
    }
    const parent = range.start.parent;
    // Range may be inside text nodes, we have to split them if that's the case.
    _splitNodeAtPosition(range.start);
    _splitNodeAtPosition(range.end);
    // Remove the text nodes using basic `Element` API.
    const removed = parent._removeChildren(range.start.index, range.end.index - range.start.index);
    // Merge text nodes, if possible. After some nodes were removed, node before and after removed range will be
    // touching at the position equal to the removed range beginning. We check merging possibility there.
    _mergeNodesAtIndex(parent, range.start.index);
    return removed;
}
/**
 * Moves nodes in given range to given target position. Only {@link module:engine/model/range~Range#isFlat flat} ranges are accepted.
 *
 * @internal
 * @param sourceRange Range containing nodes to move.
 * @param targetPosition Position to which nodes should be moved.
 * @returns Range containing moved nodes.
 */ function _move(sourceRange, targetPosition) {
    if (!sourceRange.isFlat) {
        /**
		 * Trying to move a range which starts and ends in different element.
		 *
		 * @error operation-utils-move-range-not-flat
		 */ throw new CKEditorError('operation-utils-move-range-not-flat', this);
    }
    const nodes = _remove(sourceRange);
    // We have to fix `targetPosition` because model changed after nodes from `sourceRange` got removed and
    // that change might have an impact on `targetPosition`.
    targetPosition = targetPosition._getTransformedByDeletion(sourceRange.start, sourceRange.end.offset - sourceRange.start.offset);
    return _insert(targetPosition, nodes);
}
/**
 * Sets given attribute on nodes in given range. The attributes are only set on top-level nodes of the range, not on its children.
 *
 * @internal
 * @param range Range containing nodes that should have the attribute set. Must be a flat range.
 * @param key Key of attribute to set.
 * @param value Attribute value.
 */ function _setAttribute(range, key, value) {
    // Range might start or end in text nodes, so we have to split them.
    _splitNodeAtPosition(range.start);
    _splitNodeAtPosition(range.end);
    // Iterate over all items in the range.
    for (const item of range.getItems({
        shallow: true
    })){
        // Iterator will return `TextProxy` instances but we know that those text proxies will
        // always represent full text nodes (this is guaranteed thanks to splitting we did before).
        // So, we can operate on those text proxies' text nodes.
        const node = item.is('$textProxy') ? item.textNode : item;
        if (value !== null) {
            node._setAttribute(key, value);
        } else {
            node._removeAttribute(key);
        }
        // After attributes changing it may happen that some text nodes can be merged. Try to merge with previous node.
        _mergeNodesAtIndex(node.parent, node.index);
    }
    // Try to merge last changed node with it's previous sibling (not covered by the loop above).
    _mergeNodesAtIndex(range.end.parent, range.end.index);
}
/**
 * Normalizes given object or an array of objects to an array of {@link module:engine/model/node~Node nodes}. See
 * {@link ~NodeSet NodeSet} for details on how normalization is performed.
 *
 * @internal
 * @param nodes Objects to normalize.
 * @returns Normalized nodes.
 */ function _normalizeNodes(nodes) {
    const normalized = [];
    function convert(nodes) {
        if (typeof nodes == 'string') {
            normalized.push(new Text(nodes));
        } else if (nodes instanceof TextProxy) {
            normalized.push(new Text(nodes.data, nodes.getAttributes()));
        } else if (nodes instanceof Node$1) {
            normalized.push(nodes);
        } else if (isIterable(nodes)) {
            for (const node of nodes){
                convert(node);
            }
        } else ;
    }
    convert(nodes);
    // Merge text nodes.
    for(let i = 1; i < normalized.length; i++){
        const node = normalized[i];
        const prev = normalized[i - 1];
        if (node instanceof Text && prev instanceof Text && _haveSameAttributes(node, prev)) {
            // Doing this instead changing `prev.data` because `data` is readonly.
            normalized.splice(i - 1, 2, new Text(prev.data + node.data, prev.getAttributes()));
            i--;
        }
    }
    return normalized;
}
/**
 * Checks if nodes before and after given index in given element are {@link module:engine/model/text~Text text nodes} and
 * merges them into one node if they have same attributes.
 *
 * Merging is done by removing two text nodes and inserting a new text node containing data from both merged text nodes.
 *
 * @param element Parent element of nodes to merge.
 * @param index Index between nodes to merge.
 */ function _mergeNodesAtIndex(element, index) {
    const nodeBefore = element.getChild(index - 1);
    const nodeAfter = element.getChild(index);
    // Check if both of those nodes are text objects with same attributes.
    if (nodeBefore && nodeAfter && nodeBefore.is('$text') && nodeAfter.is('$text') && _haveSameAttributes(nodeBefore, nodeAfter)) {
        // Append text of text node after index to the before one.
        const mergedNode = new Text(nodeBefore.data + nodeAfter.data, nodeBefore.getAttributes());
        // Remove separate text nodes.
        element._removeChildren(index - 1, 2);
        // Insert merged text node.
        element._insertChild(index - 1, mergedNode);
    }
}
/**
 * Checks if given position is in a text node, and if so, splits the text node in two text nodes, each of them
 * containing a part of original text node.
 *
 * @param position Position at which node should be split.
 */ function _splitNodeAtPosition(position) {
    const textNode = position.textNode;
    const element = position.parent;
    if (textNode) {
        const offsetDiff = position.offset - textNode.startOffset;
        const index = textNode.index;
        element._removeChildren(index, 1);
        const firstPart = new Text(textNode.data.substr(0, offsetDiff), textNode.getAttributes());
        const secondPart = new Text(textNode.data.substr(offsetDiff), textNode.getAttributes());
        element._insertChild(index, [
            firstPart,
            secondPart
        ]);
    }
}
/**
 * Checks whether two given nodes have same attributes.
 *
 * @param nodeA Node to check.
 * @param nodeB Node to check.
 * @returns `true` if nodes have same attributes, `false` otherwise.
 */ function _haveSameAttributes(nodeA, nodeB) {
    const iteratorA = nodeA.getAttributes();
    const iteratorB = nodeB.getAttributes();
    for (const attr of iteratorA){
        if (attr[1] !== nodeB.getAttribute(attr[0])) {
            return false;
        }
        iteratorB.next();
    }
    return iteratorB.next().done;
}

// @if CK_DEBUG_ENGINE // const ModelRange = require( '../range' ).default;
/**
 * Operation to move a range of {@link module:engine/model/item~Item model items}
 * to given {@link module:engine/model/position~Position target position}.
 */ class MoveOperation extends Operation {
    /**
	 * Position before the first {@link module:engine/model/item~Item model item} to move.
	 */ sourcePosition;
    /**
	 * Offset size of moved range.
	 */ howMany;
    /**
	 * Position at which moved nodes will be inserted.
	 */ targetPosition;
    /**
	 * Creates a move operation.
	 *
	 * @param sourcePosition Position before the first {@link module:engine/model/item~Item model item} to move.
	 * @param howMany Offset size of moved range. Moved range will start from `sourcePosition` and end at
	 * `sourcePosition` with offset shifted by `howMany`.
	 * @param targetPosition Position at which moved nodes will be inserted.
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation
	 * can be applied or `null` if the operation operates on detached (non-document) tree.
	 */ constructor(sourcePosition, howMany, targetPosition, baseVersion){
        super(baseVersion);
        this.sourcePosition = sourcePosition.clone();
        // `'toNext'` because `sourcePosition` is a bit like a start of the moved range.
        this.sourcePosition.stickiness = 'toNext';
        this.howMany = howMany;
        this.targetPosition = targetPosition.clone();
        this.targetPosition.stickiness = 'toNone';
    }
    /**
	 * @inheritDoc
	 */ get type() {
        if (this.targetPosition.root.rootName == '$graveyard') {
            return 'remove';
        } else if (this.sourcePosition.root.rootName == '$graveyard') {
            return 'reinsert';
        }
        return 'move';
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        return [
            Range._createFromPositionAndShift(this.sourcePosition, this.howMany),
            Range._createFromPositionAndShift(this.targetPosition, 0)
        ];
    }
    /**
	 * Creates and returns an operation that has the same parameters as this operation.
	 */ clone() {
        return new MoveOperation(this.sourcePosition, this.howMany, this.targetPosition, this.baseVersion);
    }
    /**
	 * Returns the start position of the moved range after it got moved. This may be different than
	 * {@link module:engine/model/operation/moveoperation~MoveOperation#targetPosition} in some cases, i.e. when a range is moved
	 * inside the same parent but {@link module:engine/model/operation/moveoperation~MoveOperation#targetPosition targetPosition}
	 * is after {@link module:engine/model/operation/moveoperation~MoveOperation#sourcePosition sourcePosition}.
	 *
	 * ```
	 *  vv              vv
	 * abcdefg ===> adefbcg
	 *      ^          ^
	 *      targetPos  movedRangeStart
	 *      offset 6   offset 4
	 *```
	 */ getMovedRangeStart() {
        return this.targetPosition._getTransformedByDeletion(this.sourcePosition, this.howMany);
    }
    /**
	 * See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
	 */ getReversed() {
        const newTargetPosition = this.sourcePosition._getTransformedByInsertion(this.targetPosition, this.howMany);
        return new MoveOperation(this.getMovedRangeStart(), this.howMany, newTargetPosition, this.baseVersion + 1);
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _validate() {
        const sourceElement = this.sourcePosition.parent;
        const targetElement = this.targetPosition.parent;
        const sourceOffset = this.sourcePosition.offset;
        const targetOffset = this.targetPosition.offset;
        // Validate whether move operation has correct parameters.
        // Validation is pretty complex but move operation is one of the core ways to manipulate the document state.
        // We expect that many errors might be connected with one of scenarios described below.
        if (sourceOffset + this.howMany > sourceElement.maxOffset) {
            /**
			 * The nodes which should be moved do not exist.
			 *
			 * @error move-operation-nodes-do-not-exist
			 */ throw new CKEditorError('move-operation-nodes-do-not-exist', this);
        } else if (sourceElement === targetElement && sourceOffset < targetOffset && targetOffset < sourceOffset + this.howMany) {
            /**
			 * Trying to move a range of nodes into the middle of that range.
			 *
			 * @error move-operation-range-into-itself
			 */ throw new CKEditorError('move-operation-range-into-itself', this);
        } else if (this.sourcePosition.root == this.targetPosition.root) {
            if (compareArrays(this.sourcePosition.getParentPath(), this.targetPosition.getParentPath()) == 'prefix') {
                const i = this.sourcePosition.path.length - 1;
                if (this.targetPosition.path[i] >= sourceOffset && this.targetPosition.path[i] < sourceOffset + this.howMany) {
                    /**
					 * Trying to move a range of nodes into one of nodes from that range.
					 *
					 * @error move-operation-node-into-itself
					 */ throw new CKEditorError('move-operation-node-into-itself', this);
                }
            }
        }
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _execute() {
        _move(Range._createFromPositionAndShift(this.sourcePosition, this.howMany), this.targetPosition);
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        const json = super.toJSON();
        json.sourcePosition = this.sourcePosition.toJSON();
        json.targetPosition = this.targetPosition.toJSON();
        return json;
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'MoveOperation';
    }
    /**
	 * Creates `MoveOperation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        const sourcePosition = Position.fromJSON(json.sourcePosition, document);
        const targetPosition = Position.fromJSON(json.targetPosition, document);
        return new this(sourcePosition, json.howMany, targetPosition, json.baseVersion);
    }
}

/**
 * Operation to insert one or more nodes at given position in the model.
 */ class InsertOperation extends Operation {
    /**
	 * Position of insertion.
	 *
	 * @readonly
	 */ position;
    /**
	 * List of nodes to insert.
	 *
	 * @readonly
	 */ nodes;
    /**
	 * Flag deciding how the operation should be transformed. If set to `true`, nodes might get additional attributes
	 * during operational transformation. This happens when the operation insertion position is inside of a range
	 * where attributes have changed.
	 */ shouldReceiveAttributes;
    /**
	 * Creates an insert operation.
	 *
	 * @param position Position of insertion.
	 * @param nodes The list of nodes to be inserted.
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation
	 * can be applied or `null` if the operation operates on detached (non-document) tree.
	 */ constructor(position, nodes, baseVersion){
        super(baseVersion);
        this.position = position.clone();
        this.position.stickiness = 'toNone';
        this.nodes = new NodeList(_normalizeNodes(nodes));
        this.shouldReceiveAttributes = false;
    }
    /**
	 * @inheritDoc
	 */ get type() {
        return 'insert';
    }
    /**
	 * Total offset size of inserted nodes.
	 */ get howMany() {
        return this.nodes.maxOffset;
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        return this.position.clone();
    }
    /**
	 * Creates and returns an operation that has the same parameters as this operation.
	 */ clone() {
        const nodes = new NodeList([
            ...this.nodes
        ].map((node)=>node._clone(true)));
        const insert = new InsertOperation(this.position, nodes, this.baseVersion);
        insert.shouldReceiveAttributes = this.shouldReceiveAttributes;
        return insert;
    }
    /**
	 * See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
	 */ getReversed() {
        const graveyard = this.position.root.document.graveyard;
        const gyPosition = new Position(graveyard, [
            0
        ]);
        return new MoveOperation(this.position, this.nodes.maxOffset, gyPosition, this.baseVersion + 1);
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _validate() {
        const targetElement = this.position.parent;
        if (!targetElement || targetElement.maxOffset < this.position.offset) {
            /**
			 * Insertion position is invalid.
			 *
			 * @error insert-operation-position-invalid
			 */ throw new CKEditorError('insert-operation-position-invalid', this);
        }
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _execute() {
        // What happens here is that we want original nodes be passed to writer because we want original nodes
        // to be inserted to the model. But in InsertOperation, we want to keep those nodes as they were added
        // to the operation, not modified. For example, text nodes can get merged or cropped while Elements can
        // get children. It is important that InsertOperation has the copy of original nodes in intact state.
        const originalNodes = this.nodes;
        this.nodes = new NodeList([
            ...originalNodes
        ].map((node)=>node._clone(true)));
        _insert(this.position, originalNodes);
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        const json = super.toJSON();
        json.position = this.position.toJSON();
        json.nodes = this.nodes.toJSON();
        return json;
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'InsertOperation';
    }
    /**
	 * Creates `InsertOperation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        const children = [];
        for (const child of json.nodes){
            if (child.name) {
                // If child has name property, it is an Element.
                children.push(Element.fromJSON(child));
            } else {
                // Otherwise, it is a Text node.
                children.push(Text.fromJSON(child));
            }
        }
        const insert = new InsertOperation(Position.fromJSON(json.position, document), children, json.baseVersion);
        insert.shouldReceiveAttributes = json.shouldReceiveAttributes;
        return insert;
    }
}

/**
 * Operation to split {@link module:engine/model/element~Element an element} at given
 * {@link module:engine/model/operation/splitoperation~SplitOperation#splitPosition split position} into two elements,
 * both containing a part of the element's original content.
 */ class SplitOperation extends Operation {
    /**
	 * Position at which an element should be split.
	 */ splitPosition;
    /**
	 * Total offset size of elements that are in the split element after `position`.
	 */ howMany;
    /**
	 * Position at which the clone of split element (or element from graveyard) will be inserted.
	 */ insertionPosition;
    /**
	 * Position in the graveyard root before the element which should be used as a parent of the nodes after `position`.
	 * If it is not set, a copy of the the `position` parent will be used.
	 *
	 * The default behavior is to clone the split element. Element from graveyard is used during undo.
	 */ graveyardPosition;
    /**
	 * Creates a split operation.
	 *
	 * @param splitPosition Position at which an element should be split.
	 * @param howMany Total offset size of elements that are in the split element after `position`.
	 * @param insertionPosition Position at which the clone of split element (or element from graveyard) will be inserted.
	 * @param graveyardPosition Position in the graveyard root before the element which
	 * should be used as a parent of the nodes after `position`. If it is not set, a copy of the the `position` parent will be used.
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation
	 * can be applied or `null` if the operation operates on detached (non-document) tree.
	 */ constructor(splitPosition, howMany, insertionPosition, graveyardPosition, baseVersion){
        super(baseVersion);
        this.splitPosition = splitPosition.clone();
        // Keep position sticking to the next node. This way any new content added at the place where the element is split
        // will be left in the original element.
        this.splitPosition.stickiness = 'toNext';
        this.howMany = howMany;
        this.insertionPosition = insertionPosition;
        this.graveyardPosition = graveyardPosition ? graveyardPosition.clone() : null;
        if (this.graveyardPosition) {
            this.graveyardPosition.stickiness = 'toNext';
        }
    }
    /**
	 * @inheritDoc
	 */ get type() {
        return 'split';
    }
    /**
	 * Position inside the new clone of a split element.
	 *
	 * This is a position where nodes that are after the split position will be moved to.
	 */ get moveTargetPosition() {
        const path = this.insertionPosition.path.slice();
        path.push(0);
        return new Position(this.insertionPosition.root, path);
    }
    /**
	 * Artificial range that contains all the nodes from the split element that will be moved to the new element.
	 * The range starts at {@link #splitPosition} and ends in the same parent, at `POSITIVE_INFINITY` offset.
	 */ get movedRange() {
        const end = this.splitPosition.getShiftedBy(Number.POSITIVE_INFINITY);
        return new Range(this.splitPosition, end);
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        // These could be positions but `Selectable` type only supports `Iterable<Range>`.
        const ranges = [
            Range._createFromPositionAndShift(this.splitPosition, 0),
            Range._createFromPositionAndShift(this.insertionPosition, 0)
        ];
        if (this.graveyardPosition) {
            ranges.push(Range._createFromPositionAndShift(this.graveyardPosition, 0));
        }
        return ranges;
    }
    /**
	 * Creates and returns an operation that has the same parameters as this operation.
	 *
	 * @returns Clone of this operation.
	 */ clone() {
        return new SplitOperation(this.splitPosition, this.howMany, this.insertionPosition, this.graveyardPosition, this.baseVersion);
    }
    /**
	 * See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
	 */ getReversed() {
        const graveyard = this.splitPosition.root.document.graveyard;
        const graveyardPosition = new Position(graveyard, [
            0
        ]);
        return new MergeOperation(this.moveTargetPosition, this.howMany, this.splitPosition, graveyardPosition, this.baseVersion + 1);
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _validate() {
        const element = this.splitPosition.parent;
        const offset = this.splitPosition.offset;
        // Validate whether split operation has correct parameters.
        if (!element || element.maxOffset < offset) {
            /**
			 * Split position is invalid.
			 *
			 * @error split-operation-position-invalid
			 */ throw new CKEditorError('split-operation-position-invalid', this);
        } else if (!element.parent) {
            /**
			 * Cannot split root element.
			 *
			 * @error split-operation-split-in-root
			 */ throw new CKEditorError('split-operation-split-in-root', this);
        } else if (this.howMany != element.maxOffset - this.splitPosition.offset) {
            /**
			 * Split operation specifies wrong number of nodes to move.
			 *
			 * @error split-operation-how-many-invalid
			 */ throw new CKEditorError('split-operation-how-many-invalid', this);
        } else if (this.graveyardPosition && !this.graveyardPosition.nodeAfter) {
            /**
			 * Graveyard position invalid.
			 *
			 * @error split-operation-graveyard-position-invalid
			 */ throw new CKEditorError('split-operation-graveyard-position-invalid', this);
        }
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _execute() {
        const splitElement = this.splitPosition.parent;
        if (this.graveyardPosition) {
            _move(Range._createFromPositionAndShift(this.graveyardPosition, 1), this.insertionPosition);
        } else {
            const newElement = splitElement._clone();
            _insert(this.insertionPosition, newElement);
        }
        const sourceRange = new Range(Position._createAt(splitElement, this.splitPosition.offset), Position._createAt(splitElement, splitElement.maxOffset));
        _move(sourceRange, this.moveTargetPosition);
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        const json = super.toJSON();
        json.splitPosition = this.splitPosition.toJSON();
        json.insertionPosition = this.insertionPosition.toJSON();
        if (this.graveyardPosition) {
            json.graveyardPosition = this.graveyardPosition.toJSON();
        }
        return json;
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'SplitOperation';
    }
    /**
	 * Helper function that returns a default insertion position basing on given `splitPosition`. The default insertion
	 * position is after the split element.
	 */ static getInsertionPosition(splitPosition) {
        const path = splitPosition.path.slice(0, -1);
        path[path.length - 1]++;
        return new Position(splitPosition.root, path, 'toPrevious');
    }
    /**
	 * Creates `SplitOperation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        const splitPosition = Position.fromJSON(json.splitPosition, document);
        const insertionPosition = Position.fromJSON(json.insertionPosition, document);
        const graveyardPosition = json.graveyardPosition ? Position.fromJSON(json.graveyardPosition, document) : null;
        return new this(splitPosition, json.howMany, insertionPosition, graveyardPosition, json.baseVersion);
    }
}

/**
 * Operation to merge two {@link module:engine/model/element~Element elements}.
 *
 * The merged element is the parent of {@link ~MergeOperation#sourcePosition} and it is merged into the parent of
 * {@link ~MergeOperation#targetPosition}. All nodes from the merged element are moved to {@link ~MergeOperation#targetPosition}.
 *
 * The merged element is moved to the graveyard at {@link ~MergeOperation#graveyardPosition}.
 */ class MergeOperation extends Operation {
    /**
	 * Position inside the merged element. All nodes from that element after that position will be moved to {@link #targetPosition}.
	 */ sourcePosition;
    /**
	 * Summary offset size of nodes which will be moved from the merged element to the new parent.
	 */ howMany;
    /**
	 * Position which the nodes from the merged elements will be moved to.
	 */ targetPosition;
    /**
	 * Position in graveyard to which the merged element will be moved.
	 */ graveyardPosition;
    /**
	 * Creates a merge operation.
	 *
	 * @param sourcePosition Position inside the merged element. All nodes from that
	 * element after that position will be moved to {@link #targetPosition}.
	 * @param howMany Summary offset size of nodes which will be moved from the merged element to the new parent.
	 * @param targetPosition Position which the nodes from the merged elements will be moved to.
	 * @param graveyardPosition Position in graveyard to which the merged element will be moved.
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation
	 * can be applied or `null` if the operation operates on detached (non-document) tree.
	 */ constructor(sourcePosition, howMany, targetPosition, graveyardPosition, baseVersion){
        super(baseVersion);
        this.sourcePosition = sourcePosition.clone();
        // This is, and should always remain, the first position in its parent.
        this.sourcePosition.stickiness = 'toPrevious';
        this.howMany = howMany;
        this.targetPosition = targetPosition.clone();
        // Except of a rare scenario in `MergeOperation` x `MergeOperation` transformation,
        // this is, and should always remain, the last position in its parent.
        this.targetPosition.stickiness = 'toNext';
        this.graveyardPosition = graveyardPosition.clone();
    }
    /**
	 * @inheritDoc
	 */ get type() {
        return 'merge';
    }
    /**
	 * Position before the merged element (which will be deleted).
	 */ get deletionPosition() {
        return new Position(this.sourcePosition.root, this.sourcePosition.path.slice(0, -1));
    }
    /**
	 * Artificial range that contains all the nodes from the merged element that will be moved to {@link ~MergeOperation#sourcePosition}.
	 * The range starts at {@link ~MergeOperation#sourcePosition} and ends in the same parent, at `POSITIVE_INFINITY` offset.
	 */ get movedRange() {
        const end = this.sourcePosition.getShiftedBy(Number.POSITIVE_INFINITY);
        return new Range(this.sourcePosition, end);
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        const mergedElement = this.sourcePosition.parent;
        return [
            Range._createOn(mergedElement),
            // These could be positions but `Selectable` type only supports `Iterable<Range>`.
            Range._createFromPositionAndShift(this.targetPosition, 0),
            Range._createFromPositionAndShift(this.graveyardPosition, 0)
        ];
    }
    /**
	 * Creates and returns an operation that has the same parameters as this operation.
	 */ clone() {
        return new MergeOperation(this.sourcePosition, this.howMany, this.targetPosition, this.graveyardPosition, this.baseVersion);
    }
    /**
	 * See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
	 */ getReversed() {
        // Positions in this method are transformed by this merge operation because the split operation bases on
        // the context after this merge operation happened (because split operation reverses it).
        // So we need to acknowledge that the merge operation happened and those positions changed a little.
        const targetPosition = this.targetPosition._getTransformedByMergeOperation(this);
        const path = this.sourcePosition.path.slice(0, -1);
        const insertionPosition = new Position(this.sourcePosition.root, path)._getTransformedByMergeOperation(this);
        return new SplitOperation(targetPosition, this.howMany, insertionPosition, this.graveyardPosition, this.baseVersion + 1);
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _validate() {
        const sourceElement = this.sourcePosition.parent;
        const targetElement = this.targetPosition.parent;
        // Validate whether merge operation has correct parameters.
        if (!sourceElement.parent) {
            /**
			 * Merge source position is invalid. The element to be merged must have a parent node.
			 *
			 * @error merge-operation-source-position-invalid
			 */ throw new CKEditorError('merge-operation-source-position-invalid', this);
        } else if (!targetElement.parent) {
            /**
			 * Merge target position is invalid. The element to be merged must have a parent node.
			 *
			 * @error merge-operation-target-position-invalid
			 */ throw new CKEditorError('merge-operation-target-position-invalid', this);
        } else if (this.howMany != sourceElement.maxOffset) {
            /**
			 * Merge operation specifies wrong number of nodes to move.
			 *
			 * @error merge-operation-how-many-invalid
			 */ throw new CKEditorError('merge-operation-how-many-invalid', this);
        }
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _execute() {
        const mergedElement = this.sourcePosition.parent;
        const sourceRange = Range._createIn(mergedElement);
        _move(sourceRange, this.targetPosition);
        _move(Range._createOn(mergedElement), this.graveyardPosition);
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        const json = super.toJSON();
        json.sourcePosition = json.sourcePosition.toJSON();
        json.targetPosition = json.targetPosition.toJSON();
        json.graveyardPosition = json.graveyardPosition.toJSON();
        return json;
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'MergeOperation';
    }
    /**
	 * Creates `MergeOperation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        const sourcePosition = Position.fromJSON(json.sourcePosition, document);
        const targetPosition = Position.fromJSON(json.targetPosition, document);
        const graveyardPosition = Position.fromJSON(json.graveyardPosition, document);
        return new this(sourcePosition, json.howMany, targetPosition, graveyardPosition, json.baseVersion);
    }
}

class MarkerOperation extends Operation {
    /**
	 * Marker name.
	 *
	 * @readonly
	 */ name;
    /**
	 * Marker range before the change.
	 *
	 * @readonly
	 */ oldRange;
    /**
	 * Marker range after the change.
	 *
	 * @readonly
	 */ newRange;
    /**
	 * Specifies whether the marker operation affects the data produced by the data pipeline
	 * (is persisted in the editor's data).
	 *
	 * @readonly
	 */ affectsData;
    /**
	 * Marker collection on which change should be executed.
	 */ _markers;
    /**
	 * @param name Marker name.
	 * @param oldRange Marker range before the change.
	 * @param newRange Marker range after the change.
	 * @param markers Marker collection on which change should be executed.
	 * @param affectsData Specifies whether the marker operation affects the data produced by the data pipeline
	 * (is persisted in the editor's data).
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation
	 * can be applied or `null` if the operation operates on detached (non-document) tree.
	 */ constructor(name, oldRange, newRange, markers, affectsData, baseVersion){
        super(baseVersion);
        this.name = name;
        this.oldRange = oldRange ? oldRange.clone() : null;
        this.newRange = newRange ? newRange.clone() : null;
        this.affectsData = affectsData;
        this._markers = markers;
    }
    /**
	 * @inheritDoc
	 */ get type() {
        return 'marker';
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        const ranges = [];
        if (this.oldRange) {
            ranges.push(this.oldRange.clone());
        }
        if (this.newRange) {
            if (this.oldRange) {
                ranges.push(...this.newRange.getDifference(this.oldRange));
            } else {
                ranges.push(this.newRange.clone());
            }
        }
        return ranges;
    }
    /**
	 * Creates and returns an operation that has the same parameters as this operation.
	 */ clone() {
        return new MarkerOperation(this.name, this.oldRange, this.newRange, this._markers, this.affectsData, this.baseVersion);
    }
    /**
	 * See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
	 */ getReversed() {
        return new MarkerOperation(this.name, this.newRange, this.oldRange, this._markers, this.affectsData, this.baseVersion + 1);
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _execute() {
        if (this.newRange) {
            this._markers._set(this.name, this.newRange, true, this.affectsData);
        } else {
            this._markers._remove(this.name);
        }
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ toJSON() {
        const json = super.toJSON();
        if (this.oldRange) {
            json.oldRange = this.oldRange.toJSON();
        }
        if (this.newRange) {
            json.newRange = this.newRange.toJSON();
        }
        delete json._markers;
        return json;
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'MarkerOperation';
    }
    /**
	 * Creates `MarkerOperation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        return new MarkerOperation(json.name, json.oldRange ? Range.fromJSON(json.oldRange, document) : null, json.newRange ? Range.fromJSON(json.newRange, document) : null, document.model.markers, json.affectsData, json.baseVersion);
    }
}

/**
 * Operation to change nodes' attribute.
 *
 * Using this class you can add, remove or change value of the attribute.
 */ class AttributeOperation extends Operation {
    /**
	 * Range on which operation should be applied.
	 *
	 * @readonly
	 */ range;
    /**
	 * Key of an attribute to change or remove.
	 *
	 * @readonly
	 */ key;
    /**
	 * Old value of the attribute with given key or `null`, if attribute was not set before.
	 *
	 * @readonly
	 */ oldValue;
    /**
	 * New value of the attribute with given key or `null`, if operation should remove attribute.
	 *
	 * @readonly
	 */ newValue;
    /**
	 * Creates an operation that changes, removes or adds attributes.
	 *
	 * If only `newValue` is set, attribute will be added on a node. Note that all nodes in operation's range must not
	 * have an attribute with the same key as the added attribute.
	 *
	 * If only `oldValue` is set, then attribute with given key will be removed. Note that all nodes in operation's range
	 * must have an attribute with that key added.
	 *
	 * If both `newValue` and `oldValue` are set, then the operation will change the attribute value. Note that all nodes in
	 * operation's ranges must already have an attribute with given key and `oldValue` as value
	 *
	 * @param range Range on which the operation should be applied. Must be a flat range.
	 * @param key Key of an attribute to change or remove.
	 * @param oldValue Old value of the attribute with given key or `null`, if attribute was not set before.
	 * @param newValue New value of the attribute with given key or `null`, if operation should remove attribute.
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation
	 * can be applied or `null` if the operation operates on detached (non-document) tree.
	 */ constructor(range, key, oldValue, newValue, baseVersion){
        super(baseVersion);
        this.range = range.clone();
        this.key = key;
        this.oldValue = oldValue === undefined ? null : oldValue;
        this.newValue = newValue === undefined ? null : newValue;
    }
    /**
	 * @inheritDoc
	 */ get type() {
        if (this.oldValue === null) {
            return 'addAttribute';
        } else if (this.newValue === null) {
            return 'removeAttribute';
        } else {
            return 'changeAttribute';
        }
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        return this.range.clone();
    }
    /**
	 * Creates and returns an operation that has the same parameters as this operation.
	 */ clone() {
        return new AttributeOperation(this.range, this.key, this.oldValue, this.newValue, this.baseVersion);
    }
    /**
	 * See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
	 */ getReversed() {
        return new AttributeOperation(this.range, this.key, this.newValue, this.oldValue, this.baseVersion + 1);
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        const json = super.toJSON();
        json.range = this.range.toJSON();
        return json;
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _validate() {
        if (!this.range.isFlat) {
            /**
			 * The range to change is not flat.
			 *
			 * @error attribute-operation-range-not-flat
			 */ throw new CKEditorError('attribute-operation-range-not-flat', this);
        }
        for (const item of this.range.getItems({
            shallow: true
        })){
            if (this.oldValue !== null && !isEqual(item.getAttribute(this.key), this.oldValue)) {
                /**
				 * Changed node has different attribute value than operation's old attribute value.
				 *
				 * @error attribute-operation-wrong-old-value
				 * @param item
				 * @param key
				 * @param value
				 */ throw new CKEditorError('attribute-operation-wrong-old-value', this, {
                    item,
                    key: this.key,
                    value: this.oldValue
                });
            }
            if (this.oldValue === null && this.newValue !== null && item.hasAttribute(this.key)) {
                /**
				 * The attribute with given key already exists for the given node.
				 *
				 * @error attribute-operation-attribute-exists
				 * @param node
				 * @param key
				 */ throw new CKEditorError('attribute-operation-attribute-exists', this, {
                    node: item,
                    key: this.key
                });
            }
        }
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _execute() {
        // If value to set is same as old value, don't do anything.
        if (!isEqual(this.oldValue, this.newValue)) {
            // Execution.
            _setAttribute(this.range, this.key, this.newValue);
        }
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'AttributeOperation';
    }
    /**
	 * Creates `AttributeOperation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        return new AttributeOperation(Range.fromJSON(json.range, document), json.key, json.oldValue, json.newValue, json.baseVersion);
    }
}

/**
 * Operation which is doing nothing ("empty operation", "do-nothing operation", "noop"). This is an operation,
 * which when executed does not change the tree model. It still has some parameters defined for transformation purposes.
 *
 * In most cases this operation is a result of transforming operations. When transformation returns
 * {@link module:engine/model/operation/nooperation~NoOperation} it means that changes done by the transformed operation
 * have already been applied.
 */ class NoOperation extends Operation {
    get type() {
        return 'noop';
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        return null;
    }
    /**
	 * Creates and returns an operation that has the same parameters as this operation.
	 */ clone() {
        return new NoOperation(this.baseVersion);
    }
    /**
	 * See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
	 */ getReversed() {
        return new NoOperation(this.baseVersion + 1);
    }
    /** @internal */ _execute() {}
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'NoOperation';
    }
}

/**
 * Operation to change element's name.
 *
 * Using this class you can change element's name.
 */ class RenameOperation extends Operation {
    /**
	 * Position before an element to change.
	 */ position;
    /**
	 * Current name of the element.
	 */ oldName;
    /**
	 * New name for the element.
	 */ newName;
    /**
	 * Creates an operation that changes element's name.
	 *
	 * @param position Position before an element to change.
	 * @param oldName Current name of the element.
	 * @param newName New name for the element.
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation
	 * can be applied or `null` if the operation operates on detached (non-document) tree.
	 */ constructor(position, oldName, newName, baseVersion){
        super(baseVersion);
        this.position = position;
        // This position sticks to the next node because it is a position before the node that we want to change.
        this.position.stickiness = 'toNext';
        this.oldName = oldName;
        this.newName = newName;
    }
    /**
	 * @inheritDoc
	 */ get type() {
        return 'rename';
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        return this.position.nodeAfter;
    }
    /**
	 * Creates and returns an operation that has the same parameters as this operation.
	 *
	 * @returns Clone of this operation.
	 */ clone() {
        return new RenameOperation(this.position.clone(), this.oldName, this.newName, this.baseVersion);
    }
    /**
	 * See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
	 */ getReversed() {
        return new RenameOperation(this.position.clone(), this.newName, this.oldName, this.baseVersion + 1);
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _validate() {
        const element = this.position.nodeAfter;
        if (!(element instanceof Element)) {
            /**
			 * Given position is invalid or node after it is not instance of Element.
			 *
			 * @error rename-operation-wrong-position
			 */ throw new CKEditorError('rename-operation-wrong-position', this);
        } else if (element.name !== this.oldName) {
            /**
			 * Element to change has different name than operation's old name.
			 *
			 * @error rename-operation-wrong-name
			 */ throw new CKEditorError('rename-operation-wrong-name', this);
        }
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _execute() {
        const element = this.position.nodeAfter;
        element.name = this.newName;
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        const json = super.toJSON();
        json.position = this.position.toJSON();
        return json;
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'RenameOperation';
    }
    /**
	 * Creates `RenameOperation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        return new RenameOperation(Position.fromJSON(json.position, document), json.oldName, json.newName, json.baseVersion);
    }
}

/**
 * Operation to change root element's attribute. Using this class you can add, remove or change value of the attribute.
 *
 * This operation is needed, because root elements can't be changed through
 * {@link module:engine/model/operation/attributeoperation~AttributeOperation}.
 * It is because {@link module:engine/model/operation/attributeoperation~AttributeOperation}
 * requires a range to change and root element can't
 * be a part of range because every {@link module:engine/model/position~Position} has to be inside a root.
 * {@link module:engine/model/position~Position} can't be created before a root element.
 */ class RootAttributeOperation extends Operation {
    /**
	 * Root element to change.
	 */ root;
    /**
	 * Key of an attribute to change or remove.
	 */ key;
    /**
	 * Old value of the attribute with given key or `null`, if attribute was not set before.
	 *
	 * @readonly
	 */ oldValue;
    /**
	 * New value of the attribute with given key or `null`, if operation should remove attribute.
	 *
	 * @readonly
	 */ newValue;
    /**
	 * Creates an operation that changes, removes or adds attributes on root element.
	 *
	 * @see module:engine/model/operation/attributeoperation~AttributeOperation
	 * @param root Root element to change.
	 * @param key Key of an attribute to change or remove.
	 * @param oldValue Old value of the attribute with given key or `null`, if attribute was not set before.
	 * @param newValue New value of the attribute with given key or `null`, if operation should remove attribute.
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation
	 * can be applied or `null` if the operation operates on detached (non-document) tree.
	 */ constructor(root, key, oldValue, newValue, baseVersion){
        super(baseVersion);
        this.root = root;
        this.key = key;
        this.oldValue = oldValue === undefined ? null : oldValue;
        this.newValue = newValue === undefined ? null : newValue;
    }
    /**
	 * @inheritDoc
	 */ get type() {
        if (this.oldValue === null) {
            return 'addRootAttribute';
        } else if (this.newValue === null) {
            return 'removeRootAttribute';
        } else {
            return 'changeRootAttribute';
        }
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        return this.root;
    }
    /**
	 * Creates and returns an operation that has the same parameters as this operation.
	 *
	 * @returns Clone of this operation.
	 */ clone() {
        return new RootAttributeOperation(this.root, this.key, this.oldValue, this.newValue, this.baseVersion);
    }
    /**
	 * See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
	 */ getReversed() {
        return new RootAttributeOperation(this.root, this.key, this.newValue, this.oldValue, this.baseVersion + 1);
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _validate() {
        if (this.root != this.root.root || this.root.is('documentFragment')) {
            /**
			 * The element to change is not a root element.
			 *
			 * @error rootattribute-operation-not-a-root
			 * @param root
			 * @param key
			 * @param value
			 */ throw new CKEditorError('rootattribute-operation-not-a-root', this, {
                root: this.root,
                key: this.key
            });
        }
        if (this.oldValue !== null && this.root.getAttribute(this.key) !== this.oldValue) {
            /**
			 * The attribute which should be removed does not exist for the given node.
			 *
			 * @error rootattribute-operation-wrong-old-value
			 * @param root
			 * @param key
			 * @param value
			 */ throw new CKEditorError('rootattribute-operation-wrong-old-value', this, {
                root: this.root,
                key: this.key
            });
        }
        if (this.oldValue === null && this.newValue !== null && this.root.hasAttribute(this.key)) {
            /**
			 * The attribute with given key already exists for the given node.
			 *
			 * @error rootattribute-operation-attribute-exists
			 * @param root
			 * @param key
			 */ throw new CKEditorError('rootattribute-operation-attribute-exists', this, {
                root: this.root,
                key: this.key
            });
        }
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _execute() {
        if (this.newValue !== null) {
            this.root._setAttribute(this.key, this.newValue);
        } else {
            this.root._removeAttribute(this.key);
        }
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        const json = super.toJSON();
        json.root = this.root.toJSON();
        return json;
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'RootAttributeOperation';
    }
    /**
	 * Creates `RootAttributeOperation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        if (!document.getRoot(json.root)) {
            /**
			 * Cannot create RootAttributeOperation for document. Root with specified name does not exist.
			 *
			 * @error rootattribute-operation-fromjson-no-root
			 * @param rootName
			 */ throw new CKEditorError('rootattribute-operation-fromjson-no-root', this, {
                rootName: json.root
            });
        }
        return new RootAttributeOperation(document.getRoot(json.root), json.key, json.oldValue, json.newValue, json.baseVersion);
    }
}

/**
 * Operation that creates (or attaches) or detaches a root element.
 */ class RootOperation extends Operation {
    /**
	 * Root name to create or detach.
	 */ rootName;
    /**
	 * Root element name.
	 */ elementName;
    /**
	 * Specifies whether the operation adds (`true`) or detaches the root (`false`).
	 */ isAdd;
    /**
	 * Document which owns the root.
	 */ _document;
    /**
	 * Creates an operation that creates or removes a root element.
	 *
	 * @param rootName Root name to create or detach.
	 * @param elementName Root element name.
	 * @param isAdd Specifies whether the operation adds (`true`) or detaches the root (`false`).
	 * @param document Document which owns the root.
	 * @param baseVersion Document {@link module:engine/model/document~Document#version} on which operation can be applied.
	 */ constructor(rootName, elementName, isAdd, document, baseVersion){
        super(baseVersion);
        this.rootName = rootName;
        this.elementName = elementName;
        this.isAdd = isAdd;
        this._document = document;
        // Make sure that the root exists ASAP, this is important for RTC.
        // If the root was dynamically added, there will be more operations that operate on/in this root.
        // These operations will require root element instance (in operation property or in position instance).
        // If the root is not created ahead of time, instantiating such operations may fail.
        if (!this._document.getRoot(this.rootName)) {
            const root = this._document.createRoot(this.elementName, this.rootName);
            root._isAttached = false;
        }
    }
    /**
	 * @inheritDoc
	 */ get type() {
        return this.isAdd ? 'addRoot' : 'detachRoot';
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        return this._document.getRoot(this.rootName);
    }
    /**
	 * @inheritDoc
	 */ clone() {
        return new RootOperation(this.rootName, this.elementName, this.isAdd, this._document, this.baseVersion);
    }
    /**
	 * @inheritDoc
	 */ getReversed() {
        return new RootOperation(this.rootName, this.elementName, !this.isAdd, this._document, this.baseVersion + 1);
    }
    /**
	 * @inheritDoc
	 */ _execute() {
        this._document.getRoot(this.rootName)._isAttached = this.isAdd;
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        const json = super.toJSON();
        delete json._document;
        return json;
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'RootOperation';
    }
    /**
	 * Creates `RootOperation` object from deserialized object, i.e. from parsed JSON string.
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        return new RootOperation(json.rootName, json.elementName, json.isAdd, document, json.baseVersion);
    }
}

const operations = {};
operations[AttributeOperation.className] = AttributeOperation;
operations[InsertOperation.className] = InsertOperation;
operations[MarkerOperation.className] = MarkerOperation;
operations[MoveOperation.className] = MoveOperation;
operations[NoOperation.className] = NoOperation;
operations[Operation.className] = Operation;
operations[RenameOperation.className] = RenameOperation;
operations[RootAttributeOperation.className] = RootAttributeOperation;
operations[RootOperation.className] = RootOperation;
operations[SplitOperation.className] = SplitOperation;
operations[MergeOperation.className] = MergeOperation;
/**
 * A factory class for creating operations.
 */ class OperationFactory {
    /**
	 * Creates an operation instance from a JSON object (parsed JSON string).
	 *
	 * @param json Deserialized JSON object.
	 * @param document Document on which this operation will be applied.
	 */ static fromJSON(json, document) {
        return operations[json.__className].fromJSON(json, document);
    }
}

const transformations = new Map();
/**
 * Sets a transformation function to be be used to transform instances of class `OperationA` by instances of class `OperationB`.
 *
 * The `transformationFunction` is passed three parameters:
 *
 * * `a` - operation to be transformed, an instance of `OperationA`,
 * * `b` - operation to be transformed by, an instance of `OperationB`,
 * * {@link module:engine/model/operation/transform~TransformationContext `context`} - object with additional information about
 * transformation context.
 *
 * The `transformationFunction` should return transformation result, which is an array with one or multiple
 * {@link module:engine/model/operation/operation~Operation operation} instances.
 *
 * @param transformationFunction Function to use for transforming.
 */ function setTransformation(OperationA, OperationB, transformationFunction) {
    let aGroup = transformations.get(OperationA);
    if (!aGroup) {
        aGroup = new Map();
        transformations.set(OperationA, aGroup);
    }
    aGroup.set(OperationB, transformationFunction);
}
/**
 * Returns a previously set transformation function for transforming an instance of `OperationA` by an instance of `OperationB`.
 *
 * If no transformation was set for given pair of operations, {@link module:engine/model/operation/transform~noUpdateTransformation}
 * is returned. This means that if no transformation was set, the `OperationA` instance will not change when transformed
 * by the `OperationB` instance.
 *
 * @returns Function set to transform an instance of `OperationA` by an instance of `OperationB`.
 */ function getTransformation(OperationA, OperationB) {
    const aGroup = transformations.get(OperationA);
    if (aGroup && aGroup.has(OperationB)) {
        return aGroup.get(OperationB);
    }
    return noUpdateTransformation;
}
/**
 * A transformation function that only clones operation to transform, without changing it.
 */ function noUpdateTransformation(a) {
    return [
        a
    ];
}
/**
 * Transforms operation `a` by operation `b`.
 *
 * @param a Operation to be transformed.
 * @param b Operation to transform by.
 * @param context Transformation context for this transformation.
 * @returns Transformation result.
 */ function transform$1(a, b, context = {}) {
    const transformationFunction = getTransformation(a.constructor, b.constructor);
    /* eslint-disable no-useless-catch */ try {
        a = a.clone();
        return transformationFunction(a, b, context);
    } catch (e) {
        // @if CK_DEBUG // console.warn( 'Error during operation transformation!', e.message );
        // @if CK_DEBUG // console.warn( 'Transformed operation', a );
        // @if CK_DEBUG // console.warn( 'Operation transformed by', b );
        // @if CK_DEBUG // console.warn( 'context.aIsStrong', context.aIsStrong );
        // @if CK_DEBUG // console.warn( 'context.aWasUndone', context.aWasUndone );
        // @if CK_DEBUG // console.warn( 'context.bWasUndone', context.bWasUndone );
        // @if CK_DEBUG // console.warn( 'context.abRelation', context.abRelation );
        // @if CK_DEBUG // console.warn( 'context.baRelation', context.baRelation );
        throw e;
    }
/* eslint-enable no-useless-catch */ }
/**
 * Performs a transformation of two sets of operations - `operationsA` and `operationsB`. The transformation is two-way -
 * both transformed `operationsA` and transformed `operationsB` are returned.
 *
 * Note, that the first operation in each set should base on the same document state (
 * {@link module:engine/model/document~Document#version document version}).
 *
 * It is assumed that `operationsA` are "more important" during conflict resolution between two operations.
 *
 * New copies of both passed arrays and operations inside them are returned. Passed arguments are not altered.
 *
 * Base versions of the transformed operations sets are updated accordingly. For example, assume that base versions are `4`
 * and there are `3` operations in `operationsA` and `5` operations in `operationsB`. Then:
 *
 * * transformed `operationsA` will start from base version `9` (`4` base version + `5` operations B),
 * * transformed `operationsB` will start from base version `7` (`4` base version + `3` operations A).
 *
 * If no operation was broken into two during transformation, then both sets will end up with an operation that bases on version `11`:
 *
 * * transformed `operationsA` start from `9` and there are `3` of them, so the last will have `baseVersion` equal to `11`,
 * * transformed `operationsB` start from `7` and there are `5` of them, so the last will have `baseVersion` equal to `11`.
 *
 * @param operationsA
 * @param operationsB
 * @param options Additional transformation options.
 * @param options.document Document which the operations change.
 * @param options.useRelations Whether during transformation relations should be used (used during undo for better conflict resolution).
 * @param options.padWithNoOps Whether additional {@link module:engine/model/operation/nooperation~NoOperation}s
 * should be added to the transformation results to force the same last base version for both transformed sets (in case
 * if some operations got broken into multiple operations during transformation).
 * @param options.forceWeakRemove If set to `false`, remove operation will be always stronger than move operation,
 * so the removed nodes won't end up back in the document root. When set to `true`, context data will be used.
 * @returns Transformation result.
 */ function transformSets(operationsA, operationsB, options) {
    // Create new arrays so the originally passed arguments are not changed.
    // No need to clone operations, they are cloned as they are transformed.
    operationsA = operationsA.slice();
    operationsB = operationsB.slice();
    const contextFactory = new ContextFactory(options.document, options.useRelations, options.forceWeakRemove);
    contextFactory.setOriginalOperations(operationsA);
    contextFactory.setOriginalOperations(operationsB);
    const originalOperations = contextFactory.originalOperations;
    // If one of sets is empty there is simply nothing to transform, so return sets as they are.
    if (operationsA.length == 0 || operationsB.length == 0) {
        return {
            operationsA,
            operationsB,
            originalOperations
        };
    }
    //
    // Following is a description of transformation process:
    //
    // There are `operationsA` and `operationsB` to be transformed, both by both.
    //
    // So, suppose we have sets of two operations each: `operationsA` = `[ a1, a2 ]`, `operationsB` = `[ b1, b2 ]`.
    //
    // Remember, that we can only transform operations that base on the same context. We assert that `a1` and `b1` base on
    // the same context and we transform them. Then, we get `a1'` and `b1'`. `a2` bases on a context with `a1` -- `a2`
    // is an operation that followed `a1`. Similarly, `b2` bases on a context with `b1`.
    //
    // However, since `a1'` is a result of transformation by `b1`, `a1'` now also has a context with `b1`. This means that
    // we can safely transform `a1'` by `b2`. As we finish transforming `a1`, we also transformed all `operationsB`.
    // All `operationsB` also have context including `a1`. Now, we can properly transform `a2` by those operations.
    //
    // The transformation process can be visualized on a transformation diagram ("diamond diagram"):
    //
    //          [the initial state]
    //         [common for a1 and b1]
    //
    //                   *
    //                  / \
    //                 /   \
    //               b1     a1
    //               /       \
    //              /         \
    //             *           *
    //            / \         / \
    //           /   \       /   \
    //         b2    a1'   b1'    a2
    //         /       \   /       \
    //        /         \ /         \
    //       *           *           *
    //        \         / \         /
    //         \       /   \       /
    //        a1''   b2'   a2'   b1''
    //           \   /       \   /
    //            \ /         \ /
    //             *           *
    //              \         /
    //               \       /
    //              a2''   b2''
    //                 \   /
    //                  \ /
    //                   *
    //
    //           [the final state]
    //
    // The final state can be reached from the initial state by applying `a1`, `a2`, `b1''` and `b2''`, as well as by
    // applying `b1`, `b2`, `a1''`, `a2''`. Note how the operations get to a proper common state before each pair is
    // transformed.
    //
    // Another thing to consider is that an operation during transformation can be broken into multiple operations.
    // Suppose that `a1` * `b1` = `[ a11', a12' ]` (instead of `a1'` that we considered previously).
    //
    // In that case, we leave `a12'` for later and we continue transforming `a11'` until it is transformed by all `operationsB`
    // (in our case it is just `b2`). At this point, `b1` is transformed by "whole" `a1`, while `b2` is only transformed
    // by `a11'`. Similarly, `a12'` is only transformed by `b1`. This leads to a conclusion that we need to start transforming `a12'`
    // from the moment just after it was broken. So, `a12'` is transformed by `b2`. Now, "the whole" `a1` is transformed
    // by `operationsB`, while all `operationsB` are transformed by "the whole" `a1`. This means that we can continue with
    // following `operationsA` (in our case it is just `a2`).
    //
    // Of course, also `operationsB` can be broken. However, since we focus on transforming operation `a` to the end,
    // the only thing to do is to store both pieces of operation `b`, so that the next transformed operation `a` will
    // be transformed by both of them.
    //
    //                       *
    //                      / \
    //                     /   \
    //                    /     \
    //                  b1       a1
    //                  /         \
    //                 /           \
    //                /             \
    //               *               *
    //              / \             / \
    //             /  a11'         /   \
    //            /     \         /     \
    //          b2       *      b1'      a2
    //          /       / \     /         \
    //         /       /  a12' /           \
    //        /       /     \ /             \
    //       *       b2'     *               *
    //        \     /       / \             /
    //       a11'' /     b21'' \           /
    //          \ /       /     \         /
    //           *       *      a2'     b1''
    //            \     / \       \     /
    //          a12'' b22''\       \   /
    //              \ /     \       \ /
    //               *      a2''     *
    //                \       \     /
    //                 \       \  b21'''
    //                  \       \ /
    //                a2'''      *
    //                    \     /
    //                     \  b22'''
    //                      \ /
    //                       *
    //
    // Note, how `a1` is broken and transformed into `a11'` and `a12'`, while `b2'` got broken and transformed into `b21''` and `b22''`.
    //
    // Having all that on mind, here is an outline for the transformation process algorithm:
    //
    // 1. We have `operationsA` and `operationsB` array, which we dynamically update as the transformation process goes.
    //
    // 2. We take next (or first) operation from `operationsA` and check from which operation `b` we need to start transforming it.
    // All original `operationsA` are set to be transformed starting from the first operation `b`.
    //
    // 3. We take operations from `operationsB`, one by one, starting from the correct one, and transform operation `a`
    // by operation `b` (and vice versa). We update `operationsA` and `operationsB` by replacing the original operations
    // with the transformation results.
    //
    // 4. If operation is broken into multiple operations, we save all the new operations in the place of the
    // original operation.
    //
    // 5. Additionally, if operation `a` was broken, for the "new" operation, we remember from which operation `b` it should
    // be transformed by.
    //
    // 6. We continue transforming "current" operation `a` until it is transformed by all `operationsB`. Then, go to 2.
    // unless the last operation `a` was transformed.
    //
    // The actual implementation of the above algorithm is slightly different, as only one loop (while) is used.
    // The difference is that we have "current" `a` operation to transform and we store the index of the next `b` operation
    // to transform by. Each loop operates on two indexes then: index pointing to currently processed `a` operation and
    // index pointing to next `b` operation. Each loop is just one `a * b` + `b * a` transformation. After each loop
    // operation `b` index is updated. If all `b` operations were visited for the current `a` operation, we change
    // current `a` operation index to the next one.
    //
    // For each operation `a`, keeps information what is the index in `operationsB` from which the transformation should start.
    const nextTransformIndex = new WeakMap();
    // For all the original `operationsA`, set that they should be transformed starting from the first of `operationsB`.
    for (const op of operationsA){
        nextTransformIndex.set(op, 0);
    }
    // Additional data that is used for some postprocessing after the main transformation process is done.
    const data = {
        nextBaseVersionA: operationsA[operationsA.length - 1].baseVersion + 1,
        nextBaseVersionB: operationsB[operationsB.length - 1].baseVersion + 1,
        originalOperationsACount: operationsA.length,
        originalOperationsBCount: operationsB.length
    };
    // Index of currently transformed operation `a`.
    let i = 0;
    // While not all `operationsA` are transformed...
    while(i < operationsA.length){
        // Get "current" operation `a`.
        const opA = operationsA[i];
        // For the "current" operation `a`, get the index of the next operation `b` to transform by.
        const indexB = nextTransformIndex.get(opA);
        // If operation `a` was already transformed by every operation `b`, change "current" operation `a` to the next one.
        if (indexB == operationsB.length) {
            i++;
            continue;
        }
        const opB = operationsB[indexB];
        // Transform `a` by `b` and `b` by `a`.
        const newOpsA = transform$1(opA, opB, contextFactory.getContext(opA, opB, true));
        const newOpsB = transform$1(opB, opA, contextFactory.getContext(opB, opA, false));
        // As a result we get one or more `newOpsA` and one or more `newOpsB` operations.
        // Update contextual information about operations.
        contextFactory.updateRelation(opA, opB);
        contextFactory.setOriginalOperations(newOpsA, opA);
        contextFactory.setOriginalOperations(newOpsB, opB);
        // For new `a` operations, update their index of the next operation `b` to transform them by.
        //
        // This is needed even if there was only one result (`a` was not broken) because that information is used
        // at the beginning of this loop every time.
        for (const newOpA of newOpsA){
            // Acknowledge, that operation `b` also might be broken into multiple operations.
            //
            // This is why we raise `indexB` not just by 1. If `newOpsB` are multiple operations, they will be
            // spliced in the place of `opB`. So we need to change `transformBy` accordingly, so that an operation won't
            // be transformed by the same operation (part of it) again.
            nextTransformIndex.set(newOpA, indexB + newOpsB.length);
        }
        // Update `operationsA` and `operationsB` with the transformed versions.
        operationsA.splice(i, 1, ...newOpsA);
        operationsB.splice(indexB, 1, ...newOpsB);
    }
    if (options.padWithNoOps) {
        // If no-operations padding is enabled, count how many extra `a` and `b` operations were generated.
        const brokenOperationsACount = operationsA.length - data.originalOperationsACount;
        const brokenOperationsBCount = operationsB.length - data.originalOperationsBCount;
        // Then, if that number is not the same, pad `operationsA` or `operationsB` with correct number of no-ops so
        // that the base versions are equalled.
        //
        // Note that only one array will be updated, as only one of those subtractions can be greater than zero.
        padWithNoOps(operationsA, brokenOperationsBCount - brokenOperationsACount);
        padWithNoOps(operationsB, brokenOperationsACount - brokenOperationsBCount);
    }
    // Finally, update base versions of transformed operations.
    updateBaseVersions(operationsA, data.nextBaseVersionB);
    updateBaseVersions(operationsB, data.nextBaseVersionA);
    return {
        operationsA,
        operationsB,
        originalOperations
    };
}
/**
 * Gathers additional data about operations processed during transformation. Can be used to obtain contextual information
 * about two operations that are about to be transformed. This contextual information can be used for better conflict resolution.
 */ class ContextFactory {
    originalOperations;
    _history;
    _useRelations;
    _forceWeakRemove;
    _relations;
    /**
	 * Creates `ContextFactory` instance.
	 *
	 * @param document Document which the operations change.
	 * @param useRelations Whether during transformation relations should be used (used during undo for
	 * better conflict resolution).
	 * @param forceWeakRemove If set to `false`, remove operation will be always stronger than move operation,
	 * so the removed nodes won't end up back in the document root. When set to `true`, context data will be used.
	 */ constructor(document, useRelations, forceWeakRemove = false){
        // For each operation that is created during transformation process, we keep a reference to the original operation
        // which it comes from. The original operation works as a kind of "identifier". Every contextual information
        // gathered during transformation that we want to save for given operation, is actually saved for the original operation.
        // This way no matter if operation `a` is cloned, then transformed, even breaks, we still have access to the previously
        // gathered data through original operation reference.
        this.originalOperations = new Map();
        // `model.History` instance which information about undone operations will be taken from.
        this._history = document.history;
        // Whether additional context should be used.
        this._useRelations = useRelations;
        this._forceWeakRemove = !!forceWeakRemove;
        // Relations is a double-map structure (maps in map) where for two operations we store how those operations were related
        // to each other. Those relations are evaluated during transformation process. For every transformated pair of operations
        // we keep relations between them.
        this._relations = new Map();
    }
    /**
	 * Sets "original operation" for given operations.
	 *
	 * During transformation process, operations are cloned, then changed, then processed again, sometimes broken into two
	 * or multiple operations. When gathering additional data it is important that all operations can be somehow linked
	 * so a cloned and transformed "version" still kept track of the data assigned earlier to it.
	 *
	 * The original operation object will be used as such an universal linking id. Throughout the transformation process
	 * all cloned operations will refer to "the original operation" when storing and reading additional data.
	 *
	 * If `takeFrom` is not set, each operation from `operations` array will be assigned itself as "the original operation".
	 * This should be used as an initialization step.
	 *
	 * If `takeFrom` is set, each operation from `operations` will be assigned the same original operation as assigned
	 * for `takeFrom` operation. This should be used to update original operations. It should be used in a way that
	 * `operations` are the result of `takeFrom` transformation to ensure proper "original operation propagation".
	 */ setOriginalOperations(operations, takeFrom = null) {
        const originalOperation = takeFrom ? this.originalOperations.get(takeFrom) : null;
        for (const operation of operations){
            this.originalOperations.set(operation, originalOperation || operation);
        }
    }
    /**
	 * Saves a relation between operations `opA` and `opB`.
	 *
	 * Relations are then later used to help solve conflicts when operations are transformed.
	 */ updateRelation(opA, opB) {
        // The use of relations is described in a bigger detail in transformation functions.
        //
        // In brief, this function, for specified pairs of operation types, checks how positions defined in those operations relate.
        // Then those relations are saved. For example, for two move operations, it is saved if one of those operations target
        // position is before the other operation source position. This kind of information gives contextual information when
        // transformation is used during undo. Similar checks are done for other pairs of operations.
        //
        if (opA instanceof MoveOperation) {
            if (opB instanceof MergeOperation) {
                if (opA.targetPosition.isEqual(opB.sourcePosition) || opB.movedRange.containsPosition(opA.targetPosition)) {
                    this._setRelation(opA, opB, 'insertAtSource');
                } else if (opA.targetPosition.isEqual(opB.deletionPosition)) {
                    this._setRelation(opA, opB, 'insertBetween');
                } else if (opA.targetPosition.isAfter(opB.sourcePosition)) {
                    this._setRelation(opA, opB, 'moveTargetAfter');
                }
            } else if (opB instanceof MoveOperation) {
                if (opA.targetPosition.isEqual(opB.sourcePosition) || opA.targetPosition.isBefore(opB.sourcePosition)) {
                    this._setRelation(opA, opB, 'insertBefore');
                } else {
                    this._setRelation(opA, opB, 'insertAfter');
                }
            }
        } else if (opA instanceof SplitOperation) {
            if (opB instanceof MergeOperation) {
                if (opA.splitPosition.isBefore(opB.sourcePosition)) {
                    this._setRelation(opA, opB, 'splitBefore');
                }
            } else if (opB instanceof MoveOperation) {
                if (opA.splitPosition.isEqual(opB.sourcePosition) || opA.splitPosition.isBefore(opB.sourcePosition)) {
                    this._setRelation(opA, opB, 'splitBefore');
                } else {
                    const range = Range._createFromPositionAndShift(opB.sourcePosition, opB.howMany);
                    if (opA.splitPosition.hasSameParentAs(opB.sourcePosition) && range.containsPosition(opA.splitPosition)) {
                        const howMany = range.end.offset - opA.splitPosition.offset;
                        const offset = opA.splitPosition.offset - range.start.offset;
                        this._setRelation(opA, opB, {
                            howMany,
                            offset
                        });
                    }
                }
            }
        } else if (opA instanceof MergeOperation) {
            if (opB instanceof MergeOperation) {
                if (!opA.targetPosition.isEqual(opB.sourcePosition)) {
                    this._setRelation(opA, opB, 'mergeTargetNotMoved');
                }
                if (opA.sourcePosition.isEqual(opB.targetPosition)) {
                    this._setRelation(opA, opB, 'mergeSourceNotMoved');
                }
                if (opA.sourcePosition.isEqual(opB.sourcePosition)) {
                    this._setRelation(opA, opB, 'mergeSameElement');
                }
            } else if (opB instanceof SplitOperation) {
                if (opA.sourcePosition.isEqual(opB.splitPosition)) {
                    this._setRelation(opA, opB, 'splitAtSource');
                }
            } else if (opB instanceof MoveOperation && opB.howMany > 0) {
                if (opA.sourcePosition.isEqual(opB.sourcePosition.getShiftedBy(opB.howMany))) {
                    this._setRelation(opA, opB, 'mergeSourceAffected');
                }
                if (opA.targetPosition.isEqual(opB.sourcePosition)) {
                    this._setRelation(opA, opB, 'mergeTargetWasBefore');
                }
            }
        } else if (opA instanceof MarkerOperation) {
            const markerRange = opA.newRange;
            if (!markerRange) {
                return;
            }
            if (opB instanceof MoveOperation) {
                const movedRange = Range._createFromPositionAndShift(opB.sourcePosition, opB.howMany);
                const affectedLeft = movedRange.containsPosition(markerRange.start) || movedRange.start.isEqual(markerRange.start);
                const affectedRight = movedRange.containsPosition(markerRange.end) || movedRange.end.isEqual(markerRange.end);
                if ((affectedLeft || affectedRight) && !movedRange.containsRange(markerRange)) {
                    this._setRelation(opA, opB, {
                        side: affectedLeft ? 'left' : 'right',
                        path: affectedLeft ? markerRange.start.path.slice() : markerRange.end.path.slice()
                    });
                }
            } else if (opB instanceof MergeOperation) {
                const wasInLeftElement = markerRange.start.isEqual(opB.targetPosition);
                const wasStartBeforeMergedElement = markerRange.start.isEqual(opB.deletionPosition);
                const wasEndBeforeMergedElement = markerRange.end.isEqual(opB.deletionPosition);
                const wasInRightElement = markerRange.end.isEqual(opB.sourcePosition);
                if (wasInLeftElement || wasStartBeforeMergedElement || wasEndBeforeMergedElement || wasInRightElement) {
                    this._setRelation(opA, opB, {
                        wasInLeftElement,
                        wasStartBeforeMergedElement,
                        wasEndBeforeMergedElement,
                        wasInRightElement
                    });
                }
            }
        }
    }
    /**
	 * Evaluates and returns contextual information about two given operations `opA` and `opB` which are about to be transformed.
	 */ getContext(opA, opB, aIsStrong) {
        return {
            aIsStrong,
            aWasUndone: this._wasUndone(opA),
            bWasUndone: this._wasUndone(opB),
            abRelation: this._useRelations ? this._getRelation(opA, opB) : null,
            baRelation: this._useRelations ? this._getRelation(opB, opA) : null,
            forceWeakRemove: this._forceWeakRemove
        };
    }
    /**
	 * Returns whether given operation `op` has already been undone.
	 *
	 * Information whether an operation was undone gives more context when making a decision when two operations are in conflict.
	 */ _wasUndone(op) {
        // For `op`, get its original operation. After all, if `op` is a clone (or even transformed clone) of another
        // operation, literally `op` couldn't be undone. It was just generated. If anything, it was the operation it origins
        // from which was undone. So get that original operation.
        const originalOp = this.originalOperations.get(op);
        // And check with the document if the original operation was undone.
        return originalOp.wasUndone || this._history.isUndoneOperation(originalOp);
    }
    /**
	 * Returns a relation between `opA` and an operation which is undone by `opB`. This can be `String` value if a relation
	 * was set earlier or `null` if there was no relation between those operations.
	 *
	 * This is a little tricky to understand, so let's compare it to `ContextFactory#_wasUndone`.
	 *
	 * When `wasUndone( opB )` is used, we check if the `opB` has already been undone. It is obvious, that the
	 * undoing operation must happen after the undone operation. So, essentially, we have `opB`, we take document history,
	 * we look forward in the future and ask if in that future `opB` was undone.
	 *
	 * Relations is a backward process to `wasUndone()`.
	 *
	 * Long story short - using relations is asking what happened in the past. Looking back. This time we have an undoing
	 * operation `opB` which has undone some other operation. When there is a transformation `opA` x `opB` and there is
	 * a conflict to solve and `opB` is an undoing operation, we can look back in the history and see what was a relation
	 * between `opA` and the operation which `opB` undone. Basing on that relation from the past, we can now make
	 * a better decision when resolving a conflict between two operations, because we know more about the context of
	 * those two operations.
	 *
	 * This is why this function does not return a relation directly between `opA` and `opB` because we need to look
	 * back to search for a meaningful contextual information.
	 */ _getRelation(opA, opB) {
        // Get the original operation. Similarly as in `wasUndone()` it is used as an universal identifier for stored data.
        const origB = this.originalOperations.get(opB);
        const undoneB = this._history.getUndoneOperation(origB);
        // If `opB` is not undoing any operation, there is no relation.
        if (!undoneB) {
            return null;
        }
        const origA = this.originalOperations.get(opA);
        const relationsA = this._relations.get(origA);
        // Get all relations for `opA`, and check if there is a relation with `opB`-undone-counterpart. If so, return it.
        if (relationsA) {
            return relationsA.get(undoneB) || null;
        }
        return null;
    }
    /**
	 * Helper function for `ContextFactory#updateRelations`.
	 */ _setRelation(opA, opB, relation) {
        // As always, setting is for original operations, not the clones/transformed operations.
        const origA = this.originalOperations.get(opA);
        const origB = this.originalOperations.get(opB);
        let relationsA = this._relations.get(origA);
        if (!relationsA) {
            relationsA = new Map();
            this._relations.set(origA, relationsA);
        }
        relationsA.set(origB, relation);
    }
}
/**
 * An utility function that updates {@link module:engine/model/operation/operation~Operation#baseVersion base versions}
 * of passed operations.
 *
 * The function simply sets `baseVersion` as a base version of the first passed operation and then increments it for
 * each following operation in `operations`.
 *
 * @param operations Operations to update.
 * @param baseVersion Base version to set for the first operation in `operations`.
 */ function updateBaseVersions(operations, baseVersion) {
    for (const operation of operations){
        operation.baseVersion = baseVersion++;
    }
}
/**
 * Adds `howMany` instances of {@link module:engine/model/operation/nooperation~NoOperation} to `operations` set.
 */ function padWithNoOps(operations, howMany) {
    for(let i = 0; i < howMany; i++){
        operations.push(new NoOperation(0));
    }
}
// -----------------------
setTransformation(AttributeOperation, AttributeOperation, (a, b, context)=>{
    // If operations in conflict, check if their ranges intersect and manage them properly.
    //
    // Operations can be in conflict only if:
    //
    // * their key is the same (they change the same attribute), and
    // * they are in the same parent (operations for ranges [ 1 ] - [ 3 ] and [ 2, 0 ] - [ 2, 5 ] change different
    // elements and can't be in conflict).
    if (a.key === b.key && a.range.start.hasSameParentAs(b.range.start)) {
        // First, we want to apply change to the part of a range that has not been changed by the other operation.
        const operations = a.range.getDifference(b.range).map((range)=>{
            return new AttributeOperation(range, a.key, a.oldValue, a.newValue, 0);
        });
        // Then we take care of the common part of ranges.
        const common = a.range.getIntersection(b.range);
        if (common) {
            // If this operation is more important, we also want to apply change to the part of the
            // original range that has already been changed by the other operation. Since that range
            // got changed we also have to update `oldValue`.
            if (context.aIsStrong) {
                operations.push(new AttributeOperation(common, b.key, b.newValue, a.newValue, 0));
            }
        }
        if (operations.length == 0) {
            return [
                new NoOperation(0)
            ];
        }
        return operations;
    } else {
        // If operations don't conflict, simply return an array containing just a clone of this operation.
        return [
            a
        ];
    }
});
setTransformation(AttributeOperation, InsertOperation, (a, b)=>{
    // Case 1:
    //
    // The attribute operation range includes the position where nodes were inserted.
    // There are two possible scenarios: the inserted nodes were text and they should receive attributes or
    // the inserted nodes were elements and they should not receive attributes.
    //
    if (a.range.start.hasSameParentAs(b.position) && a.range.containsPosition(b.position)) {
        // If new nodes should not receive attributes, two separated ranges will be returned.
        // Otherwise, one expanded range will be returned.
        const range = a.range._getTransformedByInsertion(b.position, b.howMany, !b.shouldReceiveAttributes);
        const result = range.map((r)=>{
            return new AttributeOperation(r, a.key, a.oldValue, a.newValue, a.baseVersion);
        });
        if (b.shouldReceiveAttributes) {
            // `AttributeOperation#range` includes some newly inserted text.
            // The operation should also change the attribute of that text. An example:
            //
            // Bold should be applied on the following range:
            // <p>Fo[zb]ar</p>
            //
            // In meantime, new text is typed:
            // <p>Fozxxbar</p>
            //
            // Bold should be applied also on the new text:
            // <p>Fo[zxxb]ar</p>
            // <p>Fo<$text bold="true">zxxb</$text>ar</p>
            //
            // There is a special case to consider here to consider.
            //
            // Consider setting an attribute with multiple possible values, for example `highlight`. The inserted text might
            // have already an attribute value applied and the `oldValue` property of the attribute operation might be wrong:
            //
            // Attribute `highlight="yellow"` should be applied on the following range:
            // <p>Fo[zb]ar<p>
            //
            // In meantime, character `x` with `highlight="red"` is typed:
            // <p>Fo[z<$text highlight="red">x</$text>b]ar</p>
            //
            // In this case we cannot simply apply operation changing the attribute value from `null` to `"yellow"` for the whole range
            // because that would lead to an exception (`oldValue` is incorrect for `x`).
            //
            // We also cannot break the original range as this would mess up a scenario when there are multiple following
            // insert operations, because then only the first inserted character is included in those ranges:
            // <p>Fo[z][x][b]ar</p>   -->   <p>Fo[z][x]x[b]ar</p>   -->   <p>Fo[z][x]xx[b]ar</p>
            //
            // So, the attribute range needs be expanded, no matter what attributes are set on the inserted nodes:
            //
            // <p>Fo[z<$text highlight="red">x</$text>b]ar</p>      <--- Change from `null` to `yellow`, throwing an exception.
            //
            // But before that operation would be applied, we will add an additional attribute operation that will change
            // attributes on the inserted nodes in a way which would make the original operation correct:
            //
            // <p>Fo[z{<$text highlight="red">}x</$text>b]ar</p>    <--- Change range `{}` from `red` to `null`.
            // <p>Fo[zxb]ar</p>                                     <--- Now change from `null` to `yellow` is completely fine.
            //
            // Generate complementary attribute operation. Be sure to add it before the original operation.
            const op = _getComplementaryAttributeOperations(b, a.key, a.oldValue);
            if (op) {
                result.unshift(op);
            }
        }
        // If nodes should not receive new attribute, we are done here.
        return result;
    }
    // If insert operation is not expanding the attribute operation range, simply transform the range.
    a.range = a.range._getTransformedByInsertion(b.position, b.howMany, false)[0];
    return [
        a
    ];
});
/**
 * Helper function for `AttributeOperation` x `InsertOperation` (and reverse) transformation.
 *
 * For given `insertOperation` it checks the inserted node if it has an attribute `key` set to a value different
 * than `newValue`. If so, it generates an `AttributeOperation` which changes the value of `key` attribute to `newValue`.
 */ function _getComplementaryAttributeOperations(insertOperation, key, newValue) {
    const nodes = insertOperation.nodes;
    // At the beginning we store the attribute value from the first node.
    const insertValue = nodes.getNode(0).getAttribute(key);
    if (insertValue == newValue) {
        return null;
    }
    const range = new Range(insertOperation.position, insertOperation.position.getShiftedBy(insertOperation.howMany));
    return new AttributeOperation(range, key, insertValue, newValue, 0);
}
setTransformation(AttributeOperation, MergeOperation, (a, b)=>{
    const ranges = [];
    // Case 1:
    //
    // Attribute change on the merged element. In this case, the merged element was moved to the graveyard.
    // An additional attribute operation that will change the (re)moved element needs to be generated.
    //
    if (a.range.start.hasSameParentAs(b.deletionPosition)) {
        if (a.range.containsPosition(b.deletionPosition) || a.range.start.isEqual(b.deletionPosition)) {
            ranges.push(Range._createFromPositionAndShift(b.graveyardPosition, 1));
        }
    }
    const range = a.range._getTransformedByMergeOperation(b);
    // Do not add empty (collapsed) ranges to the result. `range` may be collapsed if it contained only the merged element.
    if (!range.isCollapsed) {
        ranges.push(range);
    }
    // Create `AttributeOperation`s out of the ranges.
    return ranges.map((range)=>{
        return new AttributeOperation(range, a.key, a.oldValue, a.newValue, a.baseVersion);
    });
});
setTransformation(AttributeOperation, MoveOperation, (a, b)=>{
    const ranges = _breakRangeByMoveOperation(a.range, b);
    // Create `AttributeOperation`s out of the ranges.
    return ranges.map((range)=>new AttributeOperation(range, a.key, a.oldValue, a.newValue, a.baseVersion));
});
/**
 * Helper function for `AttributeOperation` x `MoveOperation` transformation.
 *
 * Takes the passed `range` and transforms it by move operation `moveOp` in a specific way. Only top-level nodes of `range`
 * are considered to be in the range. If move operation moves nodes deep from inside of the range, those nodes won't
 * be included in the result. In other words, top-level nodes of the ranges from the result are exactly the same as
 * top-level nodes of the original `range`.
 *
 * This is important for `AttributeOperation` because, for its range, it changes only the top-level nodes. So we need to
 * track only how those nodes have been affected by `MoveOperation`.
 */ function _breakRangeByMoveOperation(range, moveOp) {
    const moveRange = Range._createFromPositionAndShift(moveOp.sourcePosition, moveOp.howMany);
    // We are transforming `range` (original range) by `moveRange` (range moved by move operation). As usual when it comes to
    // transforming a ranges, we may have a common part of the ranges and we may have a difference part (zero to two ranges).
    let common = null;
    let difference = [];
    // Let's compare the ranges.
    if (moveRange.containsRange(range, true)) {
        // If the whole original range is moved, treat it whole as a common part. There's also no difference part.
        common = range;
    } else if (range.start.hasSameParentAs(moveRange.start)) {
        // If the ranges are "on the same level" (in the same parent) then move operation may move exactly those nodes
        // that are changed by the attribute operation. In this case we get common part and difference part in the usual way.
        difference = range.getDifference(moveRange);
        common = range.getIntersection(moveRange);
    } else {
        // In any other situation we assume that original range is different than move range, that is that move operation
        // moves other nodes that attribute operation change. Even if the moved range is deep inside in the original range.
        //
        // Note that this is different than in `.getIntersection` (we would get a common part in that case) and different
        // than `.getDifference` (we would get two ranges).
        difference = [
            range
        ];
    }
    const result = [];
    // The default behaviour of `_getTransformedByMove` might get wrong results for difference part, though, so
    // we do it by hand.
    for (let diff of difference){
        // First, transform the range by removing moved nodes. Since this is a difference, this is safe, `null` won't be returned
        // as the range is different than the moved range.
        diff = diff._getTransformedByDeletion(moveOp.sourcePosition, moveOp.howMany);
        // Transform also `targetPosition`.
        const targetPosition = moveOp.getMovedRangeStart();
        // Spread the range only if moved nodes are inserted only between the top-level nodes of the `diff` range.
        const spread = diff.start.hasSameParentAs(targetPosition);
        // Transform by insertion of moved nodes.
        const diffs = diff._getTransformedByInsertion(targetPosition, moveOp.howMany, spread);
        result.push(...diffs);
    }
    // Common part can be simply transformed by the move operation. This is because move operation will not target to
    // that common part (the operation would have to target inside its own moved range).
    if (common) {
        result.push(common._getTransformedByMove(moveOp.sourcePosition, moveOp.targetPosition, moveOp.howMany, false)[0]);
    }
    return result;
}
setTransformation(AttributeOperation, SplitOperation, (a, b)=>{
    // Case 1:
    //
    // Split node is the last node in `AttributeOperation#range`.
    // `AttributeOperation#range` needs to be expanded to include the new (split) node.
    //
    // Attribute `type` to be changed to `numbered` but the `listItem` is split.
    // <listItem type="bulleted">foobar</listItem>
    //
    // After split:
    // <listItem type="bulleted">foo</listItem><listItem type="bulleted">bar</listItem>
    //
    // After attribute change:
    // <listItem type="numbered">foo</listItem><listItem type="numbered">foo</listItem>
    //
    if (a.range.end.isEqual(b.insertionPosition)) {
        if (!b.graveyardPosition) {
            a.range.end.offset++;
        }
        return [
            a
        ];
    }
    // Case 2:
    //
    // Split position is inside `AttributeOperation#range`, at the same level, so the nodes to change are
    // not going to make a flat range.
    //
    // Content with range-to-change and split position:
    // <p>Fo[zb^a]r</p>
    //
    // After split:
    // <p>Fozb</p><p>ar</p>
    //
    // Make two separate ranges containing all nodes to change:
    // <p>Fo[zb]</p><p>[a]r</p>
    //
    if (a.range.start.hasSameParentAs(b.splitPosition) && a.range.containsPosition(b.splitPosition)) {
        const secondPart = a.clone();
        secondPart.range = new Range(b.moveTargetPosition.clone(), a.range.end._getCombined(b.splitPosition, b.moveTargetPosition));
        a.range.end = b.splitPosition.clone();
        a.range.end.stickiness = 'toPrevious';
        return [
            a,
            secondPart
        ];
    }
    // The default case.
    //
    a.range = a.range._getTransformedBySplitOperation(b);
    return [
        a
    ];
});
setTransformation(InsertOperation, AttributeOperation, (a, b)=>{
    const result = [
        a
    ];
    // Case 1:
    //
    // The attribute operation range includes the position where nodes were inserted.
    // There are two possible scenarios: the inserted nodes were text and they should receive attributes or
    // the inserted nodes were elements and they should not receive attributes.
    //
    // This is a mirror scenario to the one described in `AttributeOperation` x `InsertOperation` transformation,
    // although this case is a little less complicated. In this case we simply need to change attributes of the
    // inserted nodes and that's it.
    //
    if (a.shouldReceiveAttributes && a.position.hasSameParentAs(b.range.start) && b.range.containsPosition(a.position)) {
        const op = _getComplementaryAttributeOperations(a, b.key, b.newValue);
        if (op) {
            result.push(op);
        }
    }
    // The default case is: do nothing.
    // `AttributeOperation` does not change the model tree structure so `InsertOperation` does not need to be changed.
    //
    return result;
});
setTransformation(InsertOperation, InsertOperation, (a, b, context)=>{
    // Case 1:
    //
    // Two insert operations insert nodes at the same position. Since they are the same, it needs to be decided
    // what will be the order of inserted nodes. However, there is no additional information to help in that
    // decision. Also, when `b` will be transformed by `a`, the same order must be maintained.
    //
    // To achieve that, we will check if the operation is strong.
    // If it is, it won't get transformed. If it is not, it will be moved.
    //
    if (a.position.isEqual(b.position) && context.aIsStrong) {
        return [
            a
        ];
    }
    // The default case.
    //
    a.position = a.position._getTransformedByInsertOperation(b);
    return [
        a
    ];
});
setTransformation(InsertOperation, MoveOperation, (a, b)=>{
    // The default case.
    //
    a.position = a.position._getTransformedByMoveOperation(b);
    return [
        a
    ];
});
setTransformation(InsertOperation, SplitOperation, (a, b)=>{
    // The default case.
    //
    a.position = a.position._getTransformedBySplitOperation(b);
    return [
        a
    ];
});
setTransformation(InsertOperation, MergeOperation, (a, b)=>{
    a.position = a.position._getTransformedByMergeOperation(b);
    return [
        a
    ];
});
// -----------------------
setTransformation(MarkerOperation, InsertOperation, (a, b)=>{
    if (a.oldRange) {
        a.oldRange = a.oldRange._getTransformedByInsertOperation(b)[0];
    }
    if (a.newRange) {
        a.newRange = a.newRange._getTransformedByInsertOperation(b)[0];
    }
    return [
        a
    ];
});
setTransformation(MarkerOperation, MarkerOperation, (a, b, context)=>{
    if (a.name == b.name) {
        if (context.aIsStrong) {
            a.oldRange = b.newRange ? b.newRange.clone() : null;
        } else {
            return [
                new NoOperation(0)
            ];
        }
    }
    return [
        a
    ];
});
setTransformation(MarkerOperation, MergeOperation, (a, b)=>{
    if (a.oldRange) {
        a.oldRange = a.oldRange._getTransformedByMergeOperation(b);
    }
    if (a.newRange) {
        a.newRange = a.newRange._getTransformedByMergeOperation(b);
    }
    return [
        a
    ];
});
setTransformation(MarkerOperation, MoveOperation, (a, b, context)=>{
    if (a.oldRange) {
        a.oldRange = Range._createFromRanges(a.oldRange._getTransformedByMoveOperation(b));
    }
    if (a.newRange) {
        if (context.abRelation) {
            const aNewRange = Range._createFromRanges(a.newRange._getTransformedByMoveOperation(b));
            if (context.abRelation.side == 'left' && b.targetPosition.isEqual(a.newRange.start)) {
                a.newRange.end = aNewRange.end;
                a.newRange.start.path = context.abRelation.path;
                return [
                    a
                ];
            } else if (context.abRelation.side == 'right' && b.targetPosition.isEqual(a.newRange.end)) {
                a.newRange.start = aNewRange.start;
                a.newRange.end.path = context.abRelation.path;
                return [
                    a
                ];
            }
        }
        a.newRange = Range._createFromRanges(a.newRange._getTransformedByMoveOperation(b));
    }
    return [
        a
    ];
});
setTransformation(MarkerOperation, SplitOperation, (a, b, context)=>{
    if (a.oldRange) {
        a.oldRange = a.oldRange._getTransformedBySplitOperation(b);
    }
    if (a.newRange) {
        if (context.abRelation) {
            const aNewRange = a.newRange._getTransformedBySplitOperation(b);
            if (a.newRange.start.isEqual(b.splitPosition) && context.abRelation.wasStartBeforeMergedElement) {
                a.newRange.start = Position._createAt(b.insertionPosition);
            } else if (a.newRange.start.isEqual(b.splitPosition) && !context.abRelation.wasInLeftElement) {
                a.newRange.start = Position._createAt(b.moveTargetPosition);
            }
            if (a.newRange.end.isEqual(b.splitPosition) && context.abRelation.wasInRightElement) {
                a.newRange.end = Position._createAt(b.moveTargetPosition);
            } else if (a.newRange.end.isEqual(b.splitPosition) && context.abRelation.wasEndBeforeMergedElement) {
                a.newRange.end = Position._createAt(b.insertionPosition);
            } else {
                a.newRange.end = aNewRange.end;
            }
            return [
                a
            ];
        }
        a.newRange = a.newRange._getTransformedBySplitOperation(b);
    }
    return [
        a
    ];
});
// -----------------------
setTransformation(MergeOperation, InsertOperation, (a, b)=>{
    if (a.sourcePosition.hasSameParentAs(b.position)) {
        a.howMany += b.howMany;
    }
    a.sourcePosition = a.sourcePosition._getTransformedByInsertOperation(b);
    a.targetPosition = a.targetPosition._getTransformedByInsertOperation(b);
    return [
        a
    ];
});
setTransformation(MergeOperation, MergeOperation, (a, b, context)=>{
    // Case 1:
    //
    // Same merge operations.
    //
    // Both operations have same source and target positions. So the element already got merged and there is
    // theoretically nothing to do.
    //
    if (a.sourcePosition.isEqual(b.sourcePosition) && a.targetPosition.isEqual(b.targetPosition)) {
        // There are two ways that we can provide a do-nothing operation.
        //
        // First is simply a NoOperation instance. We will use it if `b` operation was not undone.
        //
        // Second is a merge operation that has the source operation in the merged element - in the graveyard -
        // same target position and `howMany` equal to `0`. So it is basically merging an empty element from graveyard
        // which is almost the same as NoOperation.
        //
        // This way the merge operation can be later transformed by split operation
        // to provide correct undo. This will be used if `b` operation was undone (only then it is correct).
        //
        if (!context.bWasUndone) {
            return [
                new NoOperation(0)
            ];
        } else {
            const path = b.graveyardPosition.path.slice();
            path.push(0);
            a.sourcePosition = new Position(b.graveyardPosition.root, path);
            a.howMany = 0;
            return [
                a
            ];
        }
    }
    // Case 2:
    //
    // Same merge source position but different target position.
    //
    // This can happen during collaboration. For example, if one client merged a paragraph to the previous paragraph
    // and the other person removed that paragraph and merged the same paragraph to something before:
    //
    // Client A:
    // <p>Foo</p><p>Bar</p><p>[]Xyz</p>
    // <p>Foo</p><p>BarXyz</p>
    //
    // Client B:
    // <p>Foo</p>[<p>Bar</p>]<p>Xyz</p>
    // <p>Foo</p><p>[]Xyz</p>
    // <p>FooXyz</p>
    //
    // In this case we need to decide where finally "Xyz" will land:
    //
    // <p>FooXyz</p>               graveyard: <p>Bar</p>
    // <p>Foo</p>                  graveyard: <p>BarXyz</p>
    //
    // Let's move it in a way so that a merge operation that does not target to graveyard is more important so that
    // nodes does not end up in the graveyard. It makes sense. Both for Client A and for Client B "Xyz" finally did not
    // end up in the graveyard (see above).
    //
    // If neither or both operations point to graveyard, then let `aIsStrong` decide.
    //
    if (a.sourcePosition.isEqual(b.sourcePosition) && !a.targetPosition.isEqual(b.targetPosition) && !context.bWasUndone && context.abRelation != 'splitAtSource') {
        const aToGraveyard = a.targetPosition.root.rootName == '$graveyard';
        const bToGraveyard = b.targetPosition.root.rootName == '$graveyard';
        // If `aIsWeak` it means that `a` points to graveyard while `b` doesn't. Don't move nodes then.
        const aIsWeak = aToGraveyard && !bToGraveyard;
        // If `bIsWeak` it means that `b` points to graveyard while `a` doesn't. Force moving nodes then.
        const bIsWeak = bToGraveyard && !aToGraveyard;
        // Force move if `b` is weak or neither operation is weak but `a` is stronger through `context.aIsStrong`.
        const forceMove = bIsWeak || !aIsWeak && context.aIsStrong;
        if (forceMove) {
            const sourcePosition = b.targetPosition._getTransformedByMergeOperation(b);
            const targetPosition = a.targetPosition._getTransformedByMergeOperation(b);
            return [
                new MoveOperation(sourcePosition, a.howMany, targetPosition, 0)
            ];
        } else {
            return [
                new NoOperation(0)
            ];
        }
    }
    // The default case.
    //
    if (a.sourcePosition.hasSameParentAs(b.targetPosition)) {
        a.howMany += b.howMany;
    }
    a.sourcePosition = a.sourcePosition._getTransformedByMergeOperation(b);
    a.targetPosition = a.targetPosition._getTransformedByMergeOperation(b);
    // Handle positions in graveyard.
    // If graveyard positions are same and `a` operation is strong - do not transform.
    if (!a.graveyardPosition.isEqual(b.graveyardPosition) || !context.aIsStrong) {
        a.graveyardPosition = a.graveyardPosition._getTransformedByMergeOperation(b);
    }
    return [
        a
    ];
});
setTransformation(MergeOperation, MoveOperation, (a, b, context)=>{
    // Case 1:
    //
    // The element to merge got removed.
    //
    // Merge operation does support merging elements which are not siblings. So it would not be a problem
    // from technical point of view. However, if the element was removed, the intention of the user deleting it
    // was to have it all deleted, together with its children. From user experience point of view, moving back the
    // removed nodes might be unexpected. This means that in this scenario we will block the merging.
    //
    // The exception of this rule would be if the remove operation was later undone.
    //
    const removedRange = Range._createFromPositionAndShift(b.sourcePosition, b.howMany);
    if (b.type == 'remove' && !context.bWasUndone && !context.forceWeakRemove) {
        if (a.deletionPosition.hasSameParentAs(b.sourcePosition) && removedRange.containsPosition(a.sourcePosition)) {
            return [
                new NoOperation(0)
            ];
        }
    }
    // In most cases we want `sourcePosition` to stick to previous and `targetPosition` to stick to next.
    // Usually, `sourcePosition` is at the beginning of the merged element and `targetPosition` is at the end of the merge-target element.
    //
    // However, `sourcePosition` and `targetPosition` may end up in the middle of an element due to some OT magic that happens during undo.
    // It is expected and used in `MergeOperation` x `SplitOperation` transformation.
    //
    // But when these positions are in the middle, it messes up the regular `MergeOperation` x `MoveOperation` transformation because
    // these positions may "follow" some moved elements. And we want them stick in the original elements.
    //
    // This is why we add two extra cases: (1) and (2).
    //
    // But after this `MergeOperation` is transformed by "this" move (which is undone), we also need to define extra cases for
    // the operation undoing previous move. These are (3) and (4).
    //
    // (1). Note that this case is also added to `updateRelations()` and sets `mergeSourceAffected` relation.
    //
    // [] is move operation, } is merge source position (sticks to previous by default):
    // <p>A[b]}c</p>  ->  <p>A}c</p>
    //
    if (b.sourcePosition.getShiftedBy(b.howMany).isEqual(a.sourcePosition)) {
        a.sourcePosition.stickiness = 'toNone';
    } else if (b.targetPosition.isEqual(a.sourcePosition) && context.abRelation == 'mergeSourceAffected') {
        a.sourcePosition.stickiness = 'toNext';
    } else if (b.sourcePosition.isEqual(a.targetPosition)) {
        a.targetPosition.stickiness = 'toNone';
        a.howMany -= b.howMany;
    } else if (b.targetPosition.isEqual(a.targetPosition) && context.abRelation == 'mergeTargetWasBefore') {
        a.targetPosition.stickiness = 'toPrevious';
        a.howMany += b.howMany;
    } else {
        if (a.sourcePosition.hasSameParentAs(b.targetPosition)) {
            a.howMany += b.howMany;
        }
        if (a.sourcePosition.hasSameParentAs(b.sourcePosition)) {
            a.howMany -= b.howMany;
        }
    }
    a.sourcePosition = a.sourcePosition._getTransformedByMoveOperation(b);
    a.targetPosition = a.targetPosition._getTransformedByMoveOperation(b);
    // After transformations are done, make sure to revert stickiness in case if (1) - (4) scenario happened.
    a.sourcePosition.stickiness = 'toPrevious';
    a.targetPosition.stickiness = 'toNext';
    // `MergeOperation` graveyard position is like `MoveOperation` target position. It is a position where element(s) will
    // be moved. Like in other similar cases, we need to consider the scenario when those positions are same.
    // Here, we will treat `MergeOperation` like it is always strong (see `InsertOperation` x `InsertOperation` for comparison).
    // This means that we won't transform graveyard position if it is equal to move operation target position.
    if (!a.graveyardPosition.isEqual(b.targetPosition)) {
        a.graveyardPosition = a.graveyardPosition._getTransformedByMoveOperation(b);
    }
    return [
        a
    ];
});
setTransformation(MergeOperation, SplitOperation, (a, b, context)=>{
    if (b.graveyardPosition) {
        // If `b` operation defines graveyard position, a node from graveyard will be moved. This means that we need to
        // transform `a.graveyardPosition` accordingly.
        a.graveyardPosition = a.graveyardPosition._getTransformedByDeletion(b.graveyardPosition, 1);
        // This is a scenario foreseen in `MergeOperation` x `MergeOperation`, with two identical merge operations.
        //
        // So, there was `MergeOperation` x `MergeOperation` transformation earlier. Now, `a` is a merge operation which
        // source position is in graveyard. Interestingly, split operation wants to use the node to be merged by `a`. This
        // means that `b` is undoing that merge operation from earlier, which caused `a` to be in graveyard.
        //
        // If that's the case, at this point, we will only "fix" `a.howMany`. It was earlier set to `0` in
        // `MergeOperation` x `MergeOperation` transformation. Later transformations in this function will change other
        // properties.
        //
        if (a.deletionPosition.isEqual(b.graveyardPosition)) {
            a.howMany = b.howMany;
        }
    }
    // Case 1:
    //
    // Merge operation moves nodes to the place where split happens.
    // This is a classic situation when there are two paragraphs, and there is a split (enter) after the first
    // paragraph and there is a merge (delete) at the beginning of the second paragraph:
    //
    // <p>Foo{}</p><p>[]Bar</p>.
    //
    // Split is after `Foo`, while merge is from `Bar` to the end of `Foo`.
    //
    // State after split:
    // <p>Foo</p><p></p><p>Bar</p>
    //
    // Now, `Bar` should be merged to the new paragraph:
    // <p>Foo</p><p>Bar</p>
    //
    // Instead of merging it to the original paragraph:
    // <p>FooBar</p><p></p>
    //
    // This means that `targetPosition` needs to be transformed. This is the default case though.
    // For example, if the split would be after `F`, `targetPosition` should also be transformed.
    //
    // There are three exceptions, though, when we want to keep `targetPosition` as it was.
    //
    // First exception is when the merge target position is inside an element (not at the end, as usual). This
    // happens when the merge operation earlier was transformed by "the same" merge operation. If merge operation
    // targets inside the element we want to keep the original target position (and not transform it) because
    // we have additional context telling us that we want to merge to the original element. We can check if the
    // merge operation points inside element by checking what is `SplitOperation#howMany`. Since merge target position
    // is same as split position, if `howMany` is non-zero, it means that the merge target position is inside an element.
    //
    // Second exception is when the element to merge is in the graveyard and split operation uses it. In that case
    // if target position would be transformed, the merge operation would target at the source position:
    //
    // root: <p>Foo</p>				graveyard: <p></p>
    //
    // SplitOperation: root [ 0, 3 ] using graveyard [ 0 ] (howMany = 0)
    // MergeOperation: graveyard [ 0, 0 ] -> root [ 0, 3 ] (howMany = 0)
    //
    // Since split operation moves the graveyard node back to the root, the merge operation source position changes.
    // We would like to merge from the empty <p> to the "Foo" <p>:
    //
    // root: <p>Foo</p><p></p>			graveyard:
    //
    // MergeOperation#sourcePosition = root [ 1, 0 ]
    //
    // If `targetPosition` is transformed, it would become root [ 1, 0 ] as well. It has to be kept as it was.
    //
    // Third exception is connected with relations. If this happens during undo and we have explicit information
    // that target position has not been affected by the operation which is undone by this split then this split should
    // not move the target position either.
    //
    if (a.targetPosition.isEqual(b.splitPosition)) {
        const mergeInside = b.howMany != 0;
        const mergeSplittingElement = b.graveyardPosition && a.deletionPosition.isEqual(b.graveyardPosition);
        if (mergeInside || mergeSplittingElement || context.abRelation == 'mergeTargetNotMoved') {
            a.sourcePosition = a.sourcePosition._getTransformedBySplitOperation(b);
            return [
                a
            ];
        }
    }
    // Case 2:
    //
    // Merge source is at the same position as split position. This sometimes happen, mostly during undo.
    // The decision here is mostly to choose whether merge source position should stay where it is (so it will be at the end of the
    // split element) or should be move to the beginning of the new element.
    //
    if (a.sourcePosition.isEqual(b.splitPosition)) {
        // Use context to check if `SplitOperation` is not undoing a merge operation, that didn't change the `a` operation.
        // This scenario happens the undone merge operation moved nodes at the source position of `a` operation.
        // In that case `a` operation source position should stay where it is.
        if (context.abRelation == 'mergeSourceNotMoved') {
            a.howMany = 0;
            a.targetPosition = a.targetPosition._getTransformedBySplitOperation(b);
            return [
                a
            ];
        }
        // This merge operation might have been earlier transformed by a merge operation which both merged the same element.
        // See that case in `MergeOperation` x `MergeOperation` transformation. In that scenario, if the merge operation has been undone,
        // the special case is not applied.
        //
        // Now, the merge operation is transformed by the split which has undone that previous merge operation.
        // So now we are fixing situation which was skipped in `MergeOperation` x `MergeOperation` case.
        //
        if (context.abRelation == 'mergeSameElement' || a.sourcePosition.offset > 0) {
            a.sourcePosition = b.moveTargetPosition.clone();
            a.targetPosition = a.targetPosition._getTransformedBySplitOperation(b);
            return [
                a
            ];
        }
    }
    // The default case.
    //
    if (a.sourcePosition.hasSameParentAs(b.splitPosition)) {
        a.howMany = b.splitPosition.offset;
    }
    a.sourcePosition = a.sourcePosition._getTransformedBySplitOperation(b);
    a.targetPosition = a.targetPosition._getTransformedBySplitOperation(b);
    return [
        a
    ];
});
// -----------------------
setTransformation(MoveOperation, InsertOperation, (a, b)=>{
    const moveRange = Range._createFromPositionAndShift(a.sourcePosition, a.howMany);
    const transformed = moveRange._getTransformedByInsertOperation(b, false)[0];
    a.sourcePosition = transformed.start;
    a.howMany = transformed.end.offset - transformed.start.offset;
    // See `InsertOperation` x `MoveOperation` transformation for details on this case.
    //
    // In summary, both operations point to the same place, so the order of nodes needs to be decided.
    // `MoveOperation` is considered weaker, so it is always transformed, unless there was a certain relation
    // between operations.
    //
    if (!a.targetPosition.isEqual(b.position)) {
        a.targetPosition = a.targetPosition._getTransformedByInsertOperation(b);
    }
    return [
        a
    ];
});
setTransformation(MoveOperation, MoveOperation, (a, b, context)=>{
    //
    // Setting and evaluating some variables that will be used in special cases and default algorithm.
    //
    // Create ranges from `MoveOperations` properties.
    const rangeA = Range._createFromPositionAndShift(a.sourcePosition, a.howMany);
    const rangeB = Range._createFromPositionAndShift(b.sourcePosition, b.howMany);
    // Assign `context.aIsStrong` to a different variable, because the value may change during execution of
    // this algorithm and we do not want to override original `context.aIsStrong` that will be used in later transformations.
    let aIsStrong = context.aIsStrong;
    // This will be used to decide the order of nodes if both operations target at the same position.
    // By default, use strong/weak operation mechanism.
    let insertBefore = !context.aIsStrong;
    // If the relation is set, then use it to decide nodes order.
    if (context.abRelation == 'insertBefore' || context.baRelation == 'insertAfter') {
        insertBefore = true;
    } else if (context.abRelation == 'insertAfter' || context.baRelation == 'insertBefore') {
        insertBefore = false;
    }
    // `a.targetPosition` could be affected by the `b` operation. We will transform it.
    let newTargetPosition;
    if (a.targetPosition.isEqual(b.targetPosition) && insertBefore) {
        newTargetPosition = a.targetPosition._getTransformedByDeletion(b.sourcePosition, b.howMany);
    } else {
        newTargetPosition = a.targetPosition._getTransformedByMove(b.sourcePosition, b.targetPosition, b.howMany);
    }
    //
    // Special case #1 + mirror.
    //
    // Special case when both move operations' target positions are inside nodes that are
    // being moved by the other move operation. So in other words, we move ranges into inside of each other.
    // This case can't be solved reasonably (on the other hand, it should not happen often).
    if (_moveTargetIntoMovedRange(a, b) && _moveTargetIntoMovedRange(b, a)) {
        // Instead of transforming operation, we return a reverse of the operation that we transform by.
        // So when the results of this "transformation" will be applied, `b` MoveOperation will get reversed.
        return [
            b.getReversed()
        ];
    }
    //
    // End of special case #1.
    //
    //
    // Special case #2.
    //
    // Check if `b` operation targets inside `rangeA`.
    const bTargetsToA = rangeA.containsPosition(b.targetPosition);
    // If `b` targets to `rangeA` and `rangeA` contains `rangeB`, `b` operation has no influence on `a` operation.
    // You might say that operation `b` is captured inside operation `a`.
    if (bTargetsToA && rangeA.containsRange(rangeB, true)) {
        // There is a mini-special case here, where `rangeB` is on other level than `rangeA`. That's why
        // we need to transform `a` operation anyway.
        rangeA.start = rangeA.start._getTransformedByMove(b.sourcePosition, b.targetPosition, b.howMany);
        rangeA.end = rangeA.end._getTransformedByMove(b.sourcePosition, b.targetPosition, b.howMany);
        return _makeMoveOperationsFromRanges([
            rangeA
        ], newTargetPosition);
    }
    //
    // Special case #2 mirror.
    //
    const aTargetsToB = rangeB.containsPosition(a.targetPosition);
    if (aTargetsToB && rangeB.containsRange(rangeA, true)) {
        // `a` operation is "moved together" with `b` operation.
        // Here, just move `rangeA` "inside" `rangeB`.
        rangeA.start = rangeA.start._getCombined(b.sourcePosition, b.getMovedRangeStart());
        rangeA.end = rangeA.end._getCombined(b.sourcePosition, b.getMovedRangeStart());
        return _makeMoveOperationsFromRanges([
            rangeA
        ], newTargetPosition);
    }
    //
    // End of special case #2.
    //
    //
    // Special case #3 + mirror.
    //
    // `rangeA` has a node which is an ancestor of `rangeB`. In other words, `rangeB` is inside `rangeA`
    // but not on the same tree level. In such case ranges have common part but we have to treat it
    // differently, because in such case those ranges are not really conflicting and should be treated like
    // two separate ranges. Also we have to discard two difference parts.
    const aCompB = compareArrays(a.sourcePosition.getParentPath(), b.sourcePosition.getParentPath());
    if (aCompB == 'prefix' || aCompB == 'extension') {
        // Transform `rangeA` by `b` operation and make operation out of it, and that's all.
        // Note that this is a simplified version of default case, but here we treat the common part (whole `rangeA`)
        // like a one difference part.
        rangeA.start = rangeA.start._getTransformedByMove(b.sourcePosition, b.targetPosition, b.howMany);
        rangeA.end = rangeA.end._getTransformedByMove(b.sourcePosition, b.targetPosition, b.howMany);
        return _makeMoveOperationsFromRanges([
            rangeA
        ], newTargetPosition);
    }
    //
    // End of special case #3.
    //
    //
    // Default case - ranges are on the same level or are not connected with each other.
    //
    // Modifier for default case.
    // Modifies `aIsStrong` flag in certain conditions.
    //
    // If only one of operations is a remove operation, we force remove operation to be the "stronger" one
    // to provide more expected results.
    if (a.type == 'remove' && b.type != 'remove' && !context.aWasUndone && !context.forceWeakRemove) {
        aIsStrong = true;
    } else if (a.type != 'remove' && b.type == 'remove' && !context.bWasUndone && !context.forceWeakRemove) {
        aIsStrong = false;
    }
    // Handle operation's source ranges - check how `rangeA` is affected by `b` operation.
    // This will aggregate transformed ranges.
    const ranges = [];
    // Get the "difference part" of `a` operation source range.
    // This is an array with one or two ranges. Two ranges if `rangeB` is inside `rangeA`.
    const difference = rangeA.getDifference(rangeB);
    for (const range of difference){
        // Transform those ranges by `b` operation. For example if `b` moved range from before those ranges, fix those ranges.
        range.start = range.start._getTransformedByDeletion(b.sourcePosition, b.howMany);
        range.end = range.end._getTransformedByDeletion(b.sourcePosition, b.howMany);
        // If `b` operation targets into `rangeA` on the same level, spread `rangeA` into two ranges.
        const shouldSpread = compareArrays(range.start.getParentPath(), b.getMovedRangeStart().getParentPath()) == 'same';
        const newRanges = range._getTransformedByInsertion(b.getMovedRangeStart(), b.howMany, shouldSpread);
        ranges.push(...newRanges);
    }
    // Then, we have to manage the "common part" of both move ranges.
    const common = rangeA.getIntersection(rangeB);
    if (common !== null && aIsStrong) {
        // Calculate the new position of that part of original range.
        common.start = common.start._getCombined(b.sourcePosition, b.getMovedRangeStart());
        common.end = common.end._getCombined(b.sourcePosition, b.getMovedRangeStart());
        // Take care of proper range order.
        //
        // Put `common` at appropriate place. Keep in mind that we are interested in original order.
        // Basically there are only three cases: there is zero, one or two difference ranges.
        //
        // If there is zero difference ranges, just push `common` in the array.
        if (ranges.length === 0) {
            ranges.push(common);
        } else if (ranges.length == 1) {
            if (rangeB.start.isBefore(rangeA.start) || rangeB.start.isEqual(rangeA.start)) {
                ranges.unshift(common);
            } else {
                ranges.push(common);
            }
        } else {
            ranges.splice(1, 0, common);
        }
    }
    if (ranges.length === 0) {
        // If there are no "source ranges", nothing should be changed.
        // Note that this can happen only if `aIsStrong == false` and `rangeA.isEqual( rangeB )`.
        return [
            new NoOperation(a.baseVersion)
        ];
    }
    return _makeMoveOperationsFromRanges(ranges, newTargetPosition);
});
setTransformation(MoveOperation, SplitOperation, (a, b, context)=>{
    let newTargetPosition = a.targetPosition.clone();
    // Do not transform if target position is same as split insertion position and this split comes from undo.
    // This should be done on relations but it is too much work for now as it would require relations working in collaboration.
    // We need to make a decision how we will resolve such conflict and this is less harmful way.
    if (!a.targetPosition.isEqual(b.insertionPosition) || !b.graveyardPosition || context.abRelation == 'moveTargetAfter') {
        newTargetPosition = a.targetPosition._getTransformedBySplitOperation(b);
    }
    // Case 1:
    //
    // Last element in the moved range got split.
    //
    // In this case the default range transformation will not work correctly as the element created by
    // split operation would be outside the range. The range to move needs to be fixed manually.
    //
    const moveRange = Range._createFromPositionAndShift(a.sourcePosition, a.howMany);
    if (moveRange.end.isEqual(b.insertionPosition)) {
        // Do it only if this is a "natural" split, not a one that comes from undo.
        // If this is undo split, only `targetPosition` needs to be changed (if the move is a remove).
        if (!b.graveyardPosition) {
            a.howMany++;
        }
        a.targetPosition = newTargetPosition;
        return [
            a
        ];
    }
    // Case 2:
    //
    // Split happened between the moved nodes. In this case two ranges to move need to be generated.
    //
    // Characters `ozba` are moved to the end of paragraph `Xyz` but split happened.
    // <p>F[oz|ba]r</p><p>Xyz</p>
    //
    // After split:
    // <p>F[oz</p><p>ba]r</p><p>Xyz</p>
    //
    // Correct ranges:
    // <p>F[oz]</p><p>[ba]r</p><p>Xyz</p>
    //
    // After move:
    // <p>F</p><p>r</p><p>Xyzozba</p>
    //
    if (moveRange.start.hasSameParentAs(b.splitPosition) && moveRange.containsPosition(b.splitPosition)) {
        let rightRange = new Range(b.splitPosition, moveRange.end);
        rightRange = rightRange._getTransformedBySplitOperation(b);
        const ranges = [
            new Range(moveRange.start, b.splitPosition),
            rightRange
        ];
        return _makeMoveOperationsFromRanges(ranges, newTargetPosition);
    }
    // Case 3:
    //
    // Move operation targets at the split position. We need to decide if the nodes should be inserted
    // at the end of the split element or at the beginning of the new element.
    //
    if (a.targetPosition.isEqual(b.splitPosition) && context.abRelation == 'insertAtSource') {
        newTargetPosition = b.moveTargetPosition;
    }
    // Case 4:
    //
    // Move operation targets just after the split element. We need to decide if the nodes should be inserted
    // between two parts of split element, or after the new element.
    //
    // Split at `|`, while move operation moves `<p>Xyz</p>` and targets at `^`:
    // <p>Foo|bar</p>^<p>baz</p>
    // <p>Foo</p>^<p>bar</p><p>baz</p> or <p>Foo</p><p>bar</p>^<p>baz</p>?
    //
    // If there is no contextual information between operations (for example, they come from collaborative
    // editing), we don't want to put some unrelated content (move) between parts of related content (split parts).
    // However, if the split is from undo, in the past, the moved content might be targeting between the
    // split parts, meaning that was exactly user's intention:
    //
    // <p>Foo</p>^<p>bar</p>		<--- original situation, in "past".
    // <p>Foobar</p>^				<--- after merge target position is transformed.
    // <p>Foo|bar</p>^				<--- then the merge is undone, and split happens, which leads us to current situation.
    //
    // In this case it is pretty clear that the intention was to put new paragraph between those nodes,
    // so we need to transform accordingly. We can detect this scenario thanks to relations.
    //
    if (a.targetPosition.isEqual(b.insertionPosition) && context.abRelation == 'insertBetween') {
        newTargetPosition = a.targetPosition;
    }
    // The default case.
    //
    const transformed = moveRange._getTransformedBySplitOperation(b);
    const ranges = [
        transformed
    ];
    // Case 5:
    //
    // Moved range contains graveyard element used by split operation. Add extra move operation to the result.
    //
    if (b.graveyardPosition) {
        const movesGraveyardElement = moveRange.start.isEqual(b.graveyardPosition) || moveRange.containsPosition(b.graveyardPosition);
        if (a.howMany > 1 && movesGraveyardElement && !context.aWasUndone) {
            ranges.push(Range._createFromPositionAndShift(b.insertionPosition, 1));
        }
    }
    return _makeMoveOperationsFromRanges(ranges, newTargetPosition);
});
setTransformation(MoveOperation, MergeOperation, (a, b, context)=>{
    const movedRange = Range._createFromPositionAndShift(a.sourcePosition, a.howMany);
    if (b.deletionPosition.hasSameParentAs(a.sourcePosition) && movedRange.containsPosition(b.sourcePosition)) {
        if (a.type == 'remove' && !context.forceWeakRemove) {
            // Case 1:
            //
            // The element to remove got merged.
            //
            // Merge operation does support merging elements which are not siblings. So it would not be a problem
            // from technical point of view. However, if the element was removed, the intention of the user
            // deleting it was to have it all deleted. From user experience point of view, moving back the
            // removed nodes might be unexpected. This means that in this scenario we will reverse merging and remove the element.
            //
            if (!context.aWasUndone) {
                const results = [];
                let gyMoveSource = b.graveyardPosition.clone();
                let splitNodesMoveSource = b.targetPosition._getTransformedByMergeOperation(b);
                if (a.howMany > 1) {
                    results.push(new MoveOperation(a.sourcePosition, a.howMany - 1, a.targetPosition, 0));
                    gyMoveSource = gyMoveSource._getTransformedByMove(a.sourcePosition, a.targetPosition, a.howMany - 1);
                    splitNodesMoveSource = splitNodesMoveSource._getTransformedByMove(a.sourcePosition, a.targetPosition, a.howMany - 1);
                }
                const gyMoveTarget = b.deletionPosition._getCombined(a.sourcePosition, a.targetPosition);
                const gyMove = new MoveOperation(gyMoveSource, 1, gyMoveTarget, 0);
                const splitNodesMoveTargetPath = gyMove.getMovedRangeStart().path.slice();
                splitNodesMoveTargetPath.push(0);
                const splitNodesMoveTarget = new Position(gyMove.targetPosition.root, splitNodesMoveTargetPath);
                splitNodesMoveSource = splitNodesMoveSource._getTransformedByMove(gyMoveSource, gyMoveTarget, 1);
                const splitNodesMove = new MoveOperation(splitNodesMoveSource, b.howMany, splitNodesMoveTarget, 0);
                results.push(gyMove);
                results.push(splitNodesMove);
                return results;
            }
        } else {
            // Case 2:
            //
            // The element to move got merged and it was the only element to move.
            // In this case just don't do anything, leave the node in the graveyard. Without special case
            // it would be a move operation that moves 0 nodes, so maybe it is better just to return no-op.
            //
            if (a.howMany == 1) {
                if (!context.bWasUndone) {
                    return [
                        new NoOperation(0)
                    ];
                } else {
                    a.sourcePosition = b.graveyardPosition.clone();
                    a.targetPosition = a.targetPosition._getTransformedByMergeOperation(b);
                    return [
                        a
                    ];
                }
            }
        }
    }
    // The default case.
    //
    const moveRange = Range._createFromPositionAndShift(a.sourcePosition, a.howMany);
    const transformed = moveRange._getTransformedByMergeOperation(b);
    a.sourcePosition = transformed.start;
    a.howMany = transformed.end.offset - transformed.start.offset;
    a.targetPosition = a.targetPosition._getTransformedByMergeOperation(b);
    return [
        a
    ];
});
// -----------------------
setTransformation(RenameOperation, InsertOperation, (a, b)=>{
    a.position = a.position._getTransformedByInsertOperation(b);
    return [
        a
    ];
});
setTransformation(RenameOperation, MergeOperation, (a, b)=>{
    // Case 1:
    //
    // Element to rename got merged, so it was moved to `b.graveyardPosition`.
    //
    if (a.position.isEqual(b.deletionPosition)) {
        a.position = b.graveyardPosition.clone();
        a.position.stickiness = 'toNext';
        return [
            a
        ];
    }
    a.position = a.position._getTransformedByMergeOperation(b);
    return [
        a
    ];
});
setTransformation(RenameOperation, MoveOperation, (a, b)=>{
    a.position = a.position._getTransformedByMoveOperation(b);
    return [
        a
    ];
});
setTransformation(RenameOperation, RenameOperation, (a, b, context)=>{
    if (a.position.isEqual(b.position)) {
        if (context.aIsStrong) {
            a.oldName = b.newName;
        } else {
            return [
                new NoOperation(0)
            ];
        }
    }
    return [
        a
    ];
});
setTransformation(RenameOperation, SplitOperation, (a, b)=>{
    // Case 1:
    //
    // The element to rename has been split. In this case, the new element should be also renamed.
    //
    // User decides to change the paragraph to a list item:
    // <paragraph>Foobar</paragraph>
    //
    // However, in meantime, split happens:
    // <paragraph>Foo</paragraph><paragraph>bar</paragraph>
    //
    // As a result, rename both elements:
    // <listItem>Foo</listItem><listItem>bar</listItem>
    //
    const renamePath = a.position.path;
    const splitPath = b.splitPosition.getParentPath();
    if (compareArrays(renamePath, splitPath) == 'same' && !b.graveyardPosition) {
        const extraRename = new RenameOperation(a.position.getShiftedBy(1), a.oldName, a.newName, 0);
        return [
            a,
            extraRename
        ];
    }
    // The default case.
    //
    a.position = a.position._getTransformedBySplitOperation(b);
    return [
        a
    ];
});
// -----------------------
setTransformation(RootAttributeOperation, RootAttributeOperation, (a, b, context)=>{
    if (a.root === b.root && a.key === b.key) {
        if (!context.aIsStrong || a.newValue === b.newValue) {
            return [
                new NoOperation(0)
            ];
        } else {
            a.oldValue = b.newValue;
        }
    }
    return [
        a
    ];
});
// -----------------------
setTransformation(RootOperation, RootOperation, (a, b)=>{
    if (a.rootName === b.rootName && a.isAdd === b.isAdd) {
        return [
            new NoOperation(0)
        ];
    }
    return [
        a
    ];
});
// -----------------------
setTransformation(SplitOperation, InsertOperation, (a, b)=>{
    // The default case.
    //
    if (a.splitPosition.hasSameParentAs(b.position) && a.splitPosition.offset < b.position.offset) {
        a.howMany += b.howMany;
    }
    a.splitPosition = a.splitPosition._getTransformedByInsertOperation(b);
    a.insertionPosition = a.insertionPosition._getTransformedByInsertOperation(b);
    return [
        a
    ];
});
setTransformation(SplitOperation, MergeOperation, (a, b, context)=>{
    // Case 1:
    //
    // Split element got merged. If two different elements were merged, clients will have different content.
    //
    // Example. Merge at `{}`, split at `[]`:
    // <heading>Foo</heading>{}<paragraph>B[]ar</paragraph>
    //
    // On merge side it will look like this:
    // <heading>FooB[]ar</heading>
    // <heading>FooB</heading><heading>ar</heading>
    //
    // On split side it will look like this:
    // <heading>Foo</heading>{}<paragraph>B</paragraph><paragraph>ar</paragraph>
    // <heading>FooB</heading><paragraph>ar</paragraph>
    //
    // Clearly, the second element is different for both clients.
    //
    // We could use the removed merge element from graveyard as a split element but then clients would have a different
    // model state (in graveyard), because the split side client would still have an element in graveyard (removed by merge).
    //
    // To overcome this, in `SplitOperation` x `MergeOperation` transformation we will add additional `SplitOperation`
    // in the graveyard, which will actually clone the merged-and-deleted element. Then, that cloned element will be
    // used for splitting. Example below.
    //
    // Original state:
    // <heading>Foo</heading>{}<paragraph>B[]ar</paragraph>
    //
    // Merge side client:
    //
    // After merge:
    // <heading>FooB[]ar</heading>                                 graveyard: <paragraph></paragraph>
    //
    // Extra split:
    // <heading>FooB[]ar</heading>                                 graveyard: <paragraph></paragraph><paragraph></paragraph>
    //
    // Use the "cloned" element from graveyard:
    // <heading>FooB</heading><paragraph>ar</paragraph>            graveyard: <paragraph></paragraph>
    //
    // Split side client:
    //
    // After split:
    // <heading>Foo</heading>{}<paragraph>B</paragraph><paragraph>ar</paragraph>
    //
    // After merge:
    // <heading>FooB</heading><paragraph>ar</paragraph>            graveyard: <paragraph></paragraph>
    //
    // This special case scenario only applies if the original split operation clones the split element.
    // If the original split operation has `graveyardPosition` set, it all doesn't have sense because split operation
    // knows exactly which element it should use. So there would be no original problem with different contents.
    //
    // Additionally, the special case applies only if the merge wasn't already undone.
    //
    if (!a.graveyardPosition && !context.bWasUndone && a.splitPosition.hasSameParentAs(b.sourcePosition)) {
        const splitPath = b.graveyardPosition.path.slice();
        splitPath.push(0);
        const splitPosition = new Position(b.graveyardPosition.root, splitPath);
        const insertionPosition = SplitOperation.getInsertionPosition(new Position(b.graveyardPosition.root, splitPath));
        const additionalSplit = new SplitOperation(splitPosition, 0, insertionPosition, null, 0);
        a.splitPosition = a.splitPosition._getTransformedByMergeOperation(b);
        a.insertionPosition = SplitOperation.getInsertionPosition(a.splitPosition);
        a.graveyardPosition = additionalSplit.insertionPosition.clone();
        a.graveyardPosition.stickiness = 'toNext';
        return [
            additionalSplit,
            a
        ];
    }
    // The default case.
    //
    if (a.splitPosition.hasSameParentAs(b.deletionPosition) && !a.splitPosition.isAfter(b.deletionPosition)) {
        a.howMany--;
    }
    if (a.splitPosition.hasSameParentAs(b.targetPosition)) {
        a.howMany += b.howMany;
    }
    a.splitPosition = a.splitPosition._getTransformedByMergeOperation(b);
    a.insertionPosition = SplitOperation.getInsertionPosition(a.splitPosition);
    if (a.graveyardPosition) {
        a.graveyardPosition = a.graveyardPosition._getTransformedByMergeOperation(b);
    }
    return [
        a
    ];
});
setTransformation(SplitOperation, MoveOperation, (a, b, context)=>{
    const rangeToMove = Range._createFromPositionAndShift(b.sourcePosition, b.howMany);
    if (a.graveyardPosition) {
        // Case 1:
        //
        // Split operation graveyard node was moved. In this case move operation is stronger. Since graveyard element
        // is already moved to the correct position, we need to only move the nodes after the split position.
        // This will be done by `MoveOperation` instead of `SplitOperation`.
        //
        const gyElementMoved = rangeToMove.start.isEqual(a.graveyardPosition) || rangeToMove.containsPosition(a.graveyardPosition);
        if (!context.bWasUndone && gyElementMoved) {
            const sourcePosition = a.splitPosition._getTransformedByMoveOperation(b);
            const newParentPosition = a.graveyardPosition._getTransformedByMoveOperation(b);
            const newTargetPath = newParentPosition.path.slice();
            newTargetPath.push(0);
            const newTargetPosition = new Position(newParentPosition.root, newTargetPath);
            const moveOp = new MoveOperation(sourcePosition, a.howMany, newTargetPosition, 0);
            return [
                moveOp
            ];
        }
        a.graveyardPosition = a.graveyardPosition._getTransformedByMoveOperation(b);
    }
    // Case 2:
    //
    // Split is at a position where nodes were moved.
    //
    // This is a scenario described in `MoveOperation` x `SplitOperation` transformation but from the
    // "split operation point of view".
    //
    const splitAtTarget = a.splitPosition.isEqual(b.targetPosition);
    if (splitAtTarget && (context.baRelation == 'insertAtSource' || context.abRelation == 'splitBefore')) {
        a.howMany += b.howMany;
        a.splitPosition = a.splitPosition._getTransformedByDeletion(b.sourcePosition, b.howMany);
        a.insertionPosition = SplitOperation.getInsertionPosition(a.splitPosition);
        return [
            a
        ];
    }
    if (splitAtTarget && context.abRelation && context.abRelation.howMany) {
        const { howMany, offset } = context.abRelation;
        a.howMany += howMany;
        a.splitPosition = a.splitPosition.getShiftedBy(offset);
        return [
            a
        ];
    }
    // Case 3:
    //
    // If the split position is inside the moved range, we need to shift the split position to a proper place.
    // The position cannot be moved together with moved range because that would result in splitting of an incorrect element.
    //
    // Characters `bc` should be moved to the second paragraph while split position is between them:
    // <paragraph>A[b|c]d</paragraph><paragraph>Xyz</paragraph>
    //
    // After move, new split position is incorrect:
    // <paragraph>Ad</paragraph><paragraph>Xb|cyz</paragraph>
    //
    // Correct split position:
    // <paragraph>A|d</paragraph><paragraph>Xbcyz</paragraph>
    //
    // After split:
    // <paragraph>A</paragraph><paragraph>d</paragraph><paragraph>Xbcyz</paragraph>
    //
    if (a.splitPosition.hasSameParentAs(b.sourcePosition) && rangeToMove.containsPosition(a.splitPosition)) {
        const howManyRemoved = b.howMany - (a.splitPosition.offset - b.sourcePosition.offset);
        a.howMany -= howManyRemoved;
        if (a.splitPosition.hasSameParentAs(b.targetPosition) && a.splitPosition.offset < b.targetPosition.offset) {
            a.howMany += b.howMany;
        }
        a.splitPosition = b.sourcePosition.clone();
        a.insertionPosition = SplitOperation.getInsertionPosition(a.splitPosition);
        return [
            a
        ];
    }
    // The default case.
    // Don't change `howMany` if move operation does not really move anything.
    //
    if (!b.sourcePosition.isEqual(b.targetPosition)) {
        if (a.splitPosition.hasSameParentAs(b.sourcePosition) && a.splitPosition.offset <= b.sourcePosition.offset) {
            a.howMany -= b.howMany;
        }
        if (a.splitPosition.hasSameParentAs(b.targetPosition) && a.splitPosition.offset < b.targetPosition.offset) {
            a.howMany += b.howMany;
        }
    }
    // Change position stickiness to force a correct transformation.
    a.splitPosition.stickiness = 'toNone';
    a.splitPosition = a.splitPosition._getTransformedByMoveOperation(b);
    a.splitPosition.stickiness = 'toNext';
    if (a.graveyardPosition) {
        a.insertionPosition = a.insertionPosition._getTransformedByMoveOperation(b);
    } else {
        a.insertionPosition = SplitOperation.getInsertionPosition(a.splitPosition);
    }
    return [
        a
    ];
});
setTransformation(SplitOperation, SplitOperation, (a, b, context)=>{
    // Case 1:
    //
    // Split at the same position.
    //
    // If there already was a split at the same position as in `a` operation, it means that the intention
    // conveyed by `a` operation has already been fulfilled and `a` should not do anything (to avoid double split).
    //
    // However, there is a difference if these are new splits or splits created by undo. These have different
    // intentions. Also splits moving back different elements from graveyard have different intentions. They
    // are just different operations.
    //
    // So we cancel split operation only if it was really identical.
    //
    // Also, there is additional case, where split operations aren't identical and should not be cancelled, however the
    // default transformation is incorrect too.
    //
    if (a.splitPosition.isEqual(b.splitPosition)) {
        if (!a.graveyardPosition && !b.graveyardPosition) {
            return [
                new NoOperation(0)
            ];
        }
        if (a.graveyardPosition && b.graveyardPosition && a.graveyardPosition.isEqual(b.graveyardPosition)) {
            return [
                new NoOperation(0)
            ];
        }
        // Use context to know that the `a.splitPosition` should stay where it is.
        // This happens during undo when first a merge operation moved nodes to `a.splitPosition` and now `b` operation undoes that merge.
        if (context.abRelation == 'splitBefore') {
            // Since split is at the same position, there are no nodes left to split.
            a.howMany = 0;
            // Note: there was `if ( a.graveyardPosition )` here but it was uncovered in tests and I couldn't find any scenarios for now.
            // That would have to be a `SplitOperation` that didn't come from undo but is transformed by operations that were undone.
            // It could happen if `context` is enabled in collaboration.
            a.graveyardPosition = a.graveyardPosition._getTransformedBySplitOperation(b);
            return [
                a
            ];
        }
    }
    // Case 2:
    //
    // Same node is using to split different elements. This happens in undo when previously same element was merged to
    // two different elements. This is described in `MergeOperation` x `MergeOperation` transformation.
    //
    // In this case we will follow the same logic. We will assume that `insertionPosition` is same for both
    // split operations. This might not always be true but in the real cases that were experienced it was. After all,
    // if these splits are reverses of merge operations that were merging the same element, then the `insertionPosition`
    // should be same for both of those splits.
    //
    // Again, we will decide which operation is stronger by checking if split happens in graveyard or in non-graveyard root.
    //
    if (a.graveyardPosition && b.graveyardPosition && a.graveyardPosition.isEqual(b.graveyardPosition)) {
        const aInGraveyard = a.splitPosition.root.rootName == '$graveyard';
        const bInGraveyard = b.splitPosition.root.rootName == '$graveyard';
        // If `aIsWeak` it means that `a` points to graveyard while `b` doesn't. Don't move nodes then.
        const aIsWeak = aInGraveyard && !bInGraveyard;
        // If `bIsWeak` it means that `b` points to graveyard while `a` doesn't. Force moving nodes then.
        const bIsWeak = bInGraveyard && !aInGraveyard;
        // Force move if `b` is weak or neither operation is weak but `a` is stronger through `context.aIsStrong`.
        const forceMove = bIsWeak || !aIsWeak && context.aIsStrong;
        if (forceMove) {
            const result = [];
            // First we need to move any nodes split by `b` back to where they were.
            // Do it only if `b` actually moved something.
            if (b.howMany) {
                result.push(new MoveOperation(b.moveTargetPosition, b.howMany, b.splitPosition, 0));
            }
            // Then we need to move nodes from `a` split position to their new element.
            // Do it only if `a` actually should move something.
            if (a.howMany) {
                result.push(new MoveOperation(a.splitPosition, a.howMany, a.moveTargetPosition, 0));
            }
            return result;
        } else {
            return [
                new NoOperation(0)
            ];
        }
    }
    if (a.graveyardPosition) {
        a.graveyardPosition = a.graveyardPosition._getTransformedBySplitOperation(b);
    }
    // Case 3:
    //
    // Position where operation `b` inserted a new node after split is the same as the operation `a` split position.
    // As in similar cases, there is ambiguity if the split should be before the new node (created by `b`) or after.
    //
    if (a.splitPosition.isEqual(b.insertionPosition) && context.abRelation == 'splitBefore') {
        a.howMany++;
        return [
            a
        ];
    }
    // Case 4:
    //
    // This is a mirror to the case 2. above.
    //
    if (b.splitPosition.isEqual(a.insertionPosition) && context.baRelation == 'splitBefore') {
        const newPositionPath = b.insertionPosition.path.slice();
        newPositionPath.push(0);
        const newPosition = new Position(b.insertionPosition.root, newPositionPath);
        const moveOp = new MoveOperation(a.insertionPosition, 1, newPosition, 0);
        return [
            a,
            moveOp
        ];
    }
    // The default case.
    //
    if (a.splitPosition.hasSameParentAs(b.splitPosition) && a.splitPosition.offset < b.splitPosition.offset) {
        a.howMany -= b.howMany;
    }
    a.splitPosition = a.splitPosition._getTransformedBySplitOperation(b);
    a.insertionPosition = SplitOperation.getInsertionPosition(a.splitPosition);
    return [
        a
    ];
});
/**
 * Checks whether `MoveOperation` `targetPosition` is inside a node from the moved range of the other `MoveOperation`.
 */ function _moveTargetIntoMovedRange(a, b) {
    return a.targetPosition._getTransformedByDeletion(b.sourcePosition, b.howMany) === null;
}
/**
 * Helper function for `MoveOperation` x `MoveOperation` transformation. Converts given ranges and target position to
 * move operations and returns them.
 *
 * Ranges and target position will be transformed on-the-fly when generating operations.
 *
 * Given `ranges` should be in the order of how they were in the original transformed operation.
 *
 * Given `targetPosition` is the target position of the first range from `ranges`.
 */ function _makeMoveOperationsFromRanges(ranges, targetPosition) {
    // At this moment we have some ranges and a target position, to which those ranges should be moved.
    // Order in `ranges` array is the go-to order of after transformation.
    //
    // We are almost done. We have `ranges` and `targetPosition` to make operations from.
    // Unfortunately, those operations may affect each other. Precisely, first operation after move
    // may affect source range and target position of second and third operation. Same with second
    // operation affecting third.
    //
    // We need to fix those source ranges and target positions once again, before converting `ranges` to operations.
    const operations = [];
    // Keep in mind that nothing will be transformed if there is just one range in `ranges`.
    for(let i = 0; i < ranges.length; i++){
        // Create new operation out of a range and target position.
        const range = ranges[i];
        const op = new MoveOperation(range.start, range.end.offset - range.start.offset, targetPosition, 0);
        operations.push(op);
        // Transform other ranges by the generated operation.
        for(let j = i + 1; j < ranges.length; j++){
            // All ranges in `ranges` array should be:
            //
            // * non-intersecting (these are part of original operation source range), and
            // * `targetPosition` does not target into them (opposite would mean that transformed operation targets "inside itself").
            //
            // This means that the transformation will be "clean" and always return one result.
            ranges[j] = ranges[j]._getTransformedByMove(op.sourcePosition, op.targetPosition, op.howMany)[0];
        }
        targetPosition = targetPosition._getTransformedByMove(op.sourcePosition, op.targetPosition, op.howMany);
    }
    return operations;
}

/**
 * `LivePosition` is a type of {@link module:engine/model/position~Position Position}
 * that updates itself as {@link module:engine/model/document~Document document}
 * is changed through operations. It may be used as a bookmark.
 *
 * **Note:** Contrary to {@link module:engine/model/position~Position}, `LivePosition` works only in roots that are
 * {@link module:engine/model/rootelement~RootElement}.
 * If {@link module:engine/model/documentfragment~DocumentFragment} is passed, error will be thrown.
 *
 * **Note:** Be very careful when dealing with `LivePosition`. Each `LivePosition` instance bind events that might
 * have to be unbound.
 * Use {@link module:engine/model/liveposition~LivePosition#detach} whenever you don't need `LivePosition` anymore.
 */ class LivePosition extends /* #__PURE__ */ EmitterMixin(Position) {
    /**
	 * Creates a live position.
	 *
	 * @see module:engine/model/position~Position
	 */ constructor(root, path, stickiness = 'toNone'){
        super(root, path, stickiness);
        if (!this.root.is('rootElement')) {
            /**
			 * LivePosition's root has to be an instance of RootElement.
			 *
			 * @error model-liveposition-root-not-rootelement
			 */ throw new CKEditorError('model-liveposition-root-not-rootelement', root);
        }
        bindWithDocument.call(this);
    }
    /**
	 * Unbinds all events previously bound by `LivePosition`. Use it whenever you don't need `LivePosition` instance
	 * anymore (i.e. when leaving scope in which it was declared or before re-assigning variable that was
	 * referring to it).
	 */ detach() {
        this.stopListening();
    }
    /**
	 * Creates a {@link module:engine/model/position~Position position instance}, which is equal to this live position.
	 */ toPosition() {
        return new Position(this.root, this.path.slice(), this.stickiness);
    }
    /**
	 * Creates a `LivePosition` instance that is equal to position.
	 */ static fromPosition(position, stickiness) {
        return new this(position.root, position.path.slice(), stickiness ? stickiness : position.stickiness);
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
LivePosition.prototype.is = function(type) {
    return type === 'livePosition' || type === 'model:livePosition' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
    type == 'position' || type === 'model:position';
};
/**
 * Binds this `LivePosition` to the {@link module:engine/model/document~Document document} that owns
 * this position's {@link module:engine/model/position~Position#root root}.
 */ function bindWithDocument() {
    this.listenTo(this.root.document.model, 'applyOperation', (event, args)=>{
        const operation = args[0];
        if (!operation.isDocumentOperation) {
            return;
        }
        transform.call(this, operation);
    }, {
        priority: 'low'
    });
}
/**
 * Updates this position accordingly to the updates applied to the model. Bases on change events.
 */ function transform(operation) {
    const result = this.getTransformedByOperation(operation);
    if (!this.isEqual(result)) {
        const oldPosition = this.toPosition();
        this.path = result.path;
        this.root = result.root;
        this.fire('change', oldPosition);
    }
}

/**
 * A batch instance groups model changes ({@link module:engine/model/operation/operation~Operation operations}). All operations
 * grouped in a single batch can be reverted together, so you can also think about a batch as of a single undo step. If you want
 * to extend a given undo step, you can add more changes to the batch using {@link module:engine/model/model~Model#enqueueChange}:
 *
 * ```ts
 * model.enqueueChange( batch, writer => {
 * 	writer.insertText( 'foo', paragraph, 'end' );
 * } );
 * ```
 *
 * @see module:engine/model/model~Model#enqueueChange
 * @see module:engine/model/model~Model#change
 */ class Batch {
    /**
	 * An array of operations that compose this batch.
	 */ operations;
    /**
	 * Whether the batch can be undone through the undo feature.
	 */ isUndoable;
    /**
	 * Whether the batch includes operations created locally (`true`) or operations created on other, remote editors (`false`).
	 */ isLocal;
    /**
	 * Whether the batch was created by the undo feature and undoes other operations.
	 */ isUndo;
    /**
	 * Whether the batch includes operations connected with typing.
	 */ isTyping;
    /**
	 * Creates a batch instance.
	 *
	 * @see module:engine/model/model~Model#enqueueChange
	 * @see module:engine/model/model~Model#change
	 * @param type A set of flags that specify the type of the batch. Batch type can alter how some of the features work
	 * when encountering a given `Batch` instance (for example, when a feature listens to applied operations).
	 */ constructor(type = {}){
        if (typeof type === 'string') {
            type = type === 'transparent' ? {
                isUndoable: false
            } : {};
            /**
			 * The string value for a `type` property of the `Batch` constructor has been deprecated and will be removed in the near future.
			 * Please refer to the {@link module:engine/model/batch~Batch#constructor `Batch` constructor API documentation} for more
			 * information.
			 *
			 * @error batch-constructor-deprecated-string-type
			 */ logWarning('batch-constructor-deprecated-string-type');
        }
        const { isUndoable = true, isLocal = true, isUndo = false, isTyping = false } = type;
        this.operations = [];
        this.isUndoable = isUndoable;
        this.isLocal = isLocal;
        this.isUndo = isUndo;
        this.isTyping = isTyping;
    }
    /**
	 * The type of the batch.
	 *
	 * **This property has been deprecated and is always set to the `'default'` value.**
	 *
	 * It can be one of the following values:
	 * * `'default'` &ndash; All "normal" batches. This is the most commonly used type.
	 * * `'transparent'` &ndash; A batch that should be ignored by other features, i.e. an initial batch or collaborative editing
	 * changes.
	 *
	 * @deprecated
	 */ get type() {
        /**
		 * The {@link module:engine/model/batch~Batch#type `Batch#type` } property has been deprecated and will be removed in the near
		 * future. Use `Batch#isLocal`, `Batch#isUndoable`, `Batch#isUndo` and `Batch#isTyping` instead.
		 *
		 * @error batch-type-deprecated
		 */ logWarning('batch-type-deprecated');
        return 'default';
    }
    /**
	 * Returns the base version of this batch, which is equal to the base version of the first operation in the batch.
	 * If there are no operations in the batch or neither operation has the base version set, it returns `null`.
	 */ get baseVersion() {
        for (const op of this.operations){
            if (op.baseVersion !== null) {
                return op.baseVersion;
            }
        }
        return null;
    }
    /**
	 * Adds an operation to the batch instance.
	 *
	 * @param operation An operation to add.
	 * @returns The added operation.
	 */ addOperation(operation) {
        operation.batch = this;
        this.operations.push(operation);
        return operation;
    }
}

/**
 * Calculates the difference between two model states.
 *
 * Receives operations that are to be applied on the model document. Marks parts of the model document tree which
 * are changed and saves the state of these elements before the change. Then, it compares saved elements with the
 * changed elements, after all changes are applied on the model document. Calculates the diff between saved
 * elements and new ones and returns a change set.
 */ class Differ {
    /**
	 * Priority of the {@link ~Differ#_elementState element states}. States on higher indexes of the array can overwrite states on the lower
	 * indexes.
	 */ static _statesPriority = [
        undefined,
        'refresh',
        'rename',
        'move'
    ];
    /**
	 * Reference to the model's marker collection.
	 */ _markerCollection;
    /**
	 * A map that stores changes that happened in a given element.
	 *
	 * The keys of the map are references to the model elements.
	 * The values of the map are arrays with changes that were done on this element.
	 */ _changesInElement = new Map();
    /**
	 * Stores a snapshot for these model nodes that might have changed.
	 *
	 * This complements {@link ~Differ#_elementChildrenSnapshots `_elementChildrenSnapshots`}.
	 *
	 * See also {@link ~DifferSnapshot}.
	 */ _elementsSnapshots = new Map();
    /**
	 * For each element or document fragment inside which there was a change, it stores a snapshot of the child nodes list (an array
	 * of children snapshots that represent the state in the element / fragment before any change has happened).
	 *
	 * This complements {@link ~Differ#_elementsSnapshots `_elementsSnapshots`}.
	 *
	 * See also {@link ~DifferSnapshot}.
	 */ _elementChildrenSnapshots = new Map();
    /**
	 * Keeps the state for a given element, describing how the element was changed so far. It is used to evaluate the `action` property
	 * of diff items returned by {@link ~Differ#getChanges}.
	 *
	 * Possible values, in the order from the lowest priority to the highest priority:
	 *
	 * * `'refresh'` - element was refreshed,
	 * * `'rename'` - element was renamed,
	 * * `'move'` - element was moved (or, usually, removed, that is moved to the graveyard).
	 *
	 * Element that was refreshed, may change its state to `'rename'` if it was later renamed, or to `'move'` if it was removed.
	 * But the element cannot change its state from `'move'` to `'rename'`, or from `'rename'` to `'refresh'`.
	 *
	 * Only already existing elements are registered in `_elementState`. If a new element was inserted as a result of a buffered operation,
	 * it is not be registered in `_elementState`.
	 */ _elementState = new Map();
    /**
	 * A map that stores all changed markers.
	 *
	 * The keys of the map are marker names.
	 *
	 * The values of the map are objects with the following properties:
	 *
	 * * `oldMarkerData`,
	 * * `newMarkerData`.
	 */ _changedMarkers = new Map();
    /**
	 * A map that stores all roots that have been changed.
	 *
	 * The keys are the names of the roots while value represents the changes.
	 */ _changedRoots = new Map();
    /**
	 * Stores the number of changes that were processed. Used to order the changes chronologically. It is important
	 * when changes are sorted.
	 */ _changeCount = 0;
    /**
	 * For efficiency purposes, `Differ` stores the change set returned by the differ after {@link #getChanges} call.
	 * Cache is reset each time a new operation is buffered. If the cache has not been reset, {@link #getChanges} will
	 * return the cached value instead of calculating it again.
	 *
	 * This property stores those changes that did not take place in graveyard root.
	 */ _cachedChanges = null;
    /**
	 * For efficiency purposes, `Differ` stores the change set returned by the differ after the {@link #getChanges} call.
	 * The cache is reset each time a new operation is buffered. If the cache has not been reset, {@link #getChanges} will
	 * return the cached value instead of calculating it again.
	 *
	 * This property stores all changes evaluated by `Differ`, including those that took place in the graveyard.
	 */ _cachedChangesWithGraveyard = null;
    /**
	 * Set of model items that were marked to get refreshed in {@link #_refreshItem}.
	 */ _refreshedItems = new Set();
    /**
	 * Creates a `Differ` instance.
	 *
	 * @param markerCollection Model's marker collection.
	 */ constructor(markerCollection){
        this._markerCollection = markerCollection;
    }
    /**
	 * Informs whether there are any changes buffered in `Differ`.
	 */ get isEmpty() {
        return this._changesInElement.size == 0 && this._changedMarkers.size == 0 && this._changedRoots.size == 0;
    }
    /**
	 * Buffers the given operation. **An operation has to be buffered before it is executed.**
	 *
	 * @param operationToBuffer An operation to buffer.
	 */ bufferOperation(operationToBuffer) {
        // Below we take an operation, check its type, then use its parameters in marking (private) methods.
        // The general rule is to not mark elements inside inserted element. All inserted elements are re-rendered.
        // Marking changes in them would cause a "double" changing then.
        //
        const operation = operationToBuffer;
        // Note: an operation that happens inside a non-loaded root will be ignored. If the operation happens partially inside
        // a non-loaded root, that part will be ignored (this may happen for move or marker operations).
        //
        switch(operation.type){
            case 'insert':
                {
                    if (this._isInInsertedElement(operation.position.parent)) {
                        return;
                    }
                    this._markInsert(operation.position.parent, operation.position.offset, operation.nodes.maxOffset);
                    break;
                }
            case 'addAttribute':
            case 'removeAttribute':
            case 'changeAttribute':
                {
                    for (const item of operation.range.getItems({
                        shallow: true
                    })){
                        if (this._isInInsertedElement(item.parent)) {
                            continue;
                        }
                        this._markAttribute(item);
                    }
                    break;
                }
            case 'remove':
            case 'move':
            case 'reinsert':
                {
                    // When range is moved to the same position then not mark it as a change.
                    // See: https://github.com/ckeditor/ckeditor5-engine/issues/1664.
                    if (operation.sourcePosition.isEqual(operation.targetPosition) || operation.sourcePosition.getShiftedBy(operation.howMany).isEqual(operation.targetPosition)) {
                        return;
                    }
                    const sourceParentInserted = this._isInInsertedElement(operation.sourcePosition.parent);
                    const targetParentInserted = this._isInInsertedElement(operation.targetPosition.parent);
                    if (!sourceParentInserted) {
                        this._markRemove(operation.sourcePosition.parent, operation.sourcePosition.offset, operation.howMany);
                    }
                    if (!targetParentInserted) {
                        this._markInsert(operation.targetPosition.parent, operation.getMovedRangeStart().offset, operation.howMany);
                    }
                    // Remember -- operation is buffered before it is executed. So, it was not executed yet.
                    const range = Range._createFromPositionAndShift(operation.sourcePosition, operation.howMany);
                    for (const node of range.getItems({
                        shallow: true
                    })){
                        this._setElementState(node, 'move');
                    }
                    break;
                }
            case 'rename':
                {
                    if (this._isInInsertedElement(operation.position.parent)) {
                        return;
                    }
                    this._markRemove(operation.position.parent, operation.position.offset, 1);
                    this._markInsert(operation.position.parent, operation.position.offset, 1);
                    const range = Range._createFromPositionAndShift(operation.position, 1);
                    for (const marker of this._markerCollection.getMarkersIntersectingRange(range)){
                        const markerData = marker.getData();
                        this.bufferMarkerChange(marker.name, markerData, markerData);
                    }
                    this._setElementState(operation.position.nodeAfter, 'rename');
                    break;
                }
            case 'split':
                {
                    const splitElement = operation.splitPosition.parent;
                    // Mark that children of the split element were removed.
                    if (!this._isInInsertedElement(splitElement)) {
                        this._markRemove(splitElement, operation.splitPosition.offset, operation.howMany);
                        // Remember -- operation is buffered before it is executed. So, it was not executed yet.
                        const range = Range._createFromPositionAndShift(operation.splitPosition, operation.howMany);
                        for (const node of range.getItems({
                            shallow: true
                        })){
                            this._setElementState(node, 'move');
                        }
                    }
                    // Mark that the new element (split copy) was inserted.
                    if (!this._isInInsertedElement(operation.insertionPosition.parent)) {
                        this._markInsert(operation.insertionPosition.parent, operation.insertionPosition.offset, 1);
                    }
                    // If the split took the element from the graveyard, mark that the element from the graveyard was removed.
                    if (operation.graveyardPosition) {
                        this._markRemove(operation.graveyardPosition.parent, operation.graveyardPosition.offset, 1);
                        this._setElementState(operation.graveyardPosition.nodeAfter, 'move');
                    }
                    break;
                }
            case 'merge':
                {
                    // Mark that the merged element was removed.
                    const mergedElement = operation.sourcePosition.parent;
                    if (!this._isInInsertedElement(mergedElement.parent)) {
                        this._markRemove(mergedElement.parent, mergedElement.startOffset, 1);
                    }
                    // Mark that the merged element was inserted into graveyard.
                    const graveyardParent = operation.graveyardPosition.parent;
                    this._markInsert(graveyardParent, operation.graveyardPosition.offset, 1);
                    this._setElementState(mergedElement, 'move');
                    // Mark that children of merged element were inserted at new parent.
                    const mergedIntoElement = operation.targetPosition.parent;
                    if (!this._isInInsertedElement(mergedIntoElement)) {
                        this._markInsert(mergedIntoElement, operation.targetPosition.offset, mergedElement.maxOffset);
                        // Remember -- operation is buffered before it is executed. So, it was not executed yet.
                        const range = Range._createFromPositionAndShift(operation.sourcePosition, operation.howMany);
                        for (const node of range.getItems({
                            shallow: true
                        })){
                            this._setElementState(node, 'move');
                        }
                    }
                    break;
                }
            case 'detachRoot':
            case 'addRoot':
                {
                    const root = operation.affectedSelectable;
                    if (!root._isLoaded) {
                        return;
                    }
                    // Don't buffer if the root state does not change.
                    if (root.isAttached() == operation.isAdd) {
                        return;
                    }
                    this._bufferRootStateChange(operation.rootName, operation.isAdd);
                    break;
                }
            case 'addRootAttribute':
            case 'removeRootAttribute':
            case 'changeRootAttribute':
                {
                    if (!operation.root._isLoaded) {
                        return;
                    }
                    const rootName = operation.root.rootName;
                    this._bufferRootAttributeChange(rootName, operation.key, operation.oldValue, operation.newValue);
                    break;
                }
        }
        // Clear cache after each buffered operation as it is no longer valid.
        this._cachedChanges = null;
    }
    /**
	 * Buffers a marker change.
	 *
	 * @param markerName The name of the marker that changed.
	 * @param oldMarkerData Marker data before the change.
	 * @param newMarkerData Marker data after the change.
	 */ bufferMarkerChange(markerName, oldMarkerData, newMarkerData) {
        if (oldMarkerData.range && oldMarkerData.range.root.is('rootElement') && !oldMarkerData.range.root._isLoaded) {
            oldMarkerData.range = null;
        }
        if (newMarkerData.range && newMarkerData.range.root.is('rootElement') && !newMarkerData.range.root._isLoaded) {
            newMarkerData.range = null;
        }
        let buffered = this._changedMarkers.get(markerName);
        if (!buffered) {
            buffered = {
                newMarkerData,
                oldMarkerData
            };
            this._changedMarkers.set(markerName, buffered);
        } else {
            buffered.newMarkerData = newMarkerData;
        }
        if (buffered.oldMarkerData.range == null && newMarkerData.range == null) {
            // The marker is going to be removed (`newMarkerData.range == null`) but it did not exist before the first buffered change
            // (`buffered.oldMarkerData.range == null`). In this case, do not keep the marker in buffer at all.
            this._changedMarkers.delete(markerName);
        }
    }
    /**
	 * Returns all markers that should be removed as a result of buffered changes.
	 *
	 * @returns Markers to remove. Each array item is an object containing the `name` and `range` properties.
	 */ getMarkersToRemove() {
        const result = [];
        for (const [name, change] of this._changedMarkers){
            if (change.oldMarkerData.range != null) {
                result.push({
                    name,
                    range: change.oldMarkerData.range
                });
            }
        }
        return result;
    }
    /**
	 * Returns all markers which should be added as a result of buffered changes.
	 *
	 * @returns Markers to add. Each array item is an object containing the `name` and `range` properties.
	 */ getMarkersToAdd() {
        const result = [];
        for (const [name, change] of this._changedMarkers){
            if (change.newMarkerData.range != null) {
                result.push({
                    name,
                    range: change.newMarkerData.range
                });
            }
        }
        return result;
    }
    /**
	 * Returns all markers which changed.
	 */ getChangedMarkers() {
        return Array.from(this._changedMarkers).map(([name, change])=>({
                name,
                data: {
                    oldRange: change.oldMarkerData.range,
                    newRange: change.newMarkerData.range
                }
            }));
    }
    /**
	 * Checks whether some of the buffered changes affect the editor data.
	 *
	 * Types of changes which affect the editor data:
	 *
	 * * model structure changes,
	 * * attribute changes,
	 * * a root is added or detached,
	 * * changes of markers which were defined as `affectsData`,
	 * * changes of markers' `affectsData` property.
	 */ hasDataChanges() {
        if (this.getChanges().length) {
            return true;
        }
        if (this._changedRoots.size > 0) {
            return true;
        }
        for (const { newMarkerData, oldMarkerData } of this._changedMarkers.values()){
            if (newMarkerData.affectsData !== oldMarkerData.affectsData) {
                return true;
            }
            if (newMarkerData.affectsData) {
                const markerAdded = newMarkerData.range && !oldMarkerData.range;
                const markerRemoved = !newMarkerData.range && oldMarkerData.range;
                const markerChanged = newMarkerData.range && oldMarkerData.range && !newMarkerData.range.isEqual(oldMarkerData.range);
                if (markerAdded || markerRemoved || markerChanged) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
	 * Calculates the diff between the old model tree state (the state before the first buffered operations since the last {@link #reset}
	 * call) and the new model tree state (actual one). It should be called after all buffered operations are executed.
	 *
	 * The diff set is returned as an array of {@link module:engine/model/differ~DiffItem diff items}, each describing a change done
	 * on the model. The items are sorted by the position on which the change happened. If a position
	 * {@link module:engine/model/position~Position#isBefore is before} another one, it will be on an earlier index in the diff set.
	 *
	 * **Note**: Elements inside inserted element will not have a separate diff item, only the top most element change will be reported.
	 *
	 * Because calculating the diff is a costly operation, the result is cached. If no new operation was buffered since the
	 * previous {@link #getChanges} call, the next call will return the cached value.
	 *
	 * @param options Additional options.
	 * @param options.includeChangesInGraveyard If set to `true`, also changes that happened
	 * in the graveyard root will be returned. By default, changes in the graveyard root are not returned.
	 * @returns Diff between the old and the new model tree state.
	 */ getChanges(options = {}) {
        // If there are cached changes, just return them instead of calculating changes again.
        if (this._cachedChanges) {
            if (options.includeChangesInGraveyard) {
                return this._cachedChangesWithGraveyard.slice();
            } else {
                return this._cachedChanges.slice();
            }
        }
        // Will contain returned results.
        let diffSet = [];
        // Check all changed elements/roots.
        for (const element of this._changesInElement.keys()){
            // Get changes inside this element/root and sort them.
            const changes = this._changesInElement.get(element).sort((a, b)=>{
                if (a.offset === b.offset) {
                    if (a.type != b.type) {
                        // If there are multiple changes at the same position, "remove" change should be first.
                        // If the order is different, for example, we would first add some nodes and then removed them
                        // (instead of the nodes that we should remove).
                        return a.type == 'remove' ? -1 : 1;
                    }
                    return 0;
                }
                return a.offset < b.offset ? -1 : 1;
            });
            // Get children of this element before any change was applied on it.
            const childrenBefore = this._elementChildrenSnapshots.get(element);
            // Get snapshot of current element's children.
            const childrenAfter = _getChildrenSnapshots(element.getChildren());
            // Generate diff instructions based on changes done in the element/root.
            const diffInstructions = _generateDiffInstructionsFromChanges(childrenBefore.length, changes);
            let i = 0; // Iterator in `childrenAfter` array -- iterates through current children of element.
            let j = 0; // Iterator in `childrenBefore` array -- iterates through old children of element.
            // Process every action.
            for (const instruction of diffInstructions){
                if (instruction === 'i') {
                    const action = this._getDiffActionForNode(childrenAfter[i].node, 'insert');
                    const childSnapshotBefore = this._elementsSnapshots.get(childrenAfter[i].node);
                    const diffItem = this._getInsertDiff(element, i, action, childrenAfter[i], childSnapshotBefore);
                    diffSet.push(diffItem);
                    i++;
                } else if (instruction === 'r') {
                    const action = this._getDiffActionForNode(childrenBefore[j].node, 'remove');
                    const diffItem = this._getRemoveDiff(element, i, action, childrenBefore[j]);
                    diffSet.push(diffItem);
                    j++;
                } else if (instruction === 'a') {
                    // Take attributes from saved and current children.
                    const beforeAttributes = childrenBefore[j].attributes;
                    const afterAttributes = childrenAfter[i].attributes;
                    let range;
                    if (childrenAfter[i].name == '$text') {
                        range = new Range(Position._createAt(element, i), Position._createAt(element, i + 1));
                    } else {
                        const index = element.offsetToIndex(i);
                        range = new Range(Position._createAt(element, i), Position._createAt(element.getChild(index), 0));
                    }
                    // Generate diff items for this change (there might be multiple attributes changed and
                    // there is a single diff for each of them) and insert them into the diff set.
                    const diffItems = this._getAttributesDiff(range, beforeAttributes, afterAttributes);
                    diffSet.push(...diffItems);
                    i++;
                    j++;
                } else {
                    // `action` is 'equal'. Child not changed.
                    i++;
                    j++;
                }
            }
        }
        // Then, sort the changes by the position (change at position before other changes is first).
        diffSet.sort((a, b)=>{
            // If the change is in different root, we don't care much, but we'd like to have all changes in given
            // root "together" in the array. So let's just sort them by the root name. It does not matter which root
            // will be processed first.
            if (a.position.root != b.position.root) {
                return a.position.root.rootName < b.position.root.rootName ? -1 : 1;
            }
            // If change happens at the same position...
            if (a.position.isEqual(b.position)) {
                // Keep chronological order of operations.
                return a.changeCount - b.changeCount;
            }
            // If positions differ, position "on the left" should be earlier in the result.
            return a.position.isBefore(b.position) ? -1 : 1;
        });
        // Glue together multiple changes (mostly on text nodes).
        for(let i = 1, prevIndex = 0; i < diffSet.length; i++){
            const prevDiff = diffSet[prevIndex];
            const thisDiff = diffSet[i];
            // Glue remove changes if they happen on text on same position.
            const isConsecutiveTextRemove = prevDiff.type == 'remove' && thisDiff.type == 'remove' && prevDiff.name == '$text' && thisDiff.name == '$text' && prevDiff.position.isEqual(thisDiff.position);
            // Glue insert changes if they happen on text on consecutive fragments.
            const isConsecutiveTextAdd = prevDiff.type == 'insert' && thisDiff.type == 'insert' && prevDiff.name == '$text' && thisDiff.name == '$text' && prevDiff.position.parent == thisDiff.position.parent && prevDiff.position.offset + prevDiff.length == thisDiff.position.offset;
            // Glue attribute changes if they happen on consecutive fragments and have same key, old value and new value.
            const isConsecutiveAttributeChange = prevDiff.type == 'attribute' && thisDiff.type == 'attribute' && prevDiff.position.parent == thisDiff.position.parent && prevDiff.range.isFlat && thisDiff.range.isFlat && prevDiff.position.offset + prevDiff.length == thisDiff.position.offset && prevDiff.attributeKey == thisDiff.attributeKey && prevDiff.attributeOldValue == thisDiff.attributeOldValue && prevDiff.attributeNewValue == thisDiff.attributeNewValue;
            if (isConsecutiveTextRemove || isConsecutiveTextAdd || isConsecutiveAttributeChange) {
                prevDiff.length++;
                if (isConsecutiveAttributeChange) {
                    prevDiff.range.end = prevDiff.range.end.getShiftedBy(1);
                }
                diffSet[i] = null;
            } else {
                prevIndex = i;
            }
        }
        diffSet = diffSet.filter((v)=>v);
        // Remove `changeCount` property from diff items. It is used only for sorting and is internal thing.
        for (const item of diffSet){
            delete item.changeCount;
            if (item.type == 'attribute') {
                delete item.position;
                delete item.length;
            }
        }
        this._changeCount = 0;
        // Cache changes.
        this._cachedChangesWithGraveyard = diffSet;
        this._cachedChanges = diffSet.filter(_changesInGraveyardFilter);
        if (options.includeChangesInGraveyard) {
            return this._cachedChangesWithGraveyard.slice();
        } else {
            return this._cachedChanges.slice();
        }
    }
    /**
	 * Returns all roots that have changed (either were attached, or detached, or their attributes changed).
	 *
	 * @returns Diff between the old and the new roots state.
	 */ getChangedRoots() {
        return Array.from(this._changedRoots.values()).map((diffItem)=>{
            const entry = {
                ...diffItem
            };
            if (entry.state !== undefined) {
                // The root was attached or detached -- do not return its attributes changes.
                // If the root was attached, it should be handled as a whole, together with its attributes, the same way as model nodes.
                // If the root was detached, its attributes should be discarded anyway.
                //
                // Keep in mind that filtering must happen on this stage (when retrieving changes). If filtering happens on-the-fly as
                // the attributes change, it may lead to incorrect situation, e.g.: detach root, change attribute, re-attach root.
                // In this case, attribute change cannot be filtered. After the root is re-attached, the attribute change must be kept.
                delete entry.attributes;
            }
            return entry;
        });
    }
    /**
	 * Returns a set of model items that were marked to get refreshed.
	 */ getRefreshedItems() {
        return new Set(this._refreshedItems);
    }
    /**
	 * Resets `Differ`. Removes all buffered changes.
	 */ reset() {
        this._changesInElement.clear();
        this._elementChildrenSnapshots.clear();
        this._elementsSnapshots.clear();
        this._elementState.clear();
        this._changedMarkers.clear();
        this._changedRoots.clear();
        this._refreshedItems.clear();
        this._cachedChanges = null;
    }
    /**
	 * Marks the given `item` in differ to be "refreshed". It means that the item will be marked as removed and inserted
	 * in the differ changes set, so it will be effectively re-converted when the differ changes are handled by a dispatcher.
	 *
	 * @internal
	 * @param item Item to refresh.
	 */ _refreshItem(item) {
        if (this._isInInsertedElement(item.parent)) {
            return;
        }
        this._markRemove(item.parent, item.startOffset, item.offsetSize);
        this._markInsert(item.parent, item.startOffset, item.offsetSize);
        this._refreshedItems.add(item);
        this._setElementState(item, 'refresh');
        const range = Range._createOn(item);
        for (const marker of this._markerCollection.getMarkersIntersectingRange(range)){
            const markerData = marker.getData();
            this.bufferMarkerChange(marker.name, markerData, markerData);
        }
        // Clear cache after each buffered operation as it is no longer valid.
        this._cachedChanges = null;
    }
    /**
	 * Buffers all the data related to given root like it was all just added to the editor.
	 *
	 * Following changes are buffered:
	 *
	 * * root is attached,
	 * * all root content is inserted,
	 * * all root attributes are added,
	 * * all markers inside the root are added.
	 *
	 * @internal
	 */ _bufferRootLoad(root) {
        if (!root.isAttached()) {
            return;
        }
        this._bufferRootStateChange(root.rootName, true);
        this._markInsert(root, 0, root.maxOffset);
        // Buffering root attribute changes makes sense and is actually needed, even though we buffer root state change above.
        // Because the root state change is buffered, the root attributes changes are not returned by the differ.
        // But, if the root attribute is removed in the same change block, or the root is detached, then the differ results would be wrong.
        //
        for (const key of root.getAttributeKeys()){
            this._bufferRootAttributeChange(root.rootName, key, null, root.getAttribute(key));
        }
        for (const marker of this._markerCollection){
            if (marker.getRange().root == root) {
                const markerData = marker.getData();
                this.bufferMarkerChange(marker.name, {
                    ...markerData,
                    range: null
                }, markerData);
            }
        }
    }
    /**
	 * Buffers the root state change after the root was attached or detached
	 */ _bufferRootStateChange(rootName, isAttached) {
        if (!this._changedRoots.has(rootName)) {
            this._changedRoots.set(rootName, {
                name: rootName,
                state: isAttached ? 'attached' : 'detached'
            });
            return;
        }
        const diffItem = this._changedRoots.get(rootName);
        if (diffItem.state !== undefined) {
            // Root `state` can only toggle between one of the values and no value. It cannot be any other way,
            // because if the root was originally attached it can only become detached. Then, if it is re-attached in the same batch of
            // changes, it gets back to "no change" (which means no value). Same if the root was originally detached.
            delete diffItem.state;
            if (diffItem.attributes === undefined) {
                // If there is no `state` change and no `attributes` change, remove the entry.
                this._changedRoots.delete(rootName);
            }
        } else {
            diffItem.state = isAttached ? 'attached' : 'detached';
        }
    }
    /**
	 * Buffers a root attribute change.
	 */ _bufferRootAttributeChange(rootName, key, oldValue, newValue) {
        const diffItem = this._changedRoots.get(rootName) || {
            name: rootName
        };
        const attrs = diffItem.attributes || {};
        if (attrs[key]) {
            // If this attribute or metadata was already changed earlier and is changed again, check to what value it is changed.
            const attrEntry = attrs[key];
            if (newValue === attrEntry.oldValue) {
                // If it was changed back to the old value, remove the entry.
                delete attrs[key];
            } else {
                // If it was changed to a different value, update the entry.
                attrEntry.newValue = newValue;
            }
        } else {
            // If this attribute or metadata was not set earlier, add an entry.
            attrs[key] = {
                oldValue,
                newValue
            };
        }
        if (Object.entries(attrs).length === 0) {
            // If attributes or metadata changes set became empty, remove it from the diff item.
            delete diffItem.attributes;
            if (diffItem.state === undefined) {
                // If there is no `state` change and no `attributes` change, remove the entry.
                this._changedRoots.delete(rootName);
            }
        } else {
            // Make sure that, if a new object in the structure was created, it gets set.
            diffItem.attributes = attrs;
            this._changedRoots.set(rootName, diffItem);
        }
    }
    /**
	 * Saves and handles an insert change.
	 */ _markInsert(parent, offset, howMany) {
        if (parent.root.is('rootElement') && !parent.root._isLoaded) {
            return;
        }
        const changeItem = {
            type: 'insert',
            offset,
            howMany,
            count: this._changeCount++
        };
        this._markChange(parent, changeItem);
    }
    /**
	 * Saves and handles a remove change.
	 */ _markRemove(parent, offset, howMany) {
        if (parent.root.is('rootElement') && !parent.root._isLoaded) {
            return;
        }
        const changeItem = {
            type: 'remove',
            offset,
            howMany,
            count: this._changeCount++
        };
        this._markChange(parent, changeItem);
        this._removeAllNestedChanges(parent, offset, howMany);
    }
    /**
	 * Saves and handles an attribute change.
	 */ _markAttribute(item) {
        if (item.root.is('rootElement') && !item.root._isLoaded) {
            return;
        }
        const changeItem = {
            type: 'attribute',
            offset: item.startOffset,
            howMany: item.offsetSize,
            count: this._changeCount++
        };
        this._markChange(item.parent, changeItem);
    }
    /**
	 * Saves and handles a model change.
	 */ _markChange(parent, changeItem) {
        // First, make a snapshot of the parent and its children (it will be made only if it was not made before).
        this._makeSnapshots(parent);
        // Then, get all changes that already were done on the element (empty array if this is the first change).
        const changes = this._getChangesForElement(parent);
        // Then, look through all the changes, and transform them or the new change.
        this._handleChange(changeItem, changes);
        // Add the new change.
        changes.push(changeItem);
        // Remove incorrect changes. During transformation some change might be, for example, included in another.
        // In that case, the change will have `howMany` property set to `0` or less. We need to remove those changes.
        for(let i = 0; i < changes.length; i++){
            if (changes[i].howMany < 1) {
                changes.splice(i, 1);
                i--;
            }
        }
    }
    /**
	 * Tries to set given state for given item.
	 *
	 * This method does simple validation (it sets the state only for model elements, not for text proxy nodes). It also follows state
	 * setting rules, that is, `'refresh'` cannot overwrite `'rename'`, and `'rename'` cannot overwrite `'move'`.
	 */ _setElementState(node, state) {
        if (!node.is('element')) {
            return;
        }
        const currentStatePriority = Differ._statesPriority.indexOf(this._elementState.get(node));
        const newStatePriority = Differ._statesPriority.indexOf(state);
        if (newStatePriority > currentStatePriority) {
            this._elementState.set(node, state);
        }
    }
    /**
	 * Returns a value for {@link ~DifferItemAction `action`} property for diff items returned by {@link ~Differ#getChanges}.
	 * This method aims to return `'rename'` or `'refresh'` when it should, and `diffItemType` ("default action") in all other cases.
	 *
	 * It bases on a few factors:
	 *
	 * * for text nodes, the method always returns `diffItemType`,
	 * * for newly inserted element, the method returns `diffItemType`,
	 * * if {@link ~Differ#_elementState element state} was not recorded, the method returns `diffItemType`,
	 * * if state was recorded, and it was `'move'` (default action), the method returns `diffItemType`,
	 * * finally, if state was `'refresh'` or `'rename'`, the method returns the state value.
	 */ _getDiffActionForNode(node, diffItemType) {
        if (!node.is('element')) {
            // Text node.
            return diffItemType;
        }
        if (!this._elementsSnapshots.has(node)) {
            // Newly inserted element.
            return diffItemType;
        }
        const state = this._elementState.get(node);
        if (!state || state == 'move') {
            return diffItemType;
        }
        return state;
    }
    /**
	 * Gets an array of changes that have already been saved for a given element.
	 */ _getChangesForElement(element) {
        let changes;
        if (this._changesInElement.has(element)) {
            changes = this._changesInElement.get(element);
        } else {
            changes = [];
            this._changesInElement.set(element, changes);
        }
        return changes;
    }
    /**
	 * Creates and saves a snapshot for all children of the given element.
	 */ _makeSnapshots(element) {
        if (this._elementChildrenSnapshots.has(element)) {
            return;
        }
        const childrenSnapshots = _getChildrenSnapshots(element.getChildren());
        this._elementChildrenSnapshots.set(element, childrenSnapshots);
        for (const snapshot of childrenSnapshots){
            this._elementsSnapshots.set(snapshot.node, snapshot);
        }
    }
    /**
	 * For a given newly saved change, compares it with a change already done on the element and modifies the incoming
	 * change and/or the old change.
	 *
	 * @param inc Incoming (new) change.
	 * @param changes An array containing all the changes done on that element.
	 */ _handleChange(inc, changes) {
        // We need a helper variable that will store how many nodes are to be still handled for this change item.
        // `nodesToHandle` (how many nodes still need to be handled) and `howMany` (how many nodes were affected)
        // needs to be differentiated.
        //
        // This comes up when there are multiple changes that are affected by `inc` change item.
        //
        // For example: assume two insert changes: `{ offset: 2, howMany: 1 }` and `{ offset: 5, howMany: 1 }`.
        // Assume that `inc` change is remove `{ offset: 2, howMany: 2, nodesToHandle: 2 }`.
        //
        // Then, we:
        // - "forget" about first insert change (it is "eaten" by remove),
        // - because of that, at the end we will want to remove only one node (`nodesToHandle = 1`),
        // - but still we have to change offset of the second insert change from `5` to `3`!
        //
        // So, `howMany` does not change throughout items transformation and keeps information about how many nodes were affected,
        // while `nodesToHandle` means how many nodes need to be handled after the change item is transformed by other changes.
        inc.nodesToHandle = inc.howMany;
        for (const old of changes){
            const incEnd = inc.offset + inc.howMany;
            const oldEnd = old.offset + old.howMany;
            if (inc.type == 'insert') {
                if (old.type == 'insert') {
                    if (inc.offset <= old.offset) {
                        old.offset += inc.howMany;
                    } else if (inc.offset < oldEnd) {
                        old.howMany += inc.nodesToHandle;
                        inc.nodesToHandle = 0;
                    }
                }
                if (old.type == 'remove') {
                    if (inc.offset < old.offset) {
                        old.offset += inc.howMany;
                    }
                }
                if (old.type == 'attribute') {
                    if (inc.offset <= old.offset) {
                        old.offset += inc.howMany;
                    } else if (inc.offset < oldEnd) {
                        // This case is more complicated, because attribute change has to be split into two.
                        // Example (assume that uppercase and lowercase letters mean different attributes):
                        //
                        // initial state:		abcxyz
                        // attribute change:	aBCXYz
                        // incoming insert:		aBCfooXYz
                        //
                        // Change ranges cannot intersect because each item has to be described exactly (it was either
                        // not changed, inserted, removed, or its attribute was changed). That's why old attribute
                        // change has to be split and both parts has to be handled separately from now on.
                        const howMany = old.howMany;
                        old.howMany = inc.offset - old.offset;
                        // Add the second part of attribute change to the beginning of processed array so it won't
                        // be processed again in this loop.
                        changes.unshift({
                            type: 'attribute',
                            offset: incEnd,
                            howMany: howMany - old.howMany,
                            count: this._changeCount++
                        });
                    }
                }
            }
            if (inc.type == 'remove') {
                if (old.type == 'insert') {
                    if (incEnd <= old.offset) {
                        old.offset -= inc.howMany;
                    } else if (incEnd <= oldEnd) {
                        if (inc.offset < old.offset) {
                            const intersectionLength = incEnd - old.offset;
                            old.offset = inc.offset;
                            old.howMany -= intersectionLength;
                            inc.nodesToHandle -= intersectionLength;
                        } else {
                            old.howMany -= inc.nodesToHandle;
                            inc.nodesToHandle = 0;
                        }
                    } else {
                        if (inc.offset <= old.offset) {
                            inc.nodesToHandle -= old.howMany;
                            old.howMany = 0;
                        } else if (inc.offset < oldEnd) {
                            const intersectionLength = oldEnd - inc.offset;
                            old.howMany -= intersectionLength;
                            inc.nodesToHandle -= intersectionLength;
                        }
                    }
                }
                if (old.type == 'remove') {
                    if (incEnd <= old.offset) {
                        old.offset -= inc.howMany;
                    } else if (inc.offset < old.offset) {
                        inc.nodesToHandle += old.howMany;
                        old.howMany = 0;
                    }
                }
                if (old.type == 'attribute') {
                    if (incEnd <= old.offset) {
                        old.offset -= inc.howMany;
                    } else if (inc.offset < old.offset) {
                        const intersectionLength = incEnd - old.offset;
                        old.offset = inc.offset;
                        old.howMany -= intersectionLength;
                    } else if (inc.offset < oldEnd) {
                        if (incEnd <= oldEnd) {
                            // On first sight in this case we don't need to split attribute operation into two.
                            // However the changes set is later converted to actions (see `_generateActionsFromChanges`).
                            // For that reason, no two changes may intersect.
                            // So we cannot have an attribute change that "contains" remove change.
                            // Attribute change needs to be split.
                            const howMany = old.howMany;
                            old.howMany = inc.offset - old.offset;
                            const howManyAfter = howMany - old.howMany - inc.nodesToHandle;
                            // Add the second part of attribute change to the beginning of processed array so it won't
                            // be processed again in this loop.
                            changes.unshift({
                                type: 'attribute',
                                offset: inc.offset,
                                howMany: howManyAfter,
                                count: this._changeCount++
                            });
                        } else {
                            old.howMany -= oldEnd - inc.offset;
                        }
                    }
                }
            }
            if (inc.type == 'attribute') {
                // In case of attribute change, `howMany` should be kept same as `nodesToHandle`. It's not an error.
                if (old.type == 'insert') {
                    if (inc.offset < old.offset && incEnd > old.offset) {
                        if (incEnd > oldEnd) {
                            // This case is similar to a case described when incoming change was insert and old change was attribute.
                            // See comment above.
                            //
                            // This time incoming change is attribute. We need to split incoming change in this case too.
                            // However this time, the second part of the attribute change needs to be processed further
                            // because there might be other changes that it collides with.
                            const attributePart = {
                                type: 'attribute',
                                offset: oldEnd,
                                howMany: incEnd - oldEnd,
                                count: this._changeCount++
                            };
                            this._handleChange(attributePart, changes);
                            changes.push(attributePart);
                        }
                        inc.nodesToHandle = old.offset - inc.offset;
                        inc.howMany = inc.nodesToHandle;
                    } else if (inc.offset >= old.offset && inc.offset < oldEnd) {
                        if (incEnd > oldEnd) {
                            inc.nodesToHandle = incEnd - oldEnd;
                            inc.offset = oldEnd;
                        } else {
                            inc.nodesToHandle = 0;
                        }
                    }
                }
                if (old.type == 'remove') {
                    // This is a case when attribute change "contains" remove change.
                    // The attribute change needs to be split into two because changes cannot intersect.
                    if (inc.offset < old.offset && incEnd > old.offset) {
                        const attributePart = {
                            type: 'attribute',
                            offset: old.offset,
                            howMany: incEnd - old.offset,
                            count: this._changeCount++
                        };
                        this._handleChange(attributePart, changes);
                        changes.push(attributePart);
                        inc.nodesToHandle = old.offset - inc.offset;
                        inc.howMany = inc.nodesToHandle;
                    }
                }
                if (old.type == 'attribute') {
                    // There are only two conflicting scenarios possible here:
                    if (inc.offset >= old.offset && incEnd <= oldEnd) {
                        // `old` change includes `inc` change, or they are the same.
                        inc.nodesToHandle = 0;
                        inc.howMany = 0;
                        inc.offset = 0;
                    } else if (inc.offset <= old.offset && incEnd >= oldEnd) {
                        // `inc` change includes `old` change.
                        old.howMany = 0;
                    }
                }
            }
        }
        inc.howMany = inc.nodesToHandle;
        delete inc.nodesToHandle;
    }
    /**
	 * Returns an object with a single insert change description.
	 *
	 * @param parent The element in which the change happened.
	 * @param offset The offset at which change happened.
	 * @param action Further specifies what kind of action led to generating this change.
	 * @param elementSnapshot Snapshot of the inserted node after changes.
	 * @param elementSnapshotBefore Snapshot of the inserted node before changes.
	 * @returns The diff item.
	 */ _getInsertDiff(parent, offset, action, elementSnapshot, elementSnapshotBefore) {
        const diffItem = {
            type: 'insert',
            position: Position._createAt(parent, offset),
            name: elementSnapshot.name,
            attributes: new Map(elementSnapshot.attributes),
            length: 1,
            changeCount: this._changeCount++,
            action
        };
        if (action != 'insert' && elementSnapshotBefore) {
            diffItem.before = {
                name: elementSnapshotBefore.name,
                attributes: new Map(elementSnapshotBefore.attributes)
            };
        }
        return diffItem;
    }
    /**
	 * Returns an object with a single remove change description.
	 *
	 * @param parent The element in which change happened.
	 * @param offset The offset at which change happened.
	 * @param action Further specifies what kind of action led to generating this change.
	 * @param elementSnapshot The snapshot of the removed node before changes.
	 * @returns The diff item.
	 */ _getRemoveDiff(parent, offset, action, elementSnapshot) {
        return {
            type: 'remove',
            action,
            position: Position._createAt(parent, offset),
            name: elementSnapshot.name,
            attributes: new Map(elementSnapshot.attributes),
            length: 1,
            changeCount: this._changeCount++
        };
    }
    /**
	 * Returns an array of objects where each one is a single attribute change description.
	 *
	 * @param range The range where the change happened.
	 * @param oldAttributes A map, map iterator or compatible object that contains attributes before the change.
	 * @param newAttributes A map, map iterator or compatible object that contains attributes after the change.
	 * @returns An array containing one or more diff items.
	 */ _getAttributesDiff(range, oldAttributes, newAttributes) {
        // Results holder.
        const diffs = [];
        // Clone new attributes as we will be performing changes on this object.
        newAttributes = new Map(newAttributes);
        // Look through old attributes.
        for (const [key, oldValue] of oldAttributes){
            // Check what is the new value of the attribute (or if it was removed).
            const newValue = newAttributes.has(key) ? newAttributes.get(key) : null;
            // If values are different (or attribute was removed)...
            if (newValue !== oldValue) {
                // Add diff item.
                diffs.push({
                    type: 'attribute',
                    position: range.start,
                    range: range.clone(),
                    length: 1,
                    attributeKey: key,
                    attributeOldValue: oldValue,
                    attributeNewValue: newValue,
                    changeCount: this._changeCount++
                });
            }
            // Prevent returning two diff items for the same change.
            newAttributes.delete(key);
        }
        // Look through new attributes that weren't handled above.
        for (const [key, newValue] of newAttributes){
            // Each of them is a new attribute. Add diff item.
            diffs.push({
                type: 'attribute',
                position: range.start,
                range: range.clone(),
                length: 1,
                attributeKey: key,
                attributeOldValue: null,
                attributeNewValue: newValue,
                changeCount: this._changeCount++
            });
        }
        return diffs;
    }
    /**
	 * Checks whether given element or any of its parents is an element that is buffered as an inserted element.
	 */ _isInInsertedElement(element) {
        const parent = element.parent;
        if (!parent) {
            return false;
        }
        const changes = this._changesInElement.get(parent);
        const offset = element.startOffset;
        if (changes) {
            for (const change of changes){
                if (change.type == 'insert' && offset >= change.offset && offset < change.offset + change.howMany) {
                    return true;
                }
            }
        }
        return this._isInInsertedElement(parent);
    }
    /**
	 * Removes deeply all buffered changes that are registered in elements from range specified by `parent`, `offset`
	 * and `howMany`.
	 */ _removeAllNestedChanges(parent, offset, howMany) {
        const range = new Range(Position._createAt(parent, offset), Position._createAt(parent, offset + howMany));
        for (const item of range.getItems({
            shallow: true
        })){
            if (item.is('element')) {
                this._changesInElement.delete(item);
                this._removeAllNestedChanges(item, 0, item.maxOffset);
            }
        }
    }
}
/**
 * Returns a snapshot for the specified child node. Text node snapshots have the `name` property set to `$text`.
 */ function _getSingleNodeSnapshot(node) {
    return {
        node,
        name: node.is('$text') ? '$text' : node.name,
        attributes: new Map(node.getAttributes())
    };
}
/**
 * Returns an array that is a copy of passed child list with the exception that text nodes are split to one or more
 * objects, each representing one character and attributes set on that character.
 */ function _getChildrenSnapshots(children) {
    const snapshots = [];
    for (const child of children){
        if (child.is('$text')) {
            for(let i = 0; i < child.data.length; ++i){
                snapshots.push(_getSingleNodeSnapshot(child));
            }
        } else {
            snapshots.push(_getSingleNodeSnapshot(child));
        }
    }
    return snapshots;
}
/**
 * Generates array of diff instructions for given changes set.
 *
 * Generated actions are:
 *
 * - 'e' for 'equal' - when item at that position did not change,
 * - 'i' for 'insert' - when item at that position was inserted,
 * - 'r' for 'remove' - when item at that position was removed,
 * - 'a' for 'attribute' - when item at that position has it attributes changed.
 *
 * Example (assume that uppercase letters have bold attribute, compare with function code):
 *
 * children before:	fooBAR
 * children after:	foxybAR
 *
 * changes: type: remove, offset: 1, howMany: 1
 *			type: insert, offset: 2, howMany: 2
 *			type: attribute, offset: 4, howMany: 1
 *
 * Expected actions: equal (f), remove (o), equal (o), insert (x), insert (y), attribute (b), equal (A), equal (R)
 *
 * Steps taken by the script:
 *
 * 1. change = "type: remove, offset: 1, howMany: 1"; offset = 0; oldChildrenHandled = 0
 *    1.1 between this change and the beginning is one not-changed node, fill with one equal action, one old child has been handled
 *    1.2 this change removes one node, add one remove action
 *    1.3 change last visited `offset` to 1
 *    1.4 since an old child has been removed, one more old child has been handled
 *    1.5 actions at this point are: equal, remove
 *
 * 2. change = "type: insert, offset: 2, howMany: 2"; offset = 1; oldChildrenHandled = 2
 *    2.1 between this change and previous change is one not-changed node, add equal action, another one old children has been handled
 *    2.2 this change inserts two nodes, add two insert actions
 *    2.3 change last visited offset to the end of the inserted range, that is 4
 *    2.4 actions at this point are: equal, remove, equal, insert, insert
 *
 * 3. change = "type: attribute, offset: 4, howMany: 1"; offset = 4, oldChildrenHandled = 3
 *    3.1 between this change and previous change are no not-changed nodes
 *    3.2 this change changes one node, add one attribute action
 *    3.3 change last visited `offset` to the end of change range, that is 5
 *    3.4 since an old child has been changed, one more old child has been handled
 *    3.5 actions at this point are: equal, remove, equal, insert, insert, attribute
 *
 * 4. after loop oldChildrenHandled = 4, oldChildrenLength = 6 (fooBAR is 6 characters)
 *    4.1 fill up with two equal actions
 *
 * The result actions are: equal, remove, equal, insert, insert, attribute, equal, equal.
 */ function _generateDiffInstructionsFromChanges(oldChildrenLength, changes) {
    const diff = [];
    let offset = 0;
    let oldChildrenHandled = 0;
    // Go through all buffered changes.
    for (const change of changes){
        // First, fill "holes" between changes with "equal" actions.
        if (change.offset > offset) {
            for(let i = 0; i < change.offset - offset; i++){
                diff.push('e');
            }
            oldChildrenHandled += change.offset - offset;
        }
        // Then, fill up actions accordingly to change type.
        if (change.type == 'insert') {
            for(let i = 0; i < change.howMany; i++){
                diff.push('i');
            }
            // The last handled offset is after inserted range.
            offset = change.offset + change.howMany;
        } else if (change.type == 'remove') {
            for(let i = 0; i < change.howMany; i++){
                diff.push('r');
            }
            // The last handled offset is at the position where the nodes were removed.
            offset = change.offset;
            // We removed `howMany` old nodes, update `oldChildrenHandled`.
            oldChildrenHandled += change.howMany;
        } else {
            diff.push(...'a'.repeat(change.howMany).split(''));
            // The last handled offset is at the position after the changed range.
            offset = change.offset + change.howMany;
            // We changed `howMany` old nodes, update `oldChildrenHandled`.
            oldChildrenHandled += change.howMany;
        }
    }
    // Fill "equal" actions at the end of actions set. Use `oldChildrenHandled` to see how many children
    // has not been changed / removed at the end of their parent.
    if (oldChildrenHandled < oldChildrenLength) {
        for(let i = 0; i < oldChildrenLength - oldChildrenHandled - offset; i++){
            diff.push('e');
        }
    }
    return diff;
}
/**
 * Filter callback for `Array.filter` that filters out change entries that are in graveyard.
 */ function _changesInGraveyardFilter(entry) {
    const posInGy = 'position' in entry && entry.position.root.rootName == '$graveyard';
    const rangeInGy = 'range' in entry && entry.range.root.rootName == '$graveyard';
    return !posInGy && !rangeInGy;
}

/**
 * @module engine/model/history
 */ /**
 * `History` keeps the track of all the operations applied to the {@link module:engine/model/document~Document document}.
 */ class History {
    /**
	 * Operations added to the history.
	 */ _operations = [];
    /**
	 * Holds an information which {@link module:engine/model/operation/operation~Operation operation} undoes which
	 * {@link module:engine/model/operation/operation~Operation operation}.
	 *
	 * Keys of the map are "undoing operations", that is operations that undone some other operations. For each key, the
	 * value is an operation that has been undone by the "undoing operation".
	 */ _undoPairs = new Map();
    /**
	 * Holds all undone operations.
	 */ _undoneOperations = new Set();
    /**
	 * A map that allows retrieving the operations fast based on the given base version.
	 */ _baseVersionToOperationIndex = new Map();
    /**
	 * The history version.
	 */ _version = 0;
    /**
	 * The gap pairs kept in the <from,to> format.
	 *
	 * Anytime the `history.version` is set to a version larger than `history.version + 1`,
	 * a new <lastHistoryVersion, newHistoryVersion> entry is added to the map.
	 */ _gaps = new Map();
    /**
	 * The version of the last operation in the history.
	 *
	 * The history version is incremented automatically when a new operation is added to the history.
	 * Setting the version manually should be done only in rare circumstances when a gap is planned
	 * between history versions. When doing so, a gap will be created and the history will accept adding
	 * an operation with base version equal to the new history version.
	 */ get version() {
        return this._version;
    }
    set version(version) {
        // Store a gap if there are some operations already in the history and the
        // new version does not increment the latest one.
        if (this._operations.length && version > this._version + 1) {
            this._gaps.set(this._version, version);
        }
        this._version = version;
    }
    /**
	 * The last history operation.
	 */ get lastOperation() {
        return this._operations[this._operations.length - 1];
    }
    /**
	 * Adds an operation to the history and increments the history version.
	 *
	 * The operation's base version should be equal to the history version. Otherwise an error is thrown.
	 */ addOperation(operation) {
        if (operation.baseVersion !== this.version) {
            /**
			 * Only operations with matching versions can be added to the history.
			 *
			 * @error model-document-history-addoperation-incorrect-version
			 * @param errorData The operation and the current document history version.
			 */ throw new CKEditorError('model-document-history-addoperation-incorrect-version', this, {
                operation,
                historyVersion: this.version
            });
        }
        this._operations.push(operation);
        this._version++;
        this._baseVersionToOperationIndex.set(operation.baseVersion, this._operations.length - 1);
    }
    /**
	 * Returns operations from the given range of operation base versions that were added to the history.
	 *
	 * Note that there may be gaps in operations base versions.
	 *
	 * @param fromBaseVersion Base version from which operations should be returned (inclusive).
	 * @param toBaseVersion Base version up to which operations should be returned (exclusive).
     * @returns History operations for the given range, in chronological order.
	 */ getOperations(fromBaseVersion, toBaseVersion = this.version) {
        // When there is no operation in the history, return an empty array.
        // After that we can be sure that `firstOperation`, `lastOperation` are not nullish.
        if (!this._operations.length) {
            return [];
        }
        const firstOperation = this._operations[0];
        if (fromBaseVersion === undefined) {
            fromBaseVersion = firstOperation.baseVersion;
        }
        // Change exclusive `toBaseVersion` to inclusive, so it will refer to the actual index.
        // Thanks to that mapping from base versions to operation indexes are possible.
        let inclusiveTo = toBaseVersion - 1;
        // Check if "from" or "to" point to a gap between versions.
        // If yes, then change the incorrect position to the proper side of the gap.
        // Thanks to it, it will be possible to get index of the operation.
        for (const [gapFrom, gapTo] of this._gaps){
            if (fromBaseVersion > gapFrom && fromBaseVersion < gapTo) {
                fromBaseVersion = gapTo;
            }
            if (inclusiveTo > gapFrom && inclusiveTo < gapTo) {
                inclusiveTo = gapFrom - 1;
            }
        }
        // If the whole range is outside of the operation versions, then return an empty array.
        if (inclusiveTo < firstOperation.baseVersion || fromBaseVersion > this.lastOperation.baseVersion) {
            return [];
        }
        let fromIndex = this._baseVersionToOperationIndex.get(fromBaseVersion);
        // If the range starts before the first operation, then use the first operation as the range's start.
        if (fromIndex === undefined) {
            fromIndex = 0;
        }
        let toIndex = this._baseVersionToOperationIndex.get(inclusiveTo);
        // If the range ends after the last operation, then use the last operation as the range's end.
        if (toIndex === undefined) {
            toIndex = this._operations.length - 1;
        }
        // Return the part of the history operations based on the calculated start index and end index.
        return this._operations.slice(fromIndex, // The `toIndex` should be included in the returned operations, so add `1`.
        toIndex + 1);
    }
    /**
	 * Returns operation from the history that bases on given `baseVersion`.
	 *
	 * @param baseVersion Base version of the operation to get.
	 * @returns Operation with given base version or `undefined` if there is no such operation in history.
	 */ getOperation(baseVersion) {
        const operationIndex = this._baseVersionToOperationIndex.get(baseVersion);
        if (operationIndex === undefined) {
            return;
        }
        return this._operations[operationIndex];
    }
    /**
	 * Marks in history that one operation is an operation that is undoing the other operation. By marking operation this way,
	 * history is keeping more context information about operations, which helps in operational transformation.
	 *
	 * @param undoneOperation Operation which is undone by `undoingOperation`.
	 * @param undoingOperation Operation which undoes `undoneOperation`.
	 */ setOperationAsUndone(undoneOperation, undoingOperation) {
        this._undoPairs.set(undoingOperation, undoneOperation);
        this._undoneOperations.add(undoneOperation);
    }
    /**
	 * Checks whether given `operation` is undoing any other operation.
	 *
	 * @param operation Operation to check.
	 * @returns `true` if given `operation` is undoing any other operation, `false` otherwise.
	 */ isUndoingOperation(operation) {
        return this._undoPairs.has(operation);
    }
    /**
	 * Checks whether given `operation` has been undone by any other operation.
	 *
	 * @param operation Operation to check.
	 * @returns `true` if given `operation` has been undone any other operation, `false` otherwise.
	 */ isUndoneOperation(operation) {
        return this._undoneOperations.has(operation);
    }
    /**
	 * For given `undoingOperation`, returns the operation which has been undone by it.
	 *
	 * @returns Operation that has been undone by given `undoingOperation` or `undefined`
	 * if given `undoingOperation` is not undoing any other operation.
	 */ getUndoneOperation(undoingOperation) {
        return this._undoPairs.get(undoingOperation);
    }
    /**
	 * Resets the history of operations.
	 */ reset() {
        this._version = 0;
        this._undoPairs = new Map();
        this._operations = [];
        this._undoneOperations = new Set();
        this._gaps = new Map();
        this._baseVersionToOperationIndex = new Map();
    }
}

/**
 * Type of {@link module:engine/model/element~Element} that is a root of a model tree.
 */ class RootElement extends Element {
    /**
	 * Unique root name used to identify this root element by {@link module:engine/model/document~Document}.
	 */ rootName;
    /**
	 * Document that is an owner of this root.
	 */ _document;
    /**
	 * @internal
	 */ _isAttached = true;
    /**
	 * Informs if the root element is loaded (default).
	 *
	 * @internal
	 */ _isLoaded = true;
    /**
	 * Creates root element.
	 *
	 * @param document Document that is an owner of this root.
	 * @param name Node name.
	 * @param rootName Unique root name used to identify this root element by {@link module:engine/model/document~Document}.
	 */ constructor(document, name, rootName = 'main'){
        super(name);
        this._document = document;
        this.rootName = rootName;
    }
    /**
	 * {@link module:engine/model/document~Document Document} that owns this root element.
	 */ get document() {
        return this._document;
    }
    /**
	 * Informs if the root element is currently attached to the document, or not.
	 *
	 * A detached root is equivalent to being removed and cannot contain any children or markers.
	 *
	 * By default, a newly added root is attached. It can be detached using
	 * {@link module:engine/model/writer~Writer#detachRoot `Writer#detachRoot`}. A detached root can be re-attached again using
	 * {@link module:engine/model/writer~Writer#addRoot `Writer#addRoot`}.
	 */ isAttached() {
        return this._isAttached;
    }
    /**
	 * Converts `RootElement` instance to `string` containing its name.
	 *
	 * @returns `RootElement` instance converted to `string`.
	 */ toJSON() {
        return this.rootName;
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
RootElement.prototype.is = function(type, name) {
    if (!name) {
        return type === 'rootElement' || type === 'model:rootElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
        type === 'element' || type === 'model:element' || type === 'node' || type === 'model:node';
    }
    return name === this.name && (type === 'rootElement' || type === 'model:rootElement' || // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
    type === 'element' || type === 'model:element');
};

// @if CK_DEBUG_ENGINE // const { logDocument } = require( '../dev-utils/utils' );
const graveyardName = '$graveyard';
/**
 * Data model's document. It contains the model's structure, its selection and the history of changes.
 *
 * Read more about working with the model in
 * {@glink framework/architecture/editing-engine#model introduction to the the editing engine's architecture}.
 *
 * Usually, the document contains just one {@link module:engine/model/document~Document#roots root element}, so
 * you can retrieve it by just calling {@link module:engine/model/document~Document#getRoot} without specifying its name:
 *
 * ```ts
 * model.document.getRoot(); // -> returns the main root
 * ```
 *
 * However, the document may contain multiple roots – e.g. when the editor has multiple editable areas
 * (e.g. a title and a body of a message).
 */ class Document extends /* #__PURE__ */ EmitterMixin() {
    /**
	 * The {@link module:engine/model/model~Model model} that the document is a part of.
	 */ model;
    /**
	 * The document's history.
	 */ history;
    /**
	 * The selection in this document.
	 */ selection;
    /**
	 * A list of roots that are owned and managed by this document. Use {@link #createRoot}, {@link #getRoot} and
	 * {@link #getRootNames} to manipulate it.
	 */ roots;
    /**
	 * The model differ object. Its role is to buffer changes done on the model document and then calculate a diff of those changes.
	 */ differ;
    /**
	 * Defines whether the document is in a read-only mode.
	 *
	 * The user should not be able to change the data of a document that is read-only.
	 *
	 * @readonly
	 */ isReadOnly;
    /**
	 * Post-fixer callbacks registered to the model document.
	 */ _postFixers;
    /**
	 * A flag that indicates whether the selection has changed since last change block.
	 */ _hasSelectionChangedFromTheLastChangeBlock;
    /**
	 * Creates an empty document instance with no {@link #roots} (other than
	 * the {@link #graveyard graveyard root}).
	 */ constructor(model){
        super();
        this.model = model;
        this.history = new History();
        this.selection = new DocumentSelection(this);
        this.roots = new Collection({
            idProperty: 'rootName'
        });
        this.differ = new Differ(model.markers);
        this.isReadOnly = false;
        this._postFixers = new Set();
        this._hasSelectionChangedFromTheLastChangeBlock = false;
        // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
        this.createRoot('$root', graveyardName);
        // Then, still before an operation is applied on model, buffer the change in differ.
        this.listenTo(model, 'applyOperation', (evt, args)=>{
            const operation = args[0];
            if (operation.isDocumentOperation) {
                this.differ.bufferOperation(operation);
            }
        }, {
            priority: 'high'
        });
        // After the operation is applied, bump document's version and add the operation to the history.
        this.listenTo(model, 'applyOperation', (evt, args)=>{
            const operation = args[0];
            if (operation.isDocumentOperation) {
                this.history.addOperation(operation);
            }
        }, {
            priority: 'low'
        });
        // Listen to selection changes. If selection changed, mark it.
        this.listenTo(this.selection, 'change', ()=>{
            this._hasSelectionChangedFromTheLastChangeBlock = true;
        });
        // Buffer marker changes.
        // This is not covered in buffering operations because markers may change outside of them (when they
        // are modified using `model.markers` collection, not through `MarkerOperation`).
        this.listenTo(model.markers, 'update', (evt, marker, oldRange, newRange, oldMarkerData)=>{
            // Copy the `newRange` to the new marker data as during the marker removal the range is not updated.
            const newMarkerData = {
                ...marker.getData(),
                range: newRange
            };
            // Whenever marker is updated, buffer that change.
            this.differ.bufferMarkerChange(marker.name, oldMarkerData, newMarkerData);
            if (oldRange === null) {
                // If this is a new marker, add a listener that will buffer change whenever marker changes.
                marker.on('change', (evt, oldRange)=>{
                    const markerData = marker.getData();
                    this.differ.bufferMarkerChange(marker.name, {
                        ...markerData,
                        range: oldRange
                    }, markerData);
                });
            }
        });
        // This is a solution for a problem that may occur during real-time editing. If one client detached a root and another added
        // something there at the same moment, the OT does not solve this problem currently. In such situation, the added elements would
        // stay in the detached root.
        //
        // This is incorrect, a detached root should be empty and all elements from it should be removed. To solve this, the post-fixer will
        // remove any element that is left in a detached root.
        //
        // Similarly, markers that are created at the beginning or at the end of the detached root will not be removed as well.
        //
        // The drawback of this solution over the OT solution is that the elements removed by the post-fixer will never be brought back.
        // If the root detachment gets undone (and the root is brought back), the removed elements will not be there.
        this.registerPostFixer((writer)=>{
            let result = false;
            for (const root of this.roots){
                if (!root.isAttached() && !root.isEmpty) {
                    writer.remove(writer.createRangeIn(root));
                    result = true;
                }
            }
            for (const marker of this.model.markers){
                if (!marker.getRange().root.isAttached()) {
                    writer.removeMarker(marker);
                    result = true;
                }
            }
            return result;
        });
    }
    /**
	 * The document version. Every applied operation increases the version number. It is used to
	 * ensure that operations are applied on a proper document version.
	 *
	 * This property is equal to {@link module:engine/model/history~History#version `model.Document#history#version`}.
	 *
	 * If the {@link module:engine/model/operation/operation~Operation#baseVersion base version} does not match the document version,
	 * a {@link module:utils/ckeditorerror~CKEditorError model-document-applyoperation-wrong-version} error is thrown.
	 */ get version() {
        return this.history.version;
    }
    set version(version) {
        this.history.version = version;
    }
    /**
	 * The graveyard tree root. A document always has a graveyard root that stores removed nodes.
	 */ get graveyard() {
        return this.getRoot(graveyardName);
    }
    /**
	 * Creates a new root.
	 *
	 * **Note:** do not use this method after the editor has been initialized! If you want to dynamically add a root, use
	 * {@link module:engine/model/writer~Writer#addRoot `model.Writer#addRoot`} instead.
	 *
	 * @param elementName The element name. Defaults to `'$root'` which also has some basic schema defined
	 * (e.g. `$block` elements are allowed inside the `$root`). Make sure to define a proper schema if you use a different name.
	 * @param rootName A unique root name.
	 * @returns The created root.
	 */ createRoot(elementName = '$root', rootName = 'main') {
        if (this.roots.get(rootName)) {
            /**
			 * A root with the specified name already exists.
			 *
			 * @error model-document-createroot-name-exists
			 */ throw new CKEditorError('model-document-createroot-name-exists', this, {
                name: rootName
            });
        }
        const root = new RootElement(this, elementName, rootName);
        this.roots.add(root);
        return root;
    }
    /**
	 * Removes all event listeners set by the document instance.
	 */ destroy() {
        this.selection.destroy();
        this.stopListening();
    }
    /**
	 * Returns a root by its name.
	 *
	 * Detached roots are returned by this method. This is to be able to operate on the detached root (for example, to be able to create
	 * a position inside such a root for undo feature purposes).
	 *
	 * @param name The root name of the root to return.
	 * @returns The root registered under a given name or `null` when there is no root with the given name.
	 */ getRoot(name = 'main') {
        return this.roots.get(name);
    }
    /**
	 * Returns an array with names of all roots added to the document (except the {@link #graveyard graveyard root}).
	 *
	 * Detached roots **are not** returned by this method by default. This is to make sure that all features or algorithms that operate
	 * on the document data know which roots are still a part of the document and should be processed.
	 *
	 * @param includeDetached Specified whether detached roots should be returned as well.
	 */ getRootNames(includeDetached = false) {
        return this.getRoots(includeDetached).map((root)=>root.rootName);
    }
    /**
	 * Returns an array with all roots added to the document (except the {@link #graveyard graveyard root}).
	 *
	 * Detached roots **are not** returned by this method by default. This is to make sure that all features or algorithms that operate
	 * on the document data know which roots are still a part of the document and should be processed.
	 *
	 * @param includeDetached Specified whether detached roots should be returned as well.
	 */ getRoots(includeDetached = false) {
        return this.roots.filter((root)=>root != this.graveyard && (includeDetached || root.isAttached()) && root._isLoaded);
    }
    /**
	 * Used to register a post-fixer callback. A post-fixer mechanism guarantees that the features
	 * will operate on a correct model state.
	 *
	 * An execution of a feature may lead to an incorrect document tree state. The callbacks are used to fix the document tree after
	 * it has changed. Post-fixers are fired just after all changes from the outermost change block were applied but
	 * before the {@link module:engine/model/document~Document#event:change change event} is fired. If a post-fixer callback made
	 * a change, it should return `true`. When this happens, all post-fixers are fired again to check if something else should
	 * not be fixed in the new document tree state.
	 *
	 * As a parameter, a post-fixer callback receives a {@link module:engine/model/writer~Writer writer} instance connected with the
	 * executed changes block. Thanks to that, all changes done by the callback will be added to the same
	 * {@link module:engine/model/batch~Batch batch} (and undo step) as the original changes. This makes post-fixer changes transparent
	 * for the user.
	 *
	 * An example of a post-fixer is a callback that checks if all the data were removed from the editor. If so, the
	 * callback should add an empty paragraph so that the editor is never empty:
	 *
	 * ```ts
	 * document.registerPostFixer( writer => {
	 * 	const changes = document.differ.getChanges();
	 *
	 * 	// Check if the changes lead to an empty root in the editor.
	 * 	for ( const entry of changes ) {
	 * 		if ( entry.type == 'remove' && entry.position.root.isEmpty ) {
	 * 			writer.insertElement( 'paragraph', entry.position.root, 0 );
	 *
	 * 			// It is fine to return early, even if multiple roots would need to be fixed.
	 * 			// All post-fixers will be fired again, so if there are more empty roots, those will be fixed, too.
	 * 			return true;
	 * 		}
	 * 	}
	 *
	 * 	return false;
	 * } );
	 * ```
	 */ registerPostFixer(postFixer) {
        this._postFixers.add(postFixer);
    }
    /**
	 * A custom `toJSON()` method to solve child-parent circular dependencies.
	 *
	 * @returns A clone of this object with the document property changed to a string.
	 */ toJSON() {
        const json = clone(this);
        // Due to circular references we need to remove parent reference.
        json.selection = '[engine.model.DocumentSelection]';
        json.model = '[engine.model.Model]';
        return json;
    }
    /**
	 * Check if there were any changes done on document, and if so, call post-fixers,
	 * fire `change` event for features and conversion and then reset the differ.
	 * Fire `change:data` event when at least one operation or buffered marker changes the data.
	 *
	 * @internal
	 * @fires change
	 * @fires change:data
	 * @param writer The writer on which post-fixers will be called.
	 */ _handleChangeBlock(writer) {
        if (this._hasDocumentChangedFromTheLastChangeBlock()) {
            this._callPostFixers(writer);
            // Refresh selection attributes according to the final position in the model after the change.
            this.selection.refresh();
            if (this.differ.hasDataChanges()) {
                this.fire('change:data', writer.batch);
            } else {
                this.fire('change', writer.batch);
            }
            // Theoretically, it is not necessary to refresh selection after change event because
            // post-fixers are the last who should change the model, but just in case...
            this.selection.refresh();
            this.differ.reset();
        }
        this._hasSelectionChangedFromTheLastChangeBlock = false;
    }
    /**
	 * Returns whether there is a buffered change or if the selection has changed from the last
	 * {@link module:engine/model/model~Model#enqueueChange `enqueueChange()` block}
	 * or {@link module:engine/model/model~Model#change `change()` block}.
	 *
	 * @returns Returns `true` if document has changed from the last `change()` or `enqueueChange()` block.
	 */ _hasDocumentChangedFromTheLastChangeBlock() {
        return !this.differ.isEmpty || this._hasSelectionChangedFromTheLastChangeBlock;
    }
    /**
	 * Returns the default root for this document which is either the first root that was added to the document using
	 * {@link #createRoot} or the {@link #graveyard graveyard root} if no other roots were created.
	 *
	 * @returns The default root for this document.
	 */ _getDefaultRoot() {
        const roots = this.getRoots();
        return roots.length ? roots[0] : this.graveyard;
    }
    /**
	 * Returns the default range for this selection. The default range is a collapsed range that starts and ends
	 * at the beginning of this selection's document {@link #_getDefaultRoot default root}.
	 *
	 * @internal
	 */ _getDefaultRange() {
        const defaultRoot = this._getDefaultRoot();
        const model = this.model;
        const schema = model.schema;
        // Find the first position where the selection can be put.
        const position = model.createPositionFromPath(defaultRoot, [
            0
        ]);
        const nearestRange = schema.getNearestSelectionRange(position);
        // If valid selection range is not found - return range collapsed at the beginning of the root.
        return nearestRange || model.createRange(position);
    }
    /**
	 * Checks whether a given {@link module:engine/model/range~Range range} is a valid range for
	 * the {@link #selection document's selection}.
	 *
	 * @internal
	 * @param range A range to check.
	 * @returns `true` if `range` is valid, `false` otherwise.
	 */ _validateSelectionRange(range) {
        return validateTextNodePosition(range.start) && validateTextNodePosition(range.end);
    }
    /**
	 * Performs post-fixer loops. Executes post-fixer callbacks as long as none of them has done any changes to the model.
	 *
	 * @param writer The writer on which post-fixer callbacks will be called.
	 */ _callPostFixers(writer) {
        let wasFixed = false;
        do {
            for (const callback of this._postFixers){
                // Ensure selection attributes are up to date before each post-fixer.
                // https://github.com/ckeditor/ckeditor5-engine/issues/1673.
                //
                // It might be good to refresh the selection after each operation but at the moment it leads
                // to losing attributes for composition or and spell checking
                // https://github.com/ckeditor/ckeditor5-typing/issues/188
                this.selection.refresh();
                wasFixed = callback(writer);
                if (wasFixed) {
                    break;
                }
            }
        }while (wasFixed)
    }
}
/**
 * Checks whether given range boundary position is valid for document selection, meaning that is not between
 * unicode surrogate pairs or base character and combining marks.
 */ function validateTextNodePosition(rangeBoundary) {
    const textNode = rangeBoundary.textNode;
    if (textNode) {
        const data = textNode.data;
        const offset = rangeBoundary.offset - textNode.startOffset;
        return !isInsideSurrogatePair(data, offset) && !isInsideCombinedSymbol(data, offset);
    }
    return true;
}

/**
 * The collection of all {@link module:engine/model/markercollection~Marker markers} attached to the document.
 * It lets you {@link module:engine/model/markercollection~MarkerCollection#get get} markers or track them using
 * {@link module:engine/model/markercollection~MarkerCollection#event:update} event.
 *
 * To create, change or remove makers use {@link module:engine/model/writer~Writer model writers'} methods:
 * {@link module:engine/model/writer~Writer#addMarker} or {@link module:engine/model/writer~Writer#removeMarker}. Since
 * the writer is the only proper way to change the data model it is not possible to change markers directly using this
 * collection. All markers created by the writer will be automatically added to this collection.
 *
 * By default there is one marker collection available as {@link module:engine/model/model~Model#markers model property}.
 *
 * @see module:engine/model/markercollection~Marker
 */ class MarkerCollection extends /* #__PURE__ */ EmitterMixin() {
    /**
	 * Stores {@link ~Marker markers} added to the collection.
	 */ _markers = new Map();
    /**
	 * Iterable interface.
	 *
	 * Iterates over all {@link ~Marker markers} added to the collection.
	 */ [Symbol.iterator]() {
        return this._markers.values();
    }
    /**
	 * Checks if given {@link ~Marker marker} or marker name is in the collection.
	 *
	 * @param markerOrName Name of marker or marker instance to check.
	 * @returns `true` if marker is in the collection, `false` otherwise.
	 */ has(markerOrName) {
        const markerName = markerOrName instanceof Marker ? markerOrName.name : markerOrName;
        return this._markers.has(markerName);
    }
    /**
	 * Returns {@link ~Marker marker} with given `markerName`.
	 *
	 * @param markerName Name of marker to get.
	 * @returns Marker with given name or `null` if such marker was
	 * not added to the collection.
	 */ get(markerName) {
        return this._markers.get(markerName) || null;
    }
    /**
	 * Creates and adds a {@link ~Marker marker} to the `MarkerCollection` with given name on given
	 * {@link module:engine/model/range~Range range}.
	 *
	 * If `MarkerCollection` already had a marker with given name (or {@link ~Marker marker} was passed), the marker in
	 * collection is updated and {@link module:engine/model/markercollection~MarkerCollection#event:update} event is fired
	 * but only if there was a change (marker range or {@link module:engine/model/markercollection~Marker#managedUsingOperations}
	 * flag has changed.
	 *
	 * @internal
	 * @fires update
	 * @param markerOrName Name of marker to set or marker instance to update.
	 * @param range Marker range.
	 * @param managedUsingOperations Specifies whether the marker is managed using operations.
	 * @param affectsData Specifies whether the marker affects the data produced by the data pipeline
	 * (is persisted in the editor's data).
	 * @returns `Marker` instance which was added or updated.
	 */ _set(markerOrName, range, managedUsingOperations = false, affectsData = false) {
        const markerName = markerOrName instanceof Marker ? markerOrName.name : markerOrName;
        if (markerName.includes(',')) {
            /**
			 * Marker name cannot contain the "," character.
			 *
			 * @error markercollection-incorrect-marker-name
			 */ throw new CKEditorError('markercollection-incorrect-marker-name', this);
        }
        const oldMarker = this._markers.get(markerName);
        if (oldMarker) {
            const oldMarkerData = oldMarker.getData();
            const oldRange = oldMarker.getRange();
            let hasChanged = false;
            if (!oldRange.isEqual(range)) {
                oldMarker._attachLiveRange(LiveRange.fromRange(range));
                hasChanged = true;
            }
            if (managedUsingOperations != oldMarker.managedUsingOperations) {
                oldMarker._managedUsingOperations = managedUsingOperations;
                hasChanged = true;
            }
            if (typeof affectsData === 'boolean' && affectsData != oldMarker.affectsData) {
                oldMarker._affectsData = affectsData;
                hasChanged = true;
            }
            if (hasChanged) {
                this.fire(`update:${markerName}`, oldMarker, oldRange, range, oldMarkerData);
            }
            return oldMarker;
        }
        const liveRange = LiveRange.fromRange(range);
        const marker = new Marker(markerName, liveRange, managedUsingOperations, affectsData);
        this._markers.set(markerName, marker);
        this.fire(`update:${markerName}`, marker, null, range, {
            ...marker.getData(),
            range: null
        });
        return marker;
    }
    /**
	 * Removes given {@link ~Marker marker} or a marker with given name from the `MarkerCollection`.
	 *
	 * @internal
	 * @fires update
	 * @param markerOrName Marker or name of a marker to remove.
	 * @returns `true` if marker was found and removed, `false` otherwise.
	 */ _remove(markerOrName) {
        const markerName = markerOrName instanceof Marker ? markerOrName.name : markerOrName;
        const oldMarker = this._markers.get(markerName);
        if (oldMarker) {
            this._markers.delete(markerName);
            this.fire(`update:${markerName}`, oldMarker, oldMarker.getRange(), null, oldMarker.getData());
            this._destroyMarker(oldMarker);
            return true;
        }
        return false;
    }
    /**
	 * Fires an {@link module:engine/model/markercollection~MarkerCollection#event:update} event for the given {@link ~Marker marker}
	 * but does not change the marker. Useful to force {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher downcast
	 * conversion} for the marker.
	 *
	 * @internal
	 * @fires update
	 * @param markerOrName Marker or name of a marker to refresh.
	 */ _refresh(markerOrName) {
        const markerName = markerOrName instanceof Marker ? markerOrName.name : markerOrName;
        const marker = this._markers.get(markerName);
        if (!marker) {
            /**
			 * Marker with provided name does not exists.
			 *
			 * @error markercollection-refresh-marker-not-exists
			 */ throw new CKEditorError('markercollection-refresh-marker-not-exists', this);
        }
        const range = marker.getRange();
        this.fire(`update:${markerName}`, marker, range, range, marker.getData());
    }
    /**
	 * Returns iterator that iterates over all markers, which ranges contain given {@link module:engine/model/position~Position position}.
	 */ *getMarkersAtPosition(position) {
        for (const marker of this){
            if (marker.getRange().containsPosition(position)) {
                yield marker;
            }
        }
    }
    /**
	 * Returns iterator that iterates over all markers, which intersects with given {@link module:engine/model/range~Range range}.
	 */ *getMarkersIntersectingRange(range) {
        for (const marker of this){
            if (marker.getRange().getIntersection(range) !== null) {
                yield marker;
            }
        }
    }
    /**
	 * Destroys marker collection and all markers inside it.
	 */ destroy() {
        for (const marker of this._markers.values()){
            this._destroyMarker(marker);
        }
        this._markers = null;
        this.stopListening();
    }
    /**
	 * Iterates over all markers that starts with given `prefix`.
	 *
	 * ```ts
	 * const markerFooA = markersCollection._set( 'foo:a', rangeFooA );
	 * const markerFooB = markersCollection._set( 'foo:b', rangeFooB );
	 * const markerBarA = markersCollection._set( 'bar:a', rangeBarA );
	 * const markerFooBarA = markersCollection._set( 'foobar:a', rangeFooBarA );
	 * Array.from( markersCollection.getMarkersGroup( 'foo' ) ); // [ markerFooA, markerFooB ]
	 * Array.from( markersCollection.getMarkersGroup( 'a' ) ); // []
	 * ```
	 */ *getMarkersGroup(prefix) {
        for (const marker of this._markers.values()){
            if (marker.name.startsWith(prefix + ':')) {
                yield marker;
            }
        }
    }
    /**
	 * Destroys the marker.
	 */ _destroyMarker(marker) {
        marker.stopListening();
        marker._detachLiveRange();
    }
}
/**
 * `Marker` is a continuous part of the model (like a range), is named and represents some kind of information about the
 * marked part of the model document. In contrary to {@link module:engine/model/node~Node nodes}, which are building blocks of
 * the model document tree, markers are not stored directly in the document tree but in the
 * {@link module:engine/model/model~Model#markers model markers' collection}. Still, they are document data, by giving
 * additional meaning to the part of a model document between marker start and marker end.
 *
 * In this sense, markers are similar to adding and converting attributes on nodes. The difference is that attribute is
 * connected with a given node (e.g. a character is bold no matter if it gets moved or content around it changes).
 * Markers on the other hand are continuous ranges and are characterized by their start and end position. This means that
 * any character in the marker is marked by the marker. For example, if a character is moved outside of marker it stops being
 * "special" and the marker is shrunk. Similarly, when a character is moved into the marker from other place in document
 * model, it starts being "special" and the marker is enlarged.
 *
 * Another upside of markers is that finding marked part of document is fast and easy. Using attributes to mark some nodes
 * and then trying to find that part of document would require traversing whole document tree. Marker gives instant access
 * to the range which it is marking at the moment.
 *
 * Markers are built from a name and a range.
 *
 * Range of the marker is updated automatically when document changes, using
 * {@link module:engine/model/liverange~LiveRange live range} mechanism.
 *
 * Name is used to group and identify markers. Names have to be unique, but markers can be grouped by
 * using common prefixes, separated with `:`, for example: `user:john` or `search:3`. That's useful in term of creating
 * namespaces for custom elements (e.g. comments, highlights). You can use this prefixes in
 * {@link module:engine/model/markercollection~MarkerCollection#event:update} listeners to listen on changes in a group of markers.
 * For instance: `model.markers.on( 'update:user', callback );` will be called whenever any `user:*` markers changes.
 *
 * There are two types of markers.
 *
 * 1. Markers managed directly, without using operations. They are added directly by {@link module:engine/model/writer~Writer}
 * to the {@link module:engine/model/markercollection~MarkerCollection} without any additional mechanism. They can be used
 * as bookmarks or visual markers. They are great for showing results of the find, or select link when the focus is in the input.
 *
 * 1. Markers managed using operations. These markers are also stored in {@link module:engine/model/markercollection~MarkerCollection}
 * but changes in these markers is managed the same way all other changes in the model structure - using operations.
 * Therefore, they are handled in the undo stack and synchronized between clients if the collaboration plugin is enabled.
 * This type of markers is useful for solutions like spell checking or comments.
 *
 * Both type of them should be added / updated by {@link module:engine/model/writer~Writer#addMarker}
 * and removed by {@link module:engine/model/writer~Writer#removeMarker} methods.
 *
 * ```ts
 * model.change( ( writer ) => {
 * 	const marker = writer.addMarker( name, { range, usingOperation: true } );
 *
 * 	// ...
 *
 * 	writer.removeMarker( marker );
 * } );
 * ```
 *
 * See {@link module:engine/model/writer~Writer} to find more examples.
 *
 * Since markers need to track change in the document, for efficiency reasons, it is best to create and keep as little
 * markers as possible and remove them as soon as they are not needed anymore.
 *
 * Markers can be downcasted and upcasted.
 *
 * Markers downcast happens on {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker} and
 * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:removeMarker} events.
 * Use {@link module:engine/conversion/downcasthelpers downcast converters} or attach a custom converter to mentioned events.
 * For {@link module:engine/controller/datacontroller~DataController data pipeline}, marker should be downcasted to an element.
 * Then, it can be upcasted back to a marker. Again, use {@link module:engine/conversion/upcasthelpers upcast converters} or
 * attach a custom converter to {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#event:element}.
 *
 * `Marker` instances are created and destroyed only by {@link ~MarkerCollection MarkerCollection}.
 */ class Marker extends /* #__PURE__ */ EmitterMixin(TypeCheckable) {
    /**
	 * Marker's name.
	 */ name;
    /**
	 * Flag indicates if the marker is managed using operations or not.
	 *
	 * @internal
	 */ _managedUsingOperations;
    /**
	 * Specifies whether the marker affects the data produced by the data pipeline
	 * (is persisted in the editor's data).
	 *
	 * @internal
	 */ _affectsData;
    /**
	 * Range marked by the marker.
	 */ _liveRange;
    /**
	 * Creates a marker instance.
	 *
	 * @param name Marker name.
	 * @param liveRange Range marked by the marker.
	 * @param managedUsingOperations Specifies whether the marker is managed using operations.
	 * @param affectsData Specifies whether the marker affects the data produced by the data pipeline (is persisted in the editor's data).
	 */ constructor(name, liveRange, managedUsingOperations, affectsData){
        super();
        this.name = name;
        this._liveRange = this._attachLiveRange(liveRange);
        this._managedUsingOperations = managedUsingOperations;
        this._affectsData = affectsData;
    }
    /**
	 * A value indicating if the marker is managed using operations.
	 * See {@link ~Marker marker class description} to learn more about marker types.
	 * See {@link module:engine/model/writer~Writer#addMarker}.
	 */ get managedUsingOperations() {
        if (!this._liveRange) {
            throw new CKEditorError('marker-destroyed', this);
        }
        return this._managedUsingOperations;
    }
    /**
	 * A value indicating if the marker changes the data.
	 */ get affectsData() {
        if (!this._liveRange) {
            throw new CKEditorError('marker-destroyed', this);
        }
        return this._affectsData;
    }
    /**
	 * Returns the marker data (properties defining the marker).
	 */ getData() {
        return {
            range: this.getRange(),
            affectsData: this.affectsData,
            managedUsingOperations: this.managedUsingOperations
        };
    }
    /**
	 * Returns current marker start position.
	 */ getStart() {
        if (!this._liveRange) {
            throw new CKEditorError('marker-destroyed', this);
        }
        return this._liveRange.start.clone();
    }
    /**
	 * Returns current marker end position.
	 */ getEnd() {
        if (!this._liveRange) {
            throw new CKEditorError('marker-destroyed', this);
        }
        return this._liveRange.end.clone();
    }
    /**
	 * Returns a range that represents the current state of the marker.
	 *
	 * Keep in mind that returned value is a {@link module:engine/model/range~Range Range}, not a
	 * {@link module:engine/model/liverange~LiveRange LiveRange}. This means that it is up-to-date and relevant only
	 * until next model document change. Do not store values returned by this method. Instead, store {@link ~Marker#name}
	 * and get `Marker` instance from {@link module:engine/model/markercollection~MarkerCollection MarkerCollection} every
	 * time there is a need to read marker properties. This will guarantee that the marker has not been removed and
	 * that it's data is up-to-date.
	 */ getRange() {
        if (!this._liveRange) {
            throw new CKEditorError('marker-destroyed', this);
        }
        return this._liveRange.toRange();
    }
    /**
	 * Binds new live range to the marker and detach the old one if is attached.
	 *
	 * @internal
	 * @param liveRange Live range to attach
	 * @returns Attached live range.
	 */ _attachLiveRange(liveRange) {
        if (this._liveRange) {
            this._detachLiveRange();
        }
        // Delegating does not work with namespaces. Alternatively, we could delegate all events (using `*`).
        liveRange.delegate('change:range').to(this);
        liveRange.delegate('change:content').to(this);
        this._liveRange = liveRange;
        return liveRange;
    }
    /**
	 * Unbinds and destroys currently attached live range.
	 *
	 * @internal
	 */ _detachLiveRange() {
        this._liveRange.stopDelegating('change:range', this);
        this._liveRange.stopDelegating('change:content', this);
        this._liveRange.detach();
        this._liveRange = null;
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
Marker.prototype.is = function(type) {
    return type === 'marker' || type === 'model:marker';
};
 /**
 * Cannot use a {@link module:engine/model/markercollection~MarkerCollection#destroy destroyed marker} instance.
 *
 * @error marker-destroyed
 */

// @if CK_DEBUG_ENGINE // const ModelRange = require( '../range' ).default;
/**
 * Operation to permanently remove node from detached root.
 * Note this operation is only a local operation and won't be send to the other clients.
 */ class DetachOperation extends Operation {
    /**
	 * Position before the first {@link module:engine/model/item~Item model item} to detach.
	 */ sourcePosition;
    /**
	 * Offset size of moved range.
	 */ howMany;
    /**
	 * Creates an insert operation.
	 *
	 * @param sourcePosition Position before the first {@link module:engine/model/item~Item model item} to move.
	 * @param howMany Offset size of moved range. Moved range will start from `sourcePosition` and end at
	 * `sourcePosition` with offset shifted by `howMany`.
	 */ constructor(sourcePosition, howMany){
        super(null);
        this.sourcePosition = sourcePosition.clone();
        this.howMany = howMany;
    }
    /**
	 * @inheritDoc
	 */ get type() {
        return 'detach';
    }
    /**
	 * @inheritDoc
	 */ get affectedSelectable() {
        return null;
    }
    /**
	 * @inheritDoc
	 */ toJSON() {
        const json = super.toJSON();
        json.sourcePosition = this.sourcePosition.toJSON();
        return json;
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _validate() {
        if (this.sourcePosition.root.document) {
            /**
			 * Cannot detach document node.
			 *
			 * @error detach-operation-on-document-node
			 */ throw new CKEditorError('detach-operation-on-document-node', this);
        }
    }
    /**
	 * @inheritDoc
	 * @internal
	 */ _execute() {
        _remove(Range._createFromPositionAndShift(this.sourcePosition, this.howMany));
    }
    /**
	 * @inheritDoc
	 */ static get className() {
        return 'DetachOperation';
    }
}

// @if CK_DEBUG_ENGINE // const { stringifyMap } = require( '../dev-utils/utils' );
/**
 * DocumentFragment represents a part of model which does not have a common root but its top-level nodes
 * can be seen as siblings. In other words, it is a detached part of model tree, without a root.
 *
 * DocumentFragment has own {@link module:engine/model/markercollection~MarkerCollection}. Markers from this collection
 * will be set to the {@link module:engine/model/model~Model#markers model markers} by a
 * {@link module:engine/model/writer~Writer#insert} function.
 */ class DocumentFragment extends TypeCheckable {
    /**
	 * DocumentFragment static markers map. This is a list of names and {@link module:engine/model/range~Range ranges}
	 * which will be set as Markers to {@link module:engine/model/model~Model#markers model markers collection}
	 * when DocumentFragment will be inserted to the document.
	 */ markers = new Map();
    /**
	 * List of nodes contained inside the document fragment.
	 */ _children = new NodeList();
    /**
	 * Creates an empty `DocumentFragment`.
	 *
	 * **Note:** Constructor of this class shouldn't be used directly in the code.
	 * Use the {@link module:engine/model/writer~Writer#createDocumentFragment} method instead.
	 *
	 * @internal
	 * @param children Nodes to be contained inside the `DocumentFragment`.
	 */ constructor(children){
        super();
        if (children) {
            this._insertChild(0, children);
        }
    }
    /**
	 * Returns an iterator that iterates over all nodes contained inside this document fragment.
	 */ [Symbol.iterator]() {
        return this.getChildren();
    }
    /**
	 * Number of this document fragment's children.
	 */ get childCount() {
        return this._children.length;
    }
    /**
	 * Sum of {@link module:engine/model/node~Node#offsetSize offset sizes} of all of this document fragment's children.
	 */ get maxOffset() {
        return this._children.maxOffset;
    }
    /**
	 * Is `true` if there are no nodes inside this document fragment, `false` otherwise.
	 */ get isEmpty() {
        return this.childCount === 0;
    }
    /**
	 * Artificial next sibling. Returns `null`. Added for compatibility reasons.
	 */ get nextSibling() {
        return null;
    }
    /**
	 * Artificial previous sibling. Returns `null`. Added for compatibility reasons.
	 */ get previousSibling() {
        return null;
    }
    /**
	 * Artificial root of `DocumentFragment`. Returns itself. Added for compatibility reasons.
	 */ get root() {
        return this;
    }
    /**
	 * Artificial parent of `DocumentFragment`. Returns `null`. Added for compatibility reasons.
	 */ get parent() {
        return null;
    }
    /**
	 * Artificial owner of `DocumentFragment`. Returns `null`. Added for compatibility reasons.
	 */ get document() {
        return null;
    }
    /**
	 * Returns `false` as `DocumentFragment` by definition is not attached to a document. Added for compatibility reasons.
	 */ isAttached() {
        return false;
    }
    /**
	 * Returns empty array. Added for compatibility reasons.
	 */ getAncestors() {
        return [];
    }
    /**
	 * Gets the child at the given index. Returns `null` if incorrect index was passed.
	 *
	 * @param index Index of child.
	 * @returns Child node.
	 */ getChild(index) {
        return this._children.getNode(index);
    }
    /**
	 * Returns an iterator that iterates over all of this document fragment's children.
	 */ getChildren() {
        return this._children[Symbol.iterator]();
    }
    /**
	 * Returns an index of the given child node. Returns `null` if given node is not a child of this document fragment.
	 *
	 * @param node Child node to look for.
	 * @returns Child node's index.
	 */ getChildIndex(node) {
        return this._children.getNodeIndex(node);
    }
    /**
	 * Returns the starting offset of given child. Starting offset is equal to the sum of
	 * {@link module:engine/model/node~Node#offsetSize offset sizes} of all node's siblings that are before it. Returns `null` if
	 * given node is not a child of this document fragment.
	 *
	 * @param node Child node to look for.
	 * @returns Child node's starting offset.
	 */ getChildStartOffset(node) {
        return this._children.getNodeStartOffset(node);
    }
    /**
	 * Returns path to a `DocumentFragment`, which is an empty array. Added for compatibility reasons.
	 */ getPath() {
        return [];
    }
    /**
	 * Returns a descendant node by its path relative to this element.
	 *
	 * ```ts
	 * // <this>a<b>c</b></this>
	 * this.getNodeByPath( [ 0 ] );     // -> "a"
	 * this.getNodeByPath( [ 1 ] );     // -> <b>
	 * this.getNodeByPath( [ 1, 0 ] );  // -> "c"
	 * ```
	 *
	 * @param relativePath Path of the node to find, relative to this element.
	 */ getNodeByPath(relativePath) {
        // eslint-disable-next-line @typescript-eslint/no-this-alias, consistent-this
        let node = this;
        for (const index of relativePath){
            node = node.getChild(node.offsetToIndex(index));
        }
        return node;
    }
    /**
	 * Converts offset "position" to index "position".
	 *
	 * Returns index of a node that occupies given offset. If given offset is too low, returns `0`. If given offset is
	 * too high, returns index after last child.
	 *
	 * ```ts
	 * const textNode = new Text( 'foo' );
	 * const pElement = new Element( 'p' );
	 * const docFrag = new DocumentFragment( [ textNode, pElement ] );
	 * docFrag.offsetToIndex( -1 ); // Returns 0, because offset is too low.
	 * docFrag.offsetToIndex( 0 ); // Returns 0, because offset 0 is taken by `textNode` which is at index 0.
	 * docFrag.offsetToIndex( 1 ); // Returns 0, because `textNode` has `offsetSize` equal to 3, so it occupies offset 1 too.
	 * docFrag.offsetToIndex( 2 ); // Returns 0.
	 * docFrag.offsetToIndex( 3 ); // Returns 1.
	 * docFrag.offsetToIndex( 4 ); // Returns 2. There are no nodes at offset 4, so last available index is returned.
	 * ```
	 *
	 * @param offset Offset to look for.
	 * @returns Index of a node that occupies given offset.
	 */ offsetToIndex(offset) {
        return this._children.offsetToIndex(offset);
    }
    /**
	 * Converts `DocumentFragment` instance to plain object and returns it.
	 * Takes care of converting all of this document fragment's children.
	 *
	 * @returns `DocumentFragment` instance converted to plain object.
	 */ toJSON() {
        const json = [];
        for (const node of this._children){
            json.push(node.toJSON());
        }
        return json;
    }
    /**
	 * Creates a `DocumentFragment` instance from given plain object (i.e. parsed JSON string).
	 * Converts `DocumentFragment` children to proper nodes.
	 *
	 * @param json Plain object to be converted to `DocumentFragment`.
	 * @returns `DocumentFragment` instance created using given plain object.
	 */ static fromJSON(json) {
        const children = [];
        for (const child of json){
            if (child.name) {
                // If child has name property, it is an Element.
                children.push(Element.fromJSON(child));
            } else {
                // Otherwise, it is a Text node.
                children.push(Text.fromJSON(child));
            }
        }
        return new DocumentFragment(children);
    }
    /**
	 * {@link #_insertChild Inserts} one or more nodes at the end of this document fragment.
	 *
	 * @internal
	 * @param items Items to be inserted.
	 */ _appendChild(items) {
        this._insertChild(this.childCount, items);
    }
    /**
	 * Inserts one or more nodes at the given index and sets {@link module:engine/model/node~Node#parent parent} of these nodes
	 * to this document fragment.
	 *
	 * @internal
	 * @param index Index at which nodes should be inserted.
	 * @param items Items to be inserted.
	 */ _insertChild(index, items) {
        const nodes = normalize(items);
        for (const node of nodes){
            // If node that is being added to this element is already inside another element, first remove it from the old parent.
            if (node.parent !== null) {
                node._remove();
            }
            node.parent = this;
        }
        this._children._insertNodes(index, nodes);
    }
    /**
	 * Removes one or more nodes starting at the given index
	 * and sets {@link module:engine/model/node~Node#parent parent} of these nodes to `null`.
	 *
	 * @internal
	 * @param index Index of the first node to remove.
	 * @param howMany Number of nodes to remove.
	 * @returns Array containing removed nodes.
	 */ _removeChildren(index, howMany = 1) {
        const nodes = this._children._removeNodes(index, howMany);
        for (const node of nodes){
            node.parent = null;
        }
        return nodes;
    }
}
// The magic of type inference using `is` method is centralized in `TypeCheckable` class.
// Proper overload would interfere with that.
DocumentFragment.prototype.is = function(type) {
    return type === 'documentFragment' || type === 'model:documentFragment';
};
/**
 * Converts strings to Text and non-iterables to arrays.
 */ function normalize(nodes) {
    // Separate condition because string is iterable.
    if (typeof nodes == 'string') {
        return [
            new Text(nodes)
        ];
    }
    if (!isIterable(nodes)) {
        nodes = [
            nodes
        ];
    }
    // Array.from to enable .map() on non-arrays.
    return Array.from(nodes).map((node)=>{
        if (typeof node == 'string') {
            return new Text(node);
        }
        if (node instanceof TextProxy) {
            return new Text(node.data, node.getAttributes());
        }
        return node;
    });
}

/**
 * The model can only be modified by using the writer. It should be used whenever you want to create a node, modify
 * child nodes, attributes or text, set the selection's position and its attributes.
 *
 * The instance of the writer is only available in the {@link module:engine/model/model~Model#change `change()`} or
 * {@link module:engine/model/model~Model#enqueueChange `enqueueChange()`}.
 *
 * ```ts
 * model.change( writer => {
 * 	writer.insertText( 'foo', paragraph, 'end' );
 * } );
 * ```
 *
 * Note that the writer should never be stored and used outside of the `change()` and
 * `enqueueChange()` blocks.
 *
 * Note that writer's methods do not check the {@link module:engine/model/schema~Schema}. It is possible
 * to create incorrect model structures by using the writer. Read more about in
 * {@glink framework/deep-dive/schema#who-checks-the-schema "Who checks the schema?"}.
 *
 * @see module:engine/model/model~Model#change
 * @see module:engine/model/model~Model#enqueueChange
 */ class Writer {
    /**
	 * Instance of the model on which this writer operates.
	 */ model;
    /**
	 * The batch to which this writer will add changes.
	 */ batch;
    /**
	 * Creates a writer instance.
	 *
	 * **Note:** It is not recommended to use it directly. Use {@link module:engine/model/model~Model#change `Model#change()`} or
	 * {@link module:engine/model/model~Model#enqueueChange `Model#enqueueChange()`} instead.
	 *
	 * @internal
	 */ constructor(model, batch){
        this.model = model;
        this.batch = batch;
    }
    /**
	 * Creates a new {@link module:engine/model/text~Text text node}.
	 *
	 * ```ts
	 * writer.createText( 'foo' );
	 * writer.createText( 'foo', { bold: true } );
	 * ```
	 *
	 * @param data Text data.
	 * @param attributes Text attributes.
	 * @returns {module:engine/model/text~Text} Created text node.
	 */ createText(data, attributes) {
        return new Text(data, attributes);
    }
    /**
	 * Creates a new {@link module:engine/model/element~Element element}.
	 *
	 * ```ts
	 * writer.createElement( 'paragraph' );
	 * writer.createElement( 'paragraph', { alignment: 'center' } );
	 * ```
	 *
	 * @param name Name of the element.
	 * @param attributes Elements attributes.
	 * @returns Created element.
	 */ createElement(name, attributes) {
        return new Element(name, attributes);
    }
    /**
	 * Creates a new {@link module:engine/model/documentfragment~DocumentFragment document fragment}.
	 *
	 * @returns Created document fragment.
	 */ createDocumentFragment() {
        return new DocumentFragment();
    }
    /**
	 * Creates a copy of the element and returns it. Created element has the same name and attributes as the original element.
	 * If clone is deep, the original element's children are also cloned. If not, then empty element is returned.
	 *
	 * @param element The element to clone.
	 * @param deep If set to `true` clones element and all its children recursively. When set to `false`,
	 * element will be cloned without any child.
	 */ cloneElement(element, deep = true) {
        return element._clone(deep);
    }
    /**
	 * Inserts item on given position.
	 *
	 * ```ts
	 * const paragraph = writer.createElement( 'paragraph' );
	 * writer.insert( paragraph, position );
	 * ```
	 *
	 * Instead of using position you can use parent and offset:
	 *
	 * ```ts
	 * const text = writer.createText( 'foo' );
	 * writer.insert( text, paragraph, 5 );
	 * ```
	 *
	 * You can also use `end` instead of the offset to insert at the end:
	 *
	 * ```ts
	 * const text = writer.createText( 'foo' );
	 * writer.insert( text, paragraph, 'end' );
	 * ```
	 *
	 * Or insert before or after another element:
	 *
	 * ```ts
	 * const paragraph = writer.createElement( 'paragraph' );
	 * writer.insert( paragraph, anotherParagraph, 'after' );
	 * ```
	 *
	 * These parameters works the same way as {@link #createPositionAt `writer.createPositionAt()`}.
	 *
	 * Note that if the item already has parent it will be removed from the previous parent.
	 *
	 * Note that you cannot re-insert a node from a document to a different document or a document fragment. In this case,
	 * `model-writer-insert-forbidden-move` is thrown.
	 *
	 * If you want to move {@link module:engine/model/range~Range range} instead of an
	 * {@link module:engine/model/item~Item item} use {@link module:engine/model/writer~Writer#move `Writer#move()`}.
	 *
	 * **Note:** For a paste-like content insertion mechanism see
	 * {@link module:engine/model/model~Model#insertContent `model.insertContent()`}.
	 *
	 * @param item Item or document fragment to insert.
	 * @param offset Offset or one of the flags. Used only when second parameter is a {@link module:engine/model/item~Item model item}.
	 */ insert(item, itemOrPosition, offset = 0) {
        this._assertWriterUsedCorrectly();
        if (item instanceof Text && item.data == '') {
            return;
        }
        const position = Position._createAt(itemOrPosition, offset);
        // If item has a parent already.
        if (item.parent) {
            // We need to check if item is going to be inserted within the same document.
            if (isSameTree(item.root, position.root)) {
                // If it's we just need to move it.
                this.move(Range._createOn(item), position);
                return;
            } else {
                if (item.root.document) {
                    /**
					 * Cannot move a node from a document to a different tree.
					 * It is forbidden to move a node that was already in a document outside of it.
					 *
					 * @error model-writer-insert-forbidden-move
					 */ throw new CKEditorError('model-writer-insert-forbidden-move', this);
                } else {
                    // Move between two different document fragments or from document fragment to a document is possible.
                    // In that case, remove the item from it's original parent.
                    this.remove(item);
                }
            }
        }
        const version = position.root.document ? position.root.document.version : null;
        const insert = new InsertOperation(position, item, version);
        if (item instanceof Text) {
            insert.shouldReceiveAttributes = true;
        }
        this.batch.addOperation(insert);
        this.model.applyOperation(insert);
        // When element is a DocumentFragment we need to move its markers to Document#markers.
        if (item instanceof DocumentFragment) {
            for (const [markerName, markerRange] of item.markers){
                // We need to migrate marker range from DocumentFragment to Document.
                const rangeRootPosition = Position._createAt(markerRange.root, 0);
                const range = new Range(markerRange.start._getCombined(rangeRootPosition, position), markerRange.end._getCombined(rangeRootPosition, position));
                const options = {
                    range,
                    usingOperation: true,
                    affectsData: true
                };
                if (this.model.markers.has(markerName)) {
                    this.updateMarker(markerName, options);
                } else {
                    this.addMarker(markerName, options);
                }
            }
        }
    }
    insertText(text, attributes, itemOrPosition, offset// Too complicated when not using `any`.
    ) {
        if (attributes instanceof DocumentFragment || attributes instanceof Element || attributes instanceof Position) {
            this.insert(this.createText(text), attributes, itemOrPosition);
        } else {
            this.insert(this.createText(text, attributes), itemOrPosition, offset);
        }
    }
    insertElement(name, attributes, itemOrPositionOrOffset, offset// Too complicated when not using `any`.
    ) {
        if (attributes instanceof DocumentFragment || attributes instanceof Element || attributes instanceof Position) {
            this.insert(this.createElement(name), attributes, itemOrPositionOrOffset);
        } else {
            this.insert(this.createElement(name, attributes), itemOrPositionOrOffset, offset);
        }
    }
    /**
	 * Inserts item at the end of the given parent.
	 *
	 * ```ts
	 * const paragraph = writer.createElement( 'paragraph' );
	 * writer.append( paragraph, root );
	 * ```
	 *
	 * Note that if the item already has parent it will be removed from the previous parent.
	 *
	 * If you want to move {@link module:engine/model/range~Range range} instead of an
	 * {@link module:engine/model/item~Item item} use {@link module:engine/model/writer~Writer#move `Writer#move()`}.
	 *
	 * @param item Item or document fragment to insert.
	 */ append(item, parent) {
        this.insert(item, parent, 'end');
    }
    appendText(text, attributes, parent) {
        if (attributes instanceof DocumentFragment || attributes instanceof Element) {
            this.insert(this.createText(text), attributes, 'end');
        } else {
            this.insert(this.createText(text, attributes), parent, 'end');
        }
    }
    appendElement(name, attributes, parent) {
        if (attributes instanceof DocumentFragment || attributes instanceof Element) {
            this.insert(this.createElement(name), attributes, 'end');
        } else {
            this.insert(this.createElement(name, attributes), parent, 'end');
        }
    }
    /**
	 * Sets value of the attribute with given key on a {@link module:engine/model/item~Item model item}
	 * or on a {@link module:engine/model/range~Range range}.
	 *
	 * @param key Attribute key.
	 * @param value Attribute new value.
	 * @param itemOrRange Model item or range on which the attribute will be set.
	 */ setAttribute(key, value, itemOrRange) {
        this._assertWriterUsedCorrectly();
        if (itemOrRange instanceof Range) {
            const ranges = itemOrRange.getMinimalFlatRanges();
            for (const range of ranges){
                setAttributeOnRange(this, key, value, range);
            }
        } else {
            setAttributeOnItem(this, key, value, itemOrRange);
        }
    }
    /**
	 * Sets values of attributes on a {@link module:engine/model/item~Item model item}
	 * or on a {@link module:engine/model/range~Range range}.
	 *
	 * ```ts
	 * writer.setAttributes( {
	 * 	bold: true,
	 * 	italic: true
	 * }, range );
	 * ```
	 *
	 * @param attributes Attributes keys and values.
	 * @param itemOrRange Model item or range on which the attributes will be set.
	 */ setAttributes(attributes, itemOrRange) {
        for (const [key, val] of toMap(attributes)){
            this.setAttribute(key, val, itemOrRange);
        }
    }
    /**
	 * Removes an attribute with given key from a {@link module:engine/model/item~Item model item}
	 * or from a {@link module:engine/model/range~Range range}.
	 *
	 * @param key Attribute key.
	 * @param itemOrRange Model item or range from which the attribute will be removed.
	 */ removeAttribute(key, itemOrRange) {
        this._assertWriterUsedCorrectly();
        if (itemOrRange instanceof Range) {
            const ranges = itemOrRange.getMinimalFlatRanges();
            for (const range of ranges){
                setAttributeOnRange(this, key, null, range);
            }
        } else {
            setAttributeOnItem(this, key, null, itemOrRange);
        }
    }
    /**
	 * Removes all attributes from all elements in the range or from the given item.
	 *
	 * @param itemOrRange Model item or range from which all attributes will be removed.
	 */ clearAttributes(itemOrRange) {
        this._assertWriterUsedCorrectly();
        const removeAttributesFromItem = (item)=>{
            for (const attribute of item.getAttributeKeys()){
                this.removeAttribute(attribute, item);
            }
        };
        if (!(itemOrRange instanceof Range)) {
            removeAttributesFromItem(itemOrRange);
        } else {
            for (const item of itemOrRange.getItems()){
                removeAttributesFromItem(item);
            }
        }
    }
    /**
	 * Moves all items in the source range to the target position.
	 *
	 * ```ts
	 * writer.move( sourceRange, targetPosition );
	 * ```
	 *
	 * Instead of the target position you can use parent and offset or define that range should be moved to the end
	 * or before or after chosen item:
	 *
	 * ```ts
	 * // Moves all items in the range to the paragraph at offset 5:
	 * writer.move( sourceRange, paragraph, 5 );
	 * // Moves all items in the range to the end of a blockquote:
	 * writer.move( sourceRange, blockquote, 'end' );
	 * // Moves all items in the range to a position after an image:
	 * writer.move( sourceRange, image, 'after' );
	 * ```
	 *
	 * These parameters work the same way as {@link #createPositionAt `writer.createPositionAt()`}.
	 *
	 * Note that items can be moved only within the same tree. It means that you can move items within the same root
	 * (element or document fragment) or between {@link module:engine/model/document~Document#roots documents roots},
	 * but you can not move items from document fragment to the document or from one detached element to another. Use
	 * {@link module:engine/model/writer~Writer#insert} in such cases.
	 *
	 * @param range Source range.
	 * @param offset Offset or one of the flags. Used only when second parameter is a {@link module:engine/model/item~Item model item}.
	 */ move(range, itemOrPosition, offset) {
        this._assertWriterUsedCorrectly();
        if (!(range instanceof Range)) {
            /**
			 * Invalid range to move.
			 *
			 * @error writer-move-invalid-range
			 */ throw new CKEditorError('writer-move-invalid-range', this);
        }
        if (!range.isFlat) {
            /**
			 * Range to move is not flat.
			 *
			 * @error writer-move-range-not-flat
			 */ throw new CKEditorError('writer-move-range-not-flat', this);
        }
        const position = Position._createAt(itemOrPosition, offset);
        // Do not move anything if the move target is same as moved range start.
        if (position.isEqual(range.start)) {
            return;
        }
        // If part of the marker is removed, create additional marker operation for undo purposes.
        this._addOperationForAffectedMarkers('move', range);
        if (!isSameTree(range.root, position.root)) {
            /**
			 * Range is going to be moved within not the same document. Please use
			 * {@link module:engine/model/writer~Writer#insert insert} instead.
			 *
			 * @error writer-move-different-document
			 */ throw new CKEditorError('writer-move-different-document', this);
        }
        const version = range.root.document ? range.root.document.version : null;
        const operation = new MoveOperation(range.start, range.end.offset - range.start.offset, position, version);
        this.batch.addOperation(operation);
        this.model.applyOperation(operation);
    }
    /**
	 * Removes given model {@link module:engine/model/item~Item item} or {@link module:engine/model/range~Range range}.
	 *
	 * @param itemOrRange Model item or range to remove.
	 */ remove(itemOrRange) {
        this._assertWriterUsedCorrectly();
        const rangeToRemove = itemOrRange instanceof Range ? itemOrRange : Range._createOn(itemOrRange);
        const ranges = rangeToRemove.getMinimalFlatRanges().reverse();
        for (const flat of ranges){
            // If part of the marker is removed, create additional marker operation for undo purposes.
            this._addOperationForAffectedMarkers('move', flat);
            applyRemoveOperation(flat.start, flat.end.offset - flat.start.offset, this.batch, this.model);
        }
    }
    /**
	 * Merges two siblings at the given position.
	 *
	 * Node before and after the position have to be an element. Otherwise `writer-merge-no-element-before` or
	 * `writer-merge-no-element-after` error will be thrown.
	 *
	 * @param position Position between merged elements.
	 */ merge(position) {
        this._assertWriterUsedCorrectly();
        const nodeBefore = position.nodeBefore;
        const nodeAfter = position.nodeAfter;
        // If part of the marker is removed, create additional marker operation for undo purposes.
        this._addOperationForAffectedMarkers('merge', position);
        if (!(nodeBefore instanceof Element)) {
            /**
			 * Node before merge position must be an element.
			 *
			 * @error writer-merge-no-element-before
			 */ throw new CKEditorError('writer-merge-no-element-before', this);
        }
        if (!(nodeAfter instanceof Element)) {
            /**
			 * Node after merge position must be an element.
			 *
			 * @error writer-merge-no-element-after
			 */ throw new CKEditorError('writer-merge-no-element-after', this);
        }
        if (!position.root.document) {
            this._mergeDetached(position);
        } else {
            this._merge(position);
        }
    }
    /**
	 * Shortcut for {@link module:engine/model/model~Model#createPositionFromPath `Model#createPositionFromPath()`}.
	 *
	 * @param root Root of the position.
	 * @param path Position path. See {@link module:engine/model/position~Position#path}.
	 * @param stickiness Position stickiness. See {@link module:engine/model/position~PositionStickiness}.
	 */ createPositionFromPath(root, path, stickiness) {
        return this.model.createPositionFromPath(root, path, stickiness);
    }
    /**
	 * Shortcut for {@link module:engine/model/model~Model#createPositionAt `Model#createPositionAt()`}.
	 *
	 * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/model/item~Item model item}.
	 */ createPositionAt(itemOrPosition, offset) {
        return this.model.createPositionAt(itemOrPosition, offset);
    }
    /**
	 * Shortcut for {@link module:engine/model/model~Model#createPositionAfter `Model#createPositionAfter()`}.
	 *
	 * @param item Item after which the position should be placed.
	 */ createPositionAfter(item) {
        return this.model.createPositionAfter(item);
    }
    /**
	 * Shortcut for {@link module:engine/model/model~Model#createPositionBefore `Model#createPositionBefore()`}.
	 *
	 * @param item Item after which the position should be placed.
	 */ createPositionBefore(item) {
        return this.model.createPositionBefore(item);
    }
    /**
	 * Shortcut for {@link module:engine/model/model~Model#createRange `Model#createRange()`}.
	 *
	 * @param start Start position.
	 * @param end End position. If not set, range will be collapsed at `start` position.
	 */ createRange(start, end) {
        return this.model.createRange(start, end);
    }
    /**
	 * Shortcut for {@link module:engine/model/model~Model#createRangeIn `Model#createRangeIn()`}.
	 *
	 * @param element Element which is a parent for the range.
	 */ createRangeIn(element) {
        return this.model.createRangeIn(element);
    }
    /**
	 * Shortcut for {@link module:engine/model/model~Model#createRangeOn `Model#createRangeOn()`}.
	 *
	 * @param element Element which is a parent for the range.
	 */ createRangeOn(element) {
        return this.model.createRangeOn(element);
    }
    createSelection(...args) {
        return this.model.createSelection(...args);
    }
    /**
	 * Performs merge action in a detached tree.
	 *
	 * @param position Position between merged elements.
	 */ _mergeDetached(position) {
        const nodeBefore = position.nodeBefore;
        const nodeAfter = position.nodeAfter;
        this.move(Range._createIn(nodeAfter), Position._createAt(nodeBefore, 'end'));
        this.remove(nodeAfter);
    }
    /**
	 * Performs merge action in a non-detached tree.
	 *
	 * @param position Position between merged elements.
	 */ _merge(position) {
        const targetPosition = Position._createAt(position.nodeBefore, 'end');
        const sourcePosition = Position._createAt(position.nodeAfter, 0);
        const graveyard = position.root.document.graveyard;
        const graveyardPosition = new Position(graveyard, [
            0
        ]);
        const version = position.root.document.version;
        const merge = new MergeOperation(sourcePosition, position.nodeAfter.maxOffset, targetPosition, graveyardPosition, version);
        this.batch.addOperation(merge);
        this.model.applyOperation(merge);
    }
    /**
	 * Renames the given element.
	 *
	 * @param element The element to rename.
	 * @param newName New element name.
	 */ rename(element, newName) {
        this._assertWriterUsedCorrectly();
        if (!(element instanceof Element)) {
            /**
			 * Trying to rename an object which is not an instance of Element.
			 *
			 * @error writer-rename-not-element-instance
			 */ throw new CKEditorError('writer-rename-not-element-instance', this);
        }
        const version = element.root.document ? element.root.document.version : null;
        const renameOperation = new RenameOperation(Position._createBefore(element), element.name, newName, version);
        this.batch.addOperation(renameOperation);
        this.model.applyOperation(renameOperation);
    }
    /**
	 * Splits elements starting from the given position and going to the top of the model tree as long as given
	 * `limitElement` is reached. When `limitElement` is not defined then only the parent of the given position will be split.
	 *
	 * The element needs to have a parent. It cannot be a root element nor a document fragment.
	 * The `writer-split-element-no-parent` error will be thrown if you try to split an element with no parent.
	 *
	 * @param position Position of split.
	 * @param limitElement Stop splitting when this element will be reached.
	 * @returns Split result with properties:
	 * * `position` - Position between split elements.
	 * * `range` - Range that stars from the end of the first split element and ends at the beginning of the first copy element.
	 */ split(position, limitElement) {
        this._assertWriterUsedCorrectly();
        let splitElement = position.parent;
        if (!splitElement.parent) {
            /**
			 * Element with no parent can not be split.
			 *
			 * @error writer-split-element-no-parent
			 */ throw new CKEditorError('writer-split-element-no-parent', this);
        }
        // When limit element is not defined lets set splitElement parent as limit.
        if (!limitElement) {
            limitElement = splitElement.parent;
        }
        if (!position.parent.getAncestors({
            includeSelf: true
        }).includes(limitElement)) {
            /**
			 * Limit element is not a position ancestor.
			 *
			 * @error writer-split-invalid-limit-element
			 */ throw new CKEditorError('writer-split-invalid-limit-element', this);
        }
        // We need to cache elements that will be created as a result of the first split because
        // we need to create a range from the end of the first split element to the beginning of the
        // first copy element. This should be handled by LiveRange but it doesn't work on detached nodes.
        let firstSplitElement;
        let firstCopyElement;
        do {
            const version = splitElement.root.document ? splitElement.root.document.version : null;
            const howMany = splitElement.maxOffset - position.offset;
            const insertionPosition = SplitOperation.getInsertionPosition(position);
            const split = new SplitOperation(position, howMany, insertionPosition, null, version);
            this.batch.addOperation(split);
            this.model.applyOperation(split);
            // Cache result of the first split.
            if (!firstSplitElement && !firstCopyElement) {
                firstSplitElement = splitElement;
                firstCopyElement = position.parent.nextSibling;
            }
            position = this.createPositionAfter(position.parent);
            splitElement = position.parent;
        }while (splitElement !== limitElement)
        return {
            position,
            range: new Range(Position._createAt(firstSplitElement, 'end'), Position._createAt(firstCopyElement, 0))
        };
    }
    /**
	 * Wraps the given range with the given element or with a new element (if a string was passed).
	 *
	 * **Note:** range to wrap should be a "flat range" (see {@link module:engine/model/range~Range#isFlat `Range#isFlat`}).
	 * If not, an error will be thrown.
	 *
	 * @param range Range to wrap.
	 * @param elementOrString Element or name of element to wrap the range with.
	 */ wrap(range, elementOrString) {
        this._assertWriterUsedCorrectly();
        if (!range.isFlat) {
            /**
			 * Range to wrap is not flat.
			 *
			 * @error writer-wrap-range-not-flat
			 */ throw new CKEditorError('writer-wrap-range-not-flat', this);
        }
        const element = elementOrString instanceof Element ? elementOrString : new Element(elementOrString);
        if (element.childCount > 0) {
            /**
			 * Element to wrap with is not empty.
			 *
			 * @error writer-wrap-element-not-empty
			 */ throw new CKEditorError('writer-wrap-element-not-empty', this);
        }
        if (element.parent !== null) {
            /**
			 * Element to wrap with is already attached to a tree model.
			 *
			 * @error writer-wrap-element-attached
			 */ throw new CKEditorError('writer-wrap-element-attached', this);
        }
        this.insert(element, range.start);
        // Shift the range-to-wrap because we just inserted an element before that range.
        const shiftedRange = new Range(range.start.getShiftedBy(1), range.end.getShiftedBy(1));
        this.move(shiftedRange, Position._createAt(element, 0));
    }
    /**
	 * Unwraps children of the given element – all its children are moved before it and then the element is removed.
	 * Throws error if you try to unwrap an element which does not have a parent.
	 *
	 * @param element Element to unwrap.
	 */ unwrap(element) {
        this._assertWriterUsedCorrectly();
        if (element.parent === null) {
            /**
			 * Trying to unwrap an element which has no parent.
			 *
			 * @error writer-unwrap-element-no-parent
			 */ throw new CKEditorError('writer-unwrap-element-no-parent', this);
        }
        this.move(Range._createIn(element), this.createPositionAfter(element));
        this.remove(element);
    }
    /**
	 * Adds a {@link module:engine/model/markercollection~Marker marker}. Marker is a named range, which tracks
	 * changes in the document and updates its range automatically, when model tree changes.
	 *
	 * As the first parameter you can set marker name.
	 *
	 * The required `options.usingOperation` parameter lets you decide if the marker should be managed by operations or not. See
	 * {@link module:engine/model/markercollection~Marker marker class description} to learn about the difference between
	 * markers managed by operations and not-managed by operations.
	 *
	 * The `options.affectsData` parameter, which defaults to `false`, allows you to define if a marker affects the data. It should be
	 * `true` when the marker change changes the data returned by the
	 * {@link module:core/editor/editor~Editor#getData `editor.getData()`} method.
	 * When set to `true` it fires the {@link module:engine/model/document~Document#event:change:data `change:data`} event.
	 * When set to `false` it fires the {@link module:engine/model/document~Document#event:change `change`} event.
	 *
	 * Create marker directly base on marker's name:
	 *
	 * ```ts
	 * addMarker( markerName, { range, usingOperation: false } );
	 * ```
	 *
	 * Create marker using operation:
	 *
	 * ```ts
	 * addMarker( markerName, { range, usingOperation: true } );
	 * ```
	 *
	 * Create marker that affects the editor data:
	 *
	 * ```ts
	 * addMarker( markerName, { range, usingOperation: false, affectsData: true } );
	 * ```
	 *
	 * Note: For efficiency reasons, it's best to create and keep as little markers as possible.
	 *
	 * @see module:engine/model/markercollection~Marker
	 * @param name Name of a marker to create - must be unique.
	 * @param options.usingOperation Flag indicating that the marker should be added by MarkerOperation.
	 * See {@link module:engine/model/markercollection~Marker#managedUsingOperations}.
	 * @param options.range Marker range.
	 * @param options.affectsData Flag indicating that the marker changes the editor data.
	 * @returns Marker that was set.
	 */ addMarker(name, options) {
        this._assertWriterUsedCorrectly();
        if (!options || typeof options.usingOperation != 'boolean') {
            /**
			 * The `options.usingOperation` parameter is required when adding a new marker.
			 *
			 * @error writer-addmarker-no-usingoperation
			 */ throw new CKEditorError('writer-addmarker-no-usingoperation', this);
        }
        const usingOperation = options.usingOperation;
        const range = options.range;
        const affectsData = options.affectsData === undefined ? false : options.affectsData;
        if (this.model.markers.has(name)) {
            /**
			 * Marker with provided name already exists.
			 *
			 * @error writer-addmarker-marker-exists
			 */ throw new CKEditorError('writer-addmarker-marker-exists', this);
        }
        if (!range) {
            /**
			 * Range parameter is required when adding a new marker.
			 *
			 * @error writer-addmarker-no-range
			 */ throw new CKEditorError('writer-addmarker-no-range', this);
        }
        if (!usingOperation) {
            return this.model.markers._set(name, range, usingOperation, affectsData);
        }
        applyMarkerOperation(this, name, null, range, affectsData);
        return this.model.markers.get(name);
    }
    /**
	 * Adds, updates or refreshes a {@link module:engine/model/markercollection~Marker marker}. Marker is a named range, which tracks
	 * changes in the document and updates its range automatically, when model tree changes. Still, it is possible to change the
	 * marker's range directly using this method.
	 *
	 * As the first parameter you can set marker name or instance. If none of them is provided, new marker, with a unique
	 * name is created and returned.
	 *
	 * **Note**: If you want to change the {@link module:engine/view/element~Element view element} of the marker while its data in the model
	 * remains the same, use the dedicated {@link module:engine/controller/editingcontroller~EditingController#reconvertMarker} method.
	 *
	 * The `options.usingOperation` parameter lets you change if the marker should be managed by operations or not. See
	 * {@link module:engine/model/markercollection~Marker marker class description} to learn about the difference between
	 * markers managed by operations and not-managed by operations. It is possible to change this option for an existing marker.
	 *
	 * The `options.affectsData` parameter, which defaults to `false`, allows you to define if a marker affects the data. It should be
	 * `true` when the marker change changes the data returned by
	 * the {@link module:core/editor/editor~Editor#getData `editor.getData()`} method.
	 * When set to `true` it fires the {@link module:engine/model/document~Document#event:change:data `change:data`} event.
	 * When set to `false` it fires the {@link module:engine/model/document~Document#event:change `change`} event.
	 *
	 * Update marker directly base on marker's name:
	 *
	 * ```ts
	 * updateMarker( markerName, { range } );
	 * ```
	 *
	 * Update marker using operation:
	 *
	 * ```ts
	 * updateMarker( marker, { range, usingOperation: true } );
	 * updateMarker( markerName, { range, usingOperation: true } );
	 * ```
	 *
	 * Change marker's option (start using operations to manage it):
	 *
	 * ```ts
	 * updateMarker( marker, { usingOperation: true } );
	 * ```
	 *
	 * Change marker's option (inform the engine, that the marker does not affect the data anymore):
	 *
	 * ```ts
	 * updateMarker( markerName, { affectsData: false } );
	 * ```
	 *
	 * @see module:engine/model/markercollection~Marker
	 * @param markerOrName Name of a marker to update, or a marker instance.
	 * @param options If options object is not defined then marker will be refreshed by triggering
	 * downcast conversion for this marker with the same data.
	 * @param options.range Marker range to update.
	 * @param options.usingOperation Flag indicated whether the marker should be added by MarkerOperation.
	 * See {@link module:engine/model/markercollection~Marker#managedUsingOperations}.
	 * @param options.affectsData Flag indicating that the marker changes the editor data.
	 */ updateMarker(markerOrName, options) {
        this._assertWriterUsedCorrectly();
        const markerName = typeof markerOrName == 'string' ? markerOrName : markerOrName.name;
        const currentMarker = this.model.markers.get(markerName);
        if (!currentMarker) {
            /**
			 * Marker with provided name does not exist and will not be updated.
			 *
			 * @error writer-updatemarker-marker-not-exists
			 */ throw new CKEditorError('writer-updatemarker-marker-not-exists', this);
        }
        if (!options) {
            /**
			 * The usage of `writer.updateMarker()` only to reconvert (refresh) a
			 * {@link module:engine/model/markercollection~Marker model marker} was deprecated and may not work in the future.
			 * Please update your code to use
			 * {@link module:engine/controller/editingcontroller~EditingController#reconvertMarker `editor.editing.reconvertMarker()`}
			 * instead.
			 *
			 * @error writer-updatemarker-reconvert-using-editingcontroller
			 * @param markerName The name of the updated marker.
			 */ logWarning('writer-updatemarker-reconvert-using-editingcontroller', {
                markerName
            });
            this.model.markers._refresh(currentMarker);
            return;
        }
        const hasUsingOperationDefined = typeof options.usingOperation == 'boolean';
        const affectsDataDefined = typeof options.affectsData == 'boolean';
        // Use previously defined marker's affectsData if the property is not provided.
        const affectsData = affectsDataDefined ? options.affectsData : currentMarker.affectsData;
        if (!hasUsingOperationDefined && !options.range && !affectsDataDefined) {
            /**
			 * One of the options is required - provide range, usingOperations or affectsData.
			 *
			 * @error writer-updatemarker-wrong-options
			 */ throw new CKEditorError('writer-updatemarker-wrong-options', this);
        }
        const currentRange = currentMarker.getRange();
        const updatedRange = options.range ? options.range : currentRange;
        if (hasUsingOperationDefined && options.usingOperation !== currentMarker.managedUsingOperations) {
            // The marker type is changed so it's necessary to create proper operations.
            if (options.usingOperation) {
                // If marker changes to a managed one treat this as synchronizing existing marker.
                // Create `MarkerOperation` with `oldRange` set to `null`, so reverse operation will remove the marker.
                applyMarkerOperation(this, markerName, null, updatedRange, affectsData);
            } else {
                // If marker changes to a marker that do not use operations then we need to create additional operation
                // that removes that marker first.
                applyMarkerOperation(this, markerName, currentRange, null, affectsData);
                // Although not managed the marker itself should stay in model and its range should be preserver or changed to passed range.
                this.model.markers._set(markerName, updatedRange, undefined, affectsData);
            }
            return;
        }
        // Marker's type doesn't change so update it accordingly.
        if (currentMarker.managedUsingOperations) {
            applyMarkerOperation(this, markerName, currentRange, updatedRange, affectsData);
        } else {
            this.model.markers._set(markerName, updatedRange, undefined, affectsData);
        }
    }
    /**
	 * Removes given {@link module:engine/model/markercollection~Marker marker} or marker with given name.
	 * The marker is removed accordingly to how it has been created, so if the marker was created using operation,
	 * it will be destroyed using operation.
	 *
	 * @param markerOrName Marker or marker name to remove.
	 */ removeMarker(markerOrName) {
        this._assertWriterUsedCorrectly();
        const name = typeof markerOrName == 'string' ? markerOrName : markerOrName.name;
        if (!this.model.markers.has(name)) {
            /**
			 * Trying to remove marker which does not exist.
			 *
			 * @error writer-removemarker-no-marker
			 */ throw new CKEditorError('writer-removemarker-no-marker', this);
        }
        const marker = this.model.markers.get(name);
        if (!marker.managedUsingOperations) {
            this.model.markers._remove(name);
            return;
        }
        const oldRange = marker.getRange();
        applyMarkerOperation(this, name, oldRange, null, marker.affectsData);
    }
    /**
	 * Adds a new root to the document (or re-attaches a {@link #detachRoot detached root}).
	 *
	 * Throws an error, if trying to add a root that is already added and attached.
	 *
	 * @param rootName Name of the added root.
	 * @param elementName The element name. Defaults to `'$root'` which also has some basic schema defined
	 * (e.g. `$block` elements are allowed inside the `$root`). Make sure to define a proper schema if you use a different name.
	 * @returns The added root element.
	 */ addRoot(rootName, elementName = '$root') {
        this._assertWriterUsedCorrectly();
        const root = this.model.document.getRoot(rootName);
        if (root && root.isAttached()) {
            /**
			 * Root with provided name already exists and is attached.
			 *
			 * @error writer-addroot-root-exists
			 */ throw new CKEditorError('writer-addroot-root-exists', this);
        }
        const document = this.model.document;
        const operation = new RootOperation(rootName, elementName, true, document, document.version);
        this.batch.addOperation(operation);
        this.model.applyOperation(operation);
        return this.model.document.getRoot(rootName);
    }
    /**
	 * Detaches the root from the document.
	 *
	 * All content and markers are removed from the root upon detaching. New content and new markers cannot be added to the root, as long
	 * as it is detached.
	 *
	 * A root cannot be fully removed from the document, it can be only detached. A root is permanently removed only after you
	 * re-initialize the editor and do not specify the root in the initial data.
	 *
	 * A detached root can be re-attached using {@link #addRoot}.
	 *
	 * Throws an error if the root does not exist or the root is already detached.
	 *
	 * @param rootOrName Name of the detached root.
	 */ detachRoot(rootOrName) {
        this._assertWriterUsedCorrectly();
        const root = typeof rootOrName == 'string' ? this.model.document.getRoot(rootOrName) : rootOrName;
        if (!root || !root.isAttached()) {
            /**
			 * Root with provided name does not exist or is already detached.
			 *
			 * @error writer-detachroot-no-root
			 */ throw new CKEditorError('writer-detachroot-no-root', this);
        }
        // First, remove all markers from the root. It is better to do it before removing stuff for undo purposes.
        // However, looking through all the markers may not be the best performance wise. But there's no better solution for now.
        for (const marker of this.model.markers){
            if (marker.getRange().root === root) {
                this.removeMarker(marker);
            }
        }
        // Remove all attributes from the root.
        for (const key of root.getAttributeKeys()){
            this.removeAttribute(key, root);
        }
        // Remove all contents of the root.
        this.remove(this.createRangeIn(root));
        // Finally, detach the root.
        const document = this.model.document;
        const operation = new RootOperation(root.rootName, root.name, false, document, document.version);
        this.batch.addOperation(operation);
        this.model.applyOperation(operation);
    }
    setSelection(...args) {
        this._assertWriterUsedCorrectly();
        this.model.document.selection._setTo(...args);
    }
    /**
	 * Moves {@link module:engine/model/documentselection~DocumentSelection#focus} to the specified location.
	 *
	 * The location can be specified in the same form as
	 * {@link #createPositionAt `writer.createPositionAt()`} parameters.
	 *
	 * @param itemOrPosition
	 * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/model/item~Item model item}.
	 */ setSelectionFocus(itemOrPosition, offset) {
        this._assertWriterUsedCorrectly();
        this.model.document.selection._setFocus(itemOrPosition, offset);
    }
    setSelectionAttribute(keyOrObjectOrIterable, value) {
        this._assertWriterUsedCorrectly();
        if (typeof keyOrObjectOrIterable === 'string') {
            this._setSelectionAttribute(keyOrObjectOrIterable, value);
        } else {
            for (const [key, value] of toMap(keyOrObjectOrIterable)){
                this._setSelectionAttribute(key, value);
            }
        }
    }
    /**
	 * Removes attribute(s) with given key(s) from the selection.
	 *
	 * Remove one attribute:
	 *
	 * ```ts
	 * writer.removeSelectionAttribute( 'italic' );
	 * ```
	 *
	 * Remove multiple attributes:
	 *
	 * ```ts
	 * writer.removeSelectionAttribute( [ 'italic', 'bold' ] );
	 * ```
	 *
	 * @param keyOrIterableOfKeys Key of the attribute to remove or an iterable of attribute keys to remove.
	 */ removeSelectionAttribute(keyOrIterableOfKeys) {
        this._assertWriterUsedCorrectly();
        if (typeof keyOrIterableOfKeys === 'string') {
            this._removeSelectionAttribute(keyOrIterableOfKeys);
        } else {
            for (const key of keyOrIterableOfKeys){
                this._removeSelectionAttribute(key);
            }
        }
    }
    /**
	 * Temporarily changes the {@link module:engine/model/documentselection~DocumentSelection#isGravityOverridden gravity}
	 * of the selection from left to right.
	 *
	 * The gravity defines from which direction the selection inherits its attributes. If it's the default left gravity,
	 * then the selection (after being moved by the user) inherits attributes from its left-hand side.
	 * This method allows to temporarily override this behavior by forcing the gravity to the right.
	 *
	 * For the following model fragment:
	 *
	 * ```xml
	 * <$text bold="true" linkHref="url">bar[]</$text><$text bold="true">biz</$text>
	 * ```
	 *
	 * * Default gravity: selection will have the `bold` and `linkHref` attributes.
	 * * Overridden gravity: selection will have `bold` attribute.
	 *
	 * **Note**: It returns an unique identifier which is required to restore the gravity. It guarantees the symmetry
	 * of the process.
	 *
	 * @returns The unique id which allows restoring the gravity.
	 */ overrideSelectionGravity() {
        return this.model.document.selection._overrideGravity();
    }
    /**
	 * Restores {@link ~Writer#overrideSelectionGravity} gravity to default.
	 *
	 * Restoring the gravity is only possible using the unique identifier returned by
	 * {@link ~Writer#overrideSelectionGravity}. Note that the gravity remains overridden as long as won't be restored
	 * the same number of times it was overridden.
	 *
	 * @param uid The unique id returned by {@link ~Writer#overrideSelectionGravity}.
	 */ restoreSelectionGravity(uid) {
        this.model.document.selection._restoreGravity(uid);
    }
    /**
	 * @param key Key of the attribute to remove.
	 * @param value Attribute value.
	 */ _setSelectionAttribute(key, value) {
        const selection = this.model.document.selection;
        // Store attribute in parent element if the selection is collapsed in an empty node.
        if (selection.isCollapsed && selection.anchor.parent.isEmpty) {
            const storeKey = DocumentSelection._getStoreAttributeKey(key);
            this.setAttribute(storeKey, value, selection.anchor.parent);
        }
        selection._setAttribute(key, value);
    }
    /**
	 * @param key Key of the attribute to remove.
	 */ _removeSelectionAttribute(key) {
        const selection = this.model.document.selection;
        // Remove stored attribute from parent element if the selection is collapsed in an empty node.
        if (selection.isCollapsed && selection.anchor.parent.isEmpty) {
            const storeKey = DocumentSelection._getStoreAttributeKey(key);
            this.removeAttribute(storeKey, selection.anchor.parent);
        }
        selection._removeAttribute(key);
    }
    /**
	 * Throws `writer-detached-writer-tries-to-modify-model` error when the writer is used outside of the `change()` block.
	 */ _assertWriterUsedCorrectly() {
        /**
		 * Trying to use a writer outside a {@link module:engine/model/model~Model#change `change()`} or
		 * {@link module:engine/model/model~Model#enqueueChange `enqueueChange()`} blocks.
		 *
		 * The writer can only be used inside these blocks which ensures that the model
		 * can only be changed during such "sessions".
		 *
		 * @error writer-incorrect-use
		 */ if (this.model._currentWriter !== this) {
            throw new CKEditorError('writer-incorrect-use', this);
        }
    }
    /**
	 * For given action `type` and `positionOrRange` where the action happens, this function finds all affected markers
	 * and applies a marker operation with the new marker range equal to the current range. Thanks to this, the marker range
	 * can be later correctly processed during undo.
	 *
	 * @param type Writer action type.
	 * @param positionOrRange Position or range where the writer action happens.
	 */ _addOperationForAffectedMarkers(type, positionOrRange) {
        for (const marker of this.model.markers){
            if (!marker.managedUsingOperations) {
                continue;
            }
            const markerRange = marker.getRange();
            let isAffected = false;
            if (type === 'move') {
                const range = positionOrRange;
                isAffected = range.containsPosition(markerRange.start) || range.start.isEqual(markerRange.start) || range.containsPosition(markerRange.end) || range.end.isEqual(markerRange.end);
            } else {
                // if type === 'merge'.
                const position = positionOrRange;
                const elementBefore = position.nodeBefore;
                const elementAfter = position.nodeAfter;
                //               Start:  <p>Foo[</p><p>Bar]</p>
                //         After merge:  <p>Foo[Bar]</p>
                // After undoing split:  <p>Foo</p><p>[Bar]</p>     <-- incorrect, needs remembering for undo.
                //
                const affectedInLeftElement = markerRange.start.parent == elementBefore && markerRange.start.isAtEnd;
                //               Start:  <p>[Foo</p><p>]Bar</p>
                //         After merge:  <p>[Foo]Bar</p>
                // After undoing split:  <p>[Foo]</p><p>Bar</p>     <-- incorrect, needs remembering for undo.
                //
                const affectedInRightElement = markerRange.end.parent == elementAfter && markerRange.end.offset == 0;
                //               Start:  <p>[Foo</p>]<p>Bar</p>
                //         After merge:  <p>[Foo]Bar</p>
                // After undoing split:  <p>[Foo]</p><p>Bar</p>     <-- incorrect, needs remembering for undo.
                //
                const affectedAfterLeftElement = markerRange.end.nodeAfter == elementAfter;
                //               Start:  <p>Foo</p>[<p>Bar]</p>
                //         After merge:  <p>Foo[Bar]</p>
                // After undoing split:  <p>Foo</p><p>[Bar]</p>     <-- incorrect, needs remembering for undo.
                //
                const affectedBeforeRightElement = markerRange.start.nodeAfter == elementAfter;
                isAffected = affectedInLeftElement || affectedInRightElement || affectedAfterLeftElement || affectedBeforeRightElement;
            }
            if (isAffected) {
                this.updateMarker(marker.name, {
                    range: markerRange
                });
            }
        }
    }
}
/**
 * Sets given attribute to each node in given range. When attribute value is null then attribute will be removed.
 *
 * Because attribute operation needs to have the same attribute value on the whole range, this function splits
 * the range into smaller parts.
 *
 * Given `range` must be flat.
 */ function setAttributeOnRange(writer, key, value, range) {
    const model = writer.model;
    const doc = model.document;
    // Position of the last split, the beginning of the new range.
    let lastSplitPosition = range.start;
    // Currently position in the scanning range. Because we need value after the position, it is not a current
    // position of the iterator but the previous one (we need to iterate one more time to get the value after).
    let position;
    // Value before the currently position.
    let valueBefore;
    // Value after the currently position.
    let valueAfter;
    for (const val of range.getWalker({
        shallow: true
    })){
        valueAfter = val.item.getAttribute(key);
        // At the first run of the iterator the position in undefined. We also do not have a valueBefore, but
        // because valueAfter may be null, valueBefore may be equal valueAfter ( undefined == null ).
        if (position && valueBefore != valueAfter) {
            // if valueBefore == value there is nothing to change, so we add operation only if these values are different.
            if (valueBefore != value) {
                addOperation();
            }
            lastSplitPosition = position;
        }
        position = val.nextPosition;
        valueBefore = valueAfter;
    }
    // Because position in the loop is not the iterator position (see let position comment), the last position in
    // the while loop will be last but one position in the range. We need to check the last position manually.
    if (position instanceof Position && position != lastSplitPosition && valueBefore != value) {
        addOperation();
    }
    function addOperation() {
        const range = new Range(lastSplitPosition, position);
        const version = range.root.document ? doc.version : null;
        const operation = new AttributeOperation(range, key, valueBefore, value, version);
        writer.batch.addOperation(operation);
        model.applyOperation(operation);
    }
}
/**
 * Sets given attribute to the given node. When attribute value is null then attribute will be removed.
 */ function setAttributeOnItem(writer, key, value, item) {
    const model = writer.model;
    const doc = model.document;
    const previousValue = item.getAttribute(key);
    let range, operation;
    if (previousValue != value) {
        const isRootChanged = item.root === item;
        if (isRootChanged) {
            // If we change attributes of root element, we have to use `RootAttributeOperation`.
            const version = item.document ? doc.version : null;
            operation = new RootAttributeOperation(item, key, previousValue, value, version);
        } else {
            range = new Range(Position._createBefore(item), writer.createPositionAfter(item));
            const version = range.root.document ? doc.version : null;
            operation = new AttributeOperation(range, key, previousValue, value, version);
        }
        writer.batch.addOperation(operation);
        model.applyOperation(operation);
    }
}
/**
 * Creates and applies marker operation to {@link module:engine/model/operation/operation~Operation operation}.
 */ function applyMarkerOperation(writer, name, oldRange, newRange, affectsData) {
    const model = writer.model;
    const doc = model.document;
    const operation = new MarkerOperation(name, oldRange, newRange, model.markers, !!affectsData, doc.version);
    writer.batch.addOperation(operation);
    model.applyOperation(operation);
}
/**
 * Creates `MoveOperation` or `DetachOperation` that removes `howMany` nodes starting from `position`.
 * The operation will be applied on given model instance and added to given operation instance.
 *
 * @param position Position from which nodes are removed.
 * @param howMany Number of nodes to remove.
 * @param batch Batch to which the operation will be added.
 * @param model Model instance on which operation will be applied.
 */ function applyRemoveOperation(position, howMany, batch, model) {
    let operation;
    if (position.root.document) {
        const doc = model.document;
        const graveyardPosition = new Position(doc.graveyard, [
            0
        ]);
        operation = new MoveOperation(position, howMany, graveyardPosition, doc.version);
    } else {
        operation = new DetachOperation(position, howMany);
    }
    batch.addOperation(operation);
    model.applyOperation(operation);
}
/**
 * Returns `true` if both root elements are the same element or both are documents root elements.
 *
 * Elements in the same tree can be moved (for instance you can move element form one documents root to another, or
 * within the same document fragment), but when element supposed to be moved from document fragment to the document, or
 * to another document it should be removed and inserted to avoid problems with OT. This is because features like undo or
 * collaboration may track changes on the document but ignore changes on detached fragments and should not get
 * unexpected `move` operation.
 */ function isSameTree(rootA, rootB) {
    // If it is the same root this is the same tree.
    if (rootA === rootB) {
        return true;
    }
    // If both roots are documents root it is operation within the document what we still treat as the same tree.
    if (rootA instanceof RootElement && rootB instanceof RootElement) {
        return true;
    }
    return false;
}

/**
 * Deletes content of the selection and merge siblings. The resulting selection is always collapsed.
 *
 * **Note:** Use {@link module:engine/model/model~Model#deleteContent} instead of this function.
 * This function is only exposed to be reusable in algorithms
 * which change the {@link module:engine/model/model~Model#deleteContent}
 * method's behavior.
 *
 * @param model The model in context of which the insertion should be performed.
 * @param selection Selection of which the content should be deleted.
 * @param options.leaveUnmerged Whether to merge elements after removing the content of the selection.
 *
 * For example `<heading>x[x</heading><paragraph>y]y</paragraph>` will become:
 *
 * * `<heading>x^y</heading>` with the option disabled (`leaveUnmerged == false`)
 * * `<heading>x^</heading><paragraph>y</paragraph>` with enabled (`leaveUnmerged == true`).
 *
 * Note: {@link module:engine/model/schema~Schema#isObject object} and {@link module:engine/model/schema~Schema#isLimit limit}
 * elements will not be merged.
 *
 * @param options.doNotResetEntireContent Whether to skip replacing the entire content with a
 * paragraph when the entire content was selected.
 *
 * For example `<heading>[x</heading><paragraph>y]</paragraph>` will become:
 *
 * * `<paragraph>^</paragraph>` with the option disabled (`doNotResetEntireContent == false`)
 * * `<heading>^</heading>` with enabled (`doNotResetEntireContent == true`).
 *
 * @param options.doNotAutoparagraph Whether to create a paragraph if after content deletion selection is moved
 * to a place where text cannot be inserted.
 *
 * For example `<paragraph>x</paragraph>[<imageBlock src="foo.jpg"></imageBlock>]` will become:
 *
 * * `<paragraph>x</paragraph><paragraph>[]</paragraph>` with the option disabled (`doNotAutoparagraph == false`)
 * * `<paragraph>x</paragraph>[]` with the option enabled (`doNotAutoparagraph == true`).
 *
 * If you use this option you need to make sure to handle invalid selections yourself or leave
 * them to the selection post-fixer (may not always work).
 *
 * **Note:** If there is no valid position for the selection, the paragraph will always be created:
 *
 * `[<imageBlock src="foo.jpg"></imageBlock>]` -> `<paragraph>[]</paragraph>`.
 */ function deleteContent(model, selection, options = {}) {
    if (selection.isCollapsed) {
        return;
    }
    const selRange = selection.getFirstRange();
    // If the selection is already removed, don't do anything.
    if (selRange.root.rootName == '$graveyard') {
        return;
    }
    const schema = model.schema;
    model.change((writer)=>{
        // 1. Replace the entire content with paragraph.
        // See: https://github.com/ckeditor/ckeditor5-engine/issues/1012#issuecomment-315017594.
        if (!options.doNotResetEntireContent && shouldEntireContentBeReplacedWithParagraph(schema, selection)) {
            replaceEntireContentWithParagraph(writer, selection);
            return;
        }
        // Collect attributes to copy in case of autoparagraphing.
        const attributesForAutoparagraph = {};
        if (!options.doNotAutoparagraph) {
            const selectedElement = selection.getSelectedElement();
            if (selectedElement) {
                Object.assign(attributesForAutoparagraph, schema.getAttributesWithProperty(selectedElement, 'copyOnReplace', true));
            }
        }
        // Get the live positions for the range adjusted to span only blocks selected from the user perspective.
        const [startPosition, endPosition] = getLivePositionsForSelectedBlocks(selRange);
        // 2. Remove the content if there is any.
        if (!startPosition.isTouching(endPosition)) {
            writer.remove(writer.createRange(startPosition, endPosition));
        }
        // 3. Merge elements in the right branch to the elements in the left branch.
        // The only reasonable (in terms of data and selection correctness) case in which we need to do that is:
        //
        // <heading type=1>Fo[</heading><paragraph>]ar</paragraph> => <heading type=1>Fo^ar</heading>
        //
        // However, the algorithm supports also merging deeper structures (up to the depth of the shallower branch),
        // as it's hard to imagine what should actually be the default behavior. Usually, specific features will
        // want to override that behavior anyway.
        if (!options.leaveUnmerged) {
            mergeBranches(writer, startPosition, endPosition);
            // TMP this will be replaced with a postfixer.
            // We need to check and strip disallowed attributes in all nested nodes because after merge
            // some attributes could end up in a path where are disallowed.
            //
            // e.g. bold is disallowed for <H1>
            // <h1>Fo{o</h1><p>b}a<b>r</b><p> -> <h1>Fo{}a<b>r</b><h1> -> <h1>Fo{}ar<h1>.
            schema.removeDisallowedAttributes(startPosition.parent.getChildren(), writer);
        }
        collapseSelectionAt(writer, selection, startPosition);
        // 4. Add a paragraph to set selection in it.
        // Check if a text is allowed in the new container. If not, try to create a new paragraph (if it's allowed here).
        // If autoparagraphing is off, we assume that you know what you do so we leave the selection wherever it was.
        if (!options.doNotAutoparagraph && shouldAutoparagraph(schema, startPosition)) {
            insertParagraph(writer, startPosition, selection, attributesForAutoparagraph);
        }
        startPosition.detach();
        endPosition.detach();
    });
}
/**
 * Returns the live positions for the range adjusted to span only blocks selected from the user perspective. Example:
 *
 * ```
 * <heading1>[foo</heading1>
 * <paragraph>bar</paragraph>
 * <heading1>]abc</heading1>  <-- this block is not considered as selected
 * ```
 *
 * This is the same behavior as in Selection#getSelectedBlocks() "special case".
 */ function getLivePositionsForSelectedBlocks(range) {
    const model = range.root.document.model;
    const startPosition = range.start;
    let endPosition = range.end;
    // If the end of selection is at the start position of last block in the selection, then
    // shrink it to not include that trailing block. Note that this should happen only for not empty selection.
    if (model.hasContent(range, {
        ignoreMarkers: true
    })) {
        const endBlock = getParentBlock(endPosition);
        if (endBlock && endPosition.isTouching(model.createPositionAt(endBlock, 0))) {
            // Create forward selection as a probe to find a valid position after excluding last block from the range.
            const selection = model.createSelection(range);
            // Modify the forward selection in backward direction to shrink it and remove first position of following block from it.
            // This is how modifySelection works and here we are making use of it.
            model.modifySelection(selection, {
                direction: 'backward'
            });
            const newEndPosition = selection.getLastPosition();
            // For such a model and selection:
            //     <paragraph>A[</paragraph><imageBlock></imageBlock><paragraph>]B</paragraph>
            //
            // After modifySelection(), we would end up with this:
            //     <paragraph>A[</paragraph>]<imageBlock></imageBlock><paragraph>B</paragraph>
            //
            // So we need to check if there is no content in the skipped range (because we want to include the <imageBlock>).
            const skippedRange = model.createRange(newEndPosition, endPosition);
            if (!model.hasContent(skippedRange, {
                ignoreMarkers: true
            })) {
                endPosition = newEndPosition;
            }
        }
    }
    return [
        LivePosition.fromPosition(startPosition, 'toPrevious'),
        LivePosition.fromPosition(endPosition, 'toNext')
    ];
}
/**
 * Finds the lowest element in position's ancestors which is a block.
 * Returns null if a limit element is encountered before reaching a block element.
 */ function getParentBlock(position) {
    const element = position.parent;
    const schema = element.root.document.model.schema;
    const ancestors = element.getAncestors({
        parentFirst: true,
        includeSelf: true
    });
    for (const element of ancestors){
        if (schema.isLimit(element)) {
            return null;
        }
        if (schema.isBlock(element)) {
            return element;
        }
    }
}
/**
 * This function is a result of reaching the Ballmer's peak for just the right amount of time.
 * Even I had troubles documenting it after a while and after reading it again I couldn't believe that it really works.
 */ function mergeBranches(writer, startPosition, endPosition) {
    const model = writer.model;
    // Verify if there is a need and possibility to merge.
    if (!checkShouldMerge(writer.model.schema, startPosition, endPosition)) {
        return;
    }
    // If the start element on the common ancestor level is empty, and the end element on the same level is not empty
    // then merge those to the right element so that it's properties are preserved (name, attributes).
    // Because of OT merging is used instead of removing elements.
    //
    // Merge left:
    //     <heading1>foo[</heading1>    ->  <heading1>foo[]bar</heading1>
    //     <paragraph>]bar</paragraph>  ->               --^
    //
    // Merge right:
    //     <heading1>[</heading1>       ->
    //     <paragraph>]bar</paragraph>  ->  <paragraph>[]bar</paragraph>
    //
    // Merge left:
    //     <blockQuote>                     ->  <blockQuote>
    //         <heading1>foo[</heading1>    ->      <heading1>foo[]bar</heading1>
    //         <paragraph>]bar</paragraph>  ->                   --^
    //     </blockQuote>                    ->  </blockQuote>
    //
    // Merge right:
    //     <blockQuote>                     ->  <blockQuote>
    //         <heading1>[</heading1>       ->
    //         <paragraph>]bar</paragraph>  ->      <paragraph>[]bar</paragraph>
    //     </blockQuote>                    ->  </blockQuote>
    // Merging should not go deeper than common ancestor.
    const [startAncestor, endAncestor] = getAncestorsJustBelowCommonAncestor(startPosition, endPosition);
    // Branches can't be merged if one of the positions is directly inside a common ancestor.
    //
    // Example:
    //     <blockQuote>
    //         <paragraph>[foo</paragraph>]
    //         <table> ... </table>
    //     <blockQuote>
    //
    if (!startAncestor || !endAncestor) {
        return;
    }
    if (!model.hasContent(startAncestor, {
        ignoreMarkers: true
    }) && model.hasContent(endAncestor, {
        ignoreMarkers: true
    })) {
        mergeBranchesRight(writer, startPosition, endPosition, startAncestor.parent);
    } else {
        mergeBranchesLeft(writer, startPosition, endPosition, startAncestor.parent);
    }
}
/**
 * Merging blocks to the left (properties of the left block are preserved).
 * Simple example:
 *
 * ```
 * <heading1>foo[</heading1>    ->  <heading1>foo[bar</heading1>]
 * <paragraph>]bar</paragraph>  ->              --^
 * ```
 *
 * Nested example:
 *
 * ```
 * <blockQuote>                     ->  <blockQuote>
 *     <heading1>foo[</heading1>    ->      <heading1>foo[bar</heading1>
 * </blockQuote>                    ->  </blockQuote>]    ^
 * <blockBlock>                     ->                    |
 *     <paragraph>]bar</paragraph>  ->                 ---
 * </blockBlock>                    ->
 * ```
 */ function mergeBranchesLeft(writer, startPosition, endPosition, commonAncestor) {
    const startElement = startPosition.parent;
    const endElement = endPosition.parent;
    // Merging reached the common ancestor element, stop here.
    if (startElement == commonAncestor || endElement == commonAncestor) {
        return;
    }
    // Remember next positions to merge in next recursive step (also used as modification points pointers).
    startPosition = writer.createPositionAfter(startElement);
    endPosition = writer.createPositionBefore(endElement);
    // Move endElement just after startElement if they aren't siblings.
    if (!endPosition.isEqual(startPosition)) {
        //
        //     <blockQuote>                     ->  <blockQuote>
        //         <heading1>foo[</heading1>    ->      <heading1>foo</heading1>[<paragraph>bar</paragraph>
        //     </blockQuote>                    ->  </blockQuote>                ^
        //     <blockBlock>                     ->  <blockBlock>                 |
        //         <paragraph>]bar</paragraph>  ->      ]                     ---
        //     </blockBlock>                    ->  </blockBlock>
        //
        writer.insert(endElement, startPosition);
    }
    // Merge two siblings (nodes on sides of startPosition):
    //
    //     <blockQuote>                                             ->  <blockQuote>
    //         <heading1>foo</heading1>[<paragraph>bar</paragraph>  ->      <heading1>foo[bar</heading1>
    //     </blockQuote>                                            ->  </blockQuote>
    //     <blockBlock>                                             ->  <blockBlock>
    //         ]                                                    ->      ]
    //     </blockBlock>                                            ->  </blockBlock>
    //
    // Or in simple case (without moving elements in above if):
    //     <heading1>foo</heading1>[<paragraph>bar</paragraph>]  ->  <heading1>foo[bar</heading1>]
    //
    writer.merge(startPosition);
    // Remove empty end ancestors:
    //
    //     <blockQuote>                      ->  <blockQuote>
    //         <heading1>foo[bar</heading1>  ->      <heading1>foo[bar</heading1>
    //     </blockQuote>                     ->  </blockQuote>
    //     <blockBlock>                      ->
    //         ]                             ->  ]
    //     </blockBlock>                     ->
    //
    while(endPosition.parent.isEmpty){
        const parentToRemove = endPosition.parent;
        endPosition = writer.createPositionBefore(parentToRemove);
        writer.remove(parentToRemove);
    }
    // Verify if there is a need and possibility to merge next level.
    if (!checkShouldMerge(writer.model.schema, startPosition, endPosition)) {
        return;
    }
    // Continue merging next level (blockQuote with blockBlock in the examples above if it would not be empty and got removed).
    mergeBranchesLeft(writer, startPosition, endPosition, commonAncestor);
}
/**
 * Merging blocks to the right (properties of the right block are preserved).
 * Simple example:
 *
 * ```
 * <heading1>foo[</heading1>    ->            --v
 * <paragraph>]bar</paragraph>  ->  [<paragraph>foo]bar</paragraph>
 * ```
 *
 * Nested example:
 *
 * ```
 * <blockQuote>                     ->
 *     <heading1>foo[</heading1>    ->              ---
 * </blockQuote>                    ->                 |
 * <blockBlock>                     ->  [<blockBlock>  v
 *     <paragraph>]bar</paragraph>  ->      <paragraph>foo]bar</paragraph>
 * </blockBlock>                    ->  </blockBlock>
 * ```
 */ function mergeBranchesRight(writer, startPosition, endPosition, commonAncestor) {
    const startElement = startPosition.parent;
    const endElement = endPosition.parent;
    // Merging reached the common ancestor element, stop here.
    if (startElement == commonAncestor || endElement == commonAncestor) {
        return;
    }
    // Remember next positions to merge in next recursive step (also used as modification points pointers).
    startPosition = writer.createPositionAfter(startElement);
    endPosition = writer.createPositionBefore(endElement);
    // Move startElement just before endElement if they aren't siblings.
    if (!endPosition.isEqual(startPosition)) {
        //
        //     <blockQuote>                     ->  <blockQuote>
        //         <heading1>foo[</heading1>    ->      [                   ---
        //     </blockQuote>                    ->  </blockQuote>              |
        //     <blockBlock>                     ->  <blockBlock>               v
        //         <paragraph>]bar</paragraph>  ->      <heading1>foo</heading1>]<paragraph>bar</paragraph>
        //     </blockBlock>                    ->  </blockBlock>
        //
        writer.insert(startElement, endPosition);
    }
    // Remove empty end ancestors:
    //
    //     <blockQuote>                                             ->
    //         [                                                    ->  [
    //     </blockQuote>                                            ->
    //     <blockBlock>                                             ->  <blockBlock>
    //         <heading1>foo</heading1>]<paragraph>bar</paragraph>  ->      <heading1>foo</heading1>]<paragraph>bar</paragraph>
    //     </blockBlock>                                            ->  </blockBlock>
    //
    while(startPosition.parent.isEmpty){
        const parentToRemove = startPosition.parent;
        startPosition = writer.createPositionBefore(parentToRemove);
        writer.remove(parentToRemove);
    }
    // Update endPosition after inserting and removing elements.
    endPosition = writer.createPositionBefore(endElement);
    // Merge right two siblings (nodes on sides of endPosition):
    //                                                              ->
    //     [                                                        ->  [
    //                                                              ->
    //     <blockBlock>                                             ->  <blockBlock>
    //         <heading1>foo</heading1>]<paragraph>bar</paragraph>  ->      <paragraph>foo]bar</paragraph>
    //     </blockBlock>                                            ->  </blockBlock>
    //
    // Or in simple case (without moving elements in above if):
    //     [<heading1>foo</heading1>]<paragraph>bar</paragraph>  ->  [<heading1>foo]bar</heading1>
    //
    mergeRight(writer, endPosition);
    // Verify if there is a need and possibility to merge next level.
    if (!checkShouldMerge(writer.model.schema, startPosition, endPosition)) {
        return;
    }
    // Continue merging next level (blockQuote with blockBlock in the examples above if it would not be empty and got removed).
    mergeBranchesRight(writer, startPosition, endPosition, commonAncestor);
}
/**
 * There is no right merge operation so we need to simulate it.
 */ function mergeRight(writer, position) {
    const startElement = position.nodeBefore;
    const endElement = position.nodeAfter;
    if (startElement.name != endElement.name) {
        writer.rename(startElement, endElement.name);
    }
    writer.clearAttributes(startElement);
    writer.setAttributes(Object.fromEntries(endElement.getAttributes()), startElement);
    writer.merge(position);
}
/**
 * Verifies if merging is needed and possible. It's not needed if both positions are in the same element
 * and it's not possible if some element is a limit or the range crosses a limit element.
 */ function checkShouldMerge(schema, startPosition, endPosition) {
    const startElement = startPosition.parent;
    const endElement = endPosition.parent;
    // If both positions ended up in the same parent, then there's nothing more to merge:
    // <$root><p>x[</p><p>]y</p></$root> => <$root><p>xy</p>[]</$root>
    if (startElement == endElement) {
        return false;
    }
    // If one of the positions is a limit element, then there's nothing to merge because we don't want to cross the limit boundaries.
    if (schema.isLimit(startElement) || schema.isLimit(endElement)) {
        return false;
    }
    // Check if operations we'll need to do won't need to cross object or limit boundaries.
    // E.g., we can't merge endElement into startElement in this case:
    // <limit><startElement>x[</startElement></limit><endElement>]</endElement>
    return isCrossingLimitElement(startPosition, endPosition, schema);
}
/**
 * Returns the elements that are the ancestors of the provided positions that are direct children of the common ancestor.
 */ function getAncestorsJustBelowCommonAncestor(positionA, positionB) {
    const ancestorsA = positionA.getAncestors();
    const ancestorsB = positionB.getAncestors();
    let i = 0;
    while(ancestorsA[i] && ancestorsA[i] == ancestorsB[i]){
        i++;
    }
    return [
        ancestorsA[i],
        ancestorsB[i]
    ];
}
function shouldAutoparagraph(schema, position) {
    const isTextAllowed = schema.checkChild(position, '$text');
    const isParagraphAllowed = schema.checkChild(position, 'paragraph');
    return !isTextAllowed && isParagraphAllowed;
}
/**
 * Check if parents of two positions can be merged by checking if there are no limit/object
 * boundaries between those two positions.
 *
 * E.g. in <bQ><p>x[]</p></bQ><widget><caption>{}</caption></widget>
 * we'll check <p>, <bQ>, <widget> and <caption>.
 * Usually, widget and caption are marked as objects/limits in the schema, so in this case merging will be blocked.
 */ function isCrossingLimitElement(leftPos, rightPos, schema) {
    const rangeToCheck = new Range(leftPos, rightPos);
    for (const value of rangeToCheck.getWalker()){
        if (schema.isLimit(value.item)) {
            return false;
        }
    }
    return true;
}
function insertParagraph(writer, position, selection, attributes = {}) {
    const paragraph = writer.createElement('paragraph');
    writer.model.schema.setAllowedAttributes(paragraph, attributes, writer);
    writer.insert(paragraph, position);
    collapseSelectionAt(writer, selection, writer.createPositionAt(paragraph, 0));
}
function replaceEntireContentWithParagraph(writer, selection) {
    const limitElement = writer.model.schema.getLimitElement(selection);
    writer.remove(writer.createRangeIn(limitElement));
    insertParagraph(writer, writer.createPositionAt(limitElement, 0), selection);
}
/**
 * We want to replace the entire content with a paragraph when:
 * * the entire content is selected,
 * * selection contains at least two elements,
 * * whether the paragraph is allowed in schema in the common ancestor.
 */ function shouldEntireContentBeReplacedWithParagraph(schema, selection) {
    const limitElement = schema.getLimitElement(selection);
    if (!selection.containsEntireContent(limitElement)) {
        return false;
    }
    const range = selection.getFirstRange();
    if (range.start.parent == range.end.parent) {
        return false;
    }
    return schema.checkChild(limitElement, 'paragraph');
}
/**
 * Helper function that sets the selection. Depending whether given `selection` is a document selection or not,
 * uses a different method to set it.
 */ function collapseSelectionAt(writer, selection, positionOrRange) {
    if (selection instanceof DocumentSelection) {
        writer.setSelection(positionOrRange);
    } else {
        selection.setTo(positionOrRange);
    }
}

/**
 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */ /**
 * @module engine/model/utils/getselectedcontent
 */ /**
 * Gets a clone of the selected content.
 *
 * For example, for the following selection:
 *
 * ```html
 * <p>x</p><quote><p>y</p><h>fir[st</h></quote><p>se]cond</p><p>z</p>
 * ```
 *
 * It will return a document fragment with such a content:
 *
 * ```html
 * <quote><h>st</h></quote><p>se</p>
 * ```
 *
 * @param model The model in context of which the selection modification should be performed.
 * @param selection The selection of which content will be returned.
 */ function getSelectedContent(model, selection) {
    return model.change((writer)=>{
        const frag = writer.createDocumentFragment();
        const range = selection.getFirstRange();
        if (!range || range.isCollapsed) {
            return frag;
        }
        const root = range.start.root;
        const commonPath = range.start.getCommonPath(range.end);
        const commonParent = root.getNodeByPath(commonPath);
        // ## 1st step
        //
        // First, we'll clone a fragment represented by a minimal flat range
        // containing the original range to be cloned.
        // E.g. let's consider such a range:
        //
        // <p>x</p><quote><p>y</p><h>fir[st</h></quote><p>se]cond</p><p>z</p>
        //
        // A minimal flat range containing this one is:
        //
        // <p>x</p>[<quote><p>y</p><h>first</h></quote><p>second</p>]<p>z</p>
        //
        // We can easily clone this structure, preserving e.g. the <quote> element.
        let flatSubtreeRange;
        if (range.start.parent == range.end.parent) {
            // The original range is flat, so take it.
            flatSubtreeRange = range;
        } else {
            flatSubtreeRange = writer.createRange(writer.createPositionAt(commonParent, range.start.path[commonPath.length]), writer.createPositionAt(commonParent, range.end.path[commonPath.length] + 1));
        }
        const howMany = flatSubtreeRange.end.offset - flatSubtreeRange.start.offset;
        // Clone the whole contents.
        for (const item of flatSubtreeRange.getItems({
            shallow: true
        })){
            if (item.is('$textProxy')) {
                writer.appendText(item.data, item.getAttributes(), frag);
            } else {
                writer.append(writer.cloneElement(item, true), frag);
            }
        }
        // ## 2nd step
        //
        // If the original range wasn't flat, then we need to remove the excess nodes from the both ends of the cloned fragment.
        //
        // For example, for the range shown in the 1st step comment, we need to remove these pieces:
        //
        // <quote>[<p>y</p>]<h>[fir]st</h></quote><p>se[cond]</p>
        //
        // So this will be the final copied content:
        //
        // <quote><h>st</h></quote><p>se</p>
        //
        // In order to do that, we remove content from these two ranges:
        //
        // [<quote><p>y</p><h>fir]st</h></quote><p>se[cond</p>]
        if (flatSubtreeRange != range) {
            // Find the position of the original range in the cloned fragment.
            const newRange = range._getTransformedByMove(flatSubtreeRange.start, writer.createPositionAt(frag, 0), howMany)[0];
            const leftExcessRange = writer.createRange(writer.createPositionAt(frag, 0), newRange.start);
            const rightExcessRange = writer.createRange(newRange.end, writer.createPositionAt(frag, 'end'));
            removeRangeContent(rightExcessRange, writer);
            removeRangeContent(leftExcessRange, writer);
        }
        return frag;
    });
}
// After https://github.com/ckeditor/ckeditor5-engine/issues/690 is fixed,
// this function will, most likely, be able to rewritten using getMinimalFlatRanges().
function removeRangeContent(range, writer) {
    const parentsToCheck = [];
    Array.from(range.getItems({
        direction: 'backward'
    }))// We should better store ranges because text proxies will lose integrity
    // with the text nodes when we'll start removing content.
    .map((item)=>writer.createRangeOn(item))// Filter only these items which are fully contained in the passed range.
    //
    // E.g. for the following range: [<quote><p>y</p><h>fir]st</h>
    // the walker will return the entire <h> element, when only the "fir" item inside it is fully contained.
    .filter((itemRange)=>{
        // We should be able to use Range.containsRange, but https://github.com/ckeditor/ckeditor5-engine/issues/691.
        const contained = (itemRange.start.isAfter(range.start) || itemRange.start.isEqual(range.start)) && (itemRange.end.isBefore(range.end) || itemRange.end.isEqual(range.end));
        return contained;
    }).forEach((itemRange)=>{
        parentsToCheck.push(itemRange.start.parent);
        writer.remove(itemRange);
    });
    // Remove ancestors of the removed items if they turned to be empty now
    // (their whole content was contained in the range).
    parentsToCheck.forEach((parentToCheck)=>{
        let parent = parentToCheck;
        while(parent.parent && parent.isEmpty){
            const removeRange = writer.createRangeOn(parent);
            parent = parent.parent;
            writer.remove(removeRange);
        }
    });
}

/**
 * Inserts content into the editor (specified selection) as one would expect the paste functionality to work.
 *
 * It takes care of removing the selected content, splitting elements (if needed), inserting elements and merging elements appropriately.
 *
 * Some examples:
 *
 * ```html
 * <p>x^</p> + <p>y</p> => <p>x</p><p>y</p> => <p>xy[]</p>
 * <p>x^y</p> + <p>z</p> => <p>x</p>^<p>y</p> + <p>z</p> => <p>x</p><p>z</p><p>y</p> => <p>xz[]y</p>
 * <p>x^y</p> + <img /> => <p>x</p>^<p>y</p> + <img /> => <p>x</p><img /><p>y</p>
 * <p>x</p><p>^</p><p>z</p> + <p>y</p> => <p>x</p><p>y[]</p><p>z</p> (no merging)
 * <p>x</p>[<img />]<p>z</p> + <p>y</p> => <p>x</p>^<p>z</p> + <p>y</p> => <p>x</p><p>y[]</p><p>z</p>
 * ```
 *
 * If an instance of {@link module:engine/model/selection~Selection} is passed as `selectable` it will be modified
 * to the insertion selection (equal to a range to be selected after insertion).
 *
 * If `selectable` is not passed, the content will be inserted using the current selection of the model document.
 *
 * **Note:** Use {@link module:engine/model/model~Model#insertContent} instead of this function.
 * This function is only exposed to be reusable in algorithms which change the {@link module:engine/model/model~Model#insertContent}
 * method's behavior.
 *
 * @param model The model in context of which the insertion should be performed.
 * @param content The content to insert.
 * @param selectable Selection into which the content should be inserted.
 * @param placeOrOffset Sets place or offset of the selection.
 * @returns Range which contains all the performed changes. This is a range that, if removed,
 * would return the model to the state before the insertion. If no changes were preformed by `insertContent`, returns a range collapsed
 * at the insertion position.
 */ function insertContent(model, content, selectable) {
    return model.change((writer)=>{
        const selection = selectable ? selectable : model.document.selection;
        if (!selection.isCollapsed) {
            model.deleteContent(selection, {
                doNotAutoparagraph: true
            });
        }
        const insertion = new Insertion(model, writer, selection.anchor);
        const fakeMarkerElements = [];
        let nodesToInsert;
        if (content.is('documentFragment')) {
            // If document fragment has any markers, these markers should be inserted into the model as well.
            if (content.markers.size) {
                const markersPosition = [];
                for (const [name, range] of content.markers){
                    const { start, end } = range;
                    const isCollapsed = start.isEqual(end);
                    markersPosition.push({
                        position: start,
                        name,
                        isCollapsed
                    }, {
                        position: end,
                        name,
                        isCollapsed
                    });
                }
                // Markers position is sorted backwards to ensure that the insertion of fake markers will not change
                // the position of the next markers.
                markersPosition.sort(({ position: posA }, { position: posB })=>posA.isBefore(posB) ? 1 : -1);
                for (const { position, name, isCollapsed } of markersPosition){
                    let fakeElement = null;
                    let collapsed = null;
                    const isAtBeginning = position.parent === content && position.isAtStart;
                    const isAtEnd = position.parent === content && position.isAtEnd;
                    // We have two ways of handling markers. In general, we want to add temporary <$marker> model elements to
                    // represent marker boundaries. These elements will be inserted into content together with the rest
                    // of the document fragment. After insertion is done, positions for these elements will be read
                    // and proper, actual markers will be created in the model and fake elements will be removed.
                    //
                    // However, if the <$marker> element is at the beginning or at the end of the document fragment,
                    // it may affect how the inserted content is merged with current model, impacting the insertion
                    // result. To avoid that, we don't add <$marker> elements at these positions. Instead, we will use
                    // `Insertion#getAffectedRange()` to figure out new positions for these marker boundaries.
                    if (!isAtBeginning && !isAtEnd) {
                        fakeElement = writer.createElement('$marker');
                        writer.insert(fakeElement, position);
                    } else if (isCollapsed) {
                        // Save whether the collapsed marker was at the beginning or at the end of document fragment
                        // to know where to create it after the insertion is done.
                        collapsed = isAtBeginning ? 'start' : 'end';
                    }
                    fakeMarkerElements.push({
                        name,
                        element: fakeElement,
                        collapsed
                    });
                }
            }
            nodesToInsert = content.getChildren();
        } else {
            nodesToInsert = [
                content
            ];
        }
        insertion.handleNodes(nodesToInsert);
        let newRange = insertion.getSelectionRange();
        if (content.is('documentFragment') && fakeMarkerElements.length) {
            // After insertion was done, the selection was set but the model contains fake <$marker> elements.
            // These <$marker> elements will be now removed. Because of that, we will need to fix the selection.
            // We will create a live range that will automatically be update as <$marker> elements are removed.
            const selectionLiveRange = newRange ? LiveRange.fromRange(newRange) : null;
            // Marker name -> [ start position, end position ].
            const markersData = {};
            // Note: `fakeMarkerElements` are sorted backwards. However, now, we want to handle the markers
            // from the beginning, so that existing <$marker> elements do not affect markers positions.
            // This is why we iterate from the end to the start.
            for(let i = fakeMarkerElements.length - 1; i >= 0; i--){
                const { name, element, collapsed } = fakeMarkerElements[i];
                const isStartBoundary = !markersData[name];
                if (isStartBoundary) {
                    markersData[name] = [];
                }
                if (element) {
                    // Read fake marker element position to learn where the marker should be created.
                    const elementPosition = writer.createPositionAt(element, 'before');
                    markersData[name].push(elementPosition);
                    writer.remove(element);
                } else {
                    // If the fake marker element does not exist, it means that the marker boundary was at the beginning or at the end.
                    const rangeOnInsertion = insertion.getAffectedRange();
                    if (!rangeOnInsertion) {
                        // If affected range is `null` it means that nothing was in the document fragment or all content was filtered out.
                        // Some markers that were in the filtered content may be removed (partially or totally).
                        // Let's handle only those markers that were at the beginning or at the end of the document fragment.
                        if (collapsed) {
                            markersData[name].push(insertion.position);
                        }
                        continue;
                    }
                    if (collapsed) {
                        // If the marker was collapsed at the beginning or at the end of the document fragment,
                        // put both boundaries at the beginning or at the end of inserted range (to keep the marker collapsed).
                        markersData[name].push(rangeOnInsertion[collapsed]);
                    } else {
                        markersData[name].push(isStartBoundary ? rangeOnInsertion.start : rangeOnInsertion.end);
                    }
                }
            }
            for (const [name, [start, end]] of Object.entries(markersData)){
                // For now, we ignore markers if they are included in the filtered-out content.
                // In the future implementation we will improve that case to create markers that are not filtered out completely.
                if (start && end && start.root === end.root && start.root.document && !writer.model.markers.has(name)) {
                    writer.addMarker(name, {
                        usingOperation: true,
                        affectsData: true,
                        range: new Range(start, end)
                    });
                }
            }
            if (selectionLiveRange) {
                newRange = selectionLiveRange.toRange();
                selectionLiveRange.detach();
            }
        }
        /* istanbul ignore else -- @preserve */ if (newRange) {
            if (selection instanceof DocumentSelection) {
                writer.setSelection(newRange);
            } else {
                selection.setTo(newRange);
            }
        }
        const affectedRange = insertion.getAffectedRange() || model.createRange(selection.anchor);
        insertion.destroy();
        return affectedRange;
    });
}
/**
 * Utility class for performing content insertion.
 */ class Insertion {
    /**
	 * The model in context of which the insertion should be performed.
	 */ model;
    /**
	 * Batch to which operations will be added.
	 */ writer;
    /**
	 * The position at which (or near which) the next node will be inserted.
	 */ position;
    /**
	 * Elements with which the inserted elements can be merged.
	 *
	 * ```html
	 * <p>x^</p><p>y</p> + <p>z</p> (can merge to <p>x</p>)
	 * <p>x</p><p>^y</p> + <p>z</p> (can merge to <p>y</p>)
	 * <p>x^y</p> + <p>z</p> (can merge to <p>xy</p> which will be split during the action,
	 * 						so both its pieces will be added to this set)
	 * ```
	 */ canMergeWith;
    /**
	 * Schema of the model.
	 */ schema;
    /**
	 * The temporary DocumentFragment used for grouping multiple nodes for single insert operation.
	 */ _documentFragment;
    /**
	 * The current position in the temporary DocumentFragment.
	 */ _documentFragmentPosition;
    /**
	 * The reference to the first inserted node.
	 */ _firstNode = null;
    /**
	 * The reference to the last inserted node.
	 */ _lastNode = null;
    /**
	 * The reference to the last auto paragraph node.
	 */ _lastAutoParagraph = null;
    /**
	 * The array of nodes that should be cleaned of not allowed attributes.
	 */ _filterAttributesOf = [];
    /**
	 * Beginning of the affected range. See {@link module:engine/model/utils/insertcontent~Insertion#getAffectedRange}.
	 */ _affectedStart = null;
    /**
	 * End of the affected range. See {@link module:engine/model/utils/insertcontent~Insertion#getAffectedRange}.
	 */ _affectedEnd = null;
    _nodeToSelect = null;
    constructor(model, writer, position){
        this.model = model;
        this.writer = writer;
        this.position = position;
        this.canMergeWith = new Set([
            this.position.parent
        ]);
        this.schema = model.schema;
        this._documentFragment = writer.createDocumentFragment();
        this._documentFragmentPosition = writer.createPositionAt(this._documentFragment, 0);
    }
    /**
	 * Handles insertion of a set of nodes.
	 *
	 * @param nodes Nodes to insert.
	 */ handleNodes(nodes) {
        for (const node of Array.from(nodes)){
            this._handleNode(node);
        }
        // Insert nodes collected in temporary DocumentFragment.
        this._insertPartialFragment();
        // If there was an auto paragraph then we might need to adjust the end of insertion.
        if (this._lastAutoParagraph) {
            this._updateLastNodeFromAutoParagraph(this._lastAutoParagraph);
        }
        // After the content was inserted we may try to merge it with its next sibling if the selection was in it initially.
        // Merging with the previous sibling was performed just after inserting the first node to the document.
        this._mergeOnRight();
        // TMP this will become a post-fixer.
        this.schema.removeDisallowedAttributes(this._filterAttributesOf, this.writer);
        this._filterAttributesOf = [];
    }
    /**
	 * Updates the last node after the auto paragraphing.
	 *
	 * @param node The last auto paragraphing node.
	 */ _updateLastNodeFromAutoParagraph(node) {
        const positionAfterLastNode = this.writer.createPositionAfter(this._lastNode);
        const positionAfterNode = this.writer.createPositionAfter(node);
        // If the real end was after the last auto paragraph then update relevant properties.
        if (positionAfterNode.isAfter(positionAfterLastNode)) {
            this._lastNode = node;
            /* istanbul ignore if -- @preserve */ if (this.position.parent != node || !this.position.isAtEnd) {
                // Algorithm's correctness check. We should never end up here but it's good to know that we did.
                // At this point the insertion position should be at the end of the last auto paragraph.
                // Note: This error is documented in other place in this file.
                throw new CKEditorError('insertcontent-invalid-insertion-position', this);
            }
            this.position = positionAfterNode;
            this._setAffectedBoundaries(this.position);
        }
    }
    /**
	 * Returns range to be selected after insertion.
	 * Returns `null` if there is no valid range to select after insertion.
	 */ getSelectionRange() {
        if (this._nodeToSelect) {
            return Range._createOn(this._nodeToSelect);
        }
        return this.model.schema.getNearestSelectionRange(this.position);
    }
    /**
	 * Returns a range which contains all the performed changes. This is a range that, if removed, would return the model to the state
	 * before the insertion. Returns `null` if no changes were done.
	 */ getAffectedRange() {
        if (!this._affectedStart) {
            return null;
        }
        return new Range(this._affectedStart, this._affectedEnd);
    }
    /**
	 * Destroys `Insertion` instance.
	 */ destroy() {
        if (this._affectedStart) {
            this._affectedStart.detach();
        }
        if (this._affectedEnd) {
            this._affectedEnd.detach();
        }
    }
    /**
	 * Handles insertion of a single node.
	 */ _handleNode(node) {
        // Let's handle object in a special way.
        // * They should never be merged with other elements.
        // * If they are not allowed in any of the selection ancestors, they could be either autoparagraphed or totally removed.
        if (this.schema.isObject(node)) {
            this._handleObject(node);
            return;
        }
        // Try to find a place for the given node.
        // Check if a node can be inserted in the given position or it would be accepted if a paragraph would be inserted.
        // Inserts the auto paragraph if it would allow for insertion.
        let isAllowed = this._checkAndAutoParagraphToAllowedPosition(node);
        if (!isAllowed) {
            // Split the position.parent's branch up to a point where the node can be inserted.
            // If it isn't allowed in the whole branch, then of course don't split anything.
            isAllowed = this._checkAndSplitToAllowedPosition(node);
            if (!isAllowed) {
                this._handleDisallowedNode(node);
                return;
            }
        }
        // Add node to the current temporary DocumentFragment.
        this._appendToFragment(node);
        // Store the first and last nodes for easy access for merging with sibling nodes.
        if (!this._firstNode) {
            this._firstNode = node;
        }
        this._lastNode = node;
    }
    /**
	 * Inserts the temporary DocumentFragment into the model.
	 */ _insertPartialFragment() {
        if (this._documentFragment.isEmpty) {
            return;
        }
        const livePosition = LivePosition.fromPosition(this.position, 'toNext');
        this._setAffectedBoundaries(this.position);
        // If the very first node of the whole insertion process is inserted, insert it separately for OT reasons (undo).
        // Note: there can be multiple calls to `_insertPartialFragment()` during one insertion process.
        // Note: only the very first node can be merged so we have to do separate operation only for it.
        if (this._documentFragment.getChild(0) == this._firstNode) {
            this.writer.insert(this._firstNode, this.position);
            // We must merge the first node just after inserting it to avoid problems with OT.
            // (See: https://github.com/ckeditor/ckeditor5/pull/8773#issuecomment-760945652).
            this._mergeOnLeft();
            this.position = livePosition.toPosition();
        }
        // Insert the remaining nodes from document fragment.
        if (!this._documentFragment.isEmpty) {
            this.writer.insert(this._documentFragment, this.position);
        }
        this._documentFragmentPosition = this.writer.createPositionAt(this._documentFragment, 0);
        this.position = livePosition.toPosition();
        livePosition.detach();
    }
    /**
	 * @param node The object element.
	 */ _handleObject(node) {
        // Try finding it a place in the tree.
        if (this._checkAndSplitToAllowedPosition(node)) {
            this._appendToFragment(node);
        } else {
            this._tryAutoparagraphing(node);
        }
    }
    /**
	 * @param node The disallowed node which needs to be handled.
	 */ _handleDisallowedNode(node) {
        // If the node is an element, try inserting its children (strip the parent).
        if (node.is('element')) {
            this.handleNodes(node.getChildren());
        } else {
            this._tryAutoparagraphing(node);
        }
    }
    /**
	 * Append a node to the temporary DocumentFragment.
	 *
	 * @param node The node to insert.
	 */ _appendToFragment(node) {
        /* istanbul ignore if -- @preserve */ if (!this.schema.checkChild(this.position, node)) {
            // Algorithm's correctness check. We should never end up here but it's good to know that we did.
            // Note that it would often be a silent issue if we insert node in a place where it's not allowed.
            /**
			 * Given node cannot be inserted on the given position.
			 *
			 * @error insertcontent-wrong-position
			 * @param node Node to insert.
			 * @param position Position to insert the node at.
			 */ throw new CKEditorError('insertcontent-wrong-position', this, {
                node,
                position: this.position
            });
        }
        this.writer.insert(node, this._documentFragmentPosition);
        this._documentFragmentPosition = this._documentFragmentPosition.getShiftedBy(node.offsetSize);
        // The last inserted object should be selected because we can't put a collapsed selection after it.
        if (this.schema.isObject(node) && !this.schema.checkChild(this.position, '$text')) {
            this._nodeToSelect = node;
        } else {
            this._nodeToSelect = null;
        }
        this._filterAttributesOf.push(node);
    }
    /**
	 * Sets `_affectedStart` and `_affectedEnd` to the given `position`. Should be used before a change is done during insertion process to
	 * mark the affected range.
	 *
	 * This method is used before inserting a node or splitting a parent node. `_affectedStart` and `_affectedEnd` are also changed
	 * during merging, but the logic there is more complicated so it is left out of this function.
	 */ _setAffectedBoundaries(position) {
        // Set affected boundaries stickiness so that those position will "expand" when something is inserted in between them:
        // <paragraph>Foo][bar</paragraph> -> <paragraph>Foo]xx[bar</paragraph>
        // This is why it cannot be a range but two separate positions.
        if (!this._affectedStart) {
            this._affectedStart = LivePosition.fromPosition(position, 'toPrevious');
        }
        // If `_affectedEnd` is before the new boundary position, expand `_affectedEnd`. This can happen if first inserted node was
        // inserted into the parent but the next node is moved-out of that parent:
        // (1) <paragraph>Foo][</paragraph> -> <paragraph>Foo]xx[</paragraph>
        // (2) <paragraph>Foo]xx[</paragraph> -> <paragraph>Foo]xx</paragraph><widget></widget>[
        if (!this._affectedEnd || this._affectedEnd.isBefore(position)) {
            if (this._affectedEnd) {
                this._affectedEnd.detach();
            }
            this._affectedEnd = LivePosition.fromPosition(position, 'toNext');
        }
    }
    /**
	 * Merges the previous sibling of the first node if it should be merged.
	 *
	 * After the content was inserted we may try to merge it with its siblings.
	 * This should happen only if the selection was in those elements initially.
	 */ _mergeOnLeft() {
        const node = this._firstNode;
        if (!(node instanceof Element)) {
            return;
        }
        if (!this._canMergeLeft(node)) {
            return;
        }
        const mergePosLeft = LivePosition._createBefore(node);
        mergePosLeft.stickiness = 'toNext';
        const livePosition = LivePosition.fromPosition(this.position, 'toNext');
        // If `_affectedStart` is sames as merge position, it means that the element "marked" by `_affectedStart` is going to be
        // removed and its contents will be moved. This won't transform `LivePosition` so `_affectedStart` needs to be moved
        // by hand to properly reflect affected range. (Due to `_affectedStart` and `_affectedEnd` stickiness, the "range" is
        // shown as `][`).
        //
        // Example - insert `<paragraph>Abc</paragraph><paragraph>Xyz</paragraph>` at the end of `<paragraph>Foo^</paragraph>`:
        //
        // <paragraph>Foo</paragraph><paragraph>Bar</paragraph>   -->
        // <paragraph>Foo</paragraph>]<paragraph>Abc</paragraph><paragraph>Xyz</paragraph>[<paragraph>Bar</paragraph>   -->
        // <paragraph>Foo]Abc</paragraph><paragraph>Xyz</paragraph>[<paragraph>Bar</paragraph>
        //
        // Note, that if we are here then something must have been inserted, so `_affectedStart` and `_affectedEnd` have to be set.
        if (this._affectedStart.isEqual(mergePosLeft)) {
            this._affectedStart.detach();
            this._affectedStart = LivePosition._createAt(mergePosLeft.nodeBefore, 'end', 'toPrevious');
        }
        // We need to update the references to the first and last nodes if they will be merged into the previous sibling node
        // because the reference would point to the removed node.
        //
        // <p>A^A</p> + <p>X</p>
        //
        // <p>A</p>^<p>A</p>
        // <p>A</p><p>X</p><p>A</p>
        // <p>AX</p><p>A</p>
        // <p>AXA</p>
        if (this._firstNode === this._lastNode) {
            this._firstNode = mergePosLeft.nodeBefore;
            this._lastNode = mergePosLeft.nodeBefore;
        }
        this.writer.merge(mergePosLeft);
        // If only one element (the merged one) is in the "affected range", also move the affected range end appropriately.
        //
        // Example - insert `<paragraph>Abc</paragraph>` at the of `<paragraph>Foo^</paragraph>`:
        //
        // <paragraph>Foo</paragraph><paragraph>Bar</paragraph>   -->
        // <paragraph>Foo</paragraph>]<paragraph>Abc</paragraph>[<paragraph>Bar</paragraph>   -->
        // <paragraph>Foo]Abc</paragraph>[<paragraph>Bar</paragraph>   -->
        // <paragraph>Foo]Abc[</paragraph><paragraph>Bar</paragraph>
        if (mergePosLeft.isEqual(this._affectedEnd) && this._firstNode === this._lastNode) {
            this._affectedEnd.detach();
            this._affectedEnd = LivePosition._createAt(mergePosLeft.nodeBefore, 'end', 'toNext');
        }
        this.position = livePosition.toPosition();
        livePosition.detach();
        // After merge elements that were marked by _insert() to be filtered might be gone so
        // we need to mark the new container.
        this._filterAttributesOf.push(this.position.parent);
        mergePosLeft.detach();
    }
    /**
	 * Merges the next sibling of the last node if it should be merged.
	 *
	 * After the content was inserted we may try to merge it with its siblings.
	 * This should happen only if the selection was in those elements initially.
	 */ _mergeOnRight() {
        const node = this._lastNode;
        if (!(node instanceof Element)) {
            return;
        }
        if (!this._canMergeRight(node)) {
            return;
        }
        const mergePosRight = LivePosition._createAfter(node);
        mergePosRight.stickiness = 'toNext';
        /* istanbul ignore if -- @preserve */ if (!this.position.isEqual(mergePosRight)) {
            // Algorithm's correctness check. We should never end up here but it's good to know that we did.
            // At this point the insertion position should be after the node we'll merge. If it isn't,
            // it should need to be secured as in the left merge case.
            /**
			 * An internal error occurred when merging inserted content with its siblings.
			 * The insertion position should equal the merge position.
			 *
			 * If you encountered this error, report it back to the CKEditor 5 team
			 * with as many details as possible regarding the content being inserted and the insertion position.
			 *
			 * @error insertcontent-invalid-insertion-position
			 */ throw new CKEditorError('insertcontent-invalid-insertion-position', this);
        }
        // Move the position to the previous node, so it isn't moved to the graveyard on merge.
        // <p>x</p>[]<p>y</p> => <p>x[]</p><p>y</p>
        this.position = Position._createAt(mergePosRight.nodeBefore, 'end');
        // Explanation of setting position stickiness to `'toPrevious'`:
        // OK:  <p>xx[]</p> + <p>yy</p> => <p>xx[]yy</p> (when sticks to previous)
        // NOK: <p>xx[]</p> + <p>yy</p> => <p>xxyy[]</p> (when sticks to next)
        const livePosition = LivePosition.fromPosition(this.position, 'toPrevious');
        // See comment in `_mergeOnLeft()` on moving `_affectedStart`.
        if (this._affectedEnd.isEqual(mergePosRight)) {
            this._affectedEnd.detach();
            this._affectedEnd = LivePosition._createAt(mergePosRight.nodeBefore, 'end', 'toNext');
        }
        // We need to update the references to the first and last nodes if they will be merged into the previous sibling node
        // because the reference would point to the removed node.
        //
        // <p>A^A</p> + <p>X</p>
        //
        // <p>A</p>^<p>A</p>
        // <p>A</p><p>X</p><p>A</p>
        // <p>AX</p><p>A</p>
        // <p>AXA</p>
        if (this._firstNode === this._lastNode) {
            this._firstNode = mergePosRight.nodeBefore;
            this._lastNode = mergePosRight.nodeBefore;
        }
        this.writer.merge(mergePosRight);
        // See comment in `_mergeOnLeft()` on moving `_affectedStart`.
        if (mergePosRight.getShiftedBy(-1).isEqual(this._affectedStart) && this._firstNode === this._lastNode) {
            this._affectedStart.detach();
            this._affectedStart = LivePosition._createAt(mergePosRight.nodeBefore, 0, 'toPrevious');
        }
        this.position = livePosition.toPosition();
        livePosition.detach();
        // After merge elements that were marked by _insert() to be filtered might be gone so
        // we need to mark the new container.
        this._filterAttributesOf.push(this.position.parent);
        mergePosRight.detach();
    }
    /**
	 * Checks whether specified node can be merged with previous sibling element.
	 *
	 * @param node The node which could potentially be merged.
	 */ _canMergeLeft(node) {
        const previousSibling = node.previousSibling;
        return previousSibling instanceof Element && this.canMergeWith.has(previousSibling) && this.model.schema.checkMerge(previousSibling, node);
    }
    /**
	 * Checks whether specified node can be merged with next sibling element.
	 *
	 * @param node The node which could potentially be merged.
	 */ _canMergeRight(node) {
        const nextSibling = node.nextSibling;
        return nextSibling instanceof Element && this.canMergeWith.has(nextSibling) && this.model.schema.checkMerge(node, nextSibling);
    }
    /**
	 * Tries wrapping the node in a new paragraph and inserting it this way.
	 *
	 * @param node The node which needs to be autoparagraphed.
	 */ _tryAutoparagraphing(node) {
        const paragraph = this.writer.createElement('paragraph');
        // Do not autoparagraph if the paragraph won't be allowed there,
        // cause that would lead to an infinite loop. The paragraph would be rejected in
        // the next _handleNode() call and we'd be here again.
        if (this._getAllowedIn(this.position.parent, paragraph) && this.schema.checkChild(paragraph, node)) {
            paragraph._appendChild(node);
            this._handleNode(paragraph);
        }
    }
    /**
	 * Checks if a node can be inserted in the given position or it would be accepted if a paragraph would be inserted.
	 * It also handles inserting the paragraph.
	 *
	 * @returns Whether an allowed position was found.
	 * `false` is returned if the node isn't allowed at the current position or in auto paragraph, `true` if was.
	 */ _checkAndAutoParagraphToAllowedPosition(node) {
        if (this.schema.checkChild(this.position.parent, node)) {
            return true;
        }
        // Do not auto paragraph if the paragraph won't be allowed there,
        // cause that would lead to an infinite loop. The paragraph would be rejected in
        // the next _handleNode() call and we'd be here again.
        if (!this.schema.checkChild(this.position.parent, 'paragraph') || !this.schema.checkChild('paragraph', node)) {
            return false;
        }
        // Insert nodes collected in temporary DocumentFragment if the position parent needs change to process further nodes.
        this._insertPartialFragment();
        // Insert a paragraph and move insertion position to it.
        const paragraph = this.writer.createElement('paragraph');
        this.writer.insert(paragraph, this.position);
        this._setAffectedBoundaries(this.position);
        this._lastAutoParagraph = paragraph;
        this.position = this.writer.createPositionAt(paragraph, 0);
        return true;
    }
    /**
	 * @returns Whether an allowed position was found.
	 * `false` is returned if the node isn't allowed at any position up in the tree, `true` if was.
	 */ _checkAndSplitToAllowedPosition(node) {
        const allowedIn = this._getAllowedIn(this.position.parent, node);
        if (!allowedIn) {
            return false;
        }
        // Insert nodes collected in temporary DocumentFragment if the position parent needs change to process further nodes.
        if (allowedIn != this.position.parent) {
            this._insertPartialFragment();
        }
        while(allowedIn != this.position.parent){
            if (this.position.isAtStart) {
                // If insertion position is at the beginning of the parent, move it out instead of splitting.
                // <p>^Foo</p> -> ^<p>Foo</p>
                const parent = this.position.parent;
                this.position = this.writer.createPositionBefore(parent);
                // Special case – parent is empty (<p>^</p>).
                //
                // 1. parent.isEmpty
                // We can remove the element after moving insertion position out of it.
                //
                // 2. parent.parent === allowedIn
                // However parent should remain in place when allowed element is above limit element in document tree.
                // For example there shouldn't be allowed to remove empty paragraph from tableCell, when is pasted
                // content allowed in $root.
                if (parent.isEmpty && parent.parent === allowedIn) {
                    this.writer.remove(parent);
                }
            } else if (this.position.isAtEnd) {
                // If insertion position is at the end of the parent, move it out instead of splitting.
                // <p>Foo^</p> -> <p>Foo</p>^
                this.position = this.writer.createPositionAfter(this.position.parent);
            } else {
                const tempPos = this.writer.createPositionAfter(this.position.parent);
                this._setAffectedBoundaries(this.position);
                this.writer.split(this.position);
                this.position = tempPos;
                this.canMergeWith.add(this.position.nodeAfter);
            }
        }
        return true;
    }
    /**
	 * Gets the element in which the given node is allowed. It checks the passed element and all its ancestors.
	 *
	 * @param contextElement The element in which context the node should be checked.
	 * @param childNode The node to check.
	 */ _getAllowedIn(contextElement, childNode) {
        if (this.schema.checkChild(contextElement, childNode)) {
            return contextElement;
        }
        // If the child wasn't allowed in the context element and the element is a limit there's no point in
        // checking any further towards the root. This is it: the limit is unsplittable and there's nothing
        // we can do about it. Without this check, the algorithm will analyze parent of the limit and may create
        // an illusion of the child being allowed. There's no way to insert it down there, though. It results in
        // infinite loops.
        if (this.schema.isLimit(contextElement)) {
            return null;
        }
        return this._getAllowedIn(contextElement.parent, childNode);
    }
}

/**
 * Inserts an {@glink framework/deep-dive/schema#object-elements object element} at a specific position in the editor content.
 *
 * **Note:** Use {@link module:engine/model/model~Model#insertObject} instead of this function.
 * This function is only exposed to be reusable in algorithms which change the {@link module:engine/model/model~Model#insertObject}
 * method's behavior.
 *
 * **Note**: For more documentation and examples, see {@link module:engine/model/model~Model#insertObject}.
 *
 * @param model The model in context of which the insertion should be performed.
 * @param object An object to be inserted into the model document.
 * @param selectable A selectable where the content should be inserted. If not specified, the current
 * {@link module:engine/model/document~Document#selection document selection} will be used instead.
 * @param placeOrOffset Specifies the exact place or offset for the insertion to take place, relative to `selectable`.
 * @param options Additional options.
 * @param options.findOptimalPosition An option that, when set, adjusts the insertion position (relative to
 * `selectable` and `placeOrOffset`) so that the content of `selectable` is not split upon insertion (a.k.a. non-destructive insertion).
 * * When `'auto'`, the algorithm will decide whether to insert the object before or after `selectable` to avoid content splitting.
 * * When `'before'`, the closest position before `selectable` will be used that will not result in content splitting.
 * * When `'after'`, the closest position after `selectable` will be used that will not result in content splitting.
 *
 * Note that this option works only for block objects. Inline objects are inserted into text and do not split blocks.
 * @param options.setSelection An option that, when set, moves the
 * {@link module:engine/model/document~Document#selection document selection} after inserting the object.
 * * When `'on'`, the document selection will be set on the inserted object.
 * * When `'after'`, the document selection will move to the closest text node after the inserted object. If there is no
 * such text node, a paragraph will be created and the document selection will be moved inside it.
 * @returns A range which contains all the performed changes. This is a range that, if removed,
 * would return the model to the state before the insertion. If no changes were preformed by `insertObject()`, returns a range collapsed
 * at the insertion position.
 */ function insertObject(model, object, selectable, options = {}) {
    if (!model.schema.isObject(object)) {
        /**
		 * Tried to insert an element with {@link module:engine/model/utils/insertobject insertObject()} function
		 * that is not defined as an object in schema.
		 * See {@link module:engine/model/schema~SchemaItemDefinition#isObject `SchemaItemDefinition`}.
		 * If you want to insert content that is not an object you might want to use
		 * {@link module:engine/model/utils/insertcontent insertContent()} function.
		 * @error insertobject-element-not-an-object
		 */ throw new CKEditorError('insertobject-element-not-an-object', model, {
            object
        });
    }
    // Normalize selectable to a selection instance.
    const originalSelection = selectable ? selectable : model.document.selection;
    // Adjust the insertion selection.
    let insertionSelection = originalSelection;
    if (options.findOptimalPosition && model.schema.isBlock(object)) {
        insertionSelection = model.createSelection(model.schema.findOptimalInsertionRange(originalSelection, options.findOptimalPosition));
    }
    // Collect attributes to be copied on the inserted object.
    const firstSelectedBlock = first(originalSelection.getSelectedBlocks());
    const attributesToCopy = {};
    if (firstSelectedBlock) {
        Object.assign(attributesToCopy, model.schema.getAttributesWithProperty(firstSelectedBlock, 'copyOnReplace', true));
    }
    return model.change((writer)=>{
        // Remove the selected content to find out what the parent of the inserted object would be.
        // It would be removed inside model.insertContent() anyway.
        if (!insertionSelection.isCollapsed) {
            model.deleteContent(insertionSelection, {
                doNotAutoparagraph: true
            });
        }
        let elementToInsert = object;
        const insertionPositionParent = insertionSelection.anchor.parent;
        // Autoparagraphing of an inline objects.
        if (!model.schema.checkChild(insertionPositionParent, object) && model.schema.checkChild(insertionPositionParent, 'paragraph') && model.schema.checkChild('paragraph', object)) {
            elementToInsert = writer.createElement('paragraph');
            writer.insert(object, elementToInsert);
        }
        // Apply attributes that are allowed on the inserted object (or paragraph if autoparagraphed).
        model.schema.setAllowedAttributes(elementToInsert, attributesToCopy, writer);
        // Insert the prepared content at the optionally adjusted selection.
        const affectedRange = model.insertContent(elementToInsert, insertionSelection);
        // Nothing got inserted.
        if (affectedRange.isCollapsed) {
            return affectedRange;
        }
        if (options.setSelection) {
            updateSelection(writer, object, options.setSelection, attributesToCopy);
        }
        return affectedRange;
    });
}
/**
 * Updates document selection based on given `place` parameter in relation to `contextElement` element.
 *
 * @param writer An instance of the model writer.
 * @param contextElement An element to set the attributes on.
 * @param place The place where selection should be set in relation to the `contextElement` element.
 * Value `on` will set selection on the passed `contextElement`. Value `after` will set selection after `contextElement`.
 * @param attributes Attributes keys and values to set on a paragraph that this function can create when
 * `place` parameter is equal to `after` but there is no element with `$text` node to set selection in.
 */ function updateSelection(writer, contextElement, place, paragraphAttributes) {
    const model = writer.model;
    if (place == 'on') {
        writer.setSelection(contextElement, 'on');
        return;
    }
    if (place != 'after') {
        /**
		 * The unsupported `options.setSelection` parameter was passed
		 * to the {@link module:engine/model/utils/insertobject insertObject()} function.
		 * Check the {@link module:engine/model/utils/insertobject insertObject()} API documentation for allowed
		 * `options.setSelection` parameter values.
		 *
		 * @error insertobject-invalid-place-parameter-value
		 */ throw new CKEditorError('insertobject-invalid-place-parameter-value', model);
    }
    let nextElement = contextElement.nextSibling;
    if (model.schema.isInline(contextElement)) {
        writer.setSelection(contextElement, 'after');
        return;
    }
    // Check whether an element next to the inserted element is defined and can contain a text.
    const canSetSelection = nextElement && model.schema.checkChild(nextElement, '$text');
    // If the element is missing, but a paragraph could be inserted next to the element, let's add it.
    if (!canSetSelection && model.schema.checkChild(contextElement.parent, 'paragraph')) {
        nextElement = writer.createElement('paragraph');
        model.schema.setAllowedAttributes(nextElement, paragraphAttributes, writer);
        model.insertContent(nextElement, writer.createPositionAfter(contextElement));
    }
    // Put the selection inside the element, at the beginning.
    if (nextElement) {
        writer.setSelection(nextElement, 0);
    }
}

const wordBoundaryCharacters = ' ,.?!:;"-()';
/**
 * Modifies the selection. Currently, the supported modifications are:
 *
 * * Extending. The selection focus is moved in the specified `options.direction` with a step specified in `options.unit`.
 * Possible values for `unit` are:
 *  * `'character'` (default) - moves selection by one user-perceived character. In most cases this means moving by one
 *  character in `String` sense. However, unicode also defines "combing marks". These are special symbols, that combines
 *  with a symbol before it ("base character") to create one user-perceived character. For example, `q̣̇` is a normal
 *  letter `q` with two "combining marks": upper dot (`Ux0307`) and lower dot (`Ux0323`). For most actions, i.e. extending
 *  selection by one position, it is correct to include both "base character" and all of it's "combining marks". That is
 *  why `'character'` value is most natural and common method of modifying selection.
 *  * `'codePoint'` - moves selection by one unicode code point. In contrary to, `'character'` unit, this will insert
 *  selection between "base character" and "combining mark", because "combining marks" have their own unicode code points.
 *  However, for technical reasons, unicode code points with values above `UxFFFF` are represented in native `String` by
 *  two characters, called "surrogate pairs". Halves of "surrogate pairs" have a meaning only when placed next to each other.
 *  For example `𨭎` is represented in `String` by `\uD862\uDF4E`. Both `\uD862` and `\uDF4E` do not have any meaning
 *  outside the pair (are rendered as ? when alone). Position between them would be incorrect. In this case, selection
 *  extension will include whole "surrogate pair".
 *  * `'word'` - moves selection by a whole word.
 *
 * **Note:** if you extend a forward selection in a backward direction you will in fact shrink it.
 *
 * **Note:** Use {@link module:engine/model/model~Model#modifySelection} instead of this function.
 * This function is only exposed to be reusable in algorithms
 * which change the {@link module:engine/model/model~Model#modifySelection}
 * method's behavior.
 *
 * @param model The model in context of which the selection modification should be performed.
 * @param selection The selection to modify.
 * @param options.direction The direction in which the selection should be modified. Default 'forward'.
 * @param options.unit The unit by which selection should be modified. Default 'character'.
 * @param options.treatEmojiAsSingleUnit Whether multi-characer emoji sequences should be handled as single unit.
 */ function modifySelection(model, selection, options = {}) {
    const schema = model.schema;
    const isForward = options.direction != 'backward';
    const unit = options.unit ? options.unit : 'character';
    const treatEmojiAsSingleUnit = !!options.treatEmojiAsSingleUnit;
    const focus = selection.focus;
    const walker = new TreeWalker({
        boundaries: getSearchRange(focus, isForward),
        singleCharacters: true,
        direction: isForward ? 'forward' : 'backward'
    });
    const data = {
        walker,
        schema,
        isForward,
        unit,
        treatEmojiAsSingleUnit
    };
    let next;
    while(next = walker.next()){
        if (next.done) {
            return;
        }
        const position = tryExtendingTo(data, next.value);
        if (position) {
            if (selection instanceof DocumentSelection) {
                model.change((writer)=>{
                    writer.setSelectionFocus(position);
                });
            } else {
                selection.setFocus(position);
            }
            return;
        }
    }
}
/**
 * Checks whether the selection can be extended to the the walker's next value (next position).
 */ function tryExtendingTo(data, value) {
    const { isForward, walker, unit, schema, treatEmojiAsSingleUnit } = data;
    const { type, item, nextPosition } = value;
    // If found text, we can certainly put the focus in it. Let's just find a correct position
    // based on the unit.
    if (type == 'text') {
        if (data.unit === 'word') {
            return getCorrectWordBreakPosition(walker, isForward);
        }
        return getCorrectPosition(walker, unit, treatEmojiAsSingleUnit);
    }
    // Entering an element.
    if (type == (isForward ? 'elementStart' : 'elementEnd')) {
        // If it's a selectable, we can select it now.
        if (schema.isSelectable(item)) {
            return Position._createAt(item, isForward ? 'after' : 'before');
        }
        // If text allowed on this position, extend to this place.
        if (schema.checkChild(nextPosition, '$text')) {
            return nextPosition;
        }
    } else {
        // If leaving a limit element, stop.
        if (schema.isLimit(item)) {
            // NOTE: Fast-forward the walker until the end.
            walker.skip(()=>true);
            return;
        }
        // If text allowed on this position, extend to this place.
        if (schema.checkChild(nextPosition, '$text')) {
            return nextPosition;
        }
    }
}
/**
 * Finds a correct position by walking in a text node and checking whether selection can be extended to given position
 * or should be extended further.
 */ function getCorrectPosition(walker, unit, treatEmojiAsSingleUnit) {
    const textNode = walker.position.textNode;
    if (textNode) {
        const data = textNode.data;
        let offset = walker.position.offset - textNode.startOffset;
        while(isInsideSurrogatePair(data, offset) || unit == 'character' && isInsideCombinedSymbol(data, offset) || treatEmojiAsSingleUnit && isInsideEmojiSequence(data, offset)){
            walker.next();
            offset = walker.position.offset - textNode.startOffset;
        }
    }
    return walker.position;
}
/**
 * Finds a correct position of a word break by walking in a text node and checking whether selection can be extended to given position
 * or should be extended further.
 */ function getCorrectWordBreakPosition(walker, isForward) {
    let textNode = walker.position.textNode;
    if (!textNode) {
        textNode = isForward ? walker.position.nodeAfter : walker.position.nodeBefore;
    }
    while(textNode && textNode.is('$text')){
        const offset = walker.position.offset - textNode.startOffset;
        // Check of adjacent text nodes with different attributes (like BOLD).
        // Example          : 'foofoo []bar<$text bold="true">bar</$text> bazbaz'
        // should expand to : 'foofoo [bar<$text bold="true">bar</$text>] bazbaz'.
        if (isAtNodeBoundary(textNode, offset, isForward)) {
            textNode = isForward ? walker.position.nodeAfter : walker.position.nodeBefore;
        } else if (isAtWordBoundary(textNode.data, offset, isForward)) {
            break;
        } else {
            walker.next();
        }
    }
    return walker.position;
}
function getSearchRange(start, isForward) {
    const root = start.root;
    const searchEnd = Position._createAt(root, isForward ? 'end' : 0);
    if (isForward) {
        return new Range(start, searchEnd);
    } else {
        return new Range(searchEnd, start);
    }
}
/**
 * Checks if selection is on word boundary.
 */ function isAtWordBoundary(data, offset, isForward) {
    // The offset to check depends on direction.
    const offsetToCheck = offset + (isForward ? 0 : -1);
    return wordBoundaryCharacters.includes(data.charAt(offsetToCheck));
}
/**
 * Checks if selection is on node boundary.
 */ function isAtNodeBoundary(textNode, offset, isForward) {
    return offset === (isForward ? textNode.offsetSize : 0);
}

// @if CK_DEBUG_ENGINE // const { dumpTrees, initDocumentDumping } = require( '../dev-utils/utils' );
// @if CK_DEBUG_ENGINE // const { OperationReplayer } = require( '../dev-utils/operationreplayer' ).default;
/**
 * Editor's data model. Read about the model in the
 * {@glink framework/architecture/editing-engine engine architecture} guide.
 */ class Model extends /* #__PURE__ */ ObservableMixin() {
    /**
	 * Model's marker collection.
	 */ markers;
    /**
	 * Model's document.
	 */ document;
    /**
	 * Model's schema.
	 */ schema;
    /**
	 * All callbacks added by {@link module:engine/model/model~Model#change} or
	 * {@link module:engine/model/model~Model#enqueueChange} methods waiting to be executed.
	 */ _pendingChanges;
    /**
	 * The last created and currently used writer instance.
	 */ _currentWriter;
    // @if CK_DEBUG_ENGINE // private _operationLogs: Array<string>;
    // @if CK_DEBUG_ENGINE // private _appliedOperations: Array<Operation>;
    constructor(){
        super();
        this.markers = new MarkerCollection();
        this.document = new Document(this);
        this.schema = new Schema();
        this._pendingChanges = [];
        this._currentWriter = null;
        [
            'deleteContent',
            'modifySelection',
            'getSelectedContent',
            'applyOperation'
        ].forEach((methodName)=>this.decorate(methodName));
        // Adding operation validation with `highest` priority, so it is called before any other feature would like
        // to do anything with the operation. If the operation has incorrect parameters it should throw on the earliest occasion.
        this.on('applyOperation', (evt, args)=>{
            const operation = args[0];
            operation._validate();
        }, {
            priority: 'highest'
        });
        // Register some default abstract entities.
        this.schema.register('$root', {
            isLimit: true
        });
        this.schema.register('$container', {
            allowIn: [
                '$root',
                '$container'
            ]
        });
        this.schema.register('$block', {
            allowIn: [
                '$root',
                '$container'
            ],
            isBlock: true
        });
        this.schema.register('$blockObject', {
            allowWhere: '$block',
            isBlock: true,
            isObject: true
        });
        this.schema.register('$inlineObject', {
            allowWhere: '$text',
            allowAttributesOf: '$text',
            isInline: true,
            isObject: true
        });
        this.schema.register('$text', {
            allowIn: '$block',
            isInline: true,
            isContent: true
        });
        this.schema.register('$clipboardHolder', {
            allowContentOf: '$root',
            allowChildren: '$text',
            isLimit: true
        });
        this.schema.register('$documentFragment', {
            allowContentOf: '$root',
            allowChildren: '$text',
            isLimit: true
        });
        // An element needed by the `upcastElementToMarker` converter.
        // This element temporarily represents a marker boundary during the conversion process and is removed
        // at the end of the conversion. `UpcastDispatcher` or at least `Conversion` class looks like a
        // better place for this registration but both know nothing about `Schema`.
        this.schema.register('$marker');
        this.schema.addChildCheck((context, childDefinition)=>{
            if (childDefinition.name === '$marker') {
                return true;
            }
        });
        injectSelectionPostFixer(this);
        // Post-fixer which takes care of adding empty paragraph elements to the empty roots.
        this.document.registerPostFixer(autoParagraphEmptyRoots);
        // The base implementation for "decorated" method with remapped arguments.
        this.on('insertContent', (evt, [content, selectable])=>{
            evt.return = insertContent(this, content, selectable);
        });
        // The base implementation for "decorated" method with remapped arguments.
        this.on('insertObject', (evt, [element, selection, options])=>{
            evt.return = insertObject(this, element, selection, options);
        });
        // The base implementation for "decorated" method with remapped arguments.
        this.on('canEditAt', (evt)=>{
            const canEditAt = !this.document.isReadOnly;
            evt.return = canEditAt;
            if (!canEditAt) {
                // Prevent further processing if the selection is at non-editable place.
                evt.stop();
            }
        });
    // @if CK_DEBUG_ENGINE // initDocumentDumping( this.document );
    // @if CK_DEBUG_ENGINE // this.on( 'applyOperation', () => {
    // @if CK_DEBUG_ENGINE // 	dumpTrees( this.document, this.document.version );
    // @if CK_DEBUG_ENGINE // }, { priority: 'lowest' } );
    // @if CK_DEBUG_ENGINE // this._operationLogs = [];
    // @if CK_DEBUG_ENGINE // this._appliedOperations = [];
    }
    /**
	 * The `change()` method is the primary way of changing the model. You should use it to modify all document nodes
	 * (including detached nodes – i.e. nodes not added to the {@link module:engine/model/model~Model#document model document}),
	 * the {@link module:engine/model/document~Document#selection document's selection}, and
	 * {@link module:engine/model/model~Model#markers model markers}.
	 *
	 * ```ts
	 * model.change( writer => {
	 * 	writer.insertText( 'foo', paragraph, 'end' );
	 * } );
	 * ```
	 *
	 * All changes inside the change block use the same {@link module:engine/model/batch~Batch} so they are combined
	 * into a single undo step.
	 *
	 * ```ts
	 * model.change( writer => {
	 * 	writer.insertText( 'foo', paragraph, 'end' ); // foo.
	 *
	 * 	model.change( writer => {
	 * 		writer.insertText( 'bar', paragraph, 'end' ); // foobar.
	 * 	} );
	 *
	 * 	writer.insertText( 'bom', paragraph, 'end' ); // foobarbom.
	 * } );
	 * ```
	 *
	 * The callback of the `change()` block is executed synchronously.
	 *
	 * You can also return a value from the change block.
	 *
	 * ```ts
	 * const img = model.change( writer => {
	 * 	return writer.createElement( 'img' );
	 * } );
	 * ```
	 *
	 * @see #enqueueChange
	 * @typeParam TReturn The return type of the provided callback.
	 * @param callback Callback function which may modify the model.
	 */ change(callback) {
        try {
            if (this._pendingChanges.length === 0) {
                // If this is the outermost block, create a new batch and start `_runPendingChanges` execution flow.
                this._pendingChanges.push({
                    batch: new Batch(),
                    callback
                });
                return this._runPendingChanges()[0];
            } else {
                // If this is not the outermost block, just execute the callback.
                return callback(this._currentWriter);
            }
        } catch (err) {
            // @if CK_DEBUG // throw err;
            /* istanbul ignore next -- @preserve */ CKEditorError.rethrowUnexpectedError(err, this);
        }
    }
    enqueueChange(batchOrType, callback) {
        try {
            if (!batchOrType) {
                batchOrType = new Batch();
            } else if (typeof batchOrType === 'function') {
                callback = batchOrType;
                batchOrType = new Batch();
            } else if (!(batchOrType instanceof Batch)) {
                batchOrType = new Batch(batchOrType);
            }
            this._pendingChanges.push({
                batch: batchOrType,
                callback
            });
            if (this._pendingChanges.length == 1) {
                this._runPendingChanges();
            }
        } catch (err) {
            // @if CK_DEBUG // throw err;
            /* istanbul ignore next -- @preserve */ CKEditorError.rethrowUnexpectedError(err, this);
        }
    }
    /**
	 * {@link module:utils/observablemixin~Observable#decorate Decorated} function for applying
	 * {@link module:engine/model/operation/operation~Operation operations} to the model.
	 *
	 * This is a low-level way of changing the model. It is exposed for very specific use cases (like the undo feature).
	 * Normally, to modify the model, you will want to use {@link module:engine/model/writer~Writer `Writer`}.
	 * See also {@glink framework/architecture/editing-engine#changing-the-model Changing the model} section
	 * of the {@glink framework/architecture/editing-engine Editing architecture} guide.
	 *
	 * @param operation The operation to apply.
	 */ applyOperation(operation) {
        // @if CK_DEBUG_ENGINE // console.log( 'Applying ' + operation );
        // @if CK_DEBUG_ENGINE // this._operationLogs.push( JSON.stringify( operation ) );
        // @if CK_DEBUG_ENGINE // this._appliedOperations.push( operation );
        operation._execute();
    }
    // @if CK_DEBUG_ENGINE // public getAppliedOperation(): string {
    // @if CK_DEBUG_ENGINE // 	if ( !this._appliedOperations ) {
    // @if CK_DEBUG_ENGINE // 		return '';
    // @if CK_DEBUG_ENGINE // 	}
    // @if CK_DEBUG_ENGINE // 	return this._appliedOperations.map( operation => JSON.stringify( operation ) ).join( '-------' );
    // @if CK_DEBUG_ENGINE // }
    // @if CK_DEBUG_ENGINE // public createReplayer( stringifiedOperations: string ): typeof OperationReplayer {
    // @if CK_DEBUG_ENGINE // 	return new OperationReplayer( this, '-------', stringifiedOperations );
    // @if CK_DEBUG_ENGINE // }
    /**
	 * Inserts content at the position in the editor specified by the selection, as one would expect the paste
	 * functionality to work.
	 *
	 * **Note**: If you want to insert an {@glink framework/deep-dive/schema#object-elements object element}
	 * (e.g. a {@link module:widget/utils~toWidget widget}), see {@link #insertObject} instead.
	 *
	 * This is a high-level method. It takes the {@link #schema schema} into consideration when inserting
	 * the content, clears the given selection's content before inserting nodes and moves the selection
	 * to its target position at the end of the process.
	 * It can split elements, merge them, wrap bare text nodes with paragraphs, etc. &ndash; just like the
	 * pasting feature should do.
	 *
	 * For lower-level methods see {@link module:engine/model/writer~Writer `Writer`}.
	 *
	 * This method, unlike {@link module:engine/model/writer~Writer `Writer`}'s methods, does not have to be used
	 * inside a {@link #change `change()` block}.
	 *
	 * # Conversion and schema
	 *
	 * Inserting elements and text nodes into the model is not enough to make CKEditor 5 render that content
	 * to the user. CKEditor 5 implements a model-view-controller architecture and what `model.insertContent()` does
	 * is only adding nodes to the model. Additionally, you need to define
	 * {@glink framework/architecture/editing-engine#conversion converters} between the model and view
	 * and define those nodes in the {@glink framework/architecture/editing-engine#schema schema}.
	 *
	 * So, while this method may seem similar to CKEditor 4 `editor.insertHtml()` (in fact, both methods
	 * are used for paste-like content insertion), the CKEditor 5 method cannot be use to insert arbitrary HTML
	 * unless converters are defined for all elements and attributes in that HTML.
	 *
	 * # Examples
	 *
	 * Using `insertContent()` with a manually created model structure:
	 *
	 * ```ts
	 * // Let's create a document fragment containing such content as:
	 * //
	 * // <paragraph>foo</paragraph>
	 * // <blockQuote>
	 * //    <paragraph>bar</paragraph>
	 * // </blockQuote>
	 * const docFrag = editor.model.change( writer => {
	 * 	const p1 = writer.createElement( 'paragraph' );
	 * 	const p2 = writer.createElement( 'paragraph' );
	 * 	const blockQuote = writer.createElement( 'blockQuote' );
	 * 	const docFrag = writer.createDocumentFragment();
	 *
	 * 	writer.append( p1, docFrag );
	 * 	writer.append( blockQuote, docFrag );
	 * 	writer.append( p2, blockQuote );
	 * 	writer.insertText( 'foo', p1 );
	 * 	writer.insertText( 'bar', p2 );
	 *
	 * 	return docFrag;
	 * } );
	 *
	 * // insertContent() does not have to be used in a change() block. It can, though,
	 * // so this code could be moved to the callback defined above.
	 * editor.model.insertContent( docFrag );
	 * ```
	 *
	 * Using `insertContent()` with an HTML string converted to a model document fragment (similar to the pasting mechanism):
	 *
	 * ```ts
	 * // You can create your own HtmlDataProcessor instance or use editor.data.processor
	 * // if you have not overridden the default one (which is the HtmlDataProcessor instance).
	 * const htmlDP = new HtmlDataProcessor( viewDocument );
	 *
	 * // Convert an HTML string to a view document fragment:
	 * const viewFragment = htmlDP.toView( htmlString );
	 *
	 * // Convert the view document fragment to a model document fragment
	 * // in the context of $root. This conversion takes the schema into
	 * // account so if, for example, the view document fragment contained a bare text node,
	 * // this text node cannot be a child of $root, so it will be automatically
	 * // wrapped with a <paragraph>. You can define the context yourself (in the second parameter),
	 * // and e.g. convert the content like it would happen in a <paragraph>.
	 * // Note: The clipboard feature uses a custom context called $clipboardHolder
	 * // which has a loosened schema.
	 * const modelFragment = editor.data.toModel( viewFragment );
	 *
	 * editor.model.insertContent( modelFragment );
	 * ```
	 *
	 * By default this method will use the document selection but it can also be used with a position, range or selection instance.
	 *
	 * ```ts
	 * // Insert text at the current document selection position.
	 * editor.model.change( writer => {
	 * 	editor.model.insertContent( writer.createText( 'x' ) );
	 * } );
	 *
	 * // Insert text at a given position - the document selection will not be modified.
	 * editor.model.change( writer => {
	 * 	editor.model.insertContent( writer.createText( 'x' ), doc.getRoot(), 2 );
	 *
	 * 	// Which is a shorthand for:
	 * 	editor.model.insertContent( writer.createText( 'x' ), writer.createPositionAt( doc.getRoot(), 2 ) );
	 * } );
	 * ```
	 *
	 * If you want the document selection to be moved to the inserted content, use the
	 * {@link module:engine/model/writer~Writer#setSelection `setSelection()`} method of the writer after inserting
	 * the content:
	 *
	 * ```ts
	 * editor.model.change( writer => {
	 * 	const paragraph = writer.createElement( 'paragraph' );
	 *
	 * 	// Insert an empty paragraph at the beginning of the root.
	 * 	editor.model.insertContent( paragraph, writer.createPositionAt( editor.model.document.getRoot(), 0 ) );
	 *
	 * 	// Move the document selection to the inserted paragraph.
	 * 	writer.setSelection( paragraph, 'in' );
	 * } );
	 * ```
	 *
	 * If an instance of the {@link module:engine/model/selection~Selection model selection} is passed as `selectable`,
	 * the new content will be inserted at the passed selection (instead of document selection):
	 *
	 * ```ts
	 * editor.model.change( writer => {
	 * 	// Create a selection in a paragraph that will be used as a place of insertion.
	 * 	const selection = writer.createSelection( paragraph, 'in' );
	 *
	 * 	// Insert the new text at the created selection.
	 * 	editor.model.insertContent( writer.createText( 'x' ), selection );
	 *
	 * 	// insertContent() modifies the passed selection instance so it can be used to set the document selection.
	 * 	// Note: This is not necessary when you passed the document selection to insertContent().
	 * 	writer.setSelection( selection );
	 * } );
	 * ```
	 *
	 * @fires insertContent
	 * @param content The content to insert.
	 * @param selectable The selection into which the content should be inserted.
	 * If not provided the current model document selection will be used.
	 * @param placeOrOffset To be used when a model item was passed as `selectable`.
	 * This param defines a position in relation to that item.
	 * at the insertion position.
	 */ insertContent(content, selectable, placeOrOffset, ...rest) {
        const selection = normalizeSelectable(selectable, placeOrOffset);
        // Passing all call arguments so it acts like decorated method.
        return this.fire('insertContent', [
            content,
            selection,
            placeOrOffset,
            ...rest
        ]);
    }
    /**
	 * Inserts an {@glink framework/deep-dive/schema#object-elements object element} at a specific position in the editor content.
	 *
	 * This is a high-level API:
	 * * It takes the {@link #schema schema} into consideration,
	 * * It clears the content of passed `selectable` before inserting,
	 * * It can move the selection at the end of the process,
	 * * It will copy the selected block's attributes to preserve them upon insertion,
	 * * It can split elements or wrap inline objects with paragraphs if they are not allowed in target position,
	 * * etc.
	 *
	 * # Notes
	 *
	 * * If you want to insert a non-object content, see {@link #insertContent} instead.
	 * * For lower-level API, see {@link module:engine/model/writer~Writer `Writer`}.
	 * * Unlike {@link module:engine/model/writer~Writer `Writer`}, this method does not have to be used inside
	 * a {@link #change `change()` block}.
	 * * Inserting object into the model is not enough to make CKEditor 5 render that content to the user.
	 * CKEditor 5 implements a model-view-controller architecture and what `model.insertObject()` does
	 * is only adding nodes to the model. Additionally, you need to define
	 * {@glink framework/architecture/editing-engine#conversion converters} between the model and view
	 * and define those nodes in the {@glink framework/architecture/editing-engine#schema schema}.
	 *
	 * # Examples
	 *
	 * Use the following code to insert an object at the current selection and keep the selection on the inserted element:
	 *
	 * ```ts
	 * const rawHtmlEmbedElement = writer.createElement( 'rawHtml' );
	 *
	 * model.insertObject( rawHtmlEmbedElement, null, null, {
	 * 	setSelection: 'on'
	 * } );
	 * ```
	 *
	 * Use the following code to insert an object at the current selection and nudge the selection after the inserted object:
	 *
	 * ```ts
	 * const pageBreakElement = writer.createElement( 'pageBreak' );
 	 *
	 * model.insertObject( pageBreakElement, null, null, {
	 * 	setSelection: 'after'
	 * } );
	 * ```
	 *
	 * Use the following code to insert an object at the current selection and avoid splitting the content (non-destructive insertion):
	 *
	 * ```ts
	 * const tableElement = writer.createElement( 'table' );
 	 *
	 * model.insertObject( tableElement, null, null, {
	 * 	findOptimalPosition: 'auto'
	 * } );
	 * ```
	 *
	 * Use the following code to insert an object at the specific range (also: replace the content of the range):
	 *
	 * ```ts
	 * const tableElement = writer.createElement( 'table' );
	 * const range = model.createRangeOn( model.document.getRoot().getChild( 1 ) );
 	 *
	 * model.insertObject( tableElement, range );
	 * ```
	 *
	 * @param element An object to be inserted into the model document.
	 * @param selectable A selectable where the content should be inserted. If not specified, the current
	 * {@link module:engine/model/document~Document#selection document selection} will be used instead.
	 * @param placeOrOffset Specifies the exact place or offset for the insertion to take place, relative to `selectable`.
	 * @param options Additional options.
	 * @param options.findOptimalPosition An option that, when set, adjusts the insertion position (relative to
	 * `selectable` and `placeOrOffset`) so that the content of `selectable` is not split upon insertion (a.k.a. non-destructive insertion).
	 * * When `'auto'`, the algorithm will decide whether to insert the object before or after `selectable` to avoid content splitting.
	 * * When `'before'`, the closest position before `selectable` will be used that will not result in content splitting.
	 * * When `'after'`, the closest position after `selectable` will be used that will not result in content splitting.
	 *
	 * Note that this option only works for block objects. Inline objects are inserted into text and do not split blocks.
	 * @param options.setSelection An option that, when set, moves the
	 * {@link module:engine/model/document~Document#selection document selection} after inserting the object.
	 * * When `'on'`, the document selection will be set on the inserted object.
	 * * When `'after'`, the document selection will move to the closest text node after the inserted object. If there is no
	 * such text node, a paragraph will be created and the document selection will be moved inside it.
	 * at the insertion position.
	 */ insertObject(element, selectable, placeOrOffset, options, ...rest) {
        const selection = normalizeSelectable(selectable, placeOrOffset);
        // Note that options are fired as 2 arguments for backward compatibility with the decorated method.
        // Passing all call arguments so it acts like decorated method.
        return this.fire('insertObject', [
            element,
            selection,
            options,
            options,
            ...rest
        ]);
    }
    /**
	 * Deletes content of the selection and merge siblings. The resulting selection is always collapsed.
	 *
	 * **Note:** For the sake of predictability, the resulting selection should always be collapsed.
	 * In cases where a feature wants to modify deleting behavior so selection isn't collapsed
	 * (e.g. a table feature may want to keep row selection after pressing <kbd>Backspace</kbd>),
	 * then that behavior should be implemented in the view's listener. At the same time, the table feature
	 * will need to modify this method's behavior too, e.g. to "delete contents and then collapse
	 * the selection inside the last selected cell" or "delete the row and collapse selection somewhere near".
	 * That needs to be done in order to ensure that other features which use `deleteContent()` will work well with tables.
	 *
	 * @fires deleteContent
	 * @param selection Selection of which the content should be deleted.
	 * @param options.leaveUnmerged Whether to merge elements after removing the content of the selection.
	 *
	 * For example `<heading1>x[x</heading1><paragraph>y]y</paragraph>` will become:
	 *
	 * * `<heading1>x^y</heading1>` with the option disabled (`leaveUnmerged == false`)
	 * * `<heading1>x^</heading1><paragraph>y</paragraph>` with enabled (`leaveUnmerged == true`).
	 *
	 * Note: {@link module:engine/model/schema~Schema#isObject object} and {@link module:engine/model/schema~Schema#isLimit limit}
	 * elements will not be merged.
	 *
	 * @param options.doNotResetEntireContent Whether to skip replacing the entire content with a
	 * paragraph when the entire content was selected.
	 *
	 * For example `<heading1>[x</heading1><paragraph>y]</paragraph>` will become:
	 *
	 * * `<paragraph>^</paragraph>` with the option disabled (`doNotResetEntireContent == false`)
	 * * `<heading1>^</heading1>` with enabled (`doNotResetEntireContent == true`)
	 *
	 * @param options.doNotAutoparagraph Whether to create a paragraph if after content deletion selection is moved
	 * to a place where text cannot be inserted.
	 *
	 * For example `<paragraph>x</paragraph>[<imageBlock src="foo.jpg"></imageBlock>]` will become:
	 *
	 * * `<paragraph>x</paragraph><paragraph>[]</paragraph>` with the option disabled (`doNotAutoparagraph == false`)
	 * * `<paragraph>x[]</paragraph>` with the option enabled (`doNotAutoparagraph == true`).
	 *
	 * **Note:** if there is no valid position for the selection, the paragraph will always be created:
	 *
	 * `[<imageBlock src="foo.jpg"></imageBlock>]` -> `<paragraph>[]</paragraph>`.
	 *
	 * @param options.direction The direction in which the content is being consumed.
	 * Deleting backward corresponds to using the <kbd>Backspace</kbd> key, while deleting content forward corresponds to
	 * the <kbd>Shift</kbd>+<kbd>Backspace</kbd> keystroke.
	 */ deleteContent(selection, options) {
        deleteContent(this, selection, options);
    }
    /**
	 * Modifies the selection. Currently, the supported modifications are:
	 *
	 * * Extending. The selection focus is moved in the specified `options.direction` with a step specified in `options.unit`.
	 * Possible values for `unit` are:
	 *  * `'character'` (default) - moves selection by one user-perceived character. In most cases this means moving by one
	 *  character in `String` sense. However, unicode also defines "combing marks". These are special symbols, that combines
	 *  with a symbol before it ("base character") to create one user-perceived character. For example, `q̣̇` is a normal
	 *  letter `q` with two "combining marks": upper dot (`Ux0307`) and lower dot (`Ux0323`). For most actions, i.e. extending
	 *  selection by one position, it is correct to include both "base character" and all of it's "combining marks". That is
	 *  why `'character'` value is most natural and common method of modifying selection.
	 *  * `'codePoint'` - moves selection by one unicode code point. In contrary to, `'character'` unit, this will insert
	 *  selection between "base character" and "combining mark", because "combining marks" have their own unicode code points.
	 *  However, for technical reasons, unicode code points with values above `UxFFFF` are represented in native `String` by
	 *  two characters, called "surrogate pairs". Halves of "surrogate pairs" have a meaning only when placed next to each other.
	 *  For example `𨭎` is represented in `String` by `\uD862\uDF4E`. Both `\uD862` and `\uDF4E` do not have any meaning
	 *  outside the pair (are rendered as ? when alone). Position between them would be incorrect. In this case, selection
	 *  extension will include whole "surrogate pair".
	 *  * `'word'` - moves selection by a whole word.
	 *
	 * **Note:** if you extend a forward selection in a backward direction you will in fact shrink it.
	 *
	 * @fires modifySelection
	 * @param selection The selection to modify.
	 * @param options.direction The direction in which the selection should be modified.
	 * @param options.unit The unit by which selection should be modified.
	 * @param options.treatEmojiAsSingleUnit Whether multi-characer emoji sequences should be handled as single unit.
	 */ modifySelection(selection, options) {
        modifySelection(this, selection, options);
    }
    /**
	 * Gets a clone of the selected content.
	 *
	 * For example, for the following selection:
	 *
	 * ```html
	 * <paragraph>x</paragraph>
	 * <blockQuote>
	 * 	<paragraph>y</paragraph>
	 * 	<heading1>fir[st</heading1>
	 * </blockQuote>
	 * <paragraph>se]cond</paragraph>
	 * <paragraph>z</paragraph>
	 * ```
	 *
	 * It will return a document fragment with such a content:
	 *
	 * ```html
	 * <blockQuote>
	 * 	<heading1>st</heading1>
	 * </blockQuote>
	 * <paragraph>se</paragraph>
	 * ```
	 *
	 * @fires getSelectedContent
	 * @param selection The selection of which content will be returned.
	 */ getSelectedContent(selection) {
        return getSelectedContent(this, selection);
    }
    /**
	 * Checks whether the given {@link module:engine/model/range~Range range} or
	 * {@link module:engine/model/element~Element element} has any meaningful content.
	 *
	 * Meaningful content is:
	 *
	 * * any text node (`options.ignoreWhitespaces` allows controlling whether this text node must also contain
	 * any non-whitespace characters),
	 * * or any {@link module:engine/model/schema~Schema#isContent content element},
	 * * or any {@link module:engine/model/markercollection~Marker marker} which
	 * {@link module:engine/model/markercollection~Marker#_affectsData affects data}.
	 *
	 * This means that a range containing an empty `<paragraph></paragraph>` is not considered to have a meaningful content.
	 * However, a range containing an `<imageBlock></imageBlock>` (which would normally be marked in the schema as an object element)
	 * is considered non-empty.
	 *
	 * @param rangeOrElement Range or element to check.
	 * @param options.ignoreWhitespaces Whether text node with whitespaces only should be considered empty.
	 * @param options.ignoreMarkers Whether markers should be ignored.
	 */ hasContent(rangeOrElement, options = {}) {
        const range = rangeOrElement instanceof Range ? rangeOrElement : Range._createIn(rangeOrElement);
        if (range.isCollapsed) {
            return false;
        }
        const { ignoreWhitespaces = false, ignoreMarkers = false } = options;
        // Check if there are any markers which affects data in this given range.
        if (!ignoreMarkers) {
            for (const intersectingMarker of this.markers.getMarkersIntersectingRange(range)){
                if (intersectingMarker.affectsData) {
                    return true;
                }
            }
        }
        for (const item of range.getItems()){
            if (this.schema.isContent(item)) {
                if (item.is('$textProxy')) {
                    if (!ignoreWhitespaces) {
                        return true;
                    } else if (item.data.search(/\S/) !== -1) {
                        return true;
                    }
                } else {
                    return true;
                }
            }
        }
        return false;
    }
    /**
	 * Check whether given selectable is at a place in the model where it can be edited (returns `true`) or not (returns `false`).
	 *
	 * Should be used instead of {@link module:core/editor/editor~Editor#isReadOnly} to check whether a user action can happen at
	 * given selectable. It may be decorated and used differently in different environment (e.g. multi-root editor can disable
	 * a particular root).
	 *
	 * This method is decorated. Although this method accepts any parameter of `Selectable` type, the
	 * {@link ~Model#event:canEditAt `canEditAt` event} is fired with `selectable` normalized to an instance of
	 * {@link module:engine/model/selection~Selection} or {@link module:engine/model/documentselection~DocumentSelection}
	 *
	 * @fires canEditAt
	 */ canEditAt(selectable) {
        const selection = normalizeSelectable(selectable);
        return this.fire('canEditAt', [
            selection
        ]);
    }
    /**
	 * Creates a position from the given root and path in that root.
	 *
	 * Note: This method is also available as
	 * {@link module:engine/model/writer~Writer#createPositionFromPath `Writer#createPositionFromPath()`}.
	 *
	 * @param root Root of the position.
	 * @param path Position path. See {@link module:engine/model/position~Position#path}.
	 * @param stickiness Position stickiness. See {@link module:engine/model/position~PositionStickiness}.
	 */ createPositionFromPath(root, path, stickiness) {
        return new Position(root, path, stickiness);
    }
    /**
	 * Creates position at the given location. The location can be specified as:
	 *
	 * * a {@link module:engine/model/position~Position position},
	 * * a parent element and offset in that element,
	 * * a parent element and `'end'` (the position will be set at the end of that element),
	 * * a {@link module:engine/model/item~Item model item} and `'before'` or `'after'`
	 * (the position will be set before or after the given model item).
	 *
	 * This method is a shortcut to other factory methods such as:
	 *
	 * * {@link module:engine/model/model~Model#createPositionBefore `createPositionBefore()`},
	 * * {@link module:engine/model/model~Model#createPositionAfter `createPositionAfter()`}.
	 *
	 * Note: This method is also available as
	 * {@link module:engine/model/writer~Writer#createPositionAt `Writer#createPositionAt()`},
	 *
	 * @param itemOrPosition
	 * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/model/item~Item model item}.
	 */ createPositionAt(itemOrPosition, offset) {
        return Position._createAt(itemOrPosition, offset);
    }
    /**
	 * Creates a new position after the given {@link module:engine/model/item~Item model item}.
	 *
	 * Note: This method is also available as
	 * {@link module:engine/model/writer~Writer#createPositionAfter `Writer#createPositionAfter()`}.
	 *
	 * @param item Item after which the position should be placed.
	 */ createPositionAfter(item) {
        return Position._createAfter(item);
    }
    /**
	 * Creates a new position before the given {@link module:engine/model/item~Item model item}.
	 *
	 * Note: This method is also available as
	 * {@link module:engine/model/writer~Writer#createPositionBefore `Writer#createPositionBefore()`}.
	 *
	 * @param item Item before which the position should be placed.
	 */ createPositionBefore(item) {
        return Position._createBefore(item);
    }
    /**
	 * Creates a range spanning from the `start` position to the `end` position.
	 *
	 * Note: This method is also available as
	 * {@link module:engine/model/writer~Writer#createRange `Writer#createRange()`}:
	 *
	 * ```ts
	 * model.change( writer => {
	 * 	const range = writer.createRange( start, end );
	 * } );
	 * ```
	 *
	 * @param start Start position.
	 * @param end End position. If not set, the range will be collapsed to the `start` position.
	 */ createRange(start, end) {
        return new Range(start, end);
    }
    /**
	 * Creates a range inside the given element which starts before the first child of
	 * that element and ends after the last child of that element.
	 *
	 * Note: This method is also available as
	 * {@link module:engine/model/writer~Writer#createRangeIn `Writer#createRangeIn()`}:
	 *
	 * ```ts
	 * model.change( writer => {
	 * 	const range = writer.createRangeIn( paragraph );
	 * } );
	 * ```
	 *
	 * @param element Element which is a parent for the range.
	 */ createRangeIn(element) {
        return Range._createIn(element);
    }
    /**
	 * Creates a range that starts before the given {@link module:engine/model/item~Item model item} and ends after it.
	 *
	 * Note: This method is also available on `writer` instance as
	 * {@link module:engine/model/writer~Writer#createRangeOn `Writer.createRangeOn()`}:
	 *
	 * ```ts
	 * model.change( writer => {
	 * 	const range = writer.createRangeOn( paragraph );
	 * } );
	 * ```
	 *
	 * @param item
	 */ createRangeOn(item) {
        return Range._createOn(item);
    }
    createSelection(...args) {
        return new Selection(...args);
    }
    /**
	 * Creates a {@link module:engine/model/batch~Batch} instance.
	 *
	 * **Note:** In most cases creating a batch instance is not necessary as they are created when using:
	 *
	 * * {@link #change `change()`},
	 * * {@link #enqueueChange `enqueueChange()`}.
	 *
	 * @param type {@link module:engine/model/batch~Batch#constructor The type} of the batch.
	 */ createBatch(type) {
        return new Batch(type);
    }
    /**
	 * Creates an operation instance from a JSON object (parsed JSON string).
	 *
	 * This is an alias for {@link module:engine/model/operation/operationfactory~OperationFactory.fromJSON `OperationFactory.fromJSON()`}.
	 *
	 * @param json Deserialized JSON object.
	 */ createOperationFromJSON(json) {
        return OperationFactory.fromJSON(json, this.document);
    }
    /**
	 * Removes all events listeners set by model instance and destroys {@link module:engine/model/document~Document}.
	 */ destroy() {
        this.document.destroy();
        this.stopListening();
    }
    /**
	 * Common part of {@link module:engine/model/model~Model#change} and {@link module:engine/model/model~Model#enqueueChange}
	 * which calls callbacks and returns array of values returned by these callbacks.
	 */ _runPendingChanges() {
        const ret = [];
        this.fire('_beforeChanges');
        try {
            while(this._pendingChanges.length){
                // Create a new writer using batch instance created for this chain of changes.
                const currentBatch = this._pendingChanges[0].batch;
                this._currentWriter = new Writer(this, currentBatch);
                // Execute changes callback and gather the returned value.
                const callbackReturnValue = this._pendingChanges[0].callback(this._currentWriter);
                ret.push(callbackReturnValue);
                this.document._handleChangeBlock(this._currentWriter);
                this._pendingChanges.shift();
                this._currentWriter = null;
            }
        } finally{
            this._pendingChanges.length = 0;
            this._currentWriter = null;
            this.fire('_afterChanges');
        }
        return ret;
    }
}
/**
 * Normalizes a selectable to a Selection or DocumentSelection.
 */ function normalizeSelectable(selectable, placeOrOffset) {
    if (!selectable) {
        return;
    }
    if (selectable instanceof Selection || selectable instanceof DocumentSelection) {
        return selectable;
    }
    if (selectable instanceof Node$1) {
        if (placeOrOffset || placeOrOffset === 0) {
            return new Selection(selectable, placeOrOffset);
        } else if (selectable.is('rootElement')) {
            return new Selection(selectable, 'in');
        } else {
            return new Selection(selectable, 'on');
        }
    }
    return new Selection(selectable);
}

/**
 * {@link module:engine/view/document~Document#event:click Click} event observer.
 *
 * Note that this observer is not available by default. To make it available it needs to be added to
 * {@link module:engine/view/view~View view controller} by a {@link module:engine/view/view~View#addObserver} method.
 */ class ClickObserver extends DomEventObserver {
    /**
	 * @inheritDoc
	 */ domEventType = 'click';
    /**
	 * @inheritDoc
	 */ onDomEvent(domEvent) {
        this.fire(domEvent.type, domEvent);
    }
}

/**
 * Mouse events observer.
 *
 * Note that this observer is not available by default. To make it available it needs to be added to
 * {@link module:engine/view/view~View} by {@link module:engine/view/view~View#addObserver} method.
 */ class MouseObserver extends DomEventObserver {
    /**
	 * @inheritDoc
	 */ domEventType = [
        'mousedown',
        'mouseup',
        'mouseover',
        'mouseout'
    ];
    /**
	 * @inheritDoc
	 */ onDomEvent(domEvent) {
        this.fire(domEvent.type, domEvent);
    }
}

/**
 * View upcast writer. It provides a set of methods used to manipulate non-semantic view trees.
 *
 * It should be used only while working on a non-semantic view
 * (e.g. a view created from HTML string on paste).
 * To manipulate a view which was or is being downcasted from the the model use the
 * {@link module:engine/view/downcastwriter~DowncastWriter downcast writer}.
 *
 * Read more about changing the view in the {@glink framework/architecture/editing-engine#changing-the-view Changing the view}
 * section of the {@glink framework/architecture/editing-engine Editing engine architecture} guide.
 *
 * Unlike `DowncastWriter`, which is available in the {@link module:engine/view/view~View#change `View#change()`} block,
 * `UpcastWriter` can be created wherever you need it:
 *
 * ```ts
 * const writer = new UpcastWriter( viewDocument );
 * const text = writer.createText( 'foo!' );
 *
 * writer.appendChild( text, someViewElement );
 * ```
 */ class UpcastWriter {
    /**
	 * The view document instance in which this upcast writer operates.
	 */ document;
    /**
	 * @param document The view document instance in which this upcast writer operates.
	 */ constructor(document){
        this.document = document;
    }
    /**
	 * Creates a new {@link module:engine/view/documentfragment~DocumentFragment} instance.
	 *
	 * @param children A list of nodes to be inserted into the created document fragment.
	 * @returns The created document fragment.
	 */ createDocumentFragment(children) {
        return new DocumentFragment$1(this.document, children);
    }
    /**
	 * Creates a new {@link module:engine/view/element~Element} instance.
	 *
	 * Attributes can be passed in various formats:
	 *
	 * ```ts
	 * upcastWriter.createElement( 'div', { class: 'editor', contentEditable: 'true' } ); // object
	 * upcastWriter.createElement( 'div', [ [ 'class', 'editor' ], [ 'contentEditable', 'true' ] ] ); // map-like iterator
	 * upcastWriter.createElement( 'div', mapOfAttributes ); // map
	 * ```
	 *
	 * @param name Node name.
	 * @param attrs Collection of attributes.
	 * @param children A list of nodes to be inserted into created element.
	 * @returns Created element.
	 */ createElement(name, attrs, children) {
        return new Element$1(this.document, name, attrs, children);
    }
    /**
	 * Creates a new {@link module:engine/view/text~Text} instance.
	 *
	 * @param data The text's data.
	 * @returns The created text node.
	 */ createText(data) {
        return new Text$1(this.document, data);
    }
    /**
	 * Clones the provided element.
	 *
	 * @see module:engine/view/element~Element#_clone
	 * @param element Element to be cloned.
	 * @param deep If set to `true` clones element and all its children recursively. When set to `false`,
	 * element will be cloned without any children.
	 * @returns Clone of this element.
	 */ clone(element, deep = false) {
        return element._clone(deep);
    }
    /**
	 * Appends a child node or a list of child nodes at the end of this node
	 * and sets the parent of these nodes to this element.
	 *
	 * @see module:engine/view/element~Element#_appendChild
	 * @param items Items to be inserted.
	 * @param element Element to which items will be appended.
	 * @returns Number of appended nodes.
	 */ appendChild(items, element) {
        return element._appendChild(items);
    }
    /**
	 * Inserts a child node or a list of child nodes on the given index and sets the parent of these nodes to
	 * this element.
	 *
	 * @see module:engine/view/element~Element#_insertChild
	 * @param index Offset at which nodes should be inserted.
	 * @param items Items to be inserted.
	 * @param element Element to which items will be inserted.
	 * @returns Number of inserted nodes.
	 */ insertChild(index, items, element) {
        return element._insertChild(index, items);
    }
    /**
	 * Removes the given number of child nodes starting at the given index and set the parent of these nodes to `null`.
	 *
	 * @see module:engine/view/element~Element#_removeChildren
	 * @param index Offset from which nodes will be removed.
	 * @param howMany Number of nodes to remove.
	 * @param element Element which children will be removed.
	 * @returns The array containing removed nodes.
	 */ removeChildren(index, howMany, element) {
        return element._removeChildren(index, howMany);
    }
    /**
	 * Removes given element from the view structure. Will not have effect on detached elements.
	 *
	 * @param element Element which will be removed.
	 * @returns The array containing removed nodes.
	 */ remove(element) {
        const parent = element.parent;
        if (parent) {
            return this.removeChildren(parent.getChildIndex(element), 1, parent);
        }
        return [];
    }
    /**
	 * Replaces given element with the new one in the view structure. Will not have effect on detached elements.
	 *
	 * @param oldElement Element which will be replaced.
	 * @param newElement Element which will be inserted in the place of the old element.
	 * @returns Whether old element was successfully replaced.
	 */ replace(oldElement, newElement) {
        const parent = oldElement.parent;
        if (parent) {
            const index = parent.getChildIndex(oldElement);
            this.removeChildren(index, 1, parent);
            this.insertChild(index, newElement, parent);
            return true;
        }
        return false;
    }
    /**
	 * Removes given element from view structure and places its children in its position.
	 * It does nothing if element has no parent.
	 *
	 * @param element Element to unwrap.
	 */ unwrapElement(element) {
        const parent = element.parent;
        if (parent) {
            const index = parent.getChildIndex(element);
            this.remove(element);
            this.insertChild(index, element.getChildren(), parent);
        }
    }
    /**
	 * Renames element by creating a copy of a given element but with its name changed and then moving contents of the
	 * old element to the new one.
	 *
	 * Since this function creates a new element and removes the given one, the new element is returned to keep reference.
	 *
	 * @param newName New element name.
	 * @param  element Element to be renamed.
	 * @returns New element or null if the old element was not replaced (happens for detached elements).
	 */ rename(newName, element) {
        const newElement = new Element$1(this.document, newName, element.getAttributes(), element.getChildren());
        return this.replace(element, newElement) ? newElement : null;
    }
    /**
	 * Adds or overwrites element's attribute with a specified key and value.
	 *
	 * ```ts
	 * writer.setAttribute( 'href', 'http://ckeditor.com', linkElement );
	 * ```
	 *
	 * @see module:engine/view/element~Element#_setAttribute
	 * @param key Attribute key.
	 * @param value Attribute value.
	 * @param element Element for which attribute will be set.
	 */ setAttribute(key, value, element) {
        element._setAttribute(key, value);
    }
    /**
	 * Removes attribute from the element.
	 *
	 * ```ts
	 * writer.removeAttribute( 'href', linkElement );
	 * ```
	 *
	 * @see module:engine/view/element~Element#_removeAttribute
	 * @param key Attribute key.
	 * @param element Element from which attribute will be removed.
	 */ removeAttribute(key, element) {
        element._removeAttribute(key);
    }
    /**
	 * Adds specified class to the element.
	 *
	 * ```ts
	 * writer.addClass( 'foo', linkElement );
	 * writer.addClass( [ 'foo', 'bar' ], linkElement );
	 * ```
	 *
	 * @see module:engine/view/element~Element#_addClass
	 * @param className Single class name or array of class names which will be added.
	 * @param element Element for which class will be added.
	 */ addClass(className, element) {
        element._addClass(className);
    }
    /**
	 * Removes specified class from the element.
	 *
	 * ```ts
	 * writer.removeClass( 'foo', linkElement );
	 * writer.removeClass( [ 'foo', 'bar' ], linkElement );
	 * ```
	 *
	 * @see module:engine/view/element~Element#_removeClass
	 * @param className Single class name or array of class names which will be removed.
	 * @param element Element from which class will be removed.
	 */ removeClass(className, element) {
        element._removeClass(className);
    }
    setStyle(property, valueOrElement, element) {
        if (isPlainObject(property) && element === undefined) {
            valueOrElement._setStyle(property);
        } else {
            element._setStyle(property, valueOrElement);
        }
    }
    /**
	 * Removes specified style from the element.
	 *
	 * ```ts
	 * writer.removeStyle( 'color', element );  // Removes 'color' style.
	 * writer.removeStyle( [ 'color', 'border-top' ], element ); // Removes both 'color' and 'border-top' styles.
	 * ```
	 *
	 * **Note**: This method can work with normalized style names if
	 * {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules a particular style processor rule is enabled}.
	 * See {@link module:engine/view/stylesmap~StylesMap#remove `StylesMap#remove()`} for details.
	 *
	 * @see module:engine/view/element~Element#_removeStyle
	 * @param property Style property name or names to be removed.
	 * @param element Element from which style will be removed.
	 */ removeStyle(property, element) {
        element._removeStyle(property);
    }
    /**
	 * Sets a custom property on element. Unlike attributes, custom properties are not rendered to the DOM,
	 * so they can be used to add special data to elements.
	 *
	 * @see module:engine/view/element~Element#_setCustomProperty
	 * @param key Custom property name/key.
	 * @param value Custom property value to be stored.
	 * @param element Element for which custom property will be set.
	 */ setCustomProperty(key, value, element) {
        element._setCustomProperty(key, value);
    }
    /**
	 * Removes a custom property stored under the given key.
	 *
	 * @see module:engine/view/element~Element#_removeCustomProperty
	 * @param key Name/key of the custom property to be removed.
	 * @param element Element from which the custom property will be removed.
	 * @returns Returns true if property was removed.
	 */ removeCustomProperty(key, element) {
        return element._removeCustomProperty(key);
    }
    /**
	 * Creates position at the given location. The location can be specified as:
	 *
	 * * a {@link module:engine/view/position~Position position},
	 * * parent element and offset (offset defaults to `0`),
	 * * parent element and `'end'` (sets position at the end of that element),
	 * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
	 *
	 * This method is a shortcut to other constructors such as:
	 *
	 * * {@link #createPositionBefore},
	 * * {@link #createPositionAfter},
	 *
	 * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/view/item~Item view item}.
	 */ createPositionAt(itemOrPosition, offset) {
        return Position$1._createAt(itemOrPosition, offset);
    }
    /**
	 * Creates a new position after given view item.
	 *
	 * @param item View item after which the position should be located.
	 */ createPositionAfter(item) {
        return Position$1._createAfter(item);
    }
    /**
	 * Creates a new position before given view item.
	 *
	 * @param item View item before which the position should be located.
	 */ createPositionBefore(item) {
        return Position$1._createBefore(item);
    }
    /**
	 * Creates a range spanning from `start` position to `end` position.
	 *
	 * **Note:** This factory method creates it's own {@link module:engine/view/position~Position} instances basing on passed values.
	 *
	 * @param start Start position.
	 * @param end End position. If not set, range will be collapsed at `start` position.
	 */ createRange(start, end) {
        return new Range$1(start, end);
    }
    /**
	 * Creates a range that starts before given {@link module:engine/view/item~Item view item} and ends after it.
	 */ createRangeOn(item) {
        return Range$1._createOn(item);
    }
    /**
	 * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
	 * that element and ends after the last child of that element.
	 *
	 * @param element Element which is a parent for the range.
	 */ createRangeIn(element) {
        return Range$1._createIn(element);
    }
    createSelection(...args) {
        return new Selection$1(...args);
    }
}

/**
 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */ /**
 * @module engine/view/styles/utils
 */ const HEX_COLOR_REGEXP = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
const RGB_COLOR_REGEXP = /^rgb\([ ]?([0-9]{1,3}[ %]?,[ ]?){2,3}[0-9]{1,3}[ %]?\)$/i;
const RGBA_COLOR_REGEXP = /^rgba\([ ]?([0-9]{1,3}[ %]?,[ ]?){3}(1|[0-9]+%|[0]?\.?[0-9]+)\)$/i;
const HSL_COLOR_REGEXP = /^hsl\([ ]?([0-9]{1,3}[ %]?[,]?[ ]*){3}(1|[0-9]+%|[0]?\.?[0-9]+)?\)$/i;
const HSLA_COLOR_REGEXP = /^hsla\([ ]?([0-9]{1,3}[ %]?,[ ]?){2,3}(1|[0-9]+%|[0]?\.?[0-9]+)\)$/i;
// Note: This regexp hardcodes a single level of nested () for values such as `calc( var( ...) + ...)`.
// If this gets more complex, a proper parser should be used instead.
const CSS_SHORTHAND_VALUE_REGEXP = /\w+\((?:[^()]|\([^()]*\))*\)|\S+/gi;
const COLOR_NAMES = new Set([
    // CSS Level 1
    'black',
    'silver',
    'gray',
    'white',
    'maroon',
    'red',
    'purple',
    'fuchsia',
    'green',
    'lime',
    'olive',
    'yellow',
    'navy',
    'blue',
    'teal',
    'aqua',
    // CSS Level 2 (Revision 1)
    'orange',
    // CSS Color Module Level 3
    'aliceblue',
    'antiquewhite',
    'aquamarine',
    'azure',
    'beige',
    'bisque',
    'blanchedalmond',
    'blueviolet',
    'brown',
    'burlywood',
    'cadetblue',
    'chartreuse',
    'chocolate',
    'coral',
    'cornflowerblue',
    'cornsilk',
    'crimson',
    'cyan',
    'darkblue',
    'darkcyan',
    'darkgoldenrod',
    'darkgray',
    'darkgreen',
    'darkgrey',
    'darkkhaki',
    'darkmagenta',
    'darkolivegreen',
    'darkorange',
    'darkorchid',
    'darkred',
    'darksalmon',
    'darkseagreen',
    'darkslateblue',
    'darkslategray',
    'darkslategrey',
    'darkturquoise',
    'darkviolet',
    'deeppink',
    'deepskyblue',
    'dimgray',
    'dimgrey',
    'dodgerblue',
    'firebrick',
    'floralwhite',
    'forestgreen',
    'gainsboro',
    'ghostwhite',
    'gold',
    'goldenrod',
    'greenyellow',
    'grey',
    'honeydew',
    'hotpink',
    'indianred',
    'indigo',
    'ivory',
    'khaki',
    'lavender',
    'lavenderblush',
    'lawngreen',
    'lemonchiffon',
    'lightblue',
    'lightcoral',
    'lightcyan',
    'lightgoldenrodyellow',
    'lightgray',
    'lightgreen',
    'lightgrey',
    'lightpink',
    'lightsalmon',
    'lightseagreen',
    'lightskyblue',
    'lightslategray',
    'lightslategrey',
    'lightsteelblue',
    'lightyellow',
    'limegreen',
    'linen',
    'magenta',
    'mediumaquamarine',
    'mediumblue',
    'mediumorchid',
    'mediumpurple',
    'mediumseagreen',
    'mediumslateblue',
    'mediumspringgreen',
    'mediumturquoise',
    'mediumvioletred',
    'midnightblue',
    'mintcream',
    'mistyrose',
    'moccasin',
    'navajowhite',
    'oldlace',
    'olivedrab',
    'orangered',
    'orchid',
    'palegoldenrod',
    'palegreen',
    'paleturquoise',
    'palevioletred',
    'papayawhip',
    'peachpuff',
    'peru',
    'pink',
    'plum',
    'powderblue',
    'rosybrown',
    'royalblue',
    'saddlebrown',
    'salmon',
    'sandybrown',
    'seagreen',
    'seashell',
    'sienna',
    'skyblue',
    'slateblue',
    'slategray',
    'slategrey',
    'snow',
    'springgreen',
    'steelblue',
    'tan',
    'thistle',
    'tomato',
    'turquoise',
    'violet',
    'wheat',
    'whitesmoke',
    'yellowgreen',
    // CSS Color Module Level 3 (System Colors)
    'activeborder',
    'activecaption',
    'appworkspace',
    'background',
    'buttonface',
    'buttonhighlight',
    'buttonshadow',
    'buttontext',
    'captiontext',
    'graytext',
    'highlight',
    'highlighttext',
    'inactiveborder',
    'inactivecaption',
    'inactivecaptiontext',
    'infobackground',
    'infotext',
    'menu',
    'menutext',
    'scrollbar',
    'threeddarkshadow',
    'threedface',
    'threedhighlight',
    'threedlightshadow',
    'threedshadow',
    'window',
    'windowframe',
    'windowtext',
    // CSS Color Module Level 4
    'rebeccapurple',
    // Keywords
    'currentcolor',
    'transparent'
]);
/**
 * Checks if string contains [color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) CSS value.
 *
 * ```ts
 * isColor( '#f00' );						// true
 * isColor( '#AA00BB33' );					// true
 * isColor( 'rgb(0, 0, 250)' );				// true
 * isColor( 'hsla(240, 100%, 50%, .7)' );	// true
 * isColor( 'deepskyblue' );				// true
 * ```
 *
 * **Note**: It does not support CSS Level 4 whitespace syntax, system colors and radius values for HSL colors.
 */ function isColor(string) {
    // As far as I was able to test checking some pre-conditions is faster than joining each test with ||.
    if (string.startsWith('#')) {
        return HEX_COLOR_REGEXP.test(string);
    }
    if (string.startsWith('rgb')) {
        return RGB_COLOR_REGEXP.test(string) || RGBA_COLOR_REGEXP.test(string);
    }
    if (string.startsWith('hsl')) {
        return HSL_COLOR_REGEXP.test(string) || HSLA_COLOR_REGEXP.test(string);
    }
    // Array check > RegExp test.
    return COLOR_NAMES.has(string.toLowerCase());
}
const lineStyleValues = [
    'none',
    'hidden',
    'dotted',
    'dashed',
    'solid',
    'double',
    'groove',
    'ridge',
    'inset',
    'outset'
];
/**
 * Checks if string contains [line style](https://developer.mozilla.org/en-US/docs/Web/CSS/border-style) CSS value.
 */ function isLineStyle(string) {
    return lineStyleValues.includes(string);
}
const lengthRegExp = /^([+-]?[0-9]*([.][0-9]+)?(px|cm|mm|in|pc|pt|ch|em|ex|rem|vh|vw|vmin|vmax)|0)$/;
/**
 * Checks if string contains [length](https://developer.mozilla.org/en-US/docs/Web/CSS/length) CSS value.
 */ function isLength(string) {
    return lengthRegExp.test(string);
}
const PERCENTAGE_VALUE_REGEXP = /^[+-]?[0-9]*([.][0-9]+)?%$/;
/**
 * Checks if string contains [percentage](https://developer.mozilla.org/en-US/docs/Web/CSS/percentage) CSS value.
 */ function isPercentage(string) {
    return PERCENTAGE_VALUE_REGEXP.test(string);
}
const repeatValues = [
    'repeat-x',
    'repeat-y',
    'repeat',
    'space',
    'round',
    'no-repeat'
];
/**
 * Checks if string contains [background repeat](https://developer.mozilla.org/en-US/docs/Web/CSS/background-repeat) CSS value.
 */ function isRepeat(string) {
    return repeatValues.includes(string);
}
const positionValues = [
    'center',
    'top',
    'bottom',
    'left',
    'right'
];
/**
 * Checks if string contains [background position](https://developer.mozilla.org/en-US/docs/Web/CSS/background-position) CSS value.
 */ function isPosition(string) {
    return positionValues.includes(string);
}
const attachmentValues = [
    'fixed',
    'scroll',
    'local'
];
/**
 * Checks if string contains [background attachment](https://developer.mozilla.org/en-US/docs/Web/CSS/background-attachment) CSS value.
 */ function isAttachment(string) {
    return attachmentValues.includes(string);
}
const urlRegExp = /^url\(/;
/**
 * Checks if string contains [URL](https://developer.mozilla.org/en-US/docs/Web/CSS/url) CSS value.
 */ function isURL(string) {
    return urlRegExp.test(string);
}
/**
 * Parses box sides as individual values.
 */ function getBoxSidesValues(value = '') {
    if (value === '') {
        return {
            top: undefined,
            right: undefined,
            bottom: undefined,
            left: undefined
        };
    }
    const values = getShorthandValues(value);
    const top = values[0];
    const bottom = values[2] || top;
    const right = values[1] || top;
    const left = values[3] || right;
    return {
        top,
        bottom,
        right,
        left
    };
}
/**
 * Default reducer for CSS properties that concerns edges of a box
 * [shorthand](https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties) notations:
 *
 * ```ts
 * stylesProcessor.setReducer( 'padding', getBoxSidesValueReducer( 'padding' ) );
 * ```
 */ function getBoxSidesValueReducer(styleShorthand) {
    return (value)=>{
        const { top, right, bottom, left } = value;
        const reduced = [];
        if (![
            top,
            right,
            left,
            bottom
        ].every((value)=>!!value)) {
            if (top) {
                reduced.push([
                    styleShorthand + '-top',
                    top
                ]);
            }
            if (right) {
                reduced.push([
                    styleShorthand + '-right',
                    right
                ]);
            }
            if (bottom) {
                reduced.push([
                    styleShorthand + '-bottom',
                    bottom
                ]);
            }
            if (left) {
                reduced.push([
                    styleShorthand + '-left',
                    left
                ]);
            }
        } else {
            reduced.push([
                styleShorthand,
                getBoxSidesShorthandValue(value)
            ]);
        }
        return reduced;
    };
}
/**
 * Returns a [shorthand](https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties) notation
 * of a CSS property value.
 *
 * ```ts
 * getBoxSidesShorthandValue( { top: '1px', right: '1px', bottom: '2px', left: '1px' } );
 * // will return '1px 1px 2px'
 * ```
 */ function getBoxSidesShorthandValue({ top, right, bottom, left }) {
    const out = [];
    if (left !== right) {
        out.push(top, right, bottom, left);
    } else if (bottom !== top) {
        out.push(top, right, bottom);
    } else if (right !== top) {
        out.push(top, right);
    } else {
        out.push(top);
    }
    return out.join(' ');
}
/**
 * Creates a normalizer for a [shorthand](https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties) 1-to-4 value.
 *
 * ```ts
 * stylesProcessor.setNormalizer( 'margin', getPositionShorthandNormalizer( 'margin' ) );
 * ```
 */ function getPositionShorthandNormalizer(shorthand) {
    return (value)=>{
        return {
            path: shorthand,
            value: getBoxSidesValues(value)
        };
    };
}
/**
 * Parses parts of a 1-to-4 value notation - handles some CSS values with spaces (like RGB()).
 *
 * ```ts
 * getShorthandValues( 'red blue RGB(0, 0, 0)');
 * // will return [ 'red', 'blue', 'RGB(0, 0, 0)' ]
 * ```
 */ function getShorthandValues(string) {
    const matches = string.matchAll(CSS_SHORTHAND_VALUE_REGEXP);
    return Array.from(matches).map((i)=>i[0]);
}

/**
 * Adds a background CSS styles processing rules.
 *
 * ```ts
 * editor.data.addStyleProcessorRules( addBackgroundRules );
 * ```
 *
 * The normalized value is stored as:
 *
 * ```ts
 * const styles = {
 * 	background: {
 * 		color,
 * 		repeat,
 * 		position,
 * 		attachment,
 * 		image
 * 	}
 * };
 * ````
 *
 * **Note**: Currently only `'background-color'` longhand value is parsed besides `'background'` shorthand. The reducer also supports only
 * `'background-color'` value.
 */ function addBackgroundRules(stylesProcessor) {
    stylesProcessor.setNormalizer('background', getBackgroundNormalizer());
    stylesProcessor.setNormalizer('background-color', getBackgroundColorNormalizer());
    stylesProcessor.setReducer('background', getBackgroundReducer());
    stylesProcessor.setStyleRelation('background', [
        'background-color'
    ]);
}
function getBackgroundNormalizer() {
    return (value)=>{
        const background = {};
        const parts = getShorthandValues(value);
        for (const part of parts){
            if (isRepeat(part)) {
                background.repeat = background.repeat || [];
                background.repeat.push(part);
            } else if (isPosition(part)) {
                background.position = background.position || [];
                background.position.push(part);
            } else if (isAttachment(part)) {
                background.attachment = part;
            } else if (isColor(part)) {
                background.color = part;
            } else if (isURL(part)) {
                background.image = part;
            }
        }
        return {
            path: 'background',
            value: background
        };
    };
}
function getBackgroundColorNormalizer() {
    return (value)=>({
            path: 'background.color',
            value
        });
}
function getBackgroundReducer() {
    return (value)=>{
        const ret = [];
        ret.push([
            'background-color',
            value.color
        ]);
        return ret;
    };
}

/**
 * Adds a border CSS styles processing rules.
 *
 * ```ts
 * editor.data.addStyleProcessorRules( addBorderRules );
 * ```
 *
 * This rules merges all [border](https://developer.mozilla.org/en-US/docs/Web/CSS/border) styles notation shorthands:
 *
 * - border
 * - border-top
 * - border-right
 * - border-bottom
 * - border-left
 * - border-color
 * - border-style
 * - border-width
 *
 * and all corresponding longhand forms (like `border-top-color`, `border-top-style`, etc).
 *
 * It does not handle other shorthands (like `border-radius` or `border-image`).
 *
 * The normalized model stores border values as:
 *
 * ```ts
 * const styles = {
 * 	border: {
 * 		color: { top, right, bottom, left },
 * 		style: { top, right, bottom, left },
 * 		width: { top, right, bottom, left },
 * 	}
 * };
 * ```
 */ function addBorderRules(stylesProcessor) {
    stylesProcessor.setNormalizer('border', getBorderNormalizer());
    // Border-position shorthands.
    stylesProcessor.setNormalizer('border-top', getBorderPositionNormalizer('top'));
    stylesProcessor.setNormalizer('border-right', getBorderPositionNormalizer('right'));
    stylesProcessor.setNormalizer('border-bottom', getBorderPositionNormalizer('bottom'));
    stylesProcessor.setNormalizer('border-left', getBorderPositionNormalizer('left'));
    // Border-property shorthands.
    stylesProcessor.setNormalizer('border-color', getBorderPropertyNormalizer('color'));
    stylesProcessor.setNormalizer('border-width', getBorderPropertyNormalizer('width'));
    stylesProcessor.setNormalizer('border-style', getBorderPropertyNormalizer('style'));
    // Border longhands.
    stylesProcessor.setNormalizer('border-top-color', getBorderPropertyPositionNormalizer('color', 'top'));
    stylesProcessor.setNormalizer('border-top-style', getBorderPropertyPositionNormalizer('style', 'top'));
    stylesProcessor.setNormalizer('border-top-width', getBorderPropertyPositionNormalizer('width', 'top'));
    stylesProcessor.setNormalizer('border-right-color', getBorderPropertyPositionNormalizer('color', 'right'));
    stylesProcessor.setNormalizer('border-right-style', getBorderPropertyPositionNormalizer('style', 'right'));
    stylesProcessor.setNormalizer('border-right-width', getBorderPropertyPositionNormalizer('width', 'right'));
    stylesProcessor.setNormalizer('border-bottom-color', getBorderPropertyPositionNormalizer('color', 'bottom'));
    stylesProcessor.setNormalizer('border-bottom-style', getBorderPropertyPositionNormalizer('style', 'bottom'));
    stylesProcessor.setNormalizer('border-bottom-width', getBorderPropertyPositionNormalizer('width', 'bottom'));
    stylesProcessor.setNormalizer('border-left-color', getBorderPropertyPositionNormalizer('color', 'left'));
    stylesProcessor.setNormalizer('border-left-style', getBorderPropertyPositionNormalizer('style', 'left'));
    stylesProcessor.setNormalizer('border-left-width', getBorderPropertyPositionNormalizer('width', 'left'));
    stylesProcessor.setExtractor('border-top', getBorderPositionExtractor('top'));
    stylesProcessor.setExtractor('border-right', getBorderPositionExtractor('right'));
    stylesProcessor.setExtractor('border-bottom', getBorderPositionExtractor('bottom'));
    stylesProcessor.setExtractor('border-left', getBorderPositionExtractor('left'));
    stylesProcessor.setExtractor('border-top-color', 'border.color.top');
    stylesProcessor.setExtractor('border-right-color', 'border.color.right');
    stylesProcessor.setExtractor('border-bottom-color', 'border.color.bottom');
    stylesProcessor.setExtractor('border-left-color', 'border.color.left');
    stylesProcessor.setExtractor('border-top-width', 'border.width.top');
    stylesProcessor.setExtractor('border-right-width', 'border.width.right');
    stylesProcessor.setExtractor('border-bottom-width', 'border.width.bottom');
    stylesProcessor.setExtractor('border-left-width', 'border.width.left');
    stylesProcessor.setExtractor('border-top-style', 'border.style.top');
    stylesProcessor.setExtractor('border-right-style', 'border.style.right');
    stylesProcessor.setExtractor('border-bottom-style', 'border.style.bottom');
    stylesProcessor.setExtractor('border-left-style', 'border.style.left');
    stylesProcessor.setReducer('border-color', getBoxSidesValueReducer('border-color'));
    stylesProcessor.setReducer('border-style', getBoxSidesValueReducer('border-style'));
    stylesProcessor.setReducer('border-width', getBoxSidesValueReducer('border-width'));
    stylesProcessor.setReducer('border-top', getBorderPositionReducer('top'));
    stylesProcessor.setReducer('border-right', getBorderPositionReducer('right'));
    stylesProcessor.setReducer('border-bottom', getBorderPositionReducer('bottom'));
    stylesProcessor.setReducer('border-left', getBorderPositionReducer('left'));
    stylesProcessor.setReducer('border', getBorderReducer());
    stylesProcessor.setStyleRelation('border', [
        'border-color',
        'border-style',
        'border-width',
        'border-top',
        'border-right',
        'border-bottom',
        'border-left',
        'border-top-color',
        'border-right-color',
        'border-bottom-color',
        'border-left-color',
        'border-top-style',
        'border-right-style',
        'border-bottom-style',
        'border-left-style',
        'border-top-width',
        'border-right-width',
        'border-bottom-width',
        'border-left-width'
    ]);
    stylesProcessor.setStyleRelation('border-color', [
        'border-top-color',
        'border-right-color',
        'border-bottom-color',
        'border-left-color'
    ]);
    stylesProcessor.setStyleRelation('border-style', [
        'border-top-style',
        'border-right-style',
        'border-bottom-style',
        'border-left-style'
    ]);
    stylesProcessor.setStyleRelation('border-width', [
        'border-top-width',
        'border-right-width',
        'border-bottom-width',
        'border-left-width'
    ]);
    stylesProcessor.setStyleRelation('border-top', [
        'border-top-color',
        'border-top-style',
        'border-top-width'
    ]);
    stylesProcessor.setStyleRelation('border-right', [
        'border-right-color',
        'border-right-style',
        'border-right-width'
    ]);
    stylesProcessor.setStyleRelation('border-bottom', [
        'border-bottom-color',
        'border-bottom-style',
        'border-bottom-width'
    ]);
    stylesProcessor.setStyleRelation('border-left', [
        'border-left-color',
        'border-left-style',
        'border-left-width'
    ]);
}
function getBorderNormalizer() {
    return (value)=>{
        const { color, style, width } = normalizeBorderShorthand(value);
        return {
            path: 'border',
            value: {
                color: getBoxSidesValues(color),
                style: getBoxSidesValues(style),
                width: getBoxSidesValues(width)
            }
        };
    };
}
function getBorderPositionNormalizer(side) {
    return (value)=>{
        const { color, style, width } = normalizeBorderShorthand(value);
        const border = {};
        if (color !== undefined) {
            border.color = {
                [side]: color
            };
        }
        if (style !== undefined) {
            border.style = {
                [side]: style
            };
        }
        if (width !== undefined) {
            border.width = {
                [side]: width
            };
        }
        return {
            path: 'border',
            value: border
        };
    };
}
function getBorderPropertyNormalizer(propertyName) {
    return (value)=>{
        return {
            path: 'border',
            value: toBorderPropertyShorthand(value, propertyName)
        };
    };
}
function toBorderPropertyShorthand(value, property) {
    return {
        [property]: getBoxSidesValues(value)
    };
}
function getBorderPropertyPositionNormalizer(property, side) {
    return (value)=>{
        return {
            path: 'border',
            value: {
                [property]: {
                    [side]: value
                }
            }
        };
    };
}
function getBorderPositionExtractor(which) {
    return (name, styles)=>{
        if (styles.border) {
            return extractBorderPosition(styles.border, which);
        }
    };
}
function extractBorderPosition(border, which) {
    const value = {};
    if (border.width && border.width[which]) {
        value.width = border.width[which];
    }
    if (border.style && border.style[which]) {
        value.style = border.style[which];
    }
    if (border.color && border.color[which]) {
        value.color = border.color[which];
    }
    return value;
}
function normalizeBorderShorthand(string) {
    const result = {};
    const parts = getShorthandValues(string);
    for (const part of parts){
        if (isLength(part) || /thin|medium|thick/.test(part)) {
            result.width = part;
        } else if (isLineStyle(part)) {
            result.style = part;
        } else {
            result.color = part;
        }
    }
    return result;
}
/**
 * The border reducer factory.
 *
 * It tries to produce the most optimal output for the specified styles.
 *
 * For a border style:
 *
 * ```css
 * style: {top: "solid", bottom: "solid", right: "solid", left: "solid"}
 * ```
 *
 * It will produce: `border-style: solid`.
 * For a border style and color:
 *
 * ```css
 * color: {top: "#ff0", bottom: "#ff0", right: "#ff0", left: "#ff0"}
 * style: {top: "solid", bottom: "solid", right: "solid", left: "solid"}
 * ```
 *
 * It will produce: `border-color: #ff0; border-style: solid`.
 * If all border parameters are specified:
 *
 * ```css
 * color: {top: "#ff0", bottom: "#ff0", right: "#ff0", left: "#ff0"}
 * style: {top: "solid", bottom: "solid", right: "solid", left: "solid"}
 * width: {top: "2px", bottom: "2px", right: "2px", left: "2px"}
 * ```
 *
 * It will combine everything into a single property: `border: 2px solid #ff0`.
 *
 * The definitions are merged only if all border selectors have the same values.
 */ function getBorderReducer() {
    return (value)=>{
        const topStyles = extractBorderPosition(value, 'top');
        const rightStyles = extractBorderPosition(value, 'right');
        const bottomStyles = extractBorderPosition(value, 'bottom');
        const leftStyles = extractBorderPosition(value, 'left');
        const borderStyles = [
            topStyles,
            rightStyles,
            bottomStyles,
            leftStyles
        ];
        const borderStylesByType = {
            width: getReducedStyleValueForType(borderStyles, 'width'),
            style: getReducedStyleValueForType(borderStyles, 'style'),
            color: getReducedStyleValueForType(borderStyles, 'color')
        };
        // Try reducing to a single `border:` property.
        const reducedBorderStyle = reduceBorderPosition(borderStylesByType, 'all');
        if (reducedBorderStyle.length) {
            return reducedBorderStyle;
        }
        // Try reducing to `border-style:`, `border-width:`, `border-color:` properties.
        const reducedStyleTypes = Object.entries(borderStylesByType).reduce((reducedStyleTypes, [type, value])=>{
            if (value) {
                reducedStyleTypes.push([
                    `border-${type}`,
                    value
                ]);
                // Remove it from the full set to not include it in the most specific properties later.
                borderStyles.forEach((style)=>delete style[type]);
            }
            return reducedStyleTypes;
        }, []);
        // The reduced properties (by type) and all that remains that could not be reduced.
        return [
            ...reducedStyleTypes,
            ...reduceBorderPosition(topStyles, 'top'),
            ...reduceBorderPosition(rightStyles, 'right'),
            ...reduceBorderPosition(bottomStyles, 'bottom'),
            ...reduceBorderPosition(leftStyles, 'left')
        ];
    };
    /**
	 * @param styles The array of objects with `style`, `color`, `width` properties.
	 */ function getReducedStyleValueForType(styles, type) {
        return styles.map((style)=>style[type]).reduce((result, style)=>result == style ? result : null);
    }
}
function getBorderPositionReducer(which) {
    return (value)=>reduceBorderPosition(value, which);
}
/**
 * Returns an array with reduced border styles depending on the specified values.
 *
 * If all border properties (width, style, color) are specified, the returned selector will be
 * merged into a group: `border-*: [width] [style] [color]`.
 *
 * Otherwise, the specific definitions will be returned: `border-(width|style|color)-*: [value]`.
 *
 * @param value Styles if defined.
 * @param which The border position.
 */ function reduceBorderPosition(value, which) {
    const borderTypes = [];
    if (value && value.width) {
        borderTypes.push('width');
    }
    if (value && value.style) {
        borderTypes.push('style');
    }
    if (value && value.color) {
        borderTypes.push('color');
    }
    if (borderTypes.length == 3) {
        const borderValue = borderTypes.map((item)=>value[item]).join(' ');
        return [
            which == 'all' ? [
                'border',
                borderValue
            ] : [
                `border-${which}`,
                borderValue
            ]
        ];
    }
    // We are unable to reduce to a single `border:` property.
    if (which == 'all') {
        return [];
    }
    return borderTypes.map((type)=>{
        return [
            `border-${which}-${type}`,
            value[type]
        ];
    });
}

/**
 * Adds a margin CSS styles processing rules.
 *
 * ```ts
 * editor.data.addStyleProcessorRules( addMarginRules );
 * ```
 *
 * The normalized value is stored as:
 *
 * ```ts
 * const styles = {
 * 	margin: {
 * 		top,
 * 		right,
 * 		bottom,
 * 		left
 * 	}
 * };
 * ```
 */ function addMarginRules(stylesProcessor) {
    stylesProcessor.setNormalizer('margin', getPositionShorthandNormalizer('margin'));
    stylesProcessor.setNormalizer('margin-top', (value)=>({
            path: 'margin.top',
            value
        }));
    stylesProcessor.setNormalizer('margin-right', (value)=>({
            path: 'margin.right',
            value
        }));
    stylesProcessor.setNormalizer('margin-bottom', (value)=>({
            path: 'margin.bottom',
            value
        }));
    stylesProcessor.setNormalizer('margin-left', (value)=>({
            path: 'margin.left',
            value
        }));
    stylesProcessor.setReducer('margin', getBoxSidesValueReducer('margin'));
    stylesProcessor.setStyleRelation('margin', [
        'margin-top',
        'margin-right',
        'margin-bottom',
        'margin-left'
    ]);
}

/**
 * Adds a padding CSS styles processing rules.
 *
 * ```ts
 * editor.data.addStyleProcessorRules( addPaddingRules );
 * ```
 *
 * The normalized value is stored as:
 *
 * ```ts
 * const styles = {
 * 	padding: {
 * 		top,
 * 		right,
 * 		bottom,
 * 		left
 * 	}
 * };
 * ```
 */ function addPaddingRules(stylesProcessor) {
    stylesProcessor.setNormalizer('padding', getPositionShorthandNormalizer('padding'));
    stylesProcessor.setNormalizer('padding-top', (value)=>({
            path: 'padding.top',
            value
        }));
    stylesProcessor.setNormalizer('padding-right', (value)=>({
            path: 'padding.right',
            value
        }));
    stylesProcessor.setNormalizer('padding-bottom', (value)=>({
            path: 'padding.bottom',
            value
        }));
    stylesProcessor.setNormalizer('padding-left', (value)=>({
            path: 'padding.left',
            value
        }));
    stylesProcessor.setReducer('padding', getBoxSidesValueReducer('padding'));
    stylesProcessor.setStyleRelation('padding', [
        'padding-top',
        'padding-right',
        'padding-bottom',
        'padding-left'
    ]);
}

const ELEMENT_RANGE_START_TOKEN = '[';
const ELEMENT_RANGE_END_TOKEN = ']';
const TEXT_RANGE_START_TOKEN = '{';
const TEXT_RANGE_END_TOKEN = '}';
const allowedTypes = {
    'container': ContainerElement,
    'attribute': AttributeElement,
    'empty': EmptyElement,
    'ui': UIElement,
    'raw': RawElement
};
// Returns simplified implementation of {@link module:engine/view/domconverter~DomConverter#setContentOf DomConverter.setContentOf} method.
// Used to render UIElement and RawElement.
const domConverterStub = {
    setContentOf: (node, html)=>{
        node.innerHTML = html;
    }
};
/**
 * Writes the content of the {@link module:engine/view/document~Document document} to an HTML-like string.
 *
 * @param options.withoutSelection Whether to write the selection. When set to `true`, the selection will
 * not be included in the returned string.
 * @param options.rootName The name of the root from which the data should be stringified. If not provided,
 * the default `main` name will be used.
 * @param options.showType When set to `true`, the type of elements will be printed (`<container:p>`
 * instead of `<p>`, `<attribute:b>` instead of `<b>` and `<empty:img>` instead of `<img>`).
 * @param options.showPriority When set to `true`, the attribute element's priority will be printed
 * (`<span view-priority="12">`, `<b view-priority="10">`).
 * @param options.showAttributeElementId When set to `true`, the attribute element's ID will be printed
 * (`<span id="marker:foo">`).
 * @param options.renderUIElements When set to `true`, the inner content of each
 * {@link module:engine/view/uielement~UIElement} will be printed.
 * @param options.renderRawElements When set to `true`, the inner content of each
 * {@link module:engine/view/rawelement~RawElement} will be printed.
 * @param options.domConverter When set to an actual {@link module:engine/view/domconverter~DomConverter DomConverter}
 * instance, it lets the conversion go through exactly the same flow the editing view is going through,
 * i.e. with view data filtering. Otherwise the simple stub is used.
 * @returns The stringified data.
 */ function getData$1(view, options = {}) {
    if (!(view instanceof View)) {
        throw new TypeError('View needs to be an instance of module:engine/view/view~View.');
    }
    const document1 = view.document;
    const withoutSelection = !!options.withoutSelection;
    const rootName = options.rootName || 'main';
    const root = document1.getRoot(rootName);
    const stringifyOptions = {
        showType: options.showType,
        showPriority: options.showPriority,
        renderUIElements: options.renderUIElements,
        renderRawElements: options.renderRawElements,
        ignoreRoot: true,
        domConverter: options.domConverter
    };
    return withoutSelection ? getData$1._stringify(root, null, stringifyOptions) : getData$1._stringify(root, document1.selection, stringifyOptions);
}
// Set stringify as getData private method - needed for testing/spying.
getData$1._stringify = stringify$1;
/**
 * Sets the content of a view {@link module:engine/view/document~Document document} provided as an HTML-like string.
 *
 * @param data An HTML-like string to write into the document.
 * @param options.rootName The root name where parsed data will be stored. If not provided,
 * the default `main` name will be used.
 */ function setData$1(view, data, options = {}) {
    if (!(view instanceof View)) {
        throw new TypeError('View needs to be an instance of module:engine/view/view~View.');
    }
    const document1 = view.document;
    const rootName = options.rootName || 'main';
    const root = document1.getRoot(rootName);
    view.change((writer)=>{
        const result = setData$1._parse(data, {
            rootElement: root
        });
        if (result.view && result.selection) {
            writer.setSelection(result.selection);
        }
    });
}
// Set parse as setData private method - needed for testing/spying.
setData$1._parse = parse$1;
/**
 * Converts view elements to HTML-like string representation.
 *
 * A root element can be provided as {@link module:engine/view/text~Text text}:
 *
 * ```ts
 * const text = downcastWriter.createText( 'foobar' );
 * stringify( text ); // 'foobar'
 * ```
 *
 * or as an {@link module:engine/view/element~Element element}:
 *
 * ```ts
 * const element = downcastWriter.createElement( 'p', null, downcastWriter.createText( 'foobar' ) );
 * stringify( element ); // '<p>foobar</p>'
 * ```
 *
 * or as a {@link module:engine/view/documentfragment~DocumentFragment document fragment}:
 *
 * ```ts
 * const text = downcastWriter.createText( 'foobar' );
 * const b = downcastWriter.createElement( 'b', { name: 'test' }, text );
 * const p = downcastWriter.createElement( 'p', { style: 'color:red;' } );
 * const fragment = downcastWriter.createDocumentFragment( [ p, b ] );
 *
 * stringify( fragment ); // '<p style="color:red;"></p><b name="test">foobar</b>'
 * ```
 *
 * Additionally, a {@link module:engine/view/documentselection~DocumentSelection selection} instance can be provided.
 * Ranges from the selection will then be included in the output data.
 * If a range position is placed inside the element node, it will be represented with `[` and `]`:
 *
 * ```ts
 * const text = downcastWriter.createText( 'foobar' );
 * const b = downcastWriter.createElement( 'b', null, text );
 * const p = downcastWriter.createElement( 'p', null, b );
 * const selection = downcastWriter.createSelection(
 * 	downcastWriter.createRangeIn( p )
 * );
 *
 * stringify( p, selection ); // '<p>[<b>foobar</b>]</p>'
 * ```
 *
 * If a range is placed inside the text node, it will be represented with `{` and `}`:
 *
 * ```ts
 * const text = downcastWriter.createText( 'foobar' );
 * const b = downcastWriter.createElement( 'b', null, text );
 * const p = downcastWriter.createElement( 'p', null, b );
 * const selection = downcastWriter.createSelection(
 * 	downcastWriter.createRange( downcastWriter.createPositionAt( text, 1 ), downcastWriter.createPositionAt( text, 5 ) )
 * );
 *
 * stringify( p, selection ); // '<p><b>f{ooba}r</b></p>'
 * ```
 *
 * ** Note: **
 * It is possible to unify selection markers to `[` and `]` for both (inside and outside text)
 * by setting the `sameSelectionCharacters=true` option. It is mainly used when the view stringify option is used by
 * model utilities.
 *
 * Multiple ranges are supported:
 *
 * ```ts
 * const text = downcastWriter.createText( 'foobar' );
 * const selection = downcastWriter.createSelection( [
 * 	downcastWriter.createRange( downcastWriter.createPositionAt( text, 0 ), downcastWriter.createPositionAt( text, 1 ) ),
 * 	downcastWriter.createRange( downcastWriter.createPositionAt( text, 3 ), downcastWriter.createPositionAt( text, 5 ) )
 * ] );
 *
 * stringify( text, selection ); // '{f}oo{ba}r'
 * ```
 *
 * A {@link module:engine/view/range~Range range} or {@link module:engine/view/position~Position position} instance can be provided
 * instead of the {@link module:engine/view/documentselection~DocumentSelection selection} instance. If a range instance
 * is provided, it will be converted to a selection containing this range. If a position instance is provided, it will
 * be converted to a selection containing one range collapsed at this position.
 *
 * ```ts
 * const text = downcastWriter.createText( 'foobar' );
 * const range = downcastWriter.createRange( downcastWriter.createPositionAt( text, 0 ), downcastWriter.createPositionAt( text, 1 ) );
 * const position = downcastWriter.createPositionAt( text, 3 );
 *
 * stringify( text, range ); // '{f}oobar'
 * stringify( text, position ); // 'foo{}bar'
 * ```
 *
 * An additional `options` object can be provided.
 * If `options.showType` is set to `true`, element's types will be
 * presented for {@link module:engine/view/attributeelement~AttributeElement attribute elements},
 * {@link module:engine/view/containerelement~ContainerElement container elements}
 * {@link module:engine/view/emptyelement~EmptyElement empty elements}
 * and {@link module:engine/view/uielement~UIElement UI elements}:
 *
 * ```ts
 * const attribute = downcastWriter.createAttributeElement( 'b' );
 * const container = downcastWriter.createContainerElement( 'p' );
 * const empty = downcastWriter.createEmptyElement( 'img' );
 * const ui = downcastWriter.createUIElement( 'span' );
 * getData( attribute, null, { showType: true } ); // '<attribute:b></attribute:b>'
 * getData( container, null, { showType: true } ); // '<container:p></container:p>'
 * getData( empty, null, { showType: true } ); // '<empty:img></empty:img>'
 * getData( ui, null, { showType: true } ); // '<ui:span></ui:span>'
 * ```
 *
 * If `options.showPriority` is set to `true`, a priority will be displayed for all
 * {@link module:engine/view/attributeelement~AttributeElement attribute elements}.
 *
 * ```ts
 * const attribute = downcastWriter.createAttributeElement( 'b' );
 * attribute._priority = 20;
 * getData( attribute, null, { showPriority: true } ); // <b view-priority="20"></b>
 * ```
 *
 * If `options.showAttributeElementId` is set to `true`, the attribute element's id will be displayed for all
 * {@link module:engine/view/attributeelement~AttributeElement attribute elements} that have it set.
 *
 * ```ts
 * const attribute = downcastWriter.createAttributeElement( 'span' );
 * attribute._id = 'marker:foo';
 * getData( attribute, null, { showAttributeElementId: true } ); // <span view-id="marker:foo"></span>
 * ```
 *
 * @param node The node to stringify.
 * @param selectionOrPositionOrRange A selection instance whose ranges will be included in the returned string data.
 * If a range instance is provided, it will be converted to a selection containing this range. If a position instance
 * is provided, it will be converted to a selection containing one range collapsed at this position.
 * @param options An object with additional options.
 * @param options.showType When set to `true`, the type of elements will be printed (`<container:p>`
 * instead of `<p>`, `<attribute:b>` instead of `<b>` and `<empty:img>` instead of `<img>`).
 * @param options.showPriority When set to `true`,  the attribute element's priority will be printed
 * (`<span view-priority="12">`, `<b view-priority="10">`).
 * @param options.showAttributeElementId When set to `true`, attribute element's id will be printed
 * (`<span id="marker:foo">`).
 * @param options.ignoreRoot When set to `true`, the root's element opening and closing will not be printed.
 * Mainly used by the `getData` function to ignore the {@link module:engine/view/document~Document document's} root element.
 * @param options.sameSelectionCharacters When set to `true`, the selection inside the text will be marked as
 *  `{` and `}` and the selection outside the text as `[` and `]`. When set to `false`, both will be marked as `[` and `]` only.
 * @param options.renderUIElements When set to `true`, the inner content of each
 * {@link module:engine/view/uielement~UIElement} will be printed.
 * @param options.renderRawElements When set to `true`, the inner content of each
 * {@link module:engine/view/rawelement~RawElement} will be printed.
 * @param options.domConverter When set to an actual {@link module:engine/view/domconverter~DomConverter DomConverter}
 * instance, it lets the conversion go through exactly the same flow the editing view is going through,
 * i.e. with view data filtering. Otherwise the simple stub is used.
 * @returns An HTML-like string representing the view.
 */ function stringify$1(node, selectionOrPositionOrRange = null, options = {}) {
    let selection;
    if (selectionOrPositionOrRange instanceof Position$1 || selectionOrPositionOrRange instanceof Range$1) {
        selection = new DocumentSelection$1(selectionOrPositionOrRange);
    } else {
        selection = selectionOrPositionOrRange;
    }
    const viewStringify = new ViewStringify(node, selection, options);
    return viewStringify.stringify();
}
/**
 * Parses an HTML-like string and returns a view tree.
 * A simple string will be converted to a {@link module:engine/view/text~Text text} node:
 *
 * ```ts
 * parse( 'foobar' ); // Returns an instance of text.
 * ```
 *
 * {@link module:engine/view/element~Element Elements} will be parsed with attributes as children:
 *
 * ```ts
 * parse( '<b name="baz">foobar</b>' ); // Returns an instance of element with the `baz` attribute and a text child node.
 * ```
 *
 * Multiple nodes provided on root level will be converted to a
 * {@link module:engine/view/documentfragment~DocumentFragment document fragment}:
 *
 * ```ts
 * parse( '<b>foo</b><i>bar</i>' ); // Returns a document fragment with two child elements.
 * ```
 *
 * The method can parse multiple {@link module:engine/view/range~Range ranges} provided in string data and return a
 * {@link module:engine/view/documentselection~DocumentSelection selection} instance containing these ranges. Ranges placed inside
 * {@link module:engine/view/text~Text text} nodes should be marked using `{` and `}` brackets:
 *
 * ```ts
 * const { text, selection } = parse( 'f{ooba}r' );
 * ```
 *
 * Ranges placed outside text nodes should be marked using `[` and `]` brackets:
 *
 * ```ts
 * const { root, selection } = parse( '<p>[<b>foobar</b>]</p>' );
 * ```
 *
 * ** Note: **
 * It is possible to unify selection markers to `[` and `]` for both (inside and outside text)
 * by setting `sameSelectionCharacters=true` option. It is mainly used when the view parse option is used by model utilities.
 *
 * Sometimes there is a need for defining the order of ranges inside the created selection. This can be achieved by providing
 * the range order array as an additional parameter:
 *
 * ```ts
 * const { root, selection } = parse( '{fo}ob{ar}{ba}z', { order: [ 2, 3, 1 ] } );
 * ```
 *
 * In the example above, the first range (`{fo}`) will be added to the selection as the second one, the second range (`{ar}`) will be
 * added as the third and the third range (`{ba}`) will be added as the first one.
 *
 * If the selection's last range should be added as a backward one
 * (so the {@link module:engine/view/documentselection~DocumentSelection#anchor selection anchor} is represented
 * by the `end` position and {@link module:engine/view/documentselection~DocumentSelection#focus selection focus} is
 * represented by the `start` position), use the `lastRangeBackward` flag:
 *
 * ```ts
 * const { root, selection } = parse( `{foo}bar{baz}`, { lastRangeBackward: true } );
 * ```
 *
 * Some more examples and edge cases:
 *
 * ```ts
 * // Returns an empty document fragment.
 * parse( '' );
 *
 * // Returns an empty document fragment and a collapsed selection.
 * const { root, selection } = parse( '[]' );
 *
 * // Returns an element and a selection that is placed inside the document fragment containing that element.
 * const { root, selection } = parse( '[<a></a>]' );
 * ```
 *
 * @param data An HTML-like string to be parsed.
 * @param options.order An array with the order of parsed ranges added to the returned
 * {@link module:engine/view/documentselection~DocumentSelection Selection} instance. Each element should represent the
 * desired position of each range in the selection instance. For example: `[2, 3, 1]` means that the first range will be
 * placed as the second, the second as the third and the third as the first.
 * @param options.lastRangeBackward If set to `true`, the last range will be added as backward to the returned
 * {@link module:engine/view/documentselection~DocumentSelection selection} instance.
 * @param options.rootElement The default root to use when parsing elements.
 * When set to `null`, the root element will be created automatically. If set to
 * {@link module:engine/view/element~Element Element} or {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment},
 * this node will be used as the root for all parsed nodes.
 * @param options.sameSelectionCharacters When set to `false`, the selection inside the text should be marked using
 * `{` and `}` and the selection outside the ext using `[` and `]`. When set to `true`, both should be marked with `[` and `]` only.
 * @param options.stylesProcessor Styles processor.
 * @returns Returns the parsed view node or an object with two fields: `view` and `selection` when selection ranges were included in the
 * data to parse.
 */ function parse$1(data, options = {}) {
    const viewDocument = new Document$1(new StylesProcessor());
    options.order = options.order || [];
    const rangeParser = new RangeParser({
        sameSelectionCharacters: options.sameSelectionCharacters
    });
    const processor = new XmlDataProcessor(viewDocument, {
        namespaces: Object.keys(allowedTypes)
    });
    // Convert data to view.
    let view = processor.toView(data);
    // At this point we have a view tree with Elements that could have names like `attribute:b:1`. In the next step
    // we need to parse Element's names and convert them to AttributeElements and ContainerElements.
    view = _convertViewElements(view);
    // If custom root is provided - move all nodes there.
    if (options.rootElement) {
        const root = options.rootElement;
        const nodes = view._removeChildren(0, view.childCount);
        root._removeChildren(0, root.childCount);
        root._appendChild(nodes);
        view = root;
    }
    // Parse ranges included in view text nodes.
    const ranges = rangeParser.parse(view, options.order);
    // If only one element is returned inside DocumentFragment - return that element.
    if (view.is('documentFragment') && view.childCount === 1) {
        view = view.getChild(0);
    }
    // When ranges are present - return object containing view, and selection.
    if (ranges.length) {
        const selection = new DocumentSelection$1(ranges, {
            backward: !!options.lastRangeBackward
        });
        return {
            view,
            selection
        };
    }
    // If single element is returned without selection - remove it from parent and return detached element.
    if (view.parent) {
        view._remove();
    }
    return view;
}
/**
 * Private helper class used for converting ranges represented as text inside view {@link module:engine/view/text~Text text nodes}.
 */ class RangeParser {
    sameSelectionCharacters;
    _positions;
    /**
	 * Creates a range parser instance.
	 *
	 * @param options The range parser configuration.
	 * @param options.sameSelectionCharacters When set to `true`, the selection inside the text is marked as
	 * `{` and `}` and the selection outside the text as `[` and `]`. When set to `false`, both are marked as `[` and `]`.
	 */ constructor(options){
        this.sameSelectionCharacters = !!options.sameSelectionCharacters;
    }
    /**
	 * Parses the view and returns ranges represented inside {@link module:engine/view/text~Text text nodes}.
	 * The method will remove all occurrences of `{`, `}`, `[` and `]` from found text nodes. If a text node is empty after
	 * the process, it will be removed, too.
	 *
	 * @param node The starting node.
	 * @param order The order of ranges. Each element should represent the desired position of the range after
	 * sorting. For example: `[2, 3, 1]` means that the first range will be placed as the second, the second as the third and the third
	 * as the first.
	 * @returns An array with ranges found.
	 */ parse(node, order) {
        this._positions = [];
        // Remove all range brackets from view nodes and save their positions.
        this._getPositions(node);
        // Create ranges using gathered positions.
        let ranges = this._createRanges();
        // Sort ranges if needed.
        if (order.length) {
            if (order.length != ranges.length) {
                throw new Error(`Parse error - there are ${ranges.length} ranges found, but ranges order array contains ${order.length} elements.`);
            }
            ranges = this._sortRanges(ranges, order);
        }
        return ranges;
    }
    /**
	 * Gathers positions of brackets inside the view tree starting from the provided node. The method will remove all occurrences of
	 * `{`, `}`, `[` and `]` from found text nodes. If a text node is empty after the process, it will be removed, too.
	 *
	 * @param node Staring node.
	 */ _getPositions(node) {
        if (node.is('documentFragment') || node.is('element')) {
            // Copy elements into the array, when nodes will be removed from parent node this array will still have all the
            // items needed for iteration.
            const children = [
                ...node.getChildren()
            ];
            for (const child of children){
                this._getPositions(child);
            }
        }
        if (node.is('$text')) {
            const regexp = new RegExp(`[${TEXT_RANGE_START_TOKEN}${TEXT_RANGE_END_TOKEN}\\${ELEMENT_RANGE_END_TOKEN}\\${ELEMENT_RANGE_START_TOKEN}]`, 'g');
            let text = node.data;
            let match;
            let offset = 0;
            const brackets = [];
            // Remove brackets from text and store info about offset inside text node.
            while(match = regexp.exec(text)){
                const index = match.index;
                const bracket = match[0];
                brackets.push({
                    bracket,
                    textOffset: index - offset
                });
                offset++;
            }
            text = text.replace(regexp, '');
            node._data = text;
            const index = node.index;
            const parent = node.parent;
            // Remove empty text nodes.
            if (!text) {
                node._remove();
            }
            for (const item of brackets){
                // Non-empty text node.
                if (text) {
                    if (this.sameSelectionCharacters || !this.sameSelectionCharacters && (item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN)) {
                        // Store information about text range delimiter.
                        this._positions.push({
                            bracket: item.bracket,
                            position: new Position$1(node, item.textOffset)
                        });
                    } else {
                        // Check if element range delimiter is not placed inside text node.
                        if (!this.sameSelectionCharacters && item.textOffset !== 0 && item.textOffset !== text.length) {
                            throw new Error(`Parse error - range delimiter '${item.bracket}' is placed inside text node.`);
                        }
                        // If bracket is placed at the end of the text node - it should be positioned after it.
                        const offset = item.textOffset === 0 ? index : index + 1;
                        // Store information about element range delimiter.
                        this._positions.push({
                            bracket: item.bracket,
                            position: new Position$1(parent, offset)
                        });
                    }
                } else {
                    if (!this.sameSelectionCharacters && item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN) {
                        throw new Error(`Parse error - text range delimiter '${item.bracket}' is placed inside empty text node. `);
                    }
                    // Store information about element range delimiter.
                    this._positions.push({
                        bracket: item.bracket,
                        position: new Position$1(parent, index)
                    });
                }
            }
        }
    }
    /**
	 * Sorts ranges in a given order. Range order should be an array and each element should represent the desired position
	 * of the range after sorting.
	 * For example: `[2, 3, 1]` means that the first range will be placed as the second, the second as the third and the third
	 * as the first.
	 *
	 * @param ranges Ranges to sort.
	 * @param rangesOrder An array with new range order.
	 * @returns Sorted ranges array.
	 */ _sortRanges(ranges, rangesOrder) {
        const sortedRanges = [];
        let index = 0;
        for (const newPosition of rangesOrder){
            if (ranges[newPosition - 1] === undefined) {
                throw new Error('Parse error - provided ranges order is invalid.');
            }
            sortedRanges[newPosition - 1] = ranges[index];
            index++;
        }
        return sortedRanges;
    }
    /**
	 * Uses all found bracket positions to create ranges from them.
	 */ _createRanges() {
        const ranges = [];
        let range = null;
        for (const item of this._positions){
            // When end of range is found without opening.
            if (!range && (item.bracket == ELEMENT_RANGE_END_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN)) {
                throw new Error(`Parse error - end of range was found '${item.bracket}' but range was not started before.`);
            }
            // When second start of range is found when one is already opened - selection does not allow intersecting
            // ranges.
            if (range && (item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN)) {
                throw new Error(`Parse error - start of range was found '${item.bracket}' but one range is already started.`);
            }
            if (item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN) {
                range = new Range$1(item.position, item.position);
            } else {
                range.end = item.position;
                ranges.push(range);
                range = null;
            }
        }
        // Check if all ranges have proper ending.
        if (range !== null) {
            throw new Error('Parse error - range was started but no end delimiter was found.');
        }
        return ranges;
    }
}
/**
 * Private helper class used for converting the view tree to a string.
 */ class ViewStringify {
    root;
    selection;
    ranges;
    showType;
    showPriority;
    showAttributeElementId;
    ignoreRoot;
    sameSelectionCharacters;
    renderUIElements;
    renderRawElements;
    domConverter;
    /**
	 * Creates a view stringify instance.
	 *
	 * @param selection A selection whose ranges should also be converted to a string.
	 * @param options An options object.
	 * @param options.showType When set to `true`, the type of elements will be printed (`<container:p>`
	 * instead of `<p>`, `<attribute:b>` instead of `<b>` and `<empty:img>` instead of `<img>`).
	 * @param options.showPriority When set to `true`, the attribute element's priority will be printed.
	 * @param options.ignoreRoot When set to `true`, the root's element opening and closing tag will not
	 * be outputted.
	 * @param options.sameSelectionCharacters When set to `true`, the selection inside the text is marked as
	 * `{` and `}` and the selection outside the text as `[` and `]`. When set to `false`, both are marked as `[` and `]`.
	 * @param options.renderUIElements When set to `true`, the inner content of each
	 * {@link module:engine/view/uielement~UIElement} will be printed.
	 * @param options.renderRawElements When set to `true`, the inner content of each
	 * @param options.domConverter When set to an actual {@link module:engine/view/domconverter~DomConverter DomConverter}
	 * instance, it lets the conversion go through exactly the same flow the editing view is going through,
	 * i.e. with view data filtering. Otherwise the simple stub is used.
	 * {@link module:engine/view/rawelement~RawElement} will be printed.
	 */ constructor(root, selection, options){
        this.root = root;
        this.selection = selection;
        this.ranges = [];
        if (selection) {
            this.ranges = [
                ...selection.getRanges()
            ];
        }
        this.showType = !!options.showType;
        this.showPriority = !!options.showPriority;
        this.showAttributeElementId = !!options.showAttributeElementId;
        this.ignoreRoot = !!options.ignoreRoot;
        this.sameSelectionCharacters = !!options.sameSelectionCharacters;
        this.renderUIElements = !!options.renderUIElements;
        this.renderRawElements = !!options.renderRawElements;
        this.domConverter = options.domConverter || domConverterStub;
    }
    /**
	 * Converts the view to a string.
	 *
	 * @returns String representation of the view elements.
	 */ stringify() {
        let result = '';
        this._walkView(this.root, (chunk)=>{
            result += chunk;
        });
        return result;
    }
    /**
	 * Executes a simple walker that iterates over all elements in the view tree starting from the root element.
	 * Calls the `callback` with parsed chunks of string data.
	 */ _walkView(root, callback) {
        const ignore = this.ignoreRoot && this.root === root;
        if (root.is('element') || root.is('documentFragment')) {
            if (root.is('element') && !ignore) {
                callback(this._stringifyElementOpen(root));
            }
            if (this.renderUIElements && root.is('uiElement')) {
                callback(root.render(document, this.domConverter).innerHTML);
            } else if (this.renderRawElements && root.is('rawElement')) {
                // There's no DOM element for "root" to pass to render(). Creating
                // a surrogate container to render the children instead.
                const rawContentContainer = document.createElement('div');
                root.render(rawContentContainer, this.domConverter);
                callback(rawContentContainer.innerHTML);
            } else {
                let offset = 0;
                callback(this._stringifyElementRanges(root, offset));
                for (const child of root.getChildren()){
                    this._walkView(child, callback);
                    offset++;
                    callback(this._stringifyElementRanges(root, offset));
                }
            }
            if (root.is('element') && !ignore) {
                callback(this._stringifyElementClose(root));
            }
        }
        if (root.is('$text')) {
            callback(this._stringifyTextRanges(root));
        }
    }
    /**
	 * Checks if a given {@link module:engine/view/element~Element element} has a {@link module:engine/view/range~Range#start range start}
	 * or a {@link module:engine/view/range~Range#start range end} placed at a given offset and returns its string representation.
	 */ _stringifyElementRanges(element, offset) {
        let start = '';
        let end = '';
        let collapsed = '';
        for (const range of this.ranges){
            if (range.start.parent == element && range.start.offset === offset) {
                if (range.isCollapsed) {
                    collapsed += ELEMENT_RANGE_START_TOKEN + ELEMENT_RANGE_END_TOKEN;
                } else {
                    start += ELEMENT_RANGE_START_TOKEN;
                }
            }
            if (range.end.parent === element && range.end.offset === offset && !range.isCollapsed) {
                end += ELEMENT_RANGE_END_TOKEN;
            }
        }
        return end + collapsed + start;
    }
    /**
	 * Checks if a given {@link module:engine/view/element~Element Text node} has a
	 * {@link module:engine/view/range~Range#start range start} or a
	 * {@link module:engine/view/range~Range#start range end} placed somewhere inside. Returns a string representation of text
	 * with range delimiters placed inside.
	 */ _stringifyTextRanges(node) {
        const length = node.data.length;
        const data = node.data.split('');
        let rangeStartToken, rangeEndToken;
        if (this.sameSelectionCharacters) {
            rangeStartToken = ELEMENT_RANGE_START_TOKEN;
            rangeEndToken = ELEMENT_RANGE_END_TOKEN;
        } else {
            rangeStartToken = TEXT_RANGE_START_TOKEN;
            rangeEndToken = TEXT_RANGE_END_TOKEN;
        }
        // Add one more element for ranges ending after last character in text.
        data[length] = '';
        // Represent each letter as object with information about opening/closing ranges at each offset.
        const result = data.map((letter)=>{
            return {
                letter,
                start: '',
                end: '',
                collapsed: ''
            };
        });
        for (const range of this.ranges){
            const start = range.start;
            const end = range.end;
            if (start.parent == node && start.offset >= 0 && start.offset <= length) {
                if (range.isCollapsed) {
                    result[end.offset].collapsed += rangeStartToken + rangeEndToken;
                } else {
                    result[start.offset].start += rangeStartToken;
                }
            }
            if (end.parent == node && end.offset >= 0 && end.offset <= length && !range.isCollapsed) {
                result[end.offset].end += rangeEndToken;
            }
        }
        return result.map((item)=>item.end + item.collapsed + item.start + item.letter).join('');
    }
    /**
	 * Converts the passed {@link module:engine/view/element~Element element} to an opening tag.
	 *
	 * Depending on the current configuration, the opening tag can be simple (`<a>`), contain a type prefix (`<container:p>`,
	 * `<attribute:a>` or `<empty:img>`), contain priority information ( `<attribute:a view-priority="20">` ),
	 * or contain element id ( `<attribute:span view-id="foo">` ). Element attributes will also be included
	 * (`<a href="https://ckeditor.com" name="foobar">`).
	 */ _stringifyElementOpen(element) {
        const priority = this._stringifyElementPriority(element);
        const id = this._stringifyElementId(element);
        const type = this._stringifyElementType(element);
        const name = [
            type,
            element.name
        ].filter((i)=>i !== '').join(':');
        const attributes = this._stringifyElementAttributes(element);
        const parts = [
            name,
            priority,
            id,
            attributes
        ];
        return `<${parts.filter((i)=>i !== '').join(' ')}>`;
    }
    /**
	 * Converts the passed {@link module:engine/view/element~Element element} to a closing tag.
	 * Depending on the current configuration, the closing tag can be simple (`</a>`) or contain a type prefix (`</container:p>`,
	 * `</attribute:a>` or `</empty:img>`).
	 */ _stringifyElementClose(element) {
        const type = this._stringifyElementType(element);
        const name = [
            type,
            element.name
        ].filter((i)=>i !== '').join(':');
        return `</${name}>`;
    }
    /**
	 * Converts the passed {@link module:engine/view/element~Element element's} type to its string representation
	 *
	 * Returns:
	 * * 'attribute' for {@link module:engine/view/attributeelement~AttributeElement attribute elements},
	 * * 'container' for {@link module:engine/view/containerelement~ContainerElement container elements},
	 * * 'empty' for {@link module:engine/view/emptyelement~EmptyElement empty elements},
	 * * 'ui' for {@link module:engine/view/uielement~UIElement UI elements},
	 * * 'raw' for {@link module:engine/view/rawelement~RawElement raw elements},
	 * * an empty string when the current configuration is preventing showing elements' types.
	 */ _stringifyElementType(element) {
        if (this.showType) {
            for(const type in allowedTypes){
                if (element instanceof allowedTypes[type]) {
                    return type;
                }
            }
        }
        return '';
    }
    /**
	 * Converts the passed {@link module:engine/view/element~Element element} to its priority representation.
	 *
	 * The priority string representation will be returned when the passed element is an instance of
	 * {@link module:engine/view/attributeelement~AttributeElement attribute element} and the current configuration allows to show the
	 * priority. Otherwise returns an empty string.
	 */ _stringifyElementPriority(element) {
        if (this.showPriority && element.is('attributeElement')) {
            return `view-priority="${element.priority}"`;
        }
        return '';
    }
    /**
	 * Converts the passed {@link module:engine/view/element~Element element} to its id representation.
	 *
	 * The id string representation will be returned when the passed element is an instance of
	 * {@link module:engine/view/attributeelement~AttributeElement attribute element}, the element has an id
	 * and the current configuration allows to show the id. Otherwise returns an empty string.
	 */ _stringifyElementId(element) {
        if (this.showAttributeElementId && element.is('attributeElement') && element.id) {
            return `view-id="${element.id}"`;
        }
        return '';
    }
    /**
	 * Converts the passed {@link module:engine/view/element~Element element} attributes to their string representation.
	 * If an element has no attributes, an empty string is returned.
	 */ _stringifyElementAttributes(element) {
        const attributes = [];
        const keys = [
            ...element.getAttributeKeys()
        ].sort();
        for (const attribute of keys){
            let attributeValue;
            if (attribute === 'class') {
                attributeValue = [
                    ...element.getClassNames()
                ].sort().join(' ');
            } else if (attribute === 'style') {
                attributeValue = [
                    ...element.getStyleNames()
                ].sort().map((style)=>`${style}:${element.getStyle(style).replace(/"/g, '&quot;')}`).join(';');
            } else {
                attributeValue = element.getAttribute(attribute);
            }
            attributes.push(`${attribute}="${attributeValue}"`);
        }
        return attributes.join(' ');
    }
}
/**
 * Converts {@link module:engine/view/element~Element elements} to
 * {@link module:engine/view/attributeelement~AttributeElement attribute elements},
 * {@link module:engine/view/containerelement~ContainerElement container elements},
 * {@link module:engine/view/emptyelement~EmptyElement empty elements} or
 * {@link module:engine/view/uielement~UIElement UI elements}.
 * It converts the whole tree starting from the `rootNode`. The conversion is based on element names.
 * See the `_convertElement` method for more details.
 *
 * @param rootNode The root node to convert.
 * @returns The root node of converted elements.
 */ function _convertViewElements(rootNode) {
    if (rootNode.is('element') || rootNode.is('documentFragment')) {
        // Convert element or leave document fragment.
        const convertedElement = rootNode.is('documentFragment') ? new DocumentFragment$1(rootNode.document) : _convertElement(rootNode.document, rootNode);
        // Convert all child nodes.
        // Cache the nodes in array. Otherwise, we would skip some nodes because during iteration we move nodes
        // from `rootNode` to `convertedElement`. This would interfere with iteration.
        for (const child of [
            ...rootNode.getChildren()
        ]){
            if (convertedElement.is('emptyElement')) {
                throw new Error('Parse error - cannot parse inside EmptyElement.');
            } else if (convertedElement.is('uiElement')) {
                throw new Error('Parse error - cannot parse inside UIElement.');
            } else if (convertedElement.is('rawElement')) {
                throw new Error('Parse error - cannot parse inside RawElement.');
            }
            convertedElement._appendChild(_convertViewElements(child));
        }
        return convertedElement;
    }
    return rootNode;
}
/**
 * Converts an {@link module:engine/view/element~Element element} to
 * {@link module:engine/view/attributeelement~AttributeElement attribute element},
 * {@link module:engine/view/containerelement~ContainerElement container element},
 * {@link module:engine/view/emptyelement~EmptyElement empty element} or
 * {@link module:engine/view/uielement~UIElement UI element}.
 * If the element's name is in the format of `attribute:b`, it will be converted to
 * an {@link module:engine/view/attributeelement~AttributeElement attribute element} with a priority of 11.
 * Additionally, attribute elements may have specified priority (for example `view-priority="11"`) and/or
 * id (for example `view-id="foo"`).
 * If the element's name is in the format of `container:p`, it will be converted to
 * a {@link module:engine/view/containerelement~ContainerElement container element}.
 * If the element's name is in the format of `empty:img`, it will be converted to
 * an {@link module:engine/view/emptyelement~EmptyElement empty element}.
 * If the element's name is in the format of `ui:span`, it will be converted to
 * a {@link module:engine/view/uielement~UIElement UI element}.
 * If the element's name does not contain any additional information, a {@link module:engine/view/element~Element view Element} will be
 * returned.
 *
 * @param viewElement A view element to convert.
 * @returns A tree view element converted according to its name.
 */ function _convertElement(viewDocument, viewElement) {
    const info = _convertElementNameAndInfo(viewElement);
    const ElementConstructor = allowedTypes[info.type];
    const newElement = ElementConstructor ? new ElementConstructor(viewDocument, info.name) : new Element$1(viewDocument, info.name);
    if (newElement.is('attributeElement')) {
        if (info.priority !== null) {
            newElement._priority = info.priority;
        }
        if (info.id !== null) {
            newElement._id = info.id;
        }
    }
    // Move attributes.
    for (const attributeKey of viewElement.getAttributeKeys()){
        newElement._setAttribute(attributeKey, viewElement.getAttribute(attributeKey));
    }
    return newElement;
}
/**
 * Converts the `view-priority` attribute and the {@link module:engine/view/element~Element#name element's name} information needed for
 * creating {@link module:engine/view/attributeelement~AttributeElement attribute element},
 * {@link module:engine/view/containerelement~ContainerElement container element},
 * {@link module:engine/view/emptyelement~EmptyElement empty element} or
 * {@link module:engine/view/uielement~UIElement UI element}.
 * The name can be provided in two formats: as a simple element's name (`div`), or as a type and name (`container:div`,
 * `attribute:span`, `empty:img`, `ui:span`);
 *
 * @param viewElement The element whose name should be converted.
 * @returns An object with parsed information:
 * * `name` The parsed name of the element.
 * * `type` The parsed type of the element. It can be `attribute`, `container` or `empty`.
 * * `priority` The parsed priority of the element.
 */ function _convertElementNameAndInfo(viewElement) {
    const parts = viewElement.name.split(':');
    const priority = _convertPriority(viewElement.getAttribute('view-priority'));
    const id = viewElement.hasAttribute('view-id') ? viewElement.getAttribute('view-id') : null;
    viewElement._removeAttribute('view-priority');
    viewElement._removeAttribute('view-id');
    if (parts.length == 1) {
        return {
            name: parts[0],
            type: priority !== null ? 'attribute' : null,
            priority,
            id
        };
    }
    // Check if type and name: container:div.
    const type = _convertType(parts[0]);
    if (type) {
        return {
            name: parts[1],
            type,
            priority,
            id
        };
    }
    throw new Error(`Parse error - cannot parse element's name: ${viewElement.name}.`);
}
/**
 * Checks if the element's type is allowed. Returns `attribute`, `container`, `empty` or `null`.
 */ function _convertType(type) {
    return type in allowedTypes ? type : null;
}
/**
 * Checks if a given priority is allowed. Returns null if the priority cannot be converted.
 */ function _convertPriority(priorityString) {
    const priority = parseInt(priorityString, 10);
    if (!isNaN(priority)) {
        return priority;
    }
    return null;
}

/**
 * Writes the content of a model {@link module:engine/model/document~Document document} to an HTML-like string.
 *
 * ```ts
 * getData( editor.model ); // -> '<paragraph>Foo![]</paragraph>'
 * ```
 *
 * **Note:** A {@link module:engine/model/text~Text text} node that contains attributes will be represented as:
 *
 * ```xml
 * <$text attribute="value">Text data</$text>
 * ```
 *
 * **Note:** Using this tool in production-grade code is not recommended. It was designed for development, prototyping,
 * debugging and testing.
 *
 * @param options.withoutSelection Whether to write the selection. When set to `true`, the selection will
 * not be included in the returned string.
 * @param options.rootName The name of the root from which the data should be stringified. If not provided,
 * the default `main` name will be used.
 * @param options.convertMarkers Whether to include markers in the returned string.
 * @returns The stringified data.
 */ function getData(model, options = {}) {
    if (!(model instanceof Model)) {
        throw new TypeError('Model needs to be an instance of module:engine/model/model~Model.');
    }
    const rootName = options.rootName || 'main';
    const root = model.document.getRoot(rootName);
    return getData._stringify(root, options.withoutSelection ? null : model.document.selection, options.convertMarkers ? model.markers : null);
}
// Set stringify as getData private method - needed for testing/spying.
getData._stringify = stringify;
/**
 * Sets the content of a model {@link module:engine/model/document~Document document} provided as an HTML-like string.
 *
 * ```ts
 * setData( editor.model, '<paragraph>Foo![]</paragraph>' );
 * ```
 *
 * **Note:** Remember to register elements in the {@link module:engine/model/model~Model#schema model's schema} before
 * trying to use them.
 *
 * **Note:** To create a {@link module:engine/model/text~Text text} node that contains attributes use:
 *
 * ```xml
 * <$text attribute="value">Text data</$text>
 * ```
 *
 * **Note:** Using this tool in production-grade code is not recommended. It was designed for development, prototyping,
 * debugging and testing.
 *
 * @param data HTML-like string to write into the document.
 * @param options.rootName Root name where parsed data will be stored. If not provided, the default `main`
 * name will be used.
 * @param options.selectionAttributes A list of attributes which will be passed to the selection.
 * @param options.lastRangeBackward If set to `true`, the last range will be added as backward.
 * @param options.batchType Batch type used for inserting elements. See {@link module:engine/model/batch~Batch#constructor}.
 * See {@link module:engine/model/batch~Batch#type}.
 */ function setData(model, data, options = {}) {
    if (!(model instanceof Model)) {
        throw new TypeError('Model needs to be an instance of module:engine/model/model~Model.');
    }
    let modelDocumentFragment;
    let selection = null;
    const modelRoot = model.document.getRoot(options.rootName || 'main');
    // Parse data string to model.
    const parsedResult = setData._parse(data, model.schema, {
        lastRangeBackward: options.lastRangeBackward,
        selectionAttributes: options.selectionAttributes,
        context: [
            modelRoot.name
        ]
    });
    // Retrieve DocumentFragment and Selection from parsed model.
    if ('model' in parsedResult) {
        modelDocumentFragment = parsedResult.model;
        selection = parsedResult.selection;
    } else {
        modelDocumentFragment = parsedResult;
    }
    if (options.batchType !== undefined) {
        model.enqueueChange(options.batchType, writeToModel);
    } else {
        model.change(writeToModel);
    }
    function writeToModel(writer) {
        // Replace existing model in document by new one.
        writer.remove(writer.createRangeIn(modelRoot));
        writer.insert(modelDocumentFragment, modelRoot);
        // Clean up previous document selection.
        writer.setSelection(null);
        writer.removeSelectionAttribute(model.document.selection.getAttributeKeys());
        // Update document selection if specified.
        if (selection) {
            const ranges = [];
            for (const range of selection.getRanges()){
                const start = new Position(modelRoot, range.start.path);
                const end = new Position(modelRoot, range.end.path);
                ranges.push(new Range(start, end));
            }
            writer.setSelection(ranges, {
                backward: selection.isBackward
            });
            if (options.selectionAttributes) {
                writer.setSelectionAttribute(selection.getAttributes());
            }
        }
    }
}
// Set parse as setData private method - needed for testing/spying.
setData._parse = parse;
/**
 * Converts model nodes to HTML-like string representation.
 *
 * **Note:** A {@link module:engine/model/text~Text text} node that contains attributes will be represented as:
 *
 * ```xml
 * <$text attribute="value">Text data</$text>
 * ```
 *
 * @param node A node to stringify.
 * @param selectionOrPositionOrRange A selection instance whose ranges will be included in the returned string data.
 * If a range instance is provided, it will be converted to a selection containing this range. If a position instance
 * is provided, it will be converted to a selection containing one range collapsed at this position.
 * @param markers Markers to include.
 * @returns An HTML-like string representing the model.
 */ function stringify(node, selectionOrPositionOrRange = null, markers = null) {
    const model = new Model();
    const mapper = new Mapper();
    let selection = null;
    let range;
    // Create a range witch wraps passed node.
    if (node instanceof RootElement || node instanceof DocumentFragment) {
        range = model.createRangeIn(node);
    } else {
        // Node is detached - create new document fragment.
        if (!node.parent) {
            const fragment = new DocumentFragment(node);
            range = model.createRangeIn(fragment);
        } else {
            range = new Range(model.createPositionBefore(node), model.createPositionAfter(node));
        }
    }
    // Get selection from passed selection or position or range if at least one is specified.
    if (selectionOrPositionOrRange instanceof Selection) {
        selection = selectionOrPositionOrRange;
    } else if (selectionOrPositionOrRange instanceof DocumentSelection) {
        selection = selectionOrPositionOrRange;
    } else if (selectionOrPositionOrRange instanceof Range) {
        selection = new Selection(selectionOrPositionOrRange);
    } else if (selectionOrPositionOrRange instanceof Position) {
        selection = new Selection(selectionOrPositionOrRange);
    }
    // Set up conversion.
    // Create a temporary view controller.
    const stylesProcessor = new StylesProcessor();
    const view = new View(stylesProcessor);
    const viewDocument = view.document;
    const viewRoot = new RootEditableElement(viewDocument, 'div');
    // Create a temporary root element in view document.
    viewRoot.rootName = 'main';
    viewDocument.roots.add(viewRoot);
    // Create and setup downcast dispatcher.
    const downcastDispatcher = new DowncastDispatcher({
        mapper,
        schema: model.schema
    });
    // Bind root elements.
    mapper.bindElements(node.root, viewRoot);
    downcastDispatcher.on('insert:$text', insertText());
    downcastDispatcher.on('insert', insertAttributesAndChildren(), {
        priority: 'lowest'
    });
    downcastDispatcher.on('attribute', (evt, data, conversionApi)=>{
        if (data.item instanceof Selection || data.item instanceof DocumentSelection || data.item.is('$textProxy')) {
            const converter = wrap((modelAttributeValue, { writer })=>{
                return writer.createAttributeElement('model-text-with-attributes', {
                    [data.attributeKey]: stringifyAttributeValue(modelAttributeValue)
                });
            });
            converter(evt, data, conversionApi);
        }
    });
    downcastDispatcher.on('insert', insertElement((modelItem)=>{
        // Stringify object types values for properly display as an output string.
        const attributes = convertAttributes(modelItem.getAttributes(), stringifyAttributeValue);
        return new ContainerElement(viewDocument, modelItem.name, attributes);
    }));
    downcastDispatcher.on('selection', convertRangeSelection());
    downcastDispatcher.on('selection', convertCollapsedSelection());
    downcastDispatcher.on('addMarker', insertUIElement((data, { writer })=>{
        const name = data.markerName + ':' + (data.isOpening ? 'start' : 'end');
        return writer.createUIElement(name);
    }));
    const markersMap = new Map();
    if (markers) {
        // To provide stable results, sort markers by name.
        for (const marker of Array.from(markers).sort((a, b)=>a.name < b.name ? 1 : -1)){
            markersMap.set(marker.name, marker.getRange());
        }
    }
    // Convert model to view.
    const writer = view._writer;
    downcastDispatcher.convert(range, markersMap, writer);
    // Convert model selection to view selection.
    if (selection) {
        downcastDispatcher.convertSelection(selection, markers || model.markers, writer);
    }
    // Parse view to data string.
    let data = stringify$1(viewRoot, viewDocument.selection, {
        sameSelectionCharacters: true
    });
    // Removing unnecessary <div> and </div> added because `viewRoot` was also stringified alongside input data.
    data = data.substr(5, data.length - 11);
    view.destroy();
    // Replace valid XML `model-text-with-attributes` element name to `$text`.
    return data.replace(new RegExp('model-text-with-attributes', 'g'), '$text');
}
/**
 * Parses an HTML-like string and returns the model {@link module:engine/model/rootelement~RootElement rootElement}.
 *
 * **Note:** To create a {@link module:engine/model/text~Text text} node that contains attributes use:
 *
 * ```xml
 * <$text attribute="value">Text data</$text>
 * ```
 *
 * @param data HTML-like string to be parsed.
 * @param schema A schema instance used by converters for element validation.
 * @param options Additional configuration.
 * @param options.selectionAttributes A list of attributes which will be passed to the selection.
 * @param options.lastRangeBackward If set to `true`, the last range will be added as backward.
 * @param options.context The conversion context. If not provided, the default `'$root'` will be used.
 * @returns Returns the parsed model node or an object with two fields: `model` and `selection`,
 * when selection ranges were included in the data to parse.
 */ function parse(data, schema, options = {}) {
    const mapper = new Mapper();
    // Replace not accepted by XML `$text` tag name by valid one `model-text-with-attributes`.
    data = data.replace(new RegExp('\\$text', 'g'), 'model-text-with-attributes');
    // Parse data to view using view utils.
    const parsedResult = parse$1(data, {
        sameSelectionCharacters: true,
        lastRangeBackward: !!options.lastRangeBackward
    });
    // Retrieve DocumentFragment and Selection from parsed view.
    let viewDocumentFragment;
    let viewSelection = null;
    let selection = null;
    if ('view' in parsedResult && 'selection' in parsedResult) {
        viewDocumentFragment = parsedResult.view;
        viewSelection = parsedResult.selection;
    } else {
        viewDocumentFragment = parsedResult;
    }
    // Set up upcast dispatcher.
    const modelController = new Model();
    const upcastDispatcher = new UpcastDispatcher({
        schema
    });
    upcastDispatcher.on('documentFragment', convertToModelFragment(mapper));
    upcastDispatcher.on('element:model-text-with-attributes', convertToModelText());
    upcastDispatcher.on('element', convertToModelElement(mapper));
    upcastDispatcher.on('text', convertToModelText());
    // Convert view to model.
    let model = modelController.change((writer)=>upcastDispatcher.convert(viewDocumentFragment.root, writer, options.context || '$root'));
    mapper.bindElements(model, viewDocumentFragment.root);
    // If root DocumentFragment contains only one element - return that element.
    if (model.childCount == 1) {
        model = model.getChild(0);
    }
    // Convert view selection to model selection.
    if (viewSelection) {
        const ranges = [];
        // Convert ranges.
        for (const viewRange of viewSelection.getRanges()){
            ranges.push(mapper.toModelRange(viewRange));
        }
        // Create new selection.
        selection = new Selection(ranges, {
            backward: viewSelection.isBackward
        });
        // Set attributes to selection if specified.
        for (const [key, value] of toMap(options.selectionAttributes || [])){
            selection.setAttribute(key, value);
        }
    }
    // Return model end selection when selection was specified.
    if (selection) {
        return {
            model,
            selection
        };
    }
    // Otherwise return model only.
    return model;
}
// -- Converters view -> model -----------------------------------------------------
function convertToModelFragment(mapper) {
    return (evt, data, conversionApi)=>{
        const childrenResult = conversionApi.convertChildren(data.viewItem, data.modelCursor);
        mapper.bindElements(data.modelCursor.parent, data.viewItem);
        data = Object.assign(data, childrenResult);
        evt.stop();
    };
}
function convertToModelElement(mapper) {
    return (evt, data, conversionApi)=>{
        const elementName = data.viewItem.name;
        if (!conversionApi.schema.checkChild(data.modelCursor, elementName)) {
            throw new Error(`Element '${elementName}' was not allowed in given position.`);
        }
        // View attribute value is a string so we want to typecast it to the original type.
        // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
        const attributes = convertAttributes(data.viewItem.getAttributes(), parseAttributeValue);
        const element = conversionApi.writer.createElement(data.viewItem.name, attributes);
        conversionApi.writer.insert(element, data.modelCursor);
        mapper.bindElements(element, data.viewItem);
        conversionApi.convertChildren(data.viewItem, element);
        data.modelRange = Range._createOn(element);
        data.modelCursor = data.modelRange.end;
        evt.stop();
    };
}
function convertToModelText() {
    return (evt, data, conversionApi)=>{
        if (!conversionApi.schema.checkChild(data.modelCursor, '$text')) {
            throw new Error('Text was not allowed in given position.');
        }
        let node;
        if (data.viewItem.is('element')) {
            // View attribute value is a string so we want to typecast it to the original type.
            // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
            const attributes = convertAttributes(data.viewItem.getAttributes(), parseAttributeValue);
            const viewText = data.viewItem.getChild(0);
            node = conversionApi.writer.createText(viewText.data, attributes);
        } else {
            node = conversionApi.writer.createText(data.viewItem.data);
        }
        conversionApi.writer.insert(node, data.modelCursor);
        data.modelRange = Range._createFromPositionAndShift(data.modelCursor, node.offsetSize);
        data.modelCursor = data.modelRange.end;
        evt.stop();
    };
}
// Tries to get original type of attribute value using JSON parsing:
//
//		`'true'` => `true`
//		`'1'` => `1`
//		`'{"x":1,"y":2}'` => `{ x: 1, y: 2 }`
//
// Parse error means that value should be a string:
//
//		`'foobar'` => `'foobar'`
function parseAttributeValue(attribute) {
    try {
        return JSON.parse(attribute);
    } catch (e) {
        return attribute;
    }
}
// When value is an Object stringify it.
function stringifyAttributeValue(data) {
    if (isPlainObject(data)) {
        return JSON.stringify(data);
    }
    return data;
}
// Loop trough attributes map and converts each value by passed converter.
function* convertAttributes(attributes, converter) {
    for (const [key, value] of attributes){
        yield [
            key,
            converter(value)
        ];
    }
}

export { AttributeElement, AttributeOperation, BubblingEventInfo, ClickObserver, Conversion, DataController, DataTransfer, DocumentFragment, DocumentSelection, DomConverter, DomEventData, DomEventObserver, DowncastWriter, EditingController, View as EditingView, Element, FocusObserver, History, HtmlDataProcessor, InsertOperation, LivePosition, LiveRange, MarkerOperation, Matcher, MergeOperation, Model, MouseObserver, MoveOperation, NoOperation, Observer, OperationFactory, Position, Range, RenameOperation, Renderer, RootAttributeOperation, RootOperation, SplitOperation, StylesMap, StylesProcessor, TabObserver, Text, TextProxy, TreeWalker, UpcastWriter, AttributeElement as ViewAttributeElement, ContainerElement as ViewContainerElement, Document$1 as ViewDocument, DocumentFragment$1 as ViewDocumentFragment, EditableElement as ViewEditableElement, Element$1 as ViewElement, EmptyElement as ViewEmptyElement, RawElement as ViewRawElement, RootEditableElement as ViewRootEditableElement, Text$1 as ViewText, TreeWalker$1 as ViewTreeWalker, UIElement as ViewUIElement, XmlDataProcessor, getData as _getModelData, getData$1 as _getViewData, parse as _parseModel, parse$1 as _parseView, setData as _setModelData, setData$1 as _setViewData, stringify as _stringifyModel, stringify$1 as _stringifyView, addBackgroundRules, addBorderRules, addMarginRules, addPaddingRules, disablePlaceholder, enablePlaceholder, getBoxSidesShorthandValue, getBoxSidesValueReducer, getBoxSidesValues, getFillerOffset$4 as getFillerOffset, getPositionShorthandNormalizer, getShorthandValues, hidePlaceholder, isAttachment, isColor, isLength, isLineStyle, isPercentage, isPosition, isRepeat, isURL, needsPlaceholder, showPlaceholder, transformSets };
//# sourceMappingURL=index.js.map
